Eclipse SUMO - Simulation of Urban MObility
Loading...
Searching...
No Matches
OptionsCont.cpp
Go to the documentation of this file.
1/****************************************************************************/
2// Eclipse SUMO, Simulation of Urban MObility; see https://eclipse.dev/sumo
3// Copyright (C) 2001-2026 German Aerospace Center (DLR) and others.
4// This program and the accompanying materials are made available under the
5// terms of the Eclipse Public License 2.0 which is available at
6// https://www.eclipse.org/legal/epl-2.0/
7// This Source Code may also be made available under the following Secondary
8// Licenses when the conditions for such availability set forth in the Eclipse
9// Public License 2.0 are satisfied: GNU General Public License, version 2
10// or later which is available at
11// https://www.gnu.org/licenses/old-licenses/gpl-2.0-standalone.html
12// SPDX-License-Identifier: EPL-2.0 OR GPL-2.0-or-later
13/****************************************************************************/
21// A storage for options (typed value containers)
22/****************************************************************************/
23#include <config.h>
24
25#include <map>
26#include <string>
27#include <exception>
28#include <algorithm>
29#include <vector>
30#include <iostream>
31#include <cstdlib>
32#include <ctime>
33#include <cstring>
34#include <cerrno>
35#include <iterator>
36#include <sstream>
44#include <utils/xml/XMLSubSys.h>
46#include "Option.h"
47#include "OptionsIO.h"
48#include "OptionsCont.h"
49
50
51// ===========================================================================
52// static member definitions
53// ===========================================================================
54
57
58// ===========================================================================
59// method definitions
60// ===========================================================================
61
66
67
69 myCopyrightNotices.push_back(TL("Copyright (C) 2001-2026 German Aerospace Center (DLR) and others; https://sumo.dlr.de"));
70}
71
72
76
77
78void
79OptionsCont::doRegister(const std::string& name, Option* o) {
80 // first check that option isn't null
81 if (o == nullptr) {
82 throw ProcessError("Option cannot be null");
83 }
84 // now check that there isn't another addresse (or synonym) related with the option
85 if (myValues.find(name) != myValues.end()) {
86 throw ProcessError(name + " is an already used option name.");
87 }
88 // check if previously was inserted in addresses (to avoid synonyms in addresses)
89 bool isSynonym = false;
90 for (const auto& addresse : myAddresses) {
91 if (addresse.second == o) {
92 isSynonym = true;
93 }
94 }
95 if (!isSynonym) {
96 myAddresses.push_back(std::make_pair(name, o));
97 }
98 // insert in values
99 myValues[name] = o;
100}
101
102
103void
104OptionsCont::doRegister(const std::string& name1, char abbr, Option* o) {
105 doRegister(name1, o);
106 doRegister(convertChar(abbr), o);
107}
108
109
110void
111OptionsCont::addSynonyme(const std::string& name1, const std::string& name2, bool isDeprecated) {
112 auto i1 = myValues.find(name1);
113 auto i2 = myValues.find(name2);
114 if (i1 == myValues.end() && i2 == myValues.end()) {
115 throw ProcessError("Neither the option '" + name1 + "' nor the option '" + name2 + "' is known yet");
116 }
117 if (i1 != myValues.end() && i2 != myValues.end()) {
118 if ((*i1).second == (*i2).second) {
119 return;
120 }
121 throw ProcessError("Both options '" + name1 + "' and '" + name2 + "' do exist and differ.");
122 }
123 if (i1 == myValues.end() && i2 != myValues.end()) {
124 doRegister(name1, (*i2).second);
125 if (isDeprecated) {
126 myDeprecatedSynonymes[name1] = false;
127 }
128 }
129 if (i1 != myValues.end() && i2 == myValues.end()) {
130 doRegister(name2, (*i1).second);
131 if (isDeprecated) {
132 myDeprecatedSynonymes[name2] = false;
133 }
134 }
135}
136
137
138void
139OptionsCont::addXMLDefault(const std::string& name, const std::string& xmlRoot) {
140 myXMLDefaults[xmlRoot] = name;
141}
142
143
144bool
145OptionsCont::exists(const std::string& name) const {
146 return myValues.count(name) > 0;
147}
148
149
150bool
151OptionsCont::isSet(const std::string& name, bool failOnNonExistant) const {
152 auto i = myValues.find(name);
153 if (i == myValues.end()) {
154 if (failOnNonExistant) {
155 throw ProcessError(TLF("Internal request for unknown option '%'!", name));
156 } else {
157 return false;
158 }
159 }
160 return (*i).second->isSet();
161}
162
163
164bool
165OptionsCont::isDefault(const std::string& name) const {
166 auto i = myValues.find(name);
167 if (i == myValues.end()) {
168 return false;
169 }
170 return (*i).second->isDefault();
171}
172
173
174Option*
175OptionsCont::getSecure(const std::string& name) const {
176 const auto& valuesFinder = myValues.find(name);
177 if (valuesFinder == myValues.end()) {
178 throw ProcessError(TLF("No option with the name '%' exists.", name));
179 }
180 const auto& synonymFinder = myDeprecatedSynonymes.find(name);
181 if ((synonymFinder != myDeprecatedSynonymes.end()) && !synonymFinder->second) {
182 std::string defaultName;
183 for (const auto& subtopicEntry : mySubTopicEntries) {
184 for (const auto& value : subtopicEntry.second) {
185 const auto l = myValues.find(value);
186 if ((l != myValues.end()) && (l->second == valuesFinder->second)) {
187 defaultName = value;
188 break;
189 }
190 }
191 if (defaultName != "") {
192 break;
193 }
194 }
195 WRITE_WARNINGF(TL("Please note that '%' is deprecated.\n Use '%' instead."), name, defaultName);
196 synonymFinder->second = true;
197 }
198 return valuesFinder->second;
199}
200
201
202std::string
203OptionsCont::getValueString(const std::string& name) const {
204 Option* o = getSecure(name);
205 return o->getValueString();
206}
207
208
209std::string
210OptionsCont::getString(const std::string& name) const {
211 Option* o = getSecure(name);
212 return o->getString();
213}
214
215
216double
217OptionsCont::getFloat(const std::string& name) const {
218 Option* o = getSecure(name);
219 return o->getFloat();
220}
221
222
223int
224OptionsCont::getInt(const std::string& name) const {
225 Option* o = getSecure(name);
226 return o->getInt();
227}
228
229
230bool
231OptionsCont::getBool(const std::string& name) const {
232 Option* o = getSecure(name);
233 return o->getBool();
234}
235
236
237const IntVector&
238OptionsCont::getIntVector(const std::string& name) const {
239 Option* o = getSecure(name);
240 return o->getIntVector();
241}
242
243const StringVector&
244OptionsCont::getStringVector(const std::string& name) const {
245 Option* o = getSecure(name);
246 return o->getStringVector();
247}
248
249
250bool
251OptionsCont::set(const std::string& name, const std::string& value, const bool append) {
252 Option* o = getSecure(name);
253 if (!o->isWriteable()) {
255 return false;
256 }
257 try {
258 // Substitute environment variables defined by ${NAME} with their value
259 if (!o->set(StringUtils::substituteEnvironment(value, &OptionsIO::getLoadTime()), value, append)) {
260 return false;
261 }
262 } catch (ProcessError& e) {
263 WRITE_ERROR("While processing option '" + name + "':\n " + e.what());
264 return false;
265 }
266 return true;
267}
268
269
270bool
271OptionsCont::setDefault(const std::string& name, const std::string& value) {
272 Option* const o = getSecure(name);
273 if (o->isWriteable() && set(name, value)) {
274 o->resetDefault();
275 return true;
276 }
277 return false;
278}
279
280
281bool
282OptionsCont::setByRootElement(const std::string& root, const std::string& value) {
283 if (myXMLDefaults.count(root) > 0) {
284 return set(myXMLDefaults[root], value);
285 }
286 if (myXMLDefaults.count("") > 0) {
287 return set(myXMLDefaults[""], value);
288 }
289 return false;
290}
291
292
293std::vector<std::string>
294OptionsCont::getSynonymes(const std::string& name) const {
295 Option* o = getSecure(name);
296 std::vector<std::string> synonymes;
297 for (const auto& value : myValues) {
298 if ((value.second == o) && (name != value.first)) {
299 synonymes.push_back(value.first);
300 }
301 }
302 return synonymes;
303}
304
305
306const std::string&
307OptionsCont::getDescription(const std::string& name) const {
308 return getSecure(name)->getDescription();
309}
310
311
312const std::string&
313OptionsCont::getSubTopic(const std::string& name) const {
314 return getSecure(name)->getSubTopic();
315}
316
317
318std::ostream&
319operator<<(std::ostream& os, const OptionsCont& oc) {
320 std::vector<std::string> done;
321 os << "Options set:" << std::endl;
322 for (const auto& value : oc.myValues) {
323 const auto& finder = std::find(done.begin(), done.end(), value.first);
324 if (finder == done.end()) {
325 std::vector<std::string> synonymes = oc.getSynonymes(value.first);
326 if (synonymes.size() != 0) {
327 os << value.first << " (";
328 for (auto synonym = synonymes.begin(); synonym != synonymes.end(); synonym++) {
329 if (synonym != synonymes.begin()) {
330 os << ", ";
331 }
332 os << (*synonym);
333 }
334 os << ")";
335 } else {
336 os << value.first;
337 }
338 if (value.second->isSet()) {
339 os << ": " << value.second->getValueString() << std::endl;
340 } else {
341 os << ": <INVALID>" << std::endl;
342 }
343 done.push_back(value.first);
344 copy(synonymes.begin(), synonymes.end(), back_inserter(done));
345 }
346 }
347 return os;
348}
349
350
351void
352OptionsCont::relocateFiles(const std::string& configuration) const {
353 for (const auto& addresse : myAddresses) {
354 if (addresse.second->isFileName() && addresse.second->isSet()) {
355 StringVector fileList = StringVector(addresse.second->getStringVector());
356 for (auto& file : fileList) {
357 if (addresse.first != "configuration-file") {
358 file = FileHelpers::checkForRelativity(file, configuration);
359 }
360 try {
361 file = StringUtils::urlDecode(file);
362 } catch (NumberFormatException& e) {
363 WRITE_WARNING(toString(e.what()) + " when trying to decode filename '" + file + "'.");
364 }
365 }
366 StringVector rawList = StringTokenizer(addresse.second->getValueString(), ",").getVector();
367 for (auto& file : rawList) {
368 file = FileHelpers::checkForRelativity(file, configuration);
369 }
370 const std::string conv = joinToString(fileList, ',');
371 if (conv != joinToString(addresse.second->getStringVector(), ',')) {
372 const bool hadDefault = addresse.second->isDefault();
373 addresse.second->set(conv, joinToString(rawList, ','), false);
374 if (hadDefault) {
375 addresse.second->resetDefault();
376 }
377 }
378 }
379 }
380}
381
382
383bool
384OptionsCont::isUsableFileList(const std::string& name) const {
385 Option* const o = getSecure(name);
386 if (!o->isSet()) {
387 return false;
388 }
389 // check whether the list of files is valid
390 bool ok = true;
391 std::vector<std::string> files = getStringVector(name);
392 if (files.size() == 0) {
393 WRITE_ERRORF(TL("The file list for '%' is empty."), name);
394 ok = false;
395 }
396 for (const auto& file : files) {
397 if (!FileHelpers::isReadable(file)) {
398 if (file != "") {
399 WRITE_ERRORF(TL("File '%' is not accessible (%)."), file, std::strerror(errno));
400 ok = false;
401 } else {
402 WRITE_WARNING(TL("Empty file name given; ignoring."));
403 }
404 }
405 }
406 return ok;
407}
408
409
410bool
411OptionsCont::checkDependingSuboptions(const std::string& name, const std::string& prefix) const {
412 Option* o = getSecure(name);
413 if (o->isSet()) {
414 return true;
415 }
416 bool ok = true;
417 std::vector<std::string> seenSynonymes;
418 for (const auto& value : myValues) {
419 if (std::find(seenSynonymes.begin(), seenSynonymes.end(), value.first) != seenSynonymes.end()) {
420 continue;
421 }
422 if (value.second->isSet() && !value.second->isDefault() && value.first.find(prefix) == 0) {
423 WRITE_ERRORF(TL("Option '%' needs option '%'."), value.first, name);
424 std::vector<std::string> synonymes = getSynonymes(value.first);
425 std::copy(synonymes.begin(), synonymes.end(), std::back_inserter(seenSynonymes));
426 ok = false;
427 }
428 }
429 return ok;
430}
431
432
433void
434OptionsCont::reportDoubleSetting(const std::string& arg) const {
435 std::vector<std::string> synonymes = getSynonymes(arg);
436 std::ostringstream s;
437 s << TLF("A value for the option '%' was already set.\n Possible synonymes: ", arg);
438 auto synonym = synonymes.begin();
439 while (synonym != synonymes.end()) {
440 s << (*synonym);
441 synonym++;
442 if (synonym != synonymes.end()) {
443 s << ", ";
444 }
445 }
446 WRITE_ERROR(s.str());
447}
448
449
450std::string
451OptionsCont::convertChar(char abbr) const {
452 char buf[2];
453 buf[0] = abbr;
454 buf[1] = 0;
455 std::string s(buf);
456 return s;
457}
458
459
460bool
461OptionsCont::isBool(const std::string& name) const {
462 Option* o = getSecure(name);
463 return o->isBool();
464}
465
466
467void
469 for (const auto& addresse : myAddresses) {
470 addresse.second->resetWritable();
471 }
472}
473
474
475void
476OptionsCont::resetWritable(const std::string& name) {
477 getSecure(name)->resetWritable();
478}
479
480
481void
483 for (const auto& addresse : myAddresses) {
484 addresse.second->resetDefault();
485 }
486}
487
488
489void
490OptionsCont::resetDefault(const std::string& name) {
491 getSecure(name)->resetDefault();
492}
493
494
495bool
496OptionsCont::isWriteable(const std::string& name) {
497 return getSecure(name)->isWriteable();
498}
499
500
501bool
502OptionsCont::isEditable(const std::string& name) {
503 return getSecure(name)->isEditable();
504
505}
506
507
508void
510 // delete only address (because synonyms placed in values aim to the same Option)
511 for (const auto& addresse : myAddresses) {
512 delete addresse.second;
513 }
514 myAddresses.clear();
515 myValues.clear();
516 mySubTopics.clear();
517 mySubTopicEntries.clear();
518}
519
520
521void
522OptionsCont::addDescription(const std::string& name, const std::string& subtopic,
523 const std::string& description) {
524 Option* o = getSecure(name);
525 if (o == nullptr) {
526 throw ProcessError("Option doesn't exist");
527 }
528 if (find(mySubTopics.begin(), mySubTopics.end(), subtopic) == mySubTopics.end()) {
529 throw ProcessError("SubTopic '" + subtopic + "' doesn't exist");
530 }
531 o->setDescription(description);
532 o->setSubtopic(subtopic);
533 mySubTopicEntries[subtopic].push_back(name);
534}
535
536
537void
538OptionsCont::setFurtherAttributes(const std::string& name, const std::string& subtopic, bool required, bool positional, const std::string& listSep) {
539 Option* o = getSecure(name);
540 if (o == nullptr) {
541 throw ProcessError("Option doesn't exist");
542 }
543 if (find(mySubTopics.begin(), mySubTopics.end(), subtopic) == mySubTopics.end()) {
544 throw ProcessError("SubTopic '" + subtopic + "' doesn't exist");
545 }
546 if (required) {
547 o->setRequired();
548 }
549 if (positional) {
550 o->setPositional();
551 }
552 o->setListSeparator(listSep);
553}
554
555
556void
557OptionsCont::setOptionEditable(const std::string& name, const bool value) {
558 getSecure(name)->setEditable(value);
559}
560
561
562void
563OptionsCont::setApplicationName(const std::string& appName, const std::string& fullName) {
564 myAppName = appName;
565 myFullName = fullName;
566}
567
568
569void
570OptionsCont::setApplicationDescription(const std::string& appDesc) {
571 myAppDescription = appDesc;
572}
573
574
575void
576OptionsCont::addCallExample(const std::string& example, const std::string& desc) {
577 myCallExamples.push_back(std::make_pair(example, desc));
578}
579
580
581void
584}
585
586
587void
588OptionsCont::addCopyrightNotice(const std::string& copyrightLine) {
589 myCopyrightNotices.push_back(copyrightLine);
590}
591
592
593void
597
598
599void
600OptionsCont::addOptionSubTopic(const std::string& topic) {
601 mySubTopics.push_back(topic);
602 mySubTopicEntries[topic] = std::vector<std::string>();
603}
604
605
606void
607OptionsCont::removeSubTopic(const std::string& topic) {
608 auto it = std::find(mySubTopics.begin(), mySubTopics.end(), topic);
609 if (it != mySubTopics.end()) {
610 mySubTopics.erase(it);
611 }
612 mySubTopicEntries.erase(topic);
613}
614
615
616void
617OptionsCont::removeOption(const std::string& name) {
618 for (auto& entry : mySubTopicEntries) {
619 auto it = std::find(entry.second.begin(), entry.second.end(), name);
620 if (it != entry.second.end()) {
621 entry.second.erase(it);
622 }
623 }
624}
625
626
627void
628OptionsCont::splitLines(std::ostream& os, std::string what,
629 int offset, int nextOffset) {
630 while (what.length() > 0) {
631 if ((int)what.length() > 79 - offset) {
632 std::string::size_type splitPos = what.rfind(';', 79 - offset);
633 if (splitPos == std::string::npos) {
634 splitPos = what.rfind(' ', 79 - offset);
635 } else {
636 splitPos++;
637 }
638 if (splitPos != std::string::npos) {
639 os << what.substr(0, splitPos) << std::endl;
640 what = what.substr(splitPos + 1);
641 for (int r = 0; r < (nextOffset + 1); ++r) {
642 os << ' ';
643 }
644 } else {
645 os << what;
646 what = "";
647 }
648 offset = nextOffset;
649 } else {
650 os << what;
651 what = "";
652 }
653 }
654 os << std::endl;
655}
656
657
658bool
660 MsgHandler::setupI18n(getString("language"));
662 if (missingOptions) {
663 // no options are given
664 std::cout << myFullName << std::endl;
665 std::cout << TL(" Build features: ") << HAVE_ENABLED << std::endl;
666 for (const auto& copyrightNotice : myCopyrightNotices) {
667 std::cout << " " << copyrightNotice.data() << std::endl;
668 }
669 std::cout << TL(" License EPL-2.0: Eclipse Public License Version 2 <https://eclipse.org/legal/epl-v20.html>") << std::endl;
670 std::cout << TL(" Use --help to get the list of options.") << std::endl;
671 return true;
672 }
673
674 // check whether the help shall be printed
675 if (getBool("help")) {
676 std::cout << myFullName << std::endl;
677 for (const auto& copyrightNotice : myCopyrightNotices) {
678 std::cout << " " << copyrightNotice.data() << std::endl;
679 }
680 printHelp(std::cout);
681 return true;
682 }
683 // check whether the help shall be printed
684 if (getBool("version")) {
685 std::cout << myFullName << std::endl;
686 std::cout << TL(" Build features: ") << HAVE_ENABLED << std::endl;
687 for (const auto& copyrightNotice : myCopyrightNotices) {
688 std::cout << " " << copyrightNotice.data() << std::endl;
689 }
690 std::cout << "\n" << myFullName << " is part of SUMO.\n";
691 std::cout << "This program and the accompanying materials\n";
692 std::cout << "are made available under the terms of the Eclipse Public License v2.0\n";
693 std::cout << "which accompanies this distribution, and is available at\n";
694 std::cout << "http://www.eclipse.org/legal/epl-v20.html\n";
695 std::cout << "This program may also be made available under the following Secondary\n";
696 std::cout << "Licenses when the conditions for such availability set forth in the Eclipse\n";
697 std::cout << "Public License 2.0 are satisfied: GNU General Public License, version 2\n";
698 std::cout << "or later which is available at\n";
699 std::cout << "https://www.gnu.org/licenses/old-licenses/gpl-2.0-standalone.html\n";
700 std::cout << "SPDX-License-Identifier: EPL-2.0 OR GPL-2.0-or-later" << std::endl;
701 return true;
702 }
703 // check whether the settings shall be printed
704 if (getBool("print-options")) {
705 std::cout << (*this);
706 }
707 // check whether something has to be done with options
708 // whether the current options shall be saved
709 if (isSet("save-configuration")) {
710 const std::string& configPath = getString("save-configuration");
711 if (configPath == "-" || configPath == "stdout") {
712 writeConfiguration(std::cout, true, false, getBool("save-commented"));
713 return true;
714 }
715 std::ofstream out(StringUtils::transcodeLocal(configPath, true).c_str());
716 if (!out.good()) {
717 throw ProcessError(TLF("Could not save configuration to '%'", configPath));
718 } else {
719 writeConfiguration(out, true, false, getBool("save-commented"), configPath);
720 if (getBool("verbose")) {
721 WRITE_MESSAGEF(TL("Written configuration to '%'"), configPath);
722 }
723 return true;
724 }
725 }
726 // whether the template shall be saved
727 if (isSet("save-template")) {
728 if (getString("save-template") == "-" || getString("save-template") == "stdout") {
729 writeConfiguration(std::cout, false, true, getBool("save-commented"));
730 return true;
731 }
732 std::ofstream out(StringUtils::transcodeLocal(getString("save-template"), true).c_str());
733 if (!out.good()) {
734 throw ProcessError(TLF("Could not save template to '%'", getString("save-template")));
735 } else {
736 writeConfiguration(out, false, true, getBool("save-commented"));
737 if (getBool("verbose")) {
738 WRITE_MESSAGEF(TL("Written template to '%'"), getString("save-template"));
739 }
740 return true;
741 }
742 }
743 if (isSet("save-schema")) {
744 if (getString("save-schema") == "-" || getString("save-schema") == "stdout") {
745 writeSchema(std::cout);
746 return true;
747 }
748 std::ofstream out(StringUtils::transcodeLocal(getString("save-schema"), true).c_str());
749 if (!out.good()) {
750 throw ProcessError(TLF("Could not save schema to '%'", getString("save-schema")));
751 } else {
752 writeSchema(out);
753 if (getBool("verbose")) {
754 WRITE_MESSAGEF(TL("Written schema to '%'"), getString("save-schema"));
755 }
756 return true;
757 }
758 }
759 return false;
760}
761
762
763void
766 // options
767 for (auto option : myAddresses) {
768 option.second->setDescription(TL(option.second->getDescription().c_str()));
769 }
770 // examples
771 for (auto example : myCallExamples) {
772 example.second = TL(example.second.c_str());
773 }
774 // other text
776 myAmLocalized = true;
777 }
778}
779
780
781const std::vector<std::string>&
783 return mySubTopics;
784}
785
786
787std::vector<std::string>
788OptionsCont::getSubTopicsEntries(const std::string& subtopic) const {
789 if (mySubTopicEntries.count(subtopic) > 0) {
790 return mySubTopicEntries.find(subtopic)->second;
791 } else {
792 return std::vector<std::string>();
793 }
794}
795
796
797std::string
798OptionsCont::getTypeName(const std::string name) {
799 return getSecure(name)->getTypeName();
800}
801
802
803const std::string&
805 return myFullName;
806}
807
808
809bool
811 return myAddresses.size() == 0;
812}
813
814
815std::vector<std::pair<std::string, Option*> >::const_iterator
817 return myAddresses.cbegin();
818}
819
820
821std::vector<std::pair<std::string, Option*> >::const_iterator
823 return myAddresses.cend();
824}
825
826
827void
828OptionsCont::printHelp(std::ostream& os) {
829 // print application description
830 splitLines(os, TL(myAppDescription.c_str()), 0, 0);
831 os << std::endl;
832
833 // check option sizes first
834 // we want to know how large the largest not-too-large-entry will be
835 int tooLarge = 40;
836 int maxSize = 0;
837 for (const auto& subTopic : mySubTopics) {
838 for (const auto& entry : mySubTopicEntries[subTopic]) {
839 Option* o = getSecure(entry);
840 // name, two leading spaces and "--"
841 int csize = (int)entry.length() + 2 + 4;
842 // abbreviation length ("-X, "->4chars) if any
843 const auto synonymes = getSynonymes(entry);
844 for (const auto& synonym : synonymes) {
845 if (synonym.length() == 1 && myDeprecatedSynonymes.count(synonym) == 0) {
846 csize += 4;
847 break;
848 }
849 }
850 // the type name
851 if (!o->isBool()) {
852 csize += 1 + (int)o->getTypeName().length();
853 }
854 // divider
855 csize += 2;
856 if (csize < tooLarge && maxSize < csize) {
857 maxSize = csize;
858 }
859 }
860 }
861
862 const std::string helpTopic = StringUtils::to_lower_case(getSecure("help")->getValueString());
863 if (helpTopic != "") {
864 bool foundTopic = false;
865 for (const auto& topic : mySubTopics) {
866 if (StringUtils::to_lower_case(topic).find(helpTopic) != std::string::npos) {
867 foundTopic = true;
868 printHelpOnTopic(topic, tooLarge, maxSize, os);
869 }
870 }
871 if (!foundTopic) {
872 // print topic list
873 os << TL("Help Topics:") << std::endl;
874 for (const std::string& t : mySubTopics) {
875 os << " " << t << std::endl;
876 }
877 }
878 return;
879 }
880 // print usage BNF
881 os << TL("Usage: ") << myAppName << TL(" [OPTION]*") << std::endl;
882 // print additional text if any
883 if (myAdditionalMessage.length() > 0) {
884 os << myAdditionalMessage << std::endl << std::endl;
885 }
886 // print the options
887 for (const auto& subTopic : mySubTopics) {
888 printHelpOnTopic(subTopic, tooLarge, maxSize, os);
889 }
890 os << std::endl;
891 // print usage examples, calc size first
892 if (myCallExamples.size() != 0) {
893 os << TL("Examples:") << std::endl;
894 for (const auto& callExample : myCallExamples) {
895 os << " " << myAppName << ' ' << callExample.first << std::endl;
896 os << " " << callExample.second << std::endl;
897 }
898 }
899 os << std::endl;
900 os << TLF("Report bugs at %.", "<https://github.com/eclipse-sumo/sumo/issues>") << std::endl;
901 os << TLF("Get in contact via %.", "<sumo@dlr.de>") << std::endl;
902}
903
904
905void
906OptionsCont::printHelpOnTopic(const std::string& topic, int tooLarge, int maxSize, std::ostream& os) {
907 os << TLF("% Options:", topic) << std::endl;
908 for (const auto& entry : mySubTopicEntries[topic]) {
909 // start length computation
910 int csize = (int)entry.length() + 2;
911 Option* o = getSecure(entry);
912 os << " ";
913 // write abbreviation if given
914 const auto synonymes = getSynonymes(entry);
915 for (const auto& synonym : synonymes) {
916 if (synonym.length() == 1 && myDeprecatedSynonymes.count(synonym) == 0) {
917 os << '-' << synonym << ", ";
918 csize += 4;
919 break;
920 }
921 }
922 // write leading '-'/"--"
923 os << "--";
924 csize += 2;
925 // write the name
926 os << entry;
927 // write the type if not a bool option
928 if (!o->isBool()) {
929 os << ' ' << o->getTypeName();
930 csize += 1 + (int)o->getTypeName().length();
931 }
932 csize += 2;
933 // write the description formatting it
934 os << " ";
935 for (int r = maxSize; r > csize; --r) {
936 os << ' ';
937 }
938 int offset = csize > tooLarge ? csize : maxSize;
939 splitLines(os, o->getDescription(), offset, maxSize);
940 }
941 os << std::endl;
942}
943
944
945void
946OptionsCont::writeConfiguration(std::ostream& os, const bool filled,
947 const bool complete, const bool addComments, const std::string& relativeTo,
948 const bool forceRelative, const bool inComment, const std::string& indent) const {
949 if (!inComment) {
950 writeXMLHeader(os, false);
951 }
952 const std::string& app = myAppName == "sumo-gui" ? "sumo" : myAppName;
953 os << indent << "<" << app << "Configuration xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\" "
954 << "xsi:noNamespaceSchemaLocation=\"http://sumo.dlr.de/xsd/" << app << "Configuration.xsd\">\n\n";
955 for (std::string subtopic : mySubTopics) {
956 if (subtopic == "Configuration" && !complete) {
957 continue;
958 }
959 const std::vector<std::string>& entries = mySubTopicEntries.find(subtopic)->second;
960 std::replace(subtopic.begin(), subtopic.end(), ' ', '_');
961 subtopic = StringUtils::to_lower_case(subtopic);
962 bool hadOne = false;
963 for (const std::string& name : entries) {
964 Option* o = getSecure(name);
965 bool write = complete || (filled && !o->isDefault());
966 if (!write) {
967 continue;
968 }
969 if (name == "registry-viewport" && !complete) {
970 continue;
971 }
972 if (!hadOne) {
973 os << indent << " <" << subtopic << ">\n";
974 }
975 // add the comment if wished
976 if (addComments) {
977 os << indent << " <!-- " << StringUtils::escapeXML(o->getDescription(), inComment) << " -->\n";
978 }
979 // write the option and the value (if given)
980 os << indent << " <" << name << " value=\"";
981 if (o->isSet() && (filled || o->isDefault())) {
982 if (o->isFileName() && relativeTo != "") {
984 for (auto& file : fileList) {
985 if (StringUtils::startsWith(file, "${")) {
986 // there is an environment variable up front, assume it points to an absolute path
987 // not even forcing relativity makes sense here
988 file = StringUtils::urlEncode(file, " ;%");
989 } else {
991 StringUtils::urlEncode(file, " ;%"),
992 StringUtils::urlEncode(relativeTo, " ;%"),
993 forceRelative || getBool("save-configuration.relative"));
994 }
995 }
996 os << StringUtils::escapeXML(joinToString(fileList, ','), inComment);
997 } else {
998 os << StringUtils::escapeXML(o->getValueString(), inComment);
999 }
1000 }
1001 if (complete) {
1002 const std::vector<std::string> synonymes = getSynonymes(name);
1003 if (!synonymes.empty()) {
1004 os << "\" synonymes=\"" << toString(synonymes);
1005 }
1006 std::string deprecated;
1007 for (const auto& synonym : synonymes) {
1008 if (myDeprecatedSynonymes.count(synonym) > 0) {
1009 deprecated += " " + synonym;
1010 }
1011 }
1012 if (deprecated != "") {
1013 os << "\" deprecated=\"" << deprecated.substr(1);
1014 }
1015 os << "\" type=\"" << o->getTypeName();
1016 if (!addComments) {
1017 os << "\" help=\"" << StringUtils::escapeXML(o->getDescription());
1018 }
1019 }
1020 os << "\"/>\n";
1021 // append an endline if a comment was printed
1022 if (addComments) {
1023 os << "\n";
1024 }
1025 hadOne = true;
1026 }
1027 if (hadOne) {
1028 os << indent << " </" << subtopic << ">\n\n";
1029 }
1030 }
1031 os << indent << "</" << app << "Configuration>" << std::endl; // flushing seems like a good idea here
1032}
1033
1034
1035void
1036OptionsCont::writeSchema(std::ostream& os) {
1037 const std::string& app = myAppName == "sumo-gui" ? "sumo" : myAppName;
1038 writeXMLHeader(os, false);
1039 os << "<xsd:schema elementFormDefault=\"qualified\" xmlns:xsd=\"http://www.w3.org/2001/XMLSchema\">\n";
1040 os << " <xsd:complexType name=\"" << app << "ConfigurationType\">\n";
1041 os << " <xsd:all>\n";
1042 for (std::string subtopic : mySubTopics) {
1043 if (subtopic == "Configuration") {
1044 continue;
1045 }
1046 std::replace(subtopic.begin(), subtopic.end(), ' ', '_');
1047 subtopic = StringUtils::to_lower_case(subtopic);
1048 os << " <xsd:element name=\"" << subtopic << "\" type=\"" << app << subtopic << "TopicType\" minOccurs=\"0\"/>\n";
1049 }
1050 os << " </xsd:all>\n";
1051 os << " </xsd:complexType>\n\n";
1052 for (std::string subtopic : mySubTopics) {
1053 if (subtopic == "Configuration") {
1054 continue;
1055 }
1056 const std::vector<std::string>& entries = mySubTopicEntries.find(subtopic)->second;
1057 std::replace(subtopic.begin(), subtopic.end(), ' ', '_');
1058 subtopic = StringUtils::to_lower_case(subtopic);
1059 os << " <xsd:complexType name=\"" << app << subtopic << "TopicType\">\n";
1060 os << " <xsd:all>\n";
1061 for (const auto& entry : entries) {
1062 Option* o = getSecure(entry);
1063 std::string type = o->getTypeName();
1064 type = StringUtils::to_lower_case(type);
1065 if (type == "int[]") {
1066 type = "intArray";
1067 }
1068 if (type == "str[]") {
1069 type = "strArray";
1070 }
1071 os << " <xsd:element name=\"" << entry << "\" type=\"" << type << "OptionType\" minOccurs=\"0\"/>\n";
1072 }
1073 os << " </xsd:all>\n";
1074 os << " </xsd:complexType>\n\n";
1075 }
1076 os << "</xsd:schema>\n";
1077}
1078
1079
1080void
1081OptionsCont::writeXMLHeader(std::ostream& os, const bool includeConfig) const {
1082 os << "<?xml version=\"1.0\"" << SUMOSAXAttributes::ENCODING << "?>\n\n";
1083 os << "<!-- ";
1084 if (!getBool("write-metadata")) {
1085 os << "generated on " << StringUtils::isoTimeString() << " by " << myFullName << "\n";
1086 }
1087 if (getBool("write-license")) {
1088 os << "This data file and the accompanying materials\n"
1089 "are made available under the terms of the Eclipse Public License v2.0\n"
1090 "which accompanies this distribution, and is available at\n"
1091 "http://www.eclipse.org/legal/epl-v20.html\n"
1092 "This file may also be made available under the following Secondary\n"
1093 "Licenses when the conditions for such availability set forth in the Eclipse\n"
1094 "Public License 2.0 are satisfied: GNU General Public License, version 2\n"
1095 "or later which is available at\n"
1096 "https://www.gnu.org/licenses/old-licenses/gpl-2.0-standalone.html\n"
1097 "SPDX-License-Identifier: EPL-2.0 OR GPL-2.0-or-later\n";
1098 }
1099 if (includeConfig && !getBool("write-metadata")) {
1100 writeConfiguration(os, true, false, false, "", false, true);
1101 }
1102 os << "-->\n\n";
1103}
1104
1105
1106bool
1107OptionsCont::isInStringVector(const std::string& optionName,
1108 const std::string& itemName) const {
1109 if (isSet(optionName)) {
1110 std::vector<std::string> values = getStringVector(optionName);
1111 return std::find(values.begin(), values.end(), itemName) != values.end();
1112 }
1113 return false;
1114}
1115
1116
1119 // build a clone to call writeConfiguration on
1120 // (with the possibility of changing a few settings and not affecting the original)
1121 OptionsCont* oc = new OptionsCont(*this);
1122 oc->resetWritable();
1123 for (auto& addr : oc->myAddresses) {
1124 addr.second = addr.second->clone();
1125 }
1126 return oc;
1127}
1128
1129
1130bool
1131OptionsCont::createDeviceByOption(const std::string& optionName,
1132 const std::string& rootElement,
1133 const std::string& schemaFile,
1134 const int maximumDepth) {
1135 if (!getOptions().isSet(optionName)) {
1136 return false;
1137 }
1139 dev.setExpectedAttributes(0, maximumDepth);
1140 if (rootElement != "") {
1141 dev.writeXMLHeader(rootElement, schemaFile);
1142 }
1143 return true;
1144}
1145
1146
1148OptionsCont::getDeviceByOption(const std::string& optionName) {
1149 std::string devName = getOptions().getString(optionName);
1150 if (!OutputDevice::deviceExists(devName)) {
1151 throw InvalidArgument("Output device '" + devName + "' for option '" + optionName + "' has not been created.");
1152 }
1153 return OutputDevice::getDevice(devName);
1154}
1155
1156
1157/****************************************************************************/
#define WRITE_WARNINGF(...)
Definition MsgHandler.h:299
#define WRITE_MESSAGEF(...)
Definition MsgHandler.h:301
#define WRITE_ERRORF(...)
Definition MsgHandler.h:308
#define WRITE_ERROR(msg)
Definition MsgHandler.h:307
#define WRITE_WARNING(msg)
Definition MsgHandler.h:298
#define TL(string)
Definition MsgHandler.h:316
#define TLF(string,...)
Definition MsgHandler.h:318
std::vector< std::string > StringVector
Definition of a vector of strings.
Definition Option.h:42
std::vector< int > IntVector
Definition of a vector of ints.
Definition Option.h:37
std::ostream & operator<<(std::ostream &os, const OptionsCont &oc)
bool gLocaleInitialized
Definition StdDefs.cpp:34
std::string joinToString(const std::vector< T > &v, const T_BETWEEN &between, std::streamsize accuracy=gPrecision)
Definition ToString.h:322
std::string toString(const T &t, std::streamsize accuracy=gPrecision)
Definition ToString.h:57
static std::string fixRelative(const std::string &filename, const std::string &basePath, const bool force, std::string curDir="")
Fixes the relative path for the given filename in relation to the basePath (usually a config file).
static std::string checkForRelativity(const std::string &filename, const std::string &basePath)
Returns the path from a configuration so that it is accessible from the current working directory.
static bool isReadable(std::string path)
Checks whether the given file is readable.
static void setupI18n(const std::string &locale="")
set up gettext stuff
A class representing a single program option.
Definition Option.h:74
bool isWriteable() const
Returns the information whether the option may be set a further time.
Definition Option.cpp:184
bool isSet() const
returns the information whether this options holds a valid value
Definition Option.cpp:53
virtual bool isDefault() const
Returns the information whether the option holds the default value.
Definition Option.cpp:112
void setRequired()
mark option as required
Definition Option.cpp:223
virtual std::string getString() const
Returns the stored string value.
Definition Option.cpp:71
virtual const IntVector & getIntVector() const
Returns the stored integer vector.
Definition Option.cpp:83
void resetWritable()
Resets the option to be writeable.
Definition Option.cpp:190
const std::string & getDescription() const
Returns the description of what this option does.
Definition Option.cpp:205
void setListSeparator(const std::string &listSep)
set list separator
Definition Option.cpp:255
virtual bool isFileName() const
Returns the information whether this option is a file name.
Definition Option.cpp:136
virtual const StringVector & getStringVector() const
Returns the stored string vector.
Definition Option.cpp:89
void setDescription(const std::string &desc)
Sets the description of what this option does.
Definition Option.cpp:211
virtual const std::string & getTypeName() const
Returns the mml-type name of this option.
Definition Option.cpp:272
virtual int getInt() const
Returns the stored integer value.
Definition Option.cpp:65
virtual double getFloat() const
Returns the stored double value.
Definition Option.cpp:59
virtual bool getBool() const
Returns the stored boolean value.
Definition Option.cpp:77
void setPositional()
mark option as positional
Definition Option.cpp:233
void resetDefault()
Resets the option to be on its default value.
Definition Option.cpp:196
const std::string & getSubTopic() const
Returns the subtopic to which this option belongs.
Definition Option.cpp:260
virtual bool set(const std::string &v, const std::string &orig, const bool append)=0
Stores the given value.
bool isEditable() const
check if this option is editable
Definition Option.cpp:239
virtual bool isBool() const
Returns the information whether the option is a bool option.
Definition Option.cpp:130
void setEditable(const bool value)
set editable
Definition Option.cpp:244
const std::string & getValueString() const
Returns the string-representation of the value.
Definition Option.cpp:106
void setSubtopic(const std::string &subtopic)
Sets the subtopic to which this option belongs.
Definition Option.cpp:266
A storage for options typed value containers)
Definition OptionsCont.h:92
void setAdditionalHelpMessage(const std::string &add)
Sets an additional message to be printed at the begin of the help screen.
~OptionsCont()
Destructor.
void addDescription(const std::string &name, const std::string &subtopic, const std::string &description)
Adds a description for an option.
void writeConfiguration(std::ostream &os, const bool filled, const bool complete, const bool addComments, const std::string &relativeTo="", const bool forceRelative=false, const bool inComment=false, const std::string &indent="") const
Writes the configuration.
void resetDefault()
Resets all options to default.
void setFurtherAttributes(const std::string &name, const std::string &subtopic, bool required, bool positional, const std::string &listSep)
mark option as required
bool isSet(const std::string &name, bool failOnNonExistant=true) const
Returns the information whether the named option is set.
std::vector< std::pair< std::string, std::string > > myCallExamples
list of call examples
bool isWriteable(const std::string &name)
Returns the information whether the named option may be set.
std::map< std::string, std::vector< std::string > > mySubTopicEntries
A map from subtopic to option.
void writeXMLHeader(std::ostream &os, const bool includeConfig=true) const
Writes a standard XML header, including the configuration.
double getFloat(const std::string &name) const
Returns the double-value of the named option (only for Option_Float)
int getInt(const std::string &name) const
Returns the int-value of the named option (only for Option_Integer)
static OutputDevice & getDeviceByOption(const std::string &name)
Returns the device described by the option.
void splitLines(std::ostream &os, std::string what, int offset, int nextOffset)
Writes the given string 'formatted'.
void setApplicationName(const std::string &appName, const std::string &fullName)
Sets the application name.
OptionsCont * clone() const
make a copy of this OptionsCont instance
void printHelpOnTopic(const std::string &topic, int tooLarge, int maxSize, std::ostream &os)
Prints help on the given topic.
void removeSubTopic(const std::string &topic)
Removes the given sub-topic.
const std::string & getSubTopic(const std::string &name) const
Returns the option category.
std::map< std::string, Option * > myValues
option maps sorted by name (for addresses AND their synonyms)
bool isEmpty() const
check if options container is empty
std::string myAdditionalMessage
std::vector< std::string > myCopyrightNotices
const std::vector< std::string > & getSubTopics() const
return the list of subtopics
void setOptionEditable(const std::string &name, const bool value)
set option editable
bool myAmLocalized
Whether the descriptino has already been translated to the locale language.
std::vector< std::pair< std::string, Option * > > myAddresses
option-addresses
const IntVector & getIntVector(const std::string &name) const
Returns the list of integer-value of the named option (only for Option_IntVector)
std::vector< std::string > getSynonymes(const std::string &name) const
Returns the synonymes of an option name.
void reportDoubleSetting(const std::string &arg) const
Reports an error that the option has already been set.
std::vector< std::string > mySubTopics
lists of option subtopics and copyright notices
std::string getString(const std::string &name) const
Returns the string-value of the named option (only for Option_String)
static OptionsCont EMPTY_OPTIONS
empty option container
Definition OptionsCont.h:99
void localizeDescriptions()
void addSynonyme(const std::string &name1, const std::string &name2, bool isDeprecated=false)
Adds a synonyme for an options name (any order)
bool isDefault(const std::string &name) const
Returns the information whether the named option has still the default value.
bool setDefault(const std::string &name, const std::string &value)
Sets the given value for the named option as new default value.
void removeOption(const std::string &name)
Removes an option from its subtopic.
void doRegister(const std::string &name, Option *o)
Adds an option under the given name.
bool exists(const std::string &name) const
Returns the information whether the named option is known.
static bool createDeviceByOption(const std::string &optionName, const std::string &rootElement="", const std::string &schemaFile="", const int maximumDepth=2)
Creates the device using the output definition stored in the named option.
const std::string & getFullName() const
get options full name
bool isBool(const std::string &name) const
Returns the information whether the option is a boolean option.
void addCopyrightNotice(const std::string &copyrightLine)
Adds a copyright notice to the help output.
std::string getTypeName(const std::string name)
return the type name for the given option
void writeSchema(std::ostream &os)
Writes the xml schema for the configuration.
void clear()
Removes all information from the container.
void setApplicationDescription(const std::string &appDesc)
Sets the application description.
std::vector< std::pair< std::string, Option * > >::const_iterator begin() const
get begin addresses iterator
bool set(const std::string &name, const std::string &value, const bool append=false)
Sets the given value for the named option.
bool isEditable(const std::string &name)
Returns the information whether the named option is editable.
void clearCopyrightNotices()
Removes all copyright information.
std::string convertChar(char abbr) const
Converts an abbreviation into a name.
void addOptionSubTopic(const std::string &topic)
Adds an option subtopic.
bool getBool(const std::string &name) const
Returns the boolean-value of the named option (only for Option_Bool)
const StringVector & getStringVector(const std::string &name) const
Returns the list of string-value of the named option (only for Option_StringVector)
OptionsCont()
Constructor.
void printHelp(std::ostream &os)
Prints the help.
std::vector< std::pair< std::string, Option * > >::const_iterator end() const
get begin addresses iterator
std::string getValueString(const std::string &name) const
Returns the string-value of the named option (all options)
std::string myAppDescription
const std::string & getDescription(const std::string &name) const
Returns the option description.
bool setByRootElement(const std::string &name, const std::string &value)
Sets the given value for the option which can handle the given XML root.
std::map< std::string, bool > myDeprecatedSynonymes
A map from deprecated options to a bool indicating whether we warned about deprecation.
static OptionsCont myOptions
The static options container used.
bool checkDependingSuboptions(const std::string &name, const std::string &prefix) const
Checks whether an option is set, which has options with a prefix depending on it.
std::map< std::string, std::string > myXMLDefaults
A map from XML root element to option.
std::string myAppName
some information on the application
void resetWritable()
Resets all options to be writeable.
void addXMLDefault(const std::string &name, const std::string &xmlRoot="")
Adds an XML root element to handle by default. The special root "" denotes the default handler.
static OptionsCont & getOptions()
Retrieves the options.
std::string myFullName
std::vector< std::string > getSubTopicsEntries(const std::string &subtopic) const
return the list of entries for the given subtopic
Option * getSecure(const std::string &name) const
Returns the named option.
void relocateFiles(const std::string &configuration) const
Modifies file name options according to the configuration path.
bool isInStringVector(const std::string &optionName, const std::string &itemName) const
Returns the named option is a list of string values containing the specified item.
bool processMetaOptions(bool missingOptions)
Checks for help and configuration output, returns whether we should exit.
bool isUsableFileList(const std::string &name) const
Checks whether the named option is usable as a file list (with at least a single file)
void addCallExample(const std::string &example, const std::string &desc)
Add a call example.
static const std::chrono::time_point< std::chrono::system_clock > & getLoadTime()
Return the time stamp of the last init.
Definition OptionsIO.h:101
Static storage of an output device and its base (abstract) implementation.
static bool deviceExists(const std::string &name)
Returns whether a device with the given name has already been created.
void setExpectedAttributes(const SumoXMLAttrMask &expected, const int depth)
static OutputDevice & getDevice(const std::string &name, bool usePrefix=true)
Returns the described OutputDevice.
bool writeXMLHeader(const std::string &rootElement, const std::string &schemaFile, std::map< SumoXMLAttr, std::string > attrs=std::map< SumoXMLAttr, std::string >(), bool includeConfig=true)
Writes an XML header with optional configuration.
static const std::string ENCODING
The encoding of parsed strings.
std::vector< std::string > getVector()
return vector of strings
static std::string urlEncode(const std::string &url, const std::string encodeWhich="")
encode url (stem from http://bogomip.net/blog/cpp-url-encoding-and-decoding/)
static std::string transcodeLocal(const std::string &str, bool toLocal)
convert a string between UTF-8 and the local codepage (identity on non-Windows systems)
static std::string urlDecode(const std::string &encoded)
decode url (stem from http://bogomip.net/blog/cpp-url-encoding-and-decoding/)
static std::string to_lower_case(const std::string &str)
Transfers the content to lower case.
static std::string escapeXML(const std::string &orig, const bool maskDoubleHyphen=false)
Replaces the standard escapes by their XML entities.
static bool startsWith(const std::string &str, const std::string prefix)
Checks whether a given string starts with the prefix.
static std::string substituteEnvironment(const std::string &str, const std::chrono::time_point< std::chrono::system_clock > *const timeRef=nullptr)
Replaces an environment variable with its value (similar to bash); syntax for a variable is ${NAME}.
static std::string isoTimeString(const std::chrono::time_point< std::chrono::system_clock > *const timeRef=nullptr)
Returns an ISO8601 formatted time string with microsecond precision.