commandlinetokenizer.cpp
1 //------------------------------------------------------------------------------
2 // commandlinetokenizer.cpp
3 //------------------------------------------------------------------------------
4 //
5 // This library is free software; you can redistribute it and/or
6 // modify it under the terms of the GNU Lesser General Public
7 // License as published by the Free Software Foundation; either
8 // version 2.1 of the License, or (at your option) any later version.
9 //
10 // This library is distributed in the hope that it will be useful,
11 // but WITHOUT ANY WARRANTY; without even the implied warranty of
12 // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
13 // Lesser General Public License for more details.
14 //
15 // You should have received a copy of the GNU Lesser General Public
16 // License along with this library; if not, write to the Free Software
17 // Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
18 // 02110-1301 USA
19 //
20 //------------------------------------------------------------------------------
21 // Copyright (C) 2014 "Zalewa" <zalewapl@gmail.com>
22 //------------------------------------------------------------------------------
23 #include "commandlinetokenizer.h"
24 
25 #include "scanner.h"
26 
27 #ifdef Q_OS_WIN32
28  #include <windows.h>
29 #endif
30 
31 class CommandLineTokenizer::PrivData
32 {
33 public:
34  #ifdef Q_OS_WIN32
35  static QStringList tokenize(const QString &cmdLine)
36  {
37  if (cmdLine.isEmpty())
38  {
39  // CommandLineToArgvW() returns path to current executable
40  // if lpCmdLine argument is an empty string. We don't want that
41  // here.
42  return QStringList();
43  }
44  int numArgs = 0;
45  LPCWSTR winapiCmdLine = (LPCWSTR)cmdLine.utf16();
46  LPWSTR *winapiTokens = CommandLineToArgvW(winapiCmdLine, &numArgs);
47 
48  if (winapiTokens == nullptr)
49  return QStringList();
50 
51  QStringList result;
52  for (int i = 0; i < numArgs; ++i)
53  {
54  // Conversion to "ushort*" seems to work for LPWSTR.
55  result << QString::fromUtf16((const ushort *)winapiTokens[i]);
56  }
57  LocalFree(winapiTokens);
58  return result;
59  }
60  #else
61  static QStringList tokenize(const QString &cmdLine)
62  {
63  QStringList result;
64  Scanner sc(cmdLine.toUtf8().constData(), cmdLine.length());
65  while (sc.nextString())
66  {
67  result << sc->str();
68  }
69  return result;
70  }
71  #endif
72 };
73 
74 QStringList CommandLineTokenizer::tokenize(const QString &cmdLine)
75 {
76  return PrivData::tokenize(cmdLine);
77 }