swift
processctrl.cpp
1 // SPDX-FileCopyrightText: Copyright (C) 2016 swift Project Community / Contributors
2 // SPDX-License-Identifier: GPL-3.0-or-later OR LicenseRef-swift-pilot-client-1
3 
4 #include "misc/processctrl.h"
5 
6 #include <QStringBuilder>
7 
8 #include "misc/logmessage.h"
9 
10 #ifdef Q_OS_WIN
11 # include <windows.h>
12 
13 # include <array>
14 #endif
15 
16 namespace swift::misc
17 {
18  CProcessCtrl::CProcessCtrl(QObject *parent) : QProcess(parent) {}
19 
20 #ifdef Q_OS_WIN
21  bool startDetachedWithConsoleWindow(const QString &program, const QStringList &arguments)
22  {
23  bool inherit = false;
24 
25  PROCESS_INFORMATION processInfo;
26  memset(&processInfo, 0, sizeof(processInfo));
27 
28  STARTUPINFO startupInfo;
29  memset(&startupInfo, 0, sizeof(startupInfo));
30  startupInfo.cb = sizeof(startupInfo);
31 
32  QString command = '"' % QString(program).replace('/', '\\') % '"';
33  if (!arguments.isEmpty()) { command += " \"" % arguments.join("\" \"").replace('/', '\\') % '"'; }
34 
35  DWORD flags = 0;
36  flags |= NORMAL_PRIORITY_CLASS;
37  flags |= CREATE_UNICODE_ENVIRONMENT;
38  flags |= CREATE_NEW_CONSOLE;
39 
40  Q_ASSERT(command.length() <= MAX_PATH);
41  std::array<WCHAR, MAX_PATH> wszCommandLine = { {} };
42  command.toWCharArray(wszCommandLine.data());
43 
44  int result = CreateProcess(nullptr, wszCommandLine.data(), nullptr, nullptr, inherit, flags, nullptr, nullptr,
45  &startupInfo, &processInfo);
46 
47  if (result == 0)
48  {
49  CLogMessage(static_cast<CProcessCtrl *>(nullptr)).warning(u"Failed to start %1: %2")
50  << program << GetLastError();
51  return false;
52  }
53 
54  CloseHandle(processInfo.hProcess);
55  CloseHandle(processInfo.hThread);
56  return true;
57  }
58 #else
59  bool startDetachedWithConsoleWindow(const QString &program, const QStringList &arguments)
60  {
62  return QProcess::startDetached(program, arguments);
63  }
64 #endif
65 
66  bool CProcessCtrl::startDetached(const QString &program, const QStringList &arguments, bool withConsoleWindow)
67  {
68  if (withConsoleWindow) { return startDetachedWithConsoleWindow(program, arguments); }
69  else { return QProcess::startDetached(program, arguments); }
70  }
71 
72 } // namespace swift::misc
CProcessCtrl(QObject *parent=nullptr)
Constructor.
Definition: processctrl.cpp:18
static bool startDetached(const QString &program, const QStringList &arguments, bool withConsoleWindow)
Start a programm detached and without any console window.
Definition: processctrl.cpp:66
Free functions in swift::misc.
bool startDetachedWithConsoleWindow(const QString &program, const QStringList &arguments)
Definition: processctrl.cpp:59
unsigned long DWORD
Fake Windows DWORD.