Debian Codegraph @

src/app/app.cpp

raw symbols SCIP
1 // SPDX-License-Identifier: GPL-3.0-or-later
2 // Copyright 2019 Juan Palacios <[email protected]>
3
4 #include "app.h"
5
6 #include "common/stringutils.h"
7 #include "core/isession.h"
8 #include "core/isysmodelsyncer.h"
9 #include "core/iuifactory.h"
10 #include "corefactory.h"
11 #include "helper/ihelpercontrol.h"
12 #include "settings.h"
13 #include "systray.h"
14 #include <QApplication>
15 #include <QCommandLineParser>
16 #include <QIcon>
17 #include <QLocale>
18 #include <QQmlApplicationEngine>
19 #include <QQmlContext>
20 #include <QQuickWindow>
21 #include <QTranslator>
22 #include <Qt>
23 #include <QtGlobal>
24 #include <algorithm>
25 #include <spdlog/spdlog.h>
26 #include <units.h>
27 #include <utility>
28
29 #if defined(_DEBUG)
30 #include <QQmlDebuggingEnabler>
31 #endif
32
33 App::App() noexcept
34 : QObject()
35 , appInfo_(App::Name, App::VersionStr)
36 , singleInstance_(App::Name)
37 {
38 }
39
40 App::~App() = default;
41
42 int App::exec(int argc, char **argv)
43 {
44 auto defaultHelperTimeout = std::max(
45 180000, // default helper timeout in milliseconds
46 IHelperControl::MinExitTimeout::value().to<int>());
47
48 auto app = createApplication(argc, argv);
49 setupCmdParser(*app, defaultHelperTimeout);
50
51 noop_ = cmdParser_.isSet("help") || cmdParser_.isSet("version");
52 if (noop_)
53 return 0;
54
55 // Exit if there is another instance running.
56 if (!singleInstance_.mainInstance(app->arguments()))
57 return 0;
58
59 QTranslator translator;
60 loadTranslation(*app, translator);
61
62 QQmlApplicationEngine qmlEngine;
63 bool logCommands = cmdParser_.isSet("enable-log-commands");
64 bool logProfileStack = cmdParser_.isSet("enable-log-profile-stack");
65 if (!buildComponents(qmlEngine, helperTimeout(defaultHelperTimeout),
66 logCommands, logProfileStack))
67 return -1;
68
69 // Load and apply stored settings.
70 settings_->signalSettings();
71
72 setupSysTrayWindowState();
73 handleManualProfileCmd();
74
75 return app->exec();
76 }
77
78 void App::exit()
79 {
80 if (!noop_) {
81 sysSyncer_->stop();
82 helperControl_->stop();
83
84 // Shutdown spdlog before QApplication quits to always flush the logs.
85 // See: https://github.com/gabime/spdlog/issues/2502
86 spdlog::shutdown();
87 }
88 }
89
90 void App::showMainWindow(bool show)
91 {
92 if (show) {
93 mainWindow_->show();
94 mainWindow_->raise();
95 mainWindow_->requestActivate();
96 }
97 else {
98 if (sysTray_->isVisible())
99 mainWindow_->hide();
100 else
101 mainWindow_->showMinimized();
102 }
103 }
104
105 void App::onNewInstance(QStringList args)
106 {
107 cmdParser_.parse(args);
108
109 bool runtimeCmds{false};
110 runtimeCmds |= handleLoggingCmds();
111 runtimeCmds |= handleManualProfileCmd();
112 runtimeCmds |= handleWindowVisibilityCmds();
113
114 // No runtime commands were used as arguments.
115 // Show the main window unconditionally.
116 if (!runtimeCmds)
117 showMainWindow(true);
118 }
119
120 void App::onSysTrayActivated()
121 {
122 showMainWindow(!mainWindow_->isVisible());
123 }
124
125 void App::onSettingChanged(QString const &key, QVariant const &value)
126 {
127 sysTray_->settingChanged(key, value);
128 sysSyncer_->settingChanged(key, value);
129 }
130
131 std::unique_ptr<QApplication> App::createApplication(int &argc, char **argv)
132 {
133 // Ignore QT_STYLE_OVERRIDE. It breaks the QML theme.
134 if (qEnvironmentVariableIsSet("QT_STYLE_OVERRIDE")) {
135 SPDLOG_INFO("Ignoring QT_STYLE_OVERRIDE environment variable.");
136 qunsetenv("QT_STYLE_OVERRIDE");
137 }
138
139 QCoreApplication::setApplicationName(QString(App::Name.data()).toLower());
140 QCoreApplication::setApplicationVersion(App::VersionStr.data());
141 QGuiApplication::setDesktopFileName(QString(App::Fqdn.data()));
142
143 auto app = std::make_unique<QApplication>(argc, argv);
144 app->setWindowIcon(QIcon::fromTheme(QString(App::Name.data()).toLower()));
145
146 // Ensure that the application do not implicitly call to quit after closing
147 // the last window, which is not the desired behaviour when minimize to
148 // system tray is being used.
149 app->setQuitOnLastWindowClosed(false);
150
151 return app;
152 }
153
154 bool App::buildComponents(QQmlApplicationEngine &qmlEngine, int helperTimeout,
155 bool logCommands, bool logProfileStack)
156 {
157 try {
158 auto core = CoreFactory().build(std::string(App::Name), logCommands,
159 logProfileStack);
160 if (!core)
161 return false;
162
163 std::swap(helperControl_, core->helperControl);
164 std::swap(sysSyncer_, core->sysSyncer);
165 std::swap(session_, core->session);
166
167 settings_ = std::make_unique<Settings>(QString(App::Name.data()).toLower());
168
169 helperControl_->init(units::time::millisecond_t(helperTimeout));
170 sysSyncer_->init();
171 session_->init(sysSyncer_->sysModel());
172
173 buildUI(std::move(core->uiFactory), qmlEngine);
174 }
175 catch (std::exception const &e) {
176 SPDLOG_WARN(e.what());
177 SPDLOG_WARN("Initialization failed");
178 SPDLOG_WARN("Exiting...");
179 return false;
180 }
181
182 return true;
183 }
184
185 void App::buildUI(std::unique_ptr<IUIFactory> &&uiFactory,
186 QQmlApplicationEngine &qmlEngine)
187 {
188 qmlEngine.rootContext()->setContextProperty("appInfo", &appInfo_);
189 qmlEngine.rootContext()->setContextProperty("settings", &*settings_);
190
191 uiFactory->build(qmlEngine, sysSyncer_->sysModel(), *session_);
192
193 mainWindow_ = qobject_cast<QQuickWindow *>(qmlEngine.rootObjects().value(0));
194 setupMainWindowGeometry();
195
196 connect(&qmlEngine, &QQmlApplicationEngine::quit, QApplication::instance(),
197 &QApplication::quit);
198 connect(QApplication::instance(), &QApplication::aboutToQuit, this, &App::exit);
199 connect(&*settings_, &Settings::settingChanged, this, &App::onSettingChanged);
200 connect(&singleInstance_, &SingleInstance::newInstance, this,
201 &App::onNewInstance);
202
203 sysTray_ = new SysTray(&*session_, mainWindow_);
204 connect(sysTray_, &SysTray::quit, this, &QApplication::quit);
205 connect(sysTray_, &SysTray::activated, this, &App::onSysTrayActivated);
206 connect(sysTray_, &SysTray::showMainWindowToggled, this, &App::showMainWindow);
207 connect(mainWindow_, &QQuickWindow::visibleChanged, &*sysTray_,
208 &SysTray::onMainWindowVisibleChanged);
209 qmlEngine.rootContext()->setContextProperty("systemTray", sysTray_);
210 }
211
212 void App::loadTranslation(QApplication &app, QTranslator &translator)
213 {
214 QString lang = cmdParser_.isSet("lang") ? cmdParser_.value("lang")
215 : QLocale().system().name();
216 if (!translator.load(QStringLiteral(":/translations/lang_") + lang)) {
217 SPDLOG_INFO("No translation found for locale {}", lang.toStdString());
218 SPDLOG_INFO("Using en_EN translation.");
219 if (!translator.load(QStringLiteral(":/translations/lang_en_EN")))
220 SPDLOG_ERROR("Cannot load en_EN translation.");
221 }
222 app.installTranslator(&translator);
223 }
224
225 int App::helperTimeout(int defaultTimeout) const
226 {
227 int value = defaultTimeout;
228 if (cmdParser_.isSet("helper-timeout") &&
229 Utils::String::toNumber<int>(
230 value, cmdParser_.value("helper-timeout").toStdString())) {
231 value = std::max(IHelperControl::MinExitTimeout::value().to<int>(), value);
232 }
233 return value;
234 }
235
236 void App::setupCmdParser(QApplication &app, int defaultHelperTimeout)
237 {
238 cmdParser_.addHelpOption();
239 cmdParser_.addVersionOption();
240 cmdParser_.addOptions({
241 {{"l", "lang"},
242 "Forces a specific <language>, given in locale format. Example: "
243 "en_EN.",
244 "language"},
245 {{"m", "toggle-manual-profile"},
246 "Activate the manual profile whose name is <\"profile name\">.\nWhen an "
247 "instance of the application is already running, it will toggle "
248 "the manual profile whose name is <\"profile name\">.",
249 "\"profile name\""},
250 {"activate-manual-profile",
251 "Activate the manual profile whose name is <\"profile name\">.\nWhen an "
252 "instance of the application is already running, it will activate "
253 "the manual profile whose name is <\"profile name\">.",
254 "\"profile name\""},
255 {"deactivate-manual-profile",
256 "Deactivate the manual profile whose name is <\"profile name\">.\nWhen "
257 "an instance of the application is already running, it will deactivate "
258 "the manual profile whose name is <\"profile name\">.",
259 "\"profile name\""},
260 {"minimize-systray",
261 "Minimizes the main window either to the system tray (when "
262 "available) or to the taskbar.\nWhen an instance of the application is "
263 "already running, the action will be applied to its main window."},
264 {{"t", "helper-timeout"},
265 "Sets helper auto exit timeout. "
266 "The helper process kills himself when no signals are received from "
267 "the application before the timeout expires.\nValues lesser than " +
268 QString::number(IHelperControl::MinExitTimeout::value().to<int>()) +
269 +" milliseconds will be ignored.\nDefault value: " +
270 QString::number(defaultHelperTimeout) + " milliseconds.",
271 "milliseconds"},
272 {"toggle-window-visibility",
273 "When an instance of the application is already running, it will toggle "
274 "the main window visibility showing or minimizing it, either to the "
275 "taskbar or to system tray."},
276 {"enable-log-commands",
277 "Enables logging of control commands. It takes precedence over "
278 "disable-log-commands.\nIt can be used to activate commands logging on "
279 "a running instance of the application or while starting it."},
280 {"disable-log-commands",
281 "Disables logging of control commands.\nIt can be used to deactivate "
282 "commands logging on a running instance of the application or while "
283 "starting it (no-op)."},
284 {"enable-log-profile-stack",
285 "Enables logging of the profile stack. It takes precedence over "
286 "disable-log-profile-stack.\nIt can be used to activate the profile "
287 "stack logging on a running instance of the application or while "
288 "starting it."},
289 {"disable-log-profile-stack",
290 "Disables logging of the profile stack.\nIt can be used to deactivate "
291 "the profile stack logging on a running instance of the application or "
292 "while starting it (no-op)."},
293 });
294 cmdParser_.process(app);
295 }
296
297 void App::setupSysTrayWindowState()
298 {
299 bool minimizeArgIsSet = cmdParser_.isSet("minimize-systray");
300 bool enableSysTray = settings_->getValue("sysTray", true).toBool();
301
302 if (minimizeArgIsSet || enableSysTray)
303 sysTray_->show();
304
305 bool startOnSysTray = settings_->getValue("startOnSysTray", false).toBool();
306 bool showWindow = !minimizeArgIsSet && !(sysTray_->isAvailable() &&
307 enableSysTray && startOnSysTray);
308
309 showMainWindow(showWindow);
310 }
311
312 void App::setupMainWindowGeometry()
313 {
314 restoreMainWindowGeometry();
315
316 // The geometry save timer is used to reduce the window geometry changed
317 // events fired within a time interval into a single event that will save the
318 // window geometry.
319 geometrySaveTimer_.setInterval(2000);
320 geometrySaveTimer_.setSingleShot(true);
321 connect(&geometrySaveTimer_, &QTimer::timeout, this,
322 &App::saveMainWindowGeometry);
323
324 connect(mainWindow_, &QWindow::heightChanged, this,
325 [&](int) { geometrySaveTimer_.start(); });
326 connect(mainWindow_, &QWindow::widthChanged, this,
327 [&](int) { geometrySaveTimer_.start(); });
328 connect(mainWindow_, &QWindow::xChanged, this,
329 [&](int) { geometrySaveTimer_.start(); });
330 connect(mainWindow_, &QWindow::yChanged, this,
331 [&](int) { geometrySaveTimer_.start(); });
332 }
333
334 void App::saveMainWindowGeometry()
335 {
336 if (!settings_->getValue("saveWindowGeometry", true).toBool())
337 return;
338
339 if (mainWindow_ == nullptr)
340 return;
341
342 auto windowGeometry = mainWindow_->geometry();
343
344 auto savedXPos =
345 settings_->getValue("Window/main-x-pos", DefaultWindowGeometry.x()).toInt();
346 if (savedXPos != windowGeometry.x())
347 settings_->setValue("Window/main-x-pos", windowGeometry.x());
348
349 auto savedYPos =
350 settings_->getValue("Window/main-y-pos", DefaultWindowGeometry.y()).toInt();
351 if (savedYPos != windowGeometry.y())
352 settings_->setValue("Window/main-y-pos", windowGeometry.y());
353
354 auto savedWidth =
355 settings_->getValue("Window/main-width", DefaultWindowGeometry.width())
356 .toInt();
357 if (savedWidth != windowGeometry.width())
358 settings_->setValue("Window/main-width", windowGeometry.width());
359
360 auto savedHeight =
361 settings_->getValue("Window/main-height", DefaultWindowGeometry.height())
362 .toInt();
363 if (savedHeight != windowGeometry.height())
364 settings_->setValue("Window/main-height", windowGeometry.height());
365 }
366
367 void App::restoreMainWindowGeometry()
368 {
369 if (mainWindow_ == nullptr)
370 return;
371
372 auto x =
373 settings_->getValue("Window/main-x-pos", DefaultWindowGeometry.x()).toInt();
374 auto y =
375 settings_->getValue("Window/main-y-pos", DefaultWindowGeometry.y()).toInt();
376 auto width =
377 settings_->getValue("Window/main-width", DefaultWindowGeometry.width())
378 .toInt();
379 auto height =
380 settings_->getValue("Window/main-height", DefaultWindowGeometry.height())
381 .toInt();
382
383 mainWindow_->setGeometry(x, y, width, height);
384 }
385
386 bool App::handleLoggingCmds()
387 {
388 auto cmdHandled{false};
389
390 if (cmdParser_.isSet("enable-log-commands")) {
391 sysSyncer_->logCommands(true);
392 cmdHandled = true;
393 }
394 else if (cmdParser_.isSet("disable-log-commands")) {
395 sysSyncer_->logCommands(false);
396 cmdHandled = true;
397 }
398
399 if (cmdParser_.isSet("enable-log-profile-stack")) {
400 session_->logProfileStack(true);
401 cmdHandled = true;
402 }
403 else if (cmdParser_.isSet("disable-log-profile-stack")) {
404 session_->logProfileStack(false);
405 cmdHandled = true;
406 }
407
408 return cmdHandled;
409 }
410
411 bool App::handleManualProfileCmd()
412 {
413 auto cmdHandled{false};
414 if (cmdParser_.isSet("toggle-manual-profile")) {
415
416 auto profile = cmdParser_.value("toggle-manual-profile").toStdString();
417 if (profile.empty() || profile.length() >= 512)
418 SPDLOG_WARN("'{}' is not a valid manual profile name.", profile);
419 else if (!session_->toggleManualProfile(profile))
420 SPDLOG_WARN("Cannot toggle manual profile '{}': Missing profile or not a "
421 "manual profile.",
422 profile);
423
424 cmdHandled = true;
425 }
426 else if (cmdParser_.isSet("activate-manual-profile")) {
427
428 auto profile = cmdParser_.value("activate-manual-profile").toStdString();
429 if (profile.empty() || profile.length() >= 512)
430 SPDLOG_WARN("'{}' is not a valid manual profile name.", profile);
431 else if (!session_->activateManualProfile(profile))
432 SPDLOG_WARN(
433 "Cannot activate manual profile '{}': Missing profile or not a "
434 "manual profile.",
435 profile);
436
437 cmdHandled = true;
438 }
439 else if (cmdParser_.isSet("deactivate-manual-profile")) {
440
441 auto profile = cmdParser_.value("deactivate-manual-profile").toStdString();
442 if (profile.empty() || profile.length() >= 512)
443 SPDLOG_WARN("'{}' is not a valid manual profile name.", profile);
444 else if (!session_->deactivateManualProfile(profile))
445 SPDLOG_WARN(
446 "Cannot deactivate manual profile '{}': Missing profile or not a "
447 "manual profile.",
448 profile);
449
450 cmdHandled = true;
451 }
452
453 return cmdHandled;
454 }
455
456 bool App::handleWindowVisibilityCmds()
457 {
458 auto cmdHandled{false};
459 auto show{false};
460
461 // Minimize to system tray takes precedence over any other window visibility
462 // command.
463 if (cmdParser_.isSet("minimize-systray")) {
464 cmdHandled = true;
465 }
466 else if (cmdParser_.isSet("toggle-window-visibility")) {
467
468 // When the window is minimized, calling show() will raise it.
469 auto minimized =
470 ((mainWindow_->windowState() & Qt::WindowState::WindowMinimized) ==
471 Qt::WindowState::WindowMinimized);
472
473 show = minimized ? true : !mainWindow_->isVisible();
474 cmdHandled = true;
475 }
476
477 if (cmdHandled)
478 showMainWindow(show);
479
480 return cmdHandled;
481 }