X-Git-Url: https://git.saurik.com/wxWidgets.git/blobdiff_plain/9f83044fb8785568e186bee64db4f98b7a9ac9c6..81c9effa8462662263c3b4eac2cfae1ef5caae2c:/src/common/cmdline.cpp diff --git a/src/common/cmdline.cpp b/src/common/cmdline.cpp index f42ca0f098..2c5ea56421 100644 --- a/src/common/cmdline.cpp +++ b/src/common/cmdline.cpp @@ -28,15 +28,22 @@ #pragma hdrstop #endif +#include "wx/cmdline.h" + +#if wxUSE_CMDLINE_PARSER + #ifndef WX_PRECOMP #include "wx/string.h" #include "wx/log.h" #include "wx/intl.h" + #include "wx/app.h" #include "wx/dynarray.h" + #include "wx/filefn.h" #endif //WX_PRECOMP +#include + #include "wx/datetime.h" -#include "wx/cmdline.h" // ---------------------------------------------------------------------------- // private functions @@ -58,6 +65,9 @@ struct wxCmdLineOption wxCmdLineParamType typ, int fl) { + wxASSERT_MSG( !shrt.empty() || !lng.empty(), + _T("option should have at least one name") ); + kind = k; shortName = shrt; @@ -75,7 +85,7 @@ struct wxCmdLineOption // types increases, so always use the accessor functions and don't access // the fields directly!) - void Check(wxCmdLineParamType typ) const + void Check(wxCmdLineParamType WXUNUSED_UNLESS_DEBUG(typ)) const { wxASSERT_MSG( type == typ, _T("type mismatch in wxCmdLineOption") ); } @@ -94,12 +104,14 @@ struct wxCmdLineOption void SetDateVal(const wxDateTime val) { Check(wxCMD_LINE_VAL_DATE); m_dateVal = val; m_hasVal = TRUE; } - void SetHasValue() { m_hasVal = TRUE; } + void SetHasValue(bool hasValue = TRUE) { m_hasVal = hasValue; } bool HasValue() const { return m_hasVal; } public: wxCmdLineEntryType kind; - wxString shortName, longName, description; + wxString shortName, + longName, + description; wxCmdLineParamType type; int flags; @@ -140,8 +152,8 @@ struct wxCmdLineParserData { // options wxString m_switchChars; // characters which may start an option - bool m_enableLongOptions; // TRUE if long options are enabled + wxString m_logo; // some extra text to show in Usage() // cmd line data wxArrayString m_arguments; // == argv, argc == m_arguments.GetCount() @@ -151,7 +163,7 @@ struct wxCmdLineParserData // methods wxCmdLineParserData(); - void SetArguments(int argc, char **argv); + void SetArguments(int argc, wxChar **argv); void SetArguments(const wxString& cmdline); int FindOption(const wxString& name); @@ -176,7 +188,7 @@ wxCmdLineParserData::wxCmdLineParserData() #endif } -void wxCmdLineParserData::SetArguments(int argc, char **argv) +void wxCmdLineParserData::SetArguments(int argc, wxChar **argv) { m_arguments.Empty(); @@ -186,23 +198,29 @@ void wxCmdLineParserData::SetArguments(int argc, char **argv) } } -void wxCmdLineParserData::SetArguments(const wxString& cmdline) +void wxCmdLineParserData::SetArguments(const wxString& cmdLine) { - // either use wxMSW wxApp::ConvertToStandardCommandArgs() or move its logic - // here and use this method from it - but don't duplicate the code + m_arguments.Empty(); - wxFAIL_MSG(_T("TODO")); + m_arguments.Add(wxTheApp->GetAppName()); + + wxArrayString args = wxCmdLineParser::ConvertStringToArgs(cmdLine); + + WX_APPEND_ARRAY(m_arguments, args); } int wxCmdLineParserData::FindOption(const wxString& name) { - size_t count = m_options.GetCount(); - for ( size_t n = 0; n < count; n++ ) + if ( !name.empty() ) { - if ( m_options[n].shortName == name ) + size_t count = m_options.GetCount(); + for ( size_t n = 0; n < count; n++ ) { - // found - return n; + if ( m_options[n].shortName == name ) + { + // found + return n; + } } } @@ -233,7 +251,7 @@ void wxCmdLineParser::Init() m_data = new wxCmdLineParserData; } -void wxCmdLineParser::SetCmdLine(int argc, char **argv) +void wxCmdLineParser::SetCmdLine(int argc, wxChar **argv) { m_data->SetArguments(argc, argv); } @@ -262,6 +280,11 @@ void wxCmdLineParser::EnableLongOptions(bool enable) m_data->m_enableLongOptions = enable; } +void wxCmdLineParser::SetLogo(const wxString& logo) +{ + m_data->m_logo = logo; +} + // ---------------------------------------------------------------------------- // command line construction // ---------------------------------------------------------------------------- @@ -273,7 +296,8 @@ void wxCmdLineParser::SetDesc(const wxCmdLineEntryDesc *desc) switch ( desc->kind ) { case wxCMD_LINE_SWITCH: - AddSwitch(desc->shortName, desc->longName, desc->description); + AddSwitch(desc->shortName, desc->longName, desc->description, + desc->flags); break; case wxCMD_LINE_OPTION: @@ -338,14 +362,12 @@ void wxCmdLineParser::AddParam(const wxString& desc, wxCmdLineParam& param = m_data->m_paramDesc.Last(); wxASSERT_MSG( !(param.flags & wxCMD_LINE_PARAM_MULTIPLE), - _T("all parameters after the one with " - "wxCMD_LINE_PARAM_MULTIPLE style will be ignored") ); + _T("all parameters after the one with wxCMD_LINE_PARAM_MULTIPLE style will be ignored") ); if ( !(flags & wxCMD_LINE_PARAM_OPTIONAL) ) { wxASSERT_MSG( !(param.flags & wxCMD_LINE_PARAM_OPTIONAL), - _T("a required parameter can't follow an " - "optional one") ); + _T("a required parameter can't follow an optional one") ); } } #endif // Debug @@ -362,6 +384,9 @@ void wxCmdLineParser::AddParam(const wxString& desc, bool wxCmdLineParser::Found(const wxString& name) const { int i = m_data->FindOption(name); + if ( i == wxNOT_FOUND ) + i = m_data->FindOptionByLongName(name); + wxCHECK_MSG( i != wxNOT_FOUND, FALSE, _T("unknown switch") ); wxCmdLineOption& opt = m_data->m_options[(size_t)i]; @@ -374,6 +399,9 @@ bool wxCmdLineParser::Found(const wxString& name) const bool wxCmdLineParser::Found(const wxString& name, wxString *value) const { int i = m_data->FindOption(name); + if ( i == wxNOT_FOUND ) + i = m_data->FindOptionByLongName(name); + wxCHECK_MSG( i != wxNOT_FOUND, FALSE, _T("unknown option") ); wxCmdLineOption& opt = m_data->m_options[(size_t)i]; @@ -390,6 +418,9 @@ bool wxCmdLineParser::Found(const wxString& name, wxString *value) const bool wxCmdLineParser::Found(const wxString& name, long *value) const { int i = m_data->FindOption(name); + if ( i == wxNOT_FOUND ) + i = m_data->FindOptionByLongName(name); + wxCHECK_MSG( i != wxNOT_FOUND, FALSE, _T("unknown option") ); wxCmdLineOption& opt = m_data->m_options[(size_t)i]; @@ -406,6 +437,9 @@ bool wxCmdLineParser::Found(const wxString& name, long *value) const bool wxCmdLineParser::Found(const wxString& name, wxDateTime *value) const { int i = m_data->FindOption(name); + if ( i == wxNOT_FOUND ) + i = m_data->FindOptionByLongName(name); + wxCHECK_MSG( i != wxNOT_FOUND, FALSE, _T("unknown option") ); wxCmdLineOption& opt = m_data->m_options[(size_t)i]; @@ -426,14 +460,27 @@ size_t wxCmdLineParser::GetParamCount() const wxString wxCmdLineParser::GetParam(size_t n) const { + wxCHECK_MSG( n < GetParamCount(), wxEmptyString, _T("invalid param index") ); + return m_data->m_parameters[n]; } +// Resets switches and options +void wxCmdLineParser::Reset() +{ + for ( size_t i = 0; i < m_data->m_options.Count(); i++ ) + { + wxCmdLineOption& opt = m_data->m_options[i]; + opt.SetHasValue(FALSE); + } +} + + // ---------------------------------------------------------------------------- // the real work is done here // ---------------------------------------------------------------------------- -int wxCmdLineParser::Parse() +int wxCmdLineParser::Parse(bool showUsage) { bool maybeOption = TRUE; // can the following arg be an option? bool ok = TRUE; // TRUE until an error is detected @@ -444,6 +491,8 @@ int wxCmdLineParser::Parse() size_t countParam = m_data->m_paramDesc.GetCount(); + Reset(); + // parse everything wxString arg; size_t count = m_data->m_arguments.GetCount(); @@ -477,7 +526,7 @@ int wxCmdLineParser::Parse() isLong = TRUE; const wxChar *p = arg.c_str() + 2; - while ( wxIsalpha(*p) || (*p == _T('-')) ) + while ( wxIsalnum(*p) || (*p == _T('_')) || (*p == _T('-')) ) { name += *p++; } @@ -495,7 +544,7 @@ int wxCmdLineParser::Parse() // a short one: as they can be cumulated, we try to find the // longest substring which is a valid option const wxChar *p = arg.c_str() + 1; - while ( wxIsalpha(*p) ) + while ( wxIsalnum(*p) || (*p == _T('_')) ) { name += *p++; } @@ -521,8 +570,13 @@ int wxCmdLineParser::Parse() } while ( optInd == wxNOT_FOUND ); - if ( (len > 0) && (len != name.length()) ) + len++; // compensates extra len-- above + if ( (optInd != wxNOT_FOUND) && (len != name.length()) ) { + // first of all, the option name is only part of this + // string + name = name.Left(len); + // our option is only part of this argument, there is // something else in it - it is either the value of this // option or other switches if it is a switch @@ -532,9 +586,10 @@ int wxCmdLineParser::Parse() // pretend that all the rest of the argument is the // next argument, in fact wxString arg2 = arg[0u]; - arg2 += name.Mid(len); + arg2 += arg.Mid(len + 1); // +1 for leading '-' m_data->m_arguments.Insert(arg2, n + 1); + count++; } //else: it's our value, we'll deal with it below } @@ -573,8 +628,7 @@ int wxCmdLineParser::Parse() if ( *p++ != _T('=') ) { - wxLogError(_("Option '%s' requires a value, '=' " - "expected."), name.c_str()); + wxLogError(_("Option '%s' requires a value, '=' expected."), name.c_str()); ok = FALSE; } @@ -583,6 +637,7 @@ int wxCmdLineParser::Parse() { switch ( *p ) { + case _T('='): case _T(':'): // the value follows p++; @@ -606,8 +661,15 @@ int wxCmdLineParser::Parse() break; default: - // the value is right here - ; + // the value is right here: this may be legal or + // not depending on the option style + if ( opt.flags & wxCMD_LINE_NEEDS_SEPARATOR ) + { + wxLogError(_("Separator expected after the option '%s'."), + name.c_str()); + + ok = FALSE; + } } } @@ -633,9 +695,7 @@ int wxCmdLineParser::Parse() } else { - wxLogError(_("'%s' is not a correct " - "numeric value for option " - "'%s'."), + wxLogError(_("'%s' is not a correct numeric value for option '%s'."), value.c_str(), name.c_str()); ok = FALSE; @@ -649,8 +709,7 @@ int wxCmdLineParser::Parse() const wxChar *res = dt.ParseDate(value); if ( !res || *res ) { - wxLogError(_("Options '%s': '%s' cannot " - "be converted to a date."), + wxLogError(_("Option '%s': '%s' cannot be converted to a date."), name.c_str(), value.c_str()); ok = FALSE; @@ -683,9 +742,7 @@ int wxCmdLineParser::Parse() else { wxASSERT_MSG( currentParam == countParam - 1, - _T("all parameters after the one with " - "wxCMD_LINE_PARAM_MULTIPLE style " - "are ignored") ); + _T("all parameters after the one with wxCMD_LINE_PARAM_MULTIPLE style are ignored") ); // remember that we did have this last repeatable parameter hadRepeatableParam = TRUE; @@ -750,7 +807,7 @@ int wxCmdLineParser::Parse() } } - if ( !ok ) + if ( !ok && showUsage ) { Usage(); } @@ -764,8 +821,26 @@ int wxCmdLineParser::Parse() void wxCmdLineParser::Usage() { - wxString brief, detailed; - brief.Printf(_("Usage: %s"), wxTheApp->GetAppName().c_str()); + wxString appname = wxTheApp->GetAppName(); + if ( !appname ) + { + wxCHECK_RET( !m_data->m_arguments.IsEmpty(), _T("no program name") ); + + appname = wxFileNameFromPath(m_data->m_arguments[0]); + wxStripExtension(appname); + } + + // we construct the brief cmd line desc on the fly, but not the detailed + // help message below because we want to align the options descriptions + // and for this we must first know the longest one of them + wxString brief; + wxArrayString namesOptions, descOptions; + brief.Printf(_("Usage: %s"), appname.c_str()); + + // the switch char is usually '-' but this can be changed with + // SetSwitchChars() and then the first one of possible chars is used + wxChar chSwitch = !m_data->m_switchChars ? _T('-') + : m_data->m_switchChars[0u]; size_t n, count = m_data->m_options.GetCount(); for ( n = 0; n < count; n++ ) @@ -778,11 +853,30 @@ void wxCmdLineParser::Usage() brief << _T('['); } - brief << _T('-') << opt.shortName; - detailed << _T(" -") << opt.shortName; - if ( !!opt.longName ) + if ( !opt.shortName.empty() ) + { + brief << chSwitch << opt.shortName; + } + else if ( !opt.longName.empty() ) + { + brief << _T("--") << opt.longName; + } + else + { + wxFAIL_MSG( _T("option without neither short nor long name?") ); + } + + wxString option; + + if ( !opt.shortName.empty() ) + { + option << _T(" ") << chSwitch << opt.shortName; + } + + if ( !opt.longName.empty() ) { - detailed << _T(" --") << opt.longName; + option << (option.empty() ? _T(" ") : _T(", ")) + << _T("--") << opt.longName; } if ( opt.kind != wxCMD_LINE_SWITCH ) @@ -790,7 +884,7 @@ void wxCmdLineParser::Usage() wxString val; val << _T('<') << GetTypeName(opt.type) << _T('>'); brief << _T(' ') << val; - detailed << (!opt.longName ? _T(':') : _T('=')) << val; + option << (!opt.longName ? _T(':') : _T('=')) << val; } if ( !(opt.flags & wxCMD_LINE_OPTION_MANDATORY) ) @@ -798,7 +892,8 @@ void wxCmdLineParser::Usage() brief << _T(']'); } - detailed << _T('\t') << opt.description << _T('\n'); + namesOptions.Add(option); + descOptions.Add(opt.description); } count = m_data->m_paramDesc.GetCount(); @@ -825,12 +920,49 @@ void wxCmdLineParser::Usage() } } + if ( !!m_data->m_logo ) + { + wxLogMessage(m_data->m_logo); + } + + // in console mode we want to show the brief usage message first, then the + // detailed one but in GUI build we give the details first and then the + // summary - like this, the brief message appears in the wxLogGui dialog, + // as expected +#if !wxUSE_GUI wxLogMessage(brief); +#endif // !wxUSE_GUI + + // now construct the detailed help message + size_t len, lenMax = 0; + count = namesOptions.GetCount(); + for ( n = 0; n < count; n++ ) + { + len = namesOptions[n].length(); + if ( len > lenMax ) + lenMax = len; + } + + wxString detailed; + for ( n = 0; n < count; n++ ) + { + len = namesOptions[n].length(); + detailed << namesOptions[n] + << wxString(_T(' '), lenMax - len) << _T('\t') + << descOptions[n] + << _T('\n'); + } + wxLogMessage(detailed); + + // do it now if not done above +#if wxUSE_GUI + wxLogMessage(brief); +#endif // wxUSE_GUI } // ---------------------------------------------------------------------------- -// global functions +// private functions // ---------------------------------------------------------------------------- static wxString GetTypeName(wxCmdLineParamType type) @@ -849,3 +981,133 @@ static wxString GetTypeName(wxCmdLineParamType type) return s; } + +#endif // wxUSE_CMDLINE_PARSER + +// ---------------------------------------------------------------------------- +// global functions +// ---------------------------------------------------------------------------- + +/* + This function is mainly used under Windows (as under Unix we always get the + command line arguments as agrc/argv anyhow) and so it tries to handle the + Windows path names (separated by backslashes) correctly. For this it only + considers that a backslash may be used to escape another backslash (but + normally this is _not_ needed) or a quote but nothing else. + + In particular, to pass a single argument containing a space to the program + it should be quoted: + + myprog.exe foo bar -> argc = 3, argv[1] = "foo", argv[2] = "bar" + myprog.exe "foo bar" -> argc = 2, argv[1] = "foo bar" + + To pass an argument containing spaces and quotes, the latter should be + escaped with a backslash: + + myprog.exe "foo \"bar\"" -> argc = 2, argv[1] = "foo "bar"" + + This hopefully matches the conventions used by Explorer/command line + interpreter under Windows. If not, this function should be fixed. + */ + +/* static */ +wxArrayString wxCmdLineParser::ConvertStringToArgs(const wxChar *p) +{ + wxArrayString args; + + wxString arg; + arg.reserve(1024); + + bool isInsideQuotes = FALSE; + for ( ;; ) + { + // skip white space + while ( *p == _T(' ') || *p == _T('\t') ) + p++; + + // anything left? + if ( *p == _T('\0') ) + break; + + // parse this parameter + arg.clear(); + for ( ;; p++ ) + { + // do we have a (lone) backslash? + bool isQuotedByBS = FALSE; + while ( *p == _T('\\') ) + { + p++; + + // if we have 2 backslashes in a row, output one + if ( isQuotedByBS ) + { + arg += _T('\\'); + isQuotedByBS = FALSE; + } + else // the next char is quoted + { + isQuotedByBS = TRUE; + } + } + + bool skipChar = FALSE, + endParam = FALSE; + switch ( *p ) + { + case _T('"'): + if ( !isQuotedByBS ) + { + // don't put the quote itself in the arg + skipChar = TRUE; + + isInsideQuotes = !isInsideQuotes; + } + //else: insert a literal quote + + break; + + case _T(' '): + case _T('\t'): + // we intentionally don't check for preceding backslash + // here as if we allowed it to be used to escape spaces the + // cmd line of the form "foo.exe a:\ c:\bar" wouldn't be + // parsed correctly + if ( isInsideQuotes ) + { + // preserve it, skip endParam below + break; + } + //else: fall through + + case _T('\0'): + endParam = TRUE; + break; + + default: + if ( isQuotedByBS ) + { + // ignore backslash before an ordinary character - this + // is needed to properly handle the file names under + // Windows appearing in the command line + arg += _T('\\'); + } + } + + // end of argument? + if ( endParam ) + break; + + // otherwise copy this char to arg + if ( !skipChar ) + { + arg += *p; + } + } + + args.Add(arg); + } + + return args; +} +