diff --git a/Modules/DiffusionImaging/MiniApps/ctkCommandLineParser.cpp b/Modules/DiffusionImaging/MiniApps/ctkCommandLineParser.cpp index c752c4366a..721e07c08e 100755 --- a/Modules/DiffusionImaging/MiniApps/ctkCommandLineParser.cpp +++ b/Modules/DiffusionImaging/MiniApps/ctkCommandLineParser.cpp @@ -1,845 +1,845 @@ /*=================================================================== The Medical Imaging Interaction Toolkit (MITK) Copyright (c) German Cancer Research Center, Division of Medical and Biological Informatics. All rights reserved. This software is distributed WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See LICENSE.txt or http://www.mitk.org for details. ===================================================================*/ /*========================================================================= Library: CTK Copyright (c) Kitware Inc. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0.txt Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. =========================================================================*/ // STL includes #include // CTK includes #include "ctkCommandLineParser.h" using namespace std; namespace { // -------------------------------------------------------------------------- class CommandLineParserArgumentDescription { public: CommandLineParserArgumentDescription( const string& longArg, const string& longArgPrefix, const string& shortArg, const string& shortArgPrefix, ctkCommandLineParser::Type type, const string& argHelp, const string& argLabel, const us::Any& defaultValue, bool ignoreRest, bool deprecated, bool optional) : LongArg(longArg), LongArgPrefix(longArgPrefix), ShortArg(shortArg), ShortArgPrefix(shortArgPrefix), ArgHelp(argHelp), ArgLabel(argLabel), IgnoreRest(ignoreRest), NumberOfParametersToProcess(0), Deprecated(deprecated), DefaultValue(defaultValue), Value(type), ValueType(type), Optional(optional) { Value = defaultValue; switch (type) { case ctkCommandLineParser::String: { NumberOfParametersToProcess = 1; } break; case ctkCommandLineParser::Bool: { NumberOfParametersToProcess = 0; } break; case ctkCommandLineParser::StringList: { NumberOfParametersToProcess = -1; } break; case ctkCommandLineParser::Int: { NumberOfParametersToProcess = 1; } break; case ctkCommandLineParser::Float: { NumberOfParametersToProcess = 1; } break; case ctkCommandLineParser::Directory: { NumberOfParametersToProcess = 1; } break; case ctkCommandLineParser::File: { NumberOfParametersToProcess = 1; } break; default: MITK_INFO << "Type not supported: " << static_cast(type); } } ~CommandLineParserArgumentDescription(){} bool addParameter(const string& value); string helpText(); string LongArg; string LongArgPrefix; string ShortArg; string ShortArgPrefix; string ArgHelp; string ArgLabel; bool IgnoreRest; int NumberOfParametersToProcess; bool Deprecated; bool Optional; us::Any DefaultValue; us::Any Value; ctkCommandLineParser::Type ValueType; }; // -------------------------------------------------------------------------- bool CommandLineParserArgumentDescription::addParameter(const string &value) { switch (ValueType) { case ctkCommandLineParser::String: { Value = value; } break; case ctkCommandLineParser::Bool: { if (value.compare("true")==0) Value = true; else Value = false; } break; case ctkCommandLineParser::StringList: { try { ctkCommandLineParser::StringContainerType list = us::any_cast(Value); list.push_back(value); Value = list; } catch(...) { ctkCommandLineParser::StringContainerType list; list.push_back(value); Value = list; } } break; case ctkCommandLineParser::Int: { stringstream ss(value); int i; ss >> i; Value = i; } break; case ctkCommandLineParser::Float: { stringstream ss(value); float f; ss >> f; Value = f; } break; case ctkCommandLineParser::Directory: { Value = value; } break; case ctkCommandLineParser::File: { Value = value; } break; default: return false; } return true; } // -------------------------------------------------------------------------- string CommandLineParserArgumentDescription::helpText() { string text; string shortAndLongArg; if (!this->ShortArg.empty()) { shortAndLongArg = " "; shortAndLongArg += this->ShortArgPrefix; shortAndLongArg += this->ShortArg; } if (!this->LongArg.empty()) { if (this->ShortArg.empty()) shortAndLongArg.append(" "); else shortAndLongArg.append(", "); shortAndLongArg += this->LongArgPrefix; shortAndLongArg += this->LongArg; } text = text + shortAndLongArg + ", " + this->ArgHelp; if (this->Optional) text += " (optional)"; if (!this->DefaultValue.Empty()) { text = text + ", (default: " + this->DefaultValue.ToString() + ")"; } text += "\n"; return text; } } // -------------------------------------------------------------------------- // ctkCommandLineParser::ctkInternal class // -------------------------------------------------------------------------- class ctkCommandLineParser::ctkInternal { public: ctkInternal() : Debug(false), FieldWidth(0), StrictMode(false) {} ~ctkInternal() { } CommandLineParserArgumentDescription* argumentDescription(const string& argument); vector ArgumentDescriptionList; map ArgNameToArgumentDescriptionMap; map > GroupToArgumentDescriptionListMap; StringContainerType UnparsedArguments; StringContainerType ProcessedArguments; string ErrorString; bool Debug; int FieldWidth; string LongPrefix; string ShortPrefix; string CurrentGroup; string DisableQSettingsLongArg; string DisableQSettingsShortArg; bool StrictMode; }; // -------------------------------------------------------------------------- // ctkCommandLineParser::ctkInternal methods // -------------------------------------------------------------------------- CommandLineParserArgumentDescription* ctkCommandLineParser::ctkInternal::argumentDescription(const string& argument) { string unprefixedArg = argument; if (!LongPrefix.empty() && argument.compare(0, LongPrefix.size(), LongPrefix)==0) { // Case when (ShortPrefix + UnPrefixedArgument) matches LongPrefix if (argument == LongPrefix && !ShortPrefix.empty() && argument.compare(0, ShortPrefix.size(), ShortPrefix)==0) { unprefixedArg = argument.substr(ShortPrefix.size(),argument.size()); } else { unprefixedArg = argument.substr(LongPrefix.size(),argument.size()); } } else if (!ShortPrefix.empty() && argument.compare(0, ShortPrefix.size(), ShortPrefix)==0) { unprefixedArg = argument.substr(ShortPrefix.size(),argument.size()); } else if (!LongPrefix.empty() && !ShortPrefix.empty()) { return 0; } if (ArgNameToArgumentDescriptionMap.count(unprefixedArg)) { return this->ArgNameToArgumentDescriptionMap[unprefixedArg]; } return 0; } // -------------------------------------------------------------------------- // ctkCommandLineParser methods // -------------------------------------------------------------------------- ctkCommandLineParser::ctkCommandLineParser() { this->Internal = new ctkInternal(); this->Category = string(); this->Title = string(); this->Contributor = string(); this->Description = string(); } // -------------------------------------------------------------------------- ctkCommandLineParser::~ctkCommandLineParser() { delete this->Internal; } // -------------------------------------------------------------------------- map ctkCommandLineParser::parseArguments(const StringContainerType& arguments, bool* ok) { // Reset this->Internal->UnparsedArguments.clear(); this->Internal->ProcessedArguments.clear(); this->Internal->ErrorString.clear(); // foreach (CommandLineParserArgumentDescription* desc, this->Internal->ArgumentDescriptionList) for (unsigned int i=0; iArgumentDescriptionList.size(); i++) { CommandLineParserArgumentDescription* desc = Internal->ArgumentDescriptionList.at(i); desc->Value = us::Any(desc->ValueType); if (!desc->DefaultValue.Empty()) { desc->Value = desc->DefaultValue; } } bool error = false; bool ignoreRest = false; CommandLineParserArgumentDescription * currentArgDesc = 0; vector parsedArgDescriptions; for(unsigned int i = 1; i < arguments.size(); ++i) { string argument = arguments.at(i); if (this->Internal->Debug) { MITK_DEBUG << "Processing" << argument; } if (!argument.compare("--xml") || !argument.compare("-xml") || !argument.compare("--XML") || !argument.compare("-XML")) { this->GetXML("lala", "lalalalalalalalalalalalalalalla"); return map(); } // should argument be ignored ? if (ignoreRest) { if (this->Internal->Debug) { MITK_DEBUG << " Skipping: IgnoreRest flag was been set"; } this->Internal->UnparsedArguments.push_back(argument); continue; } // Skip if the argument does not start with the defined prefix if (!(argument.compare(0, Internal->LongPrefix.size(), Internal->LongPrefix)==0 || argument.compare(0, Internal->ShortPrefix.size(), Internal->ShortPrefix)==0)) { if (this->Internal->StrictMode) { this->Internal->ErrorString = "Unknown argument "; this->Internal->ErrorString += argument; error = true; break; } if (this->Internal->Debug) { MITK_DEBUG << " Skipping: It does not start with the defined prefix"; } this->Internal->UnparsedArguments.push_back(argument); continue; } // Skip if argument has already been parsed ... bool alreadyProcessed = false; for (unsigned int i=0; iProcessedArguments.size(); i++) if (argument.compare(Internal->ProcessedArguments.at(i))==0) { alreadyProcessed = true; break; } if (alreadyProcessed) { if (this->Internal->StrictMode) { this->Internal->ErrorString = "Argument "; this->Internal->ErrorString += argument; this->Internal->ErrorString += " already processed !"; error = true; break; } if (this->Internal->Debug) { MITK_DEBUG << " Skipping: Already processed !"; } continue; } // Retrieve corresponding argument description currentArgDesc = this->Internal->argumentDescription(argument); // Is there a corresponding argument description ? if (currentArgDesc) { // If the argument is deprecated, print the help text but continue processing if (currentArgDesc->Deprecated) { MITK_WARN << "Deprecated argument " << argument << ": " << currentArgDesc->ArgHelp; } else { parsedArgDescriptions.push_back(currentArgDesc); } this->Internal->ProcessedArguments.push_back(currentArgDesc->ShortArg); this->Internal->ProcessedArguments.push_back(currentArgDesc->LongArg); int numberOfParametersToProcess = currentArgDesc->NumberOfParametersToProcess; ignoreRest = currentArgDesc->IgnoreRest; if (this->Internal->Debug && ignoreRest) { MITK_DEBUG << " IgnoreRest flag is True"; } // Is the number of parameters associated with the argument being processed known ? if (numberOfParametersToProcess == 0) { currentArgDesc->addParameter("true"); } else if (numberOfParametersToProcess > 0) { string missingParameterError = "Argument %1 has %2 value(s) associated whereas exacly %3 are expected."; for(int j=1; j <= numberOfParametersToProcess; ++j) { if (i + j >= arguments.size()) { // this->Internal->ErrorString = // missingParameterError.arg(argument).arg(j-1).arg(numberOfParametersToProcess); // if (this->Internal->Debug) { MITK_DEBUG << this->Internal->ErrorString; } if (ok) { *ok = false; } return map(); } string parameter = arguments.at(i + j); if (this->Internal->Debug) { MITK_DEBUG << " Processing parameter" << j << ", value:" << parameter; } if (this->argumentAdded(parameter)) { // this->Internal->ErrorString = // missingParameterError.arg(argument).arg(j-1).arg(numberOfParametersToProcess); // if (this->Internal->Debug) { MITK_DEBUG << this->Internal->ErrorString; } if (ok) { *ok = false; } return map(); } if (!currentArgDesc->addParameter(parameter)) { // this->Internal->ErrorString = string( // "Value(s) associated with argument %1 are incorrect. %2"). // arg(argument).arg(currentArgDesc->ExactMatchFailedMessage); // if (this->Internal->Debug) { MITK_DEBUG << this->Internal->ErrorString; } if (ok) { *ok = false; } return map(); } } // Update main loop increment i = i + numberOfParametersToProcess; } else if (numberOfParametersToProcess == -1) { if (this->Internal->Debug) { MITK_DEBUG << " Proccessing StringList ..."; } int j = 1; while(j + i < arguments.size()) { if (this->argumentAdded(arguments.at(j + i))) { if (this->Internal->Debug) { MITK_DEBUG << " No more parameter for" << argument; } break; } string parameter = arguments.at(j + i); if (parameter.compare(0, Internal->LongPrefix.size(), Internal->LongPrefix)==0 || parameter.compare(0, Internal->ShortPrefix.size(), Internal->ShortPrefix)==0) { j--; break; } if (this->Internal->Debug) { MITK_DEBUG << " Processing parameter" << j << ", value:" << parameter; } if (!currentArgDesc->addParameter(parameter)) { // this->Internal->ErrorString = string( // "Value(s) associated with argument %1 are incorrect. %2"). // arg(argument).arg(currentArgDesc->ExactMatchFailedMessage); // if (this->Internal->Debug) { MITK_DEBUG << this->Internal->ErrorString; } if (ok) { *ok = false; } return map(); } j++; } // Update main loop increment i = i + j; } } else { if (this->Internal->StrictMode) { this->Internal->ErrorString = "Unknown argument "; this->Internal->ErrorString += argument; error = true; break; } if (this->Internal->Debug) { MITK_DEBUG << " Skipping: Unknown argument"; } this->Internal->UnparsedArguments.push_back(argument); } } if (ok) { *ok = !error; } map parsedArguments; int obligatoryArgs = 0; vector::iterator it; for(it = Internal->ArgumentDescriptionList.begin(); it != Internal->ArgumentDescriptionList.end();++it) { CommandLineParserArgumentDescription* desc = *it; if(!desc->Optional) obligatoryArgs++; } int parsedObligatoryArgs = 0; for(it = parsedArgDescriptions.begin(); it != parsedArgDescriptions.end();++it) { CommandLineParserArgumentDescription* desc = *it; string key; if (!desc->LongArg.empty()) { key = desc->LongArg; } else { key = desc->ShortArg; } if(!desc->Optional) parsedObligatoryArgs++; std::pair elem; elem.first = key; elem.second = desc->Value; parsedArguments.insert(elem); } if (obligatoryArgs>parsedObligatoryArgs) { parsedArguments.clear(); cout << helpText(); } return parsedArguments; } // ------------------------------------------------------------------------- map ctkCommandLineParser::parseArguments(int argc, char** argv, bool* ok) { StringContainerType arguments; // Create a StringContainerType of arguments for(int i = 0; i < argc; ++i) arguments.push_back(argv[i]); return this->parseArguments(arguments, ok); } // ------------------------------------------------------------------------- string ctkCommandLineParser::errorString() const { return this->Internal->ErrorString; } // ------------------------------------------------------------------------- const ctkCommandLineParser::StringContainerType& ctkCommandLineParser::unparsedArguments() const { return this->Internal->UnparsedArguments; } // -------------------------------------------------------------------------- void ctkCommandLineParser::addArgument(const string& longarg, const string& shortarg, - Type type, const string& argHelp, + Type type, const string& argLabel, const string& argHelp, const us::Any& defaultValue, bool optional, bool ignoreRest, - bool deprecated, const string& argLabel) + bool deprecated) { if (longarg.empty() && shortarg.empty()) { return; } /* Make sure it's not already added */ bool added = this->Internal->ArgNameToArgumentDescriptionMap.count(longarg); if (added) { return; } added = this->Internal->ArgNameToArgumentDescriptionMap.count(shortarg); if (added) { return; } CommandLineParserArgumentDescription* argDesc = new CommandLineParserArgumentDescription(longarg, this->Internal->LongPrefix, shortarg, this->Internal->ShortPrefix, type, argHelp, argLabel, defaultValue, ignoreRest, deprecated, optional); int argWidth = 0; if (!longarg.empty()) { this->Internal->ArgNameToArgumentDescriptionMap[longarg] = argDesc; argWidth += longarg.size() + this->Internal->LongPrefix.size(); } if (!shortarg.empty()) { this->Internal->ArgNameToArgumentDescriptionMap[shortarg] = argDesc; argWidth += shortarg.size() + this->Internal->ShortPrefix.size() + 2; } argWidth += 5; // Set the field width for the arguments if (argWidth > this->Internal->FieldWidth) { this->Internal->FieldWidth = argWidth; } this->Internal->ArgumentDescriptionList.push_back(argDesc); this->Internal->GroupToArgumentDescriptionListMap[this->Internal->CurrentGroup].push_back(argDesc); } // -------------------------------------------------------------------------- void ctkCommandLineParser::addDeprecatedArgument( - const string& longarg, const string& shortarg, const string& argHelp, const string& argLabel) + const string& longarg, const string& shortarg, const string& argLabel, const string& argHelp) { - addArgument(longarg, shortarg, StringList, argHelp, us::Any(), false, true, false, argLabel); + addArgument(longarg, shortarg, StringList, argLabel, argHelp, us::Any(), false, true, false); } // -------------------------------------------------------------------------- int ctkCommandLineParser::fieldWidth() const { return this->Internal->FieldWidth; } // -------------------------------------------------------------------------- void ctkCommandLineParser::beginGroup(const string& description) { this->Internal->CurrentGroup = description; } // -------------------------------------------------------------------------- void ctkCommandLineParser::endGroup() { this->Internal->CurrentGroup.clear(); } // -------------------------------------------------------------------------- string ctkCommandLineParser::helpText() const { string text; vector deprecatedArgs; // Loop over grouped argument descriptions map >::iterator it; for(it = Internal->GroupToArgumentDescriptionListMap.begin(); it != Internal->GroupToArgumentDescriptionListMap.end();++it) { if (!(*it).first.empty()) { text = text + "\n" + (*it).first + "\n"; } vector::iterator it2; for(it2 = (*it).second.begin(); it2 != (*it).second.end(); ++it2) { CommandLineParserArgumentDescription* argDesc = *it2; if (argDesc->Deprecated) { deprecatedArgs.push_back(argDesc); } else { text += argDesc->helpText(); } } } if (!deprecatedArgs.empty()) { text += "\nDeprecated arguments:\n"; vector::iterator it2; for(it2 = deprecatedArgs.begin(); it2 != deprecatedArgs.end(); ++it2) { CommandLineParserArgumentDescription* argDesc = *it2; text += argDesc->helpText(); } } return text; } // -------------------------------------------------------------------------- bool ctkCommandLineParser::argumentAdded(const string& argument) const { return this->Internal->ArgNameToArgumentDescriptionMap.count(argument); } // -------------------------------------------------------------------------- bool ctkCommandLineParser::argumentParsed(const string& argument) const { for (unsigned int i=0; iProcessedArguments.size(); i++) if (argument.compare(Internal->ProcessedArguments.at(i))==0) return true; return false; } // -------------------------------------------------------------------------- void ctkCommandLineParser::setArgumentPrefix(const string& longPrefix, const string& shortPrefix) { this->Internal->LongPrefix = longPrefix; this->Internal->ShortPrefix = shortPrefix; } // -------------------------------------------------------------------------- void ctkCommandLineParser::setStrictModeEnabled(bool strictMode) { this->Internal->StrictMode = strictMode; } void ctkCommandLineParser::GetXML(std::string title, std::string description) { std::stringstream xml; xml << "" << endl; xml << "" << Category << "" << endl; xml << "" << Title <<"" << endl; xml << "" << Description << "" << endl; xml << "" << Contributor << "" << endl; xml << "" << endl; //TODO: nicht hard coded!! xml << "" << endl; xml << "TestTest" << endl; std::vector::iterator it; for (it = this->Internal->ArgumentDescriptionList.begin(); it != this->Internal->ArgumentDescriptionList.end(); it++) { std::string type; switch ((*it)->ValueType) { case ctkCommandLineParser::String: type = "string"; break; case ctkCommandLineParser::Bool: type = "boolean"; break; case ctkCommandLineParser::StringList: type = "string-vector"; break; case ctkCommandLineParser::Int: type = "integer"; break; case ctkCommandLineParser::Float: type = "float"; break; case ctkCommandLineParser::Directory: type = "directory"; break; case ctkCommandLineParser::File: type = "file"; break; } xml << "<" << type << ">" << endl; xml << "" << endl; xml << "" << (*it)->ArgHelp << "" << endl; xml << "" << (*it)->LongArg << "" << endl; xml << "" << (*it)->ShortArg << "" << endl; xml << "" << endl; } xml << "" << endl; xml << "" << endl; cout << xml.str(); } void ctkCommandLineParser::setTitle(string title) { Title = title; } void ctkCommandLineParser::setContributor(string contributor) { Contributor = contributor; } void ctkCommandLineParser::setCategory(string category) { Category = category; } void ctkCommandLineParser::setDescription(string description) { Description = description; } diff --git a/Modules/DiffusionImaging/MiniApps/ctkCommandLineParser.h b/Modules/DiffusionImaging/MiniApps/ctkCommandLineParser.h index 5de8019b98..44370c7272 100755 --- a/Modules/DiffusionImaging/MiniApps/ctkCommandLineParser.h +++ b/Modules/DiffusionImaging/MiniApps/ctkCommandLineParser.h @@ -1,436 +1,436 @@ /*=================================================================== The Medical Imaging Interaction Toolkit (MITK) Copyright (c) German Cancer Research Center, Division of Medical and Biological Informatics. All rights reserved. This software is distributed WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See LICENSE.txt or http://www.mitk.org for details. ===================================================================*/ /*========================================================================= Library: CTK Copyright (c) Kitware Inc. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0.txt Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. =========================================================================*/ #ifndef __ctkCommandLineParser_h #define __ctkCommandLineParser_h #include #include /** * \ingroup Core * * The CTK command line parser. * * Use this class to add information about the command line arguments * your program understands and to easily parse them from a given list * of strings. * * This parser provides the following features: * *
    *
  • Add arguments by supplying a long name and/or a short name. * Arguments are validated using a regular expression. They can have * a default value and a help string.
  • *
  • Deprecated arguments.
  • *
  • Custom regular expressions for argument validation.
  • *
  • Set different argument name prefixes for native platform look and feel.
  • *
  • QSettings support. Default values for arguments can be read from * a QSettings object.
  • *
  • Create a help text for the command line arguments with support for * grouping arguments.
  • *
* * Here is an example how to use this class inside a main function: * * \code * #include * #include * #include * * int main(int argc, char** argv) * { * QCoreApplication app(argc, argv); * // This is used by QSettings * QCoreApplication::setOrganizationName("MyOrg"); * QCoreApplication::setApplicationName("MyApp"); * * ctkCommandLineParser parser; * // Use Unix-style argument names * parser.setArgumentPrefix("--", "-"); * // Enable QSettings support * parser.enableSettings("disable-settings"); * * // Add command line argument names * parser.addArgument("disable-settings", "", us::Any::Bool, "Do not use QSettings"); * parser.addArgument("help", "h", us::Any::Bool, "Show this help text"); * parser.addArgument("search-paths", "s", us::Any::StringList, "A list of paths to search"); * * // Parse the command line arguments * bool ok = false; * map parsedArgs = parser.parseArguments(QCoreApplication::arguments(), &ok); * if (!ok) * { * QTextStream(stderr, QIODevice::WriteOnly) << "Error parsing arguments: " * << parser.errorString() << "\n"; * return EXIT_FAILURE; * } * * // Show a help message * if (parsedArgs.contains("help") || parsedArgs.contains("h")) * { * QTextStream(stdout, QIODevice::WriteOnly) << parser.helpText(); * return EXIT_SUCCESS; * } * * // Do something * * return EXIT_SUCCESS; * } * \endcode */ using namespace std; class ctkCommandLineParser { public: enum Type { String = 0, Bool = 1, StringList = 2, Int = 3, Float = 4, Directory = 5, File = 6 }; typedef std::vector< std::string > StringContainerType; /** * Constructs a parser instance. * * If QSettings support is enabled by a call to enableSettings() * a default constructed QSettings instance will be used when parsing * the command line arguments. Make sure to call QCoreApplication::setOrganizationName() * and QCoreApplication::setApplicationName() before using default * constructed QSettings objects. * * @param newParent The QObject parent. */ ctkCommandLineParser(); ~ctkCommandLineParser(); /** * Parse a given list of command line arguments. * * This method parses a list of string elements considering the known arguments * added by calls to addArgument(). If any one of the argument * values does not match the corresponding regular expression, * ok is set to false and an empty map object is returned. * * The keys in the returned map object correspond to the long argument string, * if it is not empty. Otherwise, the short argument string is used as key. The * us::Any values can safely be converted to the type specified in the * addArgument() method call. * * @param arguments A StringContainerType containing command line arguments. Usually * given by QCoreApplication::arguments(). * @param ok A pointer to a boolean variable. Will be set to true * if all regular expressions matched, false otherwise. * @return A map object mapping the long argument (if empty, the short one) * to a us::Any containing the value. */ map parseArguments(const StringContainerType &arguments, bool* ok = 0); /** * Convenient method allowing to parse a given list of command line arguments. * @see parseArguments(const StringContainerType &, bool*) */ map parseArguments(int argc, char** argv, bool* ok = 0); /** * Returns a detailed error description if a call to parseArguments() * failed. * * @return The error description, empty if no error occured. * @see parseArguments(const StringContainerType&, bool*) */ string errorString() const; /** * This method returns all unparsed arguments, i.e. all arguments * for which no long or short name has been registered via a call * to addArgument(). * * @see addArgument() * * @return A list containing unparsed arguments. */ const StringContainerType& unparsedArguments() const; /** * Checks if the given argument has been added via a call * to addArgument(). * * @see addArgument() * * @param argument The argument to be checked. * @return true if the argument was added, false * otherwise. */ bool argumentAdded(const string& argument) const; /** * Checks if the given argument has been parsed successfully by a previous * call to parseArguments(). * * @param argument The argument to be checked. * @return true if the argument was parsed, false * otherwise. */ bool argumentParsed(const string& argument) const; /** * Adds a command line argument. An argument can have a long name * (like --long-argument-name), a short name (like -l), or both. The type * of the argument can be specified by using the type parameter. * The following types are supported: * * * * * * * * *
Type# of parametersDefault regular exprExample
us::Any::String1.*--test-string StringParameter
us::Any::Bool0does not apply--enable-something
us::Any::StringList-1.*--test-list string1 string2
us::Any::Int1-?[0-9]+--test-int -5
* * The regular expressions are used to validate the parameters of command line * arguments. You can restrict the valid set of parameters by calling * setExactMatchRegularExpression() for your argument. * * Optionally, a help string and a default value can be provided for the argument. If * the us::Any type of the default value does not match type, an * exception is thrown. Arguments with default values are always returned by * parseArguments(). * * You can also declare an argument deprecated, by setting deprecated * to true. Alternatively you can add a deprecated argument by calling * addDeprecatedArgument(). * * If the long or short argument has already been added, or if both are empty strings, * the method call has no effect. * * @param longarg The long argument name. * @param shortarg The short argument name. * @param type The argument type (see the list above for supported types). * @param argHelp A help string describing the argument. * @param defaultValue A default value for the argument. * @param ignoreRest All arguments after the current one will be ignored. * @param deprecated Declares the argument deprecated. * * @see setExactMatchRegularExpression() * @see addDeprecatedArgument() * @throws std::logic_error If the us::Any type of defaultValue * does not match type, a std::logic_error is thrown. */ void addArgument(const string& longarg, const string& shortarg, - Type type, const string& argHelp = string(), + Type type, const string& argLabel, const string& argHelp = string(), const us::Any& defaultValue = us::Any(), bool optional=true, - bool ignoreRest = false, bool deprecated = false, const string& argLabel = string()); + bool ignoreRest = false, bool deprecated = false); /** * Adds a deprecated command line argument. If a deprecated argument is provided * on the command line, argHelp is displayed in the console and * processing continues with the next argument. * * Deprecated arguments are grouped separately at the end of the help text * returned by helpText(). * * @param longarg The long argument name. * @param shortarg The short argument name. * @param argHelp A help string describing alternatives to the deprecated argument. */ - void addDeprecatedArgument(const string& longarg, const string& shortarg, - const string& argHelp, const string& argLabel); + void addDeprecatedArgument(const string& longarg, const string& shortarg, const string& argLabel, + const string& argHelp); /** * Sets a custom regular expression for validating argument parameters. The method * errorString() can be used the get the last error description. * * @param argument The previously added long or short argument name. * @param expression A regular expression which the arugment parameters must match. * @param exactMatchFailedMessage An error message explaining why the parameter did * not match. * * @return true if the argument was found and the regular expression was set, * false otherwise. * * @see errorString() */ bool setExactMatchRegularExpression(const string& argument, const string& expression, const string& exactMatchFailedMessage); /** * The field width for the argument names without the help text. * * @return The argument names field width in the help text. */ int fieldWidth() const; /** * Creates a help text containing properly formatted argument names and help strings * provided by calls to addArgument(). The arguments can be grouped by * using beginGroup() and endGroup(). * * @param charPad The padding character. * @return The formatted help text. */ string helpText() const; /** * Sets the argument prefix for long and short argument names. This can be used * to create native command line arguments without changing the calls to * addArgument(). For example on Unix-based systems, long argument * names start with "--" and short names with "-", while on Windows argument names * always start with "/". * * Note that all methods in ctkCommandLineParser which take an argument name * expect the name as it was supplied to addArgument. * * Example usage: * * \code * ctkCommandLineParser parser; * parser.setArgumentPrefix("--", "-"); * parser.addArgument("long-argument", "l", us::Any::String); * StringContainerType args; * args << "program name" << "--long-argument Hi"; * parser.parseArguments(args); * \endcode * * @param longPrefix The prefix for long argument names. * @param shortPrefix The prefix for short argument names. */ void setArgumentPrefix(const string& longPrefix, const string& shortPrefix); /** * Begins a new group for documenting arguments. All newly added arguments via * addArgument() will be put in the new group. You can close the * current group by calling endGroup() or be opening a new group. * * Note that groups cannot be nested and all arguments which do not belong to * a group will be listed at the top of the text created by helpText(). * * @param description The description of the group */ void beginGroup(const string& description); /** * Ends the current group. * * @see beginGroup(const string&) */ void endGroup(); /** * Enables QSettings support in ctkCommandLineParser. If an argument name is found * in the QSettings instance with a valid us::Any, the value is considered as * a default value and overwrites default values registered with * addArgument(). User supplied values on the command line overwrite * values in the QSettings instance, except for arguments with multiple parameters * which are merged with QSettings values. Call mergeSettings(false) * to disable merging. * * See ctkCommandLineParser(QSettings*) for information about how to * supply a QSettings instance. * * Additionally, a long and short argument name can be specified which will disable * QSettings support if supplied on the command line. The argument name must be * registered as a regular argument via addArgument(). * * @param disableLongArg Long argument name. * @param disableShortArg Short argument name. * * @see ctkCommandLineParser(QSettings*) */ void enableSettings(const string& disableLongArg = "", const string& disableShortArg = ""); /** * Controlls the merging behavior of user values and QSettings values. * * If merging is on (the default), user supplied values for an argument * which can take more than one parameter are merged with values stored * in the QSettings instance. If merging is off, the user values overwrite * the QSettings values. * * @param merge true enables QSettings merging, false * disables it. */ void mergeSettings(bool merge); /** * Can be used to check if QSettings support has been enabled by a call to * enableSettings(). * * @return true if QSettings support is enabled, false * otherwise. */ bool settingsEnabled() const; /** * Can be used to teach the parser to stop parsing the arguments and return False when * an unknown argument is encountered. By default StrictMode is disabled. * * @see parseArguments(const StringContainerType &, bool*) */ void setStrictModeEnabled(bool strictMode); void GetXML(std::string title, std::string description); void setTitle(std::string title); void setContributor(std::string contributor); void setCategory(std::string category); void setDescription(std::string description); private: class ctkInternal; ctkInternal * Internal; string Title; string Contributor; string Category; string Description; }; #endif