swift
Loading...
Searching...
No Matches
application.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 "core/application.h"
5
6#include <cstdio>
7#include <cstdlib>
8
9#include <QCoreApplication>
10#include <QDateTime>
11#include <QEventLoop>
12#include <QFileInfo>
13#include <QHttpMultiPart>
14#include <QNetworkReply>
15#include <QNetworkRequest>
16#include <QProcess>
17#include <QRegularExpression>
18#include <QSslSocket>
19#include <QStandardPaths>
20#include <QStringBuilder>
21#include <QStringList>
22#include <QSysInfo>
23#include <QTemporaryDir>
24#include <QThread>
25#include <QTimer>
26#include <QWriteLocker>
27#include <Qt>
28#include <QtGlobal>
29
30#include "config/buildconfig.h"
35#include "core/cookiemanager.h"
36#include "core/corefacade.h"
37#include "core/inputmanager.h"
39#include "core/setupreader.h"
42#include "misc/crashhandler.h"
43#include "misc/datacache.h"
44#include "misc/dbusserver.h"
45#include "misc/eventloop.h"
46#include "misc/filelogger.h"
47#include "misc/loghandler.h"
48#include "misc/logmessage.h"
49#include "misc/logpattern.h"
52#include "misc/settingscache.h"
53#include "misc/stringutils.h"
55#include "misc/threadutils.h"
56#include "misc/verify.h"
57
58using namespace swift::config;
59using namespace swift::misc;
60using namespace swift::misc::db;
61using namespace swift::misc::network;
62using namespace swift::misc::aviation;
63using namespace swift::misc::simulation;
64using namespace swift::misc::weather;
65using namespace swift::core;
66using namespace swift::core::context;
67using namespace swift::core::vatsim;
68using namespace swift::core::data;
69using namespace swift::core::db;
70
71swift::core::CApplication *sApp = nullptr; // set by constructor
72
74static const QString &swiftDataRoot()
75{
76 static const QString path =
78 return path;
79}
80
81namespace swift::core
82{
86
88 : CIdentifiable(this), m_accessManager(new QNetworkAccessManager(this)), m_applicationInfo(application),
89 m_applicationName(applicationName), m_coreFacadeConfig(CCoreFacadeConfig::NotUsed)
90 {
91 Q_ASSERT_X(!sApp, Q_FUNC_INFO, "already initialized");
92 Q_ASSERT_X(QCoreApplication::instance(), Q_FUNC_INFO, "no application object");
93
94 m_applicationInfo.setApplicationDataDirectory(CSwiftDirectories::normalizedApplicationDataDirectory());
95 QCoreApplication::setApplicationName(m_applicationName);
97 this->setObjectName(m_applicationName);
98 this->thread()->setObjectName(
99 m_applicationName); // normally no effect as thread already runs, but does not harm either
100
101 // init skipped when called from CGuiApplication
102 if (init)
103 {
104 this->init(true);
105 }
106 }
107
108 void CApplication::init(bool withMetadata)
109 {
110 if (!sApp)
111 {
112 // notify when app goes down
115
116 // metadata
117 if (withMetadata)
118 {
120 }
121
122 // unit test
123 if (this->getApplicationInfo().getApplication() == CApplicationInfo::UnitTest)
124 {
127 }
129 CApplication::getApplicationInfo().getApplication());
130 this->initParser();
131 this->initLogging();
132 this->tagApplicationDataDirectory();
133
134 //
135 // cmd line arguments not yet parsed here
136 //
137
138 // main app
139 sApp = this;
140
141 this->initNetwork();
142
143 // global setup
144 m_setupReader.reset(new CSetupReader(this));
145
146 // check for updates
147 m_gitHubPackagesReader.reset(new CGitHubPackagesReader(this));
148 connect(m_gitHubPackagesReader.data(), &CGitHubPackagesReader::updateInfoAvailable, this,
151
152 // startup done
157
158 if (!this->getApplicationInfo().isUnitTest())
159 {
160 m_inputManager = new CInputManager(this);
161 m_inputManager->createDevices();
162 }
163
164 connect(this, &QObject::destroyed, [cat = CLogCategoryList(this)] {
165 for (CWorkerBase *worker : CWorkerBase::allWorkers())
166 {
167 CLogMessage(cat).debug(u"Worker named '%1' still exists after application destroyed")
168 << worker->objectName();
169 }
170 });
171 }
172 }
173
175 {
179 if (!apps.contains(myself))
180 {
181 apps.push_back(myself);
182 }
184 CFileUtils::appendFilePaths(swiftDataRoot(), "apps.json"));
185 if (!ok)
186 {
187 CLogMessage(static_cast<CApplication *>(nullptr)).error(u"Failed to write to application list file");
188 }
189 return ok;
190 }
191
193 {
197 if (!apps.contains(myself))
198 {
199 return true;
200 }
201 apps.remove(myself);
203 CFileUtils::appendFilePaths(swiftDataRoot(), "apps.json"));
204 if (!ok)
205 {
206 CLogMessage(static_cast<CApplication *>(nullptr)).error(u"Failed to write to application list file");
207 }
208 return ok;
209 }
210
212 {
213 Q_ASSERT_X(instance(), Q_FUNC_INFO, "missing application");
214 emit this->startUpCompleted(true);
216 return QCoreApplication::exec();
217 }
218
219 void CApplication::restartApplication(const QStringList &newArguments, const QStringList &removeArguments)
220 {
223 const QStringList args = this->argumentsJoined(newArguments, removeArguments);
224 this->gracefulShutdown();
225 QProcess::startDetached(prg, args);
227 }
228
230
232 {
234 apps.convertFromJsonNoThrow(CFileUtils::readLockedFileToString(swiftDataRoot() + "apps.json"), {}, {});
235 apps.removeIf([](const CApplicationInfo &info) { return !info.getProcessInfo().exists(); });
236 return apps;
237 }
238
244
246 {
247 return getRunningApplications().containsBy([this](const CApplicationInfo &info) {
249 });
250 }
251
253
254 bool CApplication::isIncognito() const { return m_incognito; }
255
256 void CApplication::setIncognito(bool incognito) { m_incognito = incognito; }
257
259
261 {
262 static const QString s(m_applicationName % u" " % CBuildConfig::getVersionString());
263 return s;
264 }
265
267 {
268 static const QString s(m_applicationName % u" " % this->versionStringDetailed());
269 return s;
270 }
271
273 {
274 if (m_shutdown)
275 {
276 return {};
277 }
278 const CSetupReader *r = m_setupReader.data();
279 if (!r)
280 {
281 return {};
282 }
283 return r->getSetup();
284 }
285
287 {
288 if (m_shutdown)
289 {
290 return {};
291 }
292 if (!m_gitHubPackagesReader)
293 {
294 return {};
295 }
296 return m_gitHubPackagesReader->getUpdateInfo();
297 }
298
300 {
301 if (m_shutdown)
302 {
303 return;
304 }
305 if (!m_gitHubPackagesReader)
306 {
307 return;
308 }
309 m_gitHubPackagesReader->readUpdateInfo();
310 }
311
321
323 {
324 m_started = false; // reset
325
326 Q_ASSERT_X(m_parsed, Q_FUNC_INFO, "Call this function after parsing");
327
328 // parsing itself is done
330 do
331 {
332 // clear cache?
333 if (this->isSet(m_cmdClearCache))
334 {
336 msgs.push_back(CLogMessage(this).debug() << "Cleared cache, " << files.size() << " files");
337 }
338
339 // crashpad dump
340 if (this->isSet(m_cmdTestCrashpad))
341 {
342 msgs.push_back(CLogMessage(this).info(u"About to simulate crash"));
343 QTimer::singleShot(10 * 1000, [=, this] {
344 if (!sApp || sApp->isShuttingDown())
345 {
346 return;
347 }
348 this->simulateCrash();
349 });
350 }
351
352 Q_ASSERT_X(m_setupReader && m_setupReader->isSetupAvailable(), Q_FUNC_INFO, "Setup not available");
353
354 // start hookin
355 msgs.push_back(this->startHookIn());
356 if (msgs.isFailure())
357 {
358 break;
359 }
360
361 // Settings if not already initialized
362 msgs.push_back(this->initLocalSettings());
363 if (msgs.isFailure())
364 {
365 break;
366 }
367 }
368 while (false);
369
370 // terminate with failures, otherwise log messages
371 if (msgs.isFailure())
372 {
373 this->cmdLineErrorMessage(msgs);
374 return false;
375 }
376 else if (!msgs.isEmpty())
377 {
379 }
380
381 m_started = true;
382 return m_started;
383 }
384
386 {
387 if (m_shutdown || !m_setupReader)
388 {
389 return false;
390 }
391 return m_setupReader->isSetupAvailable();
392 }
393
395 {
396 return (this->getGlobalSetup().isSwiftVersionMinimumMappingVersion());
397 }
398
400 {
401 if (this->isShuttingDown())
402 {
403 return false;
404 } // service will not survive for long
405 return !m_webDataServices.isNull();
406 }
407
409 {
410 // use hasWebDataServices() to test if services are available
411 // getting the assert means web services are accessed before the are initialized
412
413 Q_ASSERT_X(m_webDataServices, Q_FUNC_INFO,
414 "Missing web data services, use hasWebDataServices to test if existing");
415 return m_webDataServices.data();
416 }
417
419 {
421 {
422 static const QString s(CBuildConfig::getVersionStringPlatform() % u" [dev,DEVDBG]");
423 return s;
424 }
425 if (isDeveloperFlagSet())
426 {
427 static const QString s(CBuildConfig::getVersionStringPlatform() % u" [dev]");
428 return s;
429 }
431 {
432 static const QString s(CBuildConfig::getVersionStringPlatform() % u" [DEVDBG]");
433 return s;
434 }
436 }
437
439 {
440 static const QString s(QStringLiteral("swift %1").arg(versionStringDetailed()));
441 return s;
442 }
443
445 {
446 static const QByteArray a(swiftVersionString().toUtf8());
447 return a.constData();
448 }
449
450 bool CApplication::initIsRunningInDeveloperEnvironment() const
451 {
452 //
453 // assumption: restricted distributions are development versions
454 //
455
456 if (this->getApplicationInfo().isSampleOrUnitTest())
457 {
458 return true;
459 }
461 {
462 return true;
463 }
464
465 const CDistribution d(this->getOwnDistribution());
466 return d.isRestricted() && this->isSet(m_cmdDevelopment);
467 }
468
469 CStatusMessage CApplication::initLocalSettings()
470 {
471 if (m_localSettingsLoaded)
472 {
473 return {};
474 }
475 m_localSettingsLoaded = true;
476
477 // trigger loading and saving of settings in appropriate scenarios
478 if (m_coreFacadeConfig.getMode() != CCoreFacadeConfig::Remote)
479 {
480 // facade running here locally
481 const CStatusMessage msg = CSettingsCache::instance()->loadFromStore();
482 if (msg.isFailure())
483 {
484 return msg;
485 }
486
487 // Settings are distributed via DBus. So only one application is responsible for saving. `enableLocalSave()`
488 // means "this is the application responsible for saving". If swiftgui requests a setting to be saved, it is
489 // sent to swiftcore and saved by swiftcore.
491 }
492 return {};
493 }
494
496
497 void CApplication::saveSettingsOnShutdown(bool saveSettings) { m_saveSettingsOnShutdown = saveSettings; }
498
504
506 {
507 if (keys.isEmpty())
508 {
509 return {};
510 }
511 return this->supportsContexts() ? this->getIContextApplication()->saveSettingsByKey(keys) :
513 }
514
516 {
517 static const QTemporaryDir tempDir;
518 if (tempDir.isValid())
519 {
520 return tempDir.path();
521 }
522 return QDir::tempPath();
523 }
524
526 {
528 (CBuildConfig::isReleaseBuild() ? u"Release build" : u"Debug build") % separator %
529 u"Local dev.dbg.: " % boolToYesNo(CBuildConfig::isLocalDeveloperDebugBuild()) % separator %
530 u"dev.env.: " % boolToYesNo(this->isDeveloperFlagSet()) % separator % u"distribution: " %
531 this->getOwnDistribution().toQString(true) % separator % u"Windows NT: " %
532 boolToYesNo(CBuildConfig::isRunningOnWindowsNtPlatform()) % separator % u"Linux: " %
534 boolToYesNo(CBuildConfig::isRunningOnUnixPlatform()) % separator % u"MacOS: " %
535 boolToYesNo(CBuildConfig::isRunningOnMacOSPlatform()) % separator % "Build Abi: " %
536 QSysInfo::buildAbi() % separator % u"Build CPU: " % QSysInfo::buildCpuArchitecture() % separator %
538
539 if (this->supportsContexts())
540 {
541 str += (separator % u"Supporting contexts");
542 }
543
544 return str;
545 }
546
548 int maxRedirects)
549 {
550 const CApplication::ProgressSlot progress;
551 return this->getFromNetwork(url, callback, progress, maxRedirects);
552 }
553
555 const CApplication::ProgressSlot &progress, int maxRedirects)
556 {
557 return this->getFromNetwork(url.toNetworkRequest(), NoLogRequestId, callback, progress, maxRedirects);
558 }
559
561 const CApplication::ProgressSlot &progress, int maxRedirects)
562 {
563 return this->getFromNetwork(url.toNetworkRequest(), logId, callback, progress, maxRedirects);
564 }
565
567 const CApplication::CallbackSlot &callback, int maxRedirects)
568 {
569 const CApplication::ProgressSlot progress;
570 return this->getFromNetwork(request, callback, progress, maxRedirects);
571 }
572
574 const CApplication::CallbackSlot &callback,
575 const CApplication::ProgressSlot &progress, int maxRedirects)
576 {
577 return this->getFromNetwork(request, NoLogRequestId, callback, progress, maxRedirects);
578 }
579
581 const CApplication::CallbackSlot &callback,
582 const CApplication::ProgressSlot &progress, int maxRedirects)
583 {
584 return this->httpRequestImpl(request, logId, callback, progress, maxRedirects,
585 [](QNetworkAccessManager &qam, const QNetworkRequest &request) {
586 QNetworkReply *nr = qam.get(request);
587 return nr;
588 });
589 }
590
592 const CApplication::CallbackSlot &callback, int maxRedirects)
593 {
594 const CApplication::ProgressSlot progress;
595 return this->httpRequestImpl(request, logId, callback, progress, maxRedirects,
596 [](QNetworkAccessManager &qam, const QNetworkRequest &request) {
597 QNetworkReply *nr = qam.deleteResource(request);
598 return nr;
599 });
600 }
601
603 const CSlot<void(QNetworkReply *)> &callback)
604 {
605 return this->httpRequestImpl(request, logId, callback, NoRedirects,
606 [data](QNetworkAccessManager &qam, const QNetworkRequest &request) {
607 QNetworkReply *nr = qam.post(request, data);
608 return nr;
609 });
610 }
611
613 const CSlot<void(QNetworkReply *)> &callback)
614 {
615 if (multiPart->thread() != m_accessManager->thread())
616 {
617 multiPart->moveToThread(m_accessManager->thread());
618 }
619
620 QPointer<CApplication> myself(this);
621 return httpRequestImpl(request, logId, callback, NoRedirects,
622 [=](QNetworkAccessManager &qam, const QNetworkRequest &request) {
623 QNetworkReply *nr = nullptr;
624 if (!myself)
625 {
626 return nr;
627 }
628 if (!multiPart)
629 {
630 return nr;
631 }
632 nr = qam.post(request, multiPart);
633 multiPart->setParent(nr);
634 return nr;
635 });
636 }
637
638 QNetworkReply *CApplication::headerFromNetwork(const CUrl &url, const CallbackSlot &callback, int maxRedirects)
639 {
640 return headerFromNetwork(url.toNetworkRequest(), callback, maxRedirects);
641 }
642
644 int maxRedirects)
645 {
646 return httpRequestImpl(
647 request, NoLogRequestId, callback, maxRedirects,
648 [](QNetworkAccessManager &qam, const QNetworkRequest &request) { return qam.head(request); });
649 }
650
652 const CSlot<void(const CStatusMessage &)> &callback,
653 int maxRedirects)
654 {
655 // upfront checks
656 if (url.isEmpty())
657 {
658 return nullptr;
659 }
660 if (saveAsFileName.isEmpty())
661 {
662 return nullptr;
663 }
664 const QFileInfo fi(saveAsFileName);
665 if (!fi.dir().exists())
666 {
667 return nullptr;
668 }
669
670 // function called with reply when done
671 CallbackSlot callbackSlot(this, [=, this](QNetworkReply *reply) {
673 CStatusMessage msg;
674 if (reply->error() != QNetworkReply::NoError)
675 {
676 msg = CStatusMessage(this, CStatusMessage::SeverityError, u"Download for '%1' failed: '%2'")
677 << url.getFullUrl() << nwReply->errorString();
678 }
679 else
680 {
681 const bool ok = CFileUtils::writeByteArrayToFile(reply->readAll(), saveAsFileName);
682 msg = ok ? CStatusMessage(this, CStatusMessage::SeverityInfo, u"Saved file '%1' downloaded from '%2'")
683 << saveAsFileName << url.getFullUrl() :
685 u"Saving file '%1' downloaded from '%2' failed")
686 << saveAsFileName << url.getFullUrl();
687 }
688 nwReply->close();
689 QTimer::singleShot(0, callback.object(), [=] {
690 if (!sApp || sApp->isShuttingDown())
691 {
692 return;
693 }
694 callback(msg);
695 });
696 });
697
698 ProgressSlot progressSlot(this, [=](int, qint64, qint64, const QUrl &) {
699 // so far not implemented
700 });
701
702 QNetworkReply *reply = this->getFromNetwork(url, callbackSlot, progressSlot, maxRedirects);
703 return reply;
704 }
705
706 void CApplication::deleteAllCookies() { m_cookieManager->deleteAllCookies(); }
707
708 void CApplication::exit(int retcode)
709 {
710 if (sApp)
711 {
712 instance()->gracefulShutdown();
713 }
714
715 // when the event loop is not running, this does nothing
716 QCoreApplication::exit(retcode);
717 }
718
720
722 {
723 const QStringList names = option.names();
724 if (names.isEmpty() || args.isEmpty())
725 {
726 return -1;
727 }
728 int i = -1;
729 for (const QString &arg : args)
730 {
731 i++;
732 QString a;
733 if (arg.startsWith("--"))
734 {
735 a = arg.mid(2);
736 }
737 else if (arg.startsWith("-"))
738 {
739 a = arg.mid(1);
740 }
741 else
742 {
743 continue;
744 }
745
746 if (names.contains(a, Qt::CaseInsensitive))
747 {
748 return i;
749 }
750 }
751 return -1;
752 }
753
755 {
756 const int index = indexOfCommandLineOption(option, args);
757 if (index < 0)
758 {
759 return;
760 }
761
762 // remove argument and its value
763 args.removeAt(index);
764 if (!option.valueName().isEmpty() && args.size() > index)
765 {
766 args.removeAt(index);
767 }
768 }
769
770 void CApplication::processEventsFor(int milliseconds)
771 {
772 // sApp check allows to use it in test cases without sApp
773 if (sApp && sApp->isShuttingDown())
774 {
775 return;
776 }
777 QEventLoop eventLoop;
778 QTimer::singleShot(milliseconds, &eventLoop, &QEventLoop::quit);
780 eventLoop.exec();
781 }
782
784 {
785 Q_ASSERT_X(m_parsed, Q_FUNC_INFO, "Call this function after parsing");
786
787 m_coreFacadeConfig = coreConfig;
788 const CStatusMessage msg = this->initLocalSettings();
789 if (msg.isFailure())
790 {
791 return msg;
792 }
793
794 // now we can use settings
795 // if not yet initialized, init web data services
796 if (!m_webDataServices)
797 {
800 if (msgs.hasErrorMessages())
801 {
802 return msgs;
803 }
804 }
805 return this->startCoreFacade(); // will do nothing if setup is not yet loaded
806 }
807
809 {
810 Q_ASSERT_X(m_parsed, Q_FUNC_INFO, "Call this function after parsing");
811
812 m_coreFacadeConfig = CCoreFacadeConfig(CCoreFacadeConfig::NotUsed);
813 const CStatusMessage msg = this->initLocalSettings();
814 if (msg.isFailure())
815 {
816 return msg;
817 }
818
819 return this->startCoreFacade(); // will do nothing if setup is not yet loaded
820 }
821
823 const db::CDatabaseReaderConfigList &dbReaderConfig)
824 {
825 Q_ASSERT_X(m_webDataServices.isNull(), Q_FUNC_INFO, "Services already started");
826 SWIFT_VERIFY_X(QSslSocket::supportsSsl(), Q_FUNC_INFO, "No SSL");
828 {
829 return CStatusMessage(this).error(u"No SSL supported, can`t be used");
830 }
831
832 return this->startWebDataServices(webReader, dbReaderConfig);
833 }
834
836 {
837 return this->getIContextApplication() && this->getIContextApplication()->isUsingImplementingObject();
838 }
839
841 {
842 return this->getIContextApplication() && !this->getIContextApplication()->isUsingImplementingObject() &&
843 !this->getIContextApplication()->isEmptyObject();
844 }
845
847 {
848 Q_ASSERT_X(m_parsed, Q_FUNC_INFO, "Call this function after parsing");
849
850 if (!m_setupReader || !m_setupReader->isSetupAvailable())
851 {
852 return CStatusMessage(this).error(u"No setup reader or setup available");
853 }
854
855 Q_ASSERT_X(m_coreFacade.isNull(), Q_FUNC_INFO, "Cannot alter facade");
856 Q_ASSERT_X(m_setupReader, Q_FUNC_INFO, "No facade without setup possible");
857 Q_ASSERT_X(m_webDataServices, Q_FUNC_INFO, "Need running web data services");
858
859 const CStatusMessageList msgs(CStatusMessage(this).info(u"Will start core facade now"));
860 m_coreFacade.reset(new CCoreFacade(m_coreFacadeConfig));
861 emit this->coreFacadeStarted();
862 return msgs;
863 }
864
865 CStatusMessageList CApplication::startWebDataServices(CWebReaderFlags::WebReader webReader,
866 const db::CDatabaseReaderConfigList &dbReaderConfig)
867 {
868 Q_ASSERT_X(m_parsed, Q_FUNC_INFO, "Call this function after parsing");
869
870 if (!m_setupReader || !m_setupReader->isSetupAvailable())
871 {
872 return CStatusMessage(this).error(u"No setup reader or setup available");
873 }
874
875 Q_ASSERT_X(m_setupReader, Q_FUNC_INFO, "No web data services without setup possible");
877 if (!m_webDataServices)
878 {
879 msgs.push_back(CStatusMessage(this).info(u"Will start web data services now"));
880 m_webDataServices.reset(new CWebDataServices(webReader, dbReaderConfig, this));
881 Q_ASSERT_X(m_webDataServices, Q_FUNC_INFO, "Missing web services");
882
883 emit this->webDataServicesStarted(true);
884 }
885 else
886 {
887 msgs.push_back(CStatusMessage(this).info(u"Web data services already running"));
888 }
889
890 return msgs;
891 }
892
893 void CApplication::initLogging()
894 {
895 CLogHandler::instance()->install(); // make sure we have a log handler!
896
897 // File logger
898 m_fileLogger.reset(new CFileLogger(this));
899 connect(CLogHandler::instance(), &CLogHandler::localMessageLogged, m_fileLogger.data(),
901 connect(CLogHandler::instance(), &CLogHandler::remoteMessageLogged, m_fileLogger.data(),
903 m_fileLogger->changeLogPattern(CLogPattern().withSeverityAtOrAbove(CStatusMessage::SeverityDebug));
904 }
905
906 void CApplication::initParser()
907 {
908 m_parser.setSingleDashWordOptionMode(QCommandLineParser::ParseAsLongOptions);
909 m_parser.setApplicationDescription(m_applicationName);
910 m_cmdHelp = m_parser.addHelpOption();
911 m_cmdVersion = m_parser.addVersionOption();
912 m_allOptions.append(m_cmdHelp);
913 m_allOptions.append(m_cmdVersion);
914
915 // dev. system
916 m_cmdDevelopment = QCommandLineOption({ "dev", "development" },
917 QCoreApplication::translate("application", "Dev. system features?"));
918 this->addParserOption(m_cmdDevelopment);
919
920 // Skip single application check
921 m_cmdSkipSingleApp = QCommandLineOption(
922 { "skipsa", "skipsingleapp" }, QCoreApplication::translate("application", "Skip the single app.test."));
923 this->addParserOption(m_cmdSkipSingleApp);
924
925 // reset caches upfront
926 m_cmdClearCache = QCommandLineOption({ "ccache", "clearcache" },
927 QCoreApplication::translate("application", "Clear (reset) the caches."));
928 this->addParserOption(m_cmdClearCache);
929
930 // test crashpad upload
931 m_cmdTestCrashpad = QCommandLineOption(
932 { "testcp", "testcrashpad" }, QCoreApplication::translate("application", "Trigger crashpad situation."));
933 this->addParserOption(m_cmdTestCrashpad);
934 }
935
936 bool CApplication::isSet(const QCommandLineOption &option) const { return (m_parser.isSet(option)); }
937
943
945 {
946 const QStringList files(CDataCache::instance()->enumerateStore());
948 return files;
949 }
950
952 {
953 if (m_shutdown)
954 {
955 return;
956 }
958 {
959 return;
960 }
962
963 CLogMessage(this).info(u"Graceful shutdown of CApplication started");
964
965 // info that we will shutdown
966 emit this->aboutToShutdown();
967
968 // Release all input devices to not cause any accidental hotkey triggers anymore.
969 // This is also necessary to properly free platform specific instances at a defined point in time.
970 if (m_inputManager)
971 {
972 CLogMessage(this).info(u"Graceful shutdown of CApplication, released devices");
973 m_inputManager->releaseDevices();
974 }
975
976 // save settings (but only when application was really alive)
977 if (m_parsed && m_saveSettingsOnShutdown)
978 {
979 const CStatusMessage m = this->supportsContexts() ? this->getIContextApplication()->saveSettings() :
982 }
983
984 // from here on we really rip apart the application object
985 // and it should no longer be used
986
987 if (this->supportsContexts(true))
988 {
989 CLogMessage(this).info(u"Graceful shutdown of CApplication, shutdown of contexts");
990
991 // clean up facade
992 m_coreFacade->gracefulShutdown();
993 m_coreFacade.reset();
994 }
995
996 if (m_webDataServices)
997 {
998 CLogMessage(this).info(u"Graceful shutdown of CApplication, shutdown of web services");
999
1000 m_webDataServices->gracefulShutdown();
1001 m_webDataServices.reset();
1002 }
1003
1004 if (m_gitHubPackagesReader)
1005 {
1006 m_gitHubPackagesReader.reset();
1007 }
1008
1009 if (m_setupReader)
1010 {
1011 m_setupReader.reset();
1012 }
1013
1014 CLogMessage(this).info(u"Graceful shutdown of CApplication, shutdown of logger");
1015 m_fileLogger->close();
1016
1017 // clean up all in "deferred delete state"
1018 qApp->sendPostedEvents(nullptr, QEvent::DeferredDelete);
1019 processEventsFor(500);
1020
1021 // completed
1022 m_shutdown = true;
1023 sApp = nullptr;
1024
1025 disconnect(this);
1026 }
1027
1029 {
1030 // void
1031 }
1032
1033 void CApplication::initNetwork()
1034 {
1035 if (!m_accessManager)
1036 {
1037 m_accessManager = new QNetworkAccessManager(this);
1038 }
1039
1040 m_cookieManager = new CCookieManager(this);
1041 m_cookieManager->setParent(m_accessManager);
1042 m_accessManager->setCookieJar(m_cookieManager);
1043
1044 // Init network
1045 Q_ASSERT_X(m_accessManager, Q_FUNC_INFO, "Need QAM");
1046 }
1047
1049
1051 {
1052 static const QString e(QFileInfo(QCoreApplication::applicationFilePath()).completeBaseName());
1053 return e;
1054 }
1055
1057 {
1058 static const QStringList l({ "swift.application", "swift." % executable() });
1059 return l;
1060 }
1061
1062 // ---------------------------------------------------------------------------------
1063 // Parsing
1064 // ---------------------------------------------------------------------------------
1065
1067 {
1068 m_allOptions.append(option);
1069 return m_parser.addOption(option);
1070 }
1071
1073 {
1074 m_allOptions.append(options);
1075 return m_parser.addOptions(options);
1076 }
1077
1079 {
1081 { "dbus", "dbusaddress" },
1082 QCoreApplication::translate("application", "DBus address (session, system, P2P IP e.g. 192.168.23.5)"),
1083 "dbusaddress");
1085 }
1086
1088
1090 {
1092 {
1093 return {};
1094 }
1095 const QString v(this->getParserValue(m_cmdDBusAddress));
1096 const QString dBusAddress(CDBusServer::normalizeAddress(v));
1097 return dBusAddress;
1098 }
1099
1100 bool CApplication::isParserOptionSet(const QString &option) const { return m_parser.isSet(option); }
1101
1103
1104 bool CApplication::isParserOptionSet(const QCommandLineOption &option) const { return m_parser.isSet(option); }
1105
1106 QString CApplication::getParserValue(const QString &option) const { return m_parser.value(option).trimmed(); }
1107
1109 {
1110 return m_parser.value(option).trimmed();
1111 }
1112
1114 {
1115 if (!this->startupCheck()) return false;
1116 if (!this->parseCommandLineArguments()) return false;
1117 if (!this->loadSetupAndHandleErrors()) return false;
1118 return true;
1119 }
1120
1121 bool CApplication::parseCommandLineArguments()
1122 {
1123 if (m_parsed)
1124 {
1125 return m_parsed;
1126 } // already done
1127
1128 // we call parse because we also want to display a GUI error message when applicable
1130 if (!m_parser.parse(args))
1131 {
1132 this->cmdLineErrorMessage("Parser error:", m_parser.errorText());
1133 return false;
1134 }
1135
1136 if (m_alreadyRunning && !this->skipSingleApplicationCheck())
1137 {
1138 this->cmdLineErrorMessage("Program must only run once",
1139 "You cannot run two or more instances side-by-side.");
1140 return false;
1141 }
1142
1143 // help/version
1144 if (m_parser.isSet(m_cmdHelp))
1145 {
1146 // Important: parser help will already stop application
1147 this->cmdLineHelpMessage();
1148 return false;
1149 }
1150 if (m_parser.isSet(m_cmdVersion))
1151 {
1152 // Important: version will already stop application
1153 this->cmdLineVersionMessage();
1154 return false;
1155 }
1156
1157 // dev.
1158 m_devFlag = this->initIsRunningInDeveloperEnvironment();
1159
1160 // Hookin, other parsing
1161 if (!this->parsingHookIn())
1162 {
1163 return false;
1164 }
1165
1166 // setup reader
1167 m_parsed = true;
1168 return true;
1169 }
1170
1171 bool CApplication::startupCheck() const
1172 {
1173 const QStringList verifyErrors = CSwiftDirectories::verifyRuntimeDirectoriesAndFiles();
1174 if (!verifyErrors.isEmpty() && !m_applicationInfo.isUnitTest())
1175 {
1176 cmdLineErrorMessage("Missing runtime directories/files:", verifyErrors.join(", "));
1177 return false;
1178 }
1179 return true;
1180 }
1181
1182 bool CApplication::loadSetupAndHandleErrors()
1183 {
1184 const CStatusMessageList msgs = loadSetup();
1185
1186 if (msgs.isFailure())
1187 {
1188 displaySetupLoadFailure(msgs);
1189 }
1190 return msgs.isSuccess();
1191 }
1192
1194 {
1195 // Ignore for CLI application
1196 // Already logged to console
1197 }
1198
1199 void CApplication::cmdLineErrorMessage(const QString &text, const QString &informativeText) const
1200 {
1201 fputs(qPrintable(text + informativeText), stderr);
1202 }
1203
1205 {
1206 if (msgs.isEmpty())
1207 {
1208 return;
1209 }
1210 if (!msgs.hasErrorMessages())
1211 {
1212 return;
1213 }
1215 }
1216
1218 {
1219 if (!this->hasSimulator())
1220 {
1221 return nullptr;
1222 }
1223 return this->getCoreFacade()->getCContextSimulator()->simulator();
1224 }
1225
1227 {
1228 if (!this->getCoreFacade())
1229 {
1230 return false;
1231 }
1232 if (!this->getCoreFacade()->getIContextSimulator()->isUsingImplementingObject())
1233 {
1234 return false;
1235 }
1236 return (this->getCoreFacade()->getCContextSimulator()); // should always be true
1237 }
1238
1239 void CApplication::cmdLineHelpMessage()
1240 {
1241 m_parser.showHelp(); // terminates
1242 Q_UNREACHABLE();
1243 }
1244
1245 void CApplication::cmdLineVersionMessage()
1246 {
1247 m_parser.showVersion(); // terminates
1248 Q_UNREACHABLE();
1249 }
1250
1251 QStringList CApplication::argumentsJoined(const QStringList &newArguments, const QStringList &removeArguments) const
1252 {
1253 QStringList joinedArguments = CApplication::arguments();
1254 QStringList newArgumentsChecked = newArguments;
1255
1256 // remove the executable argument if it exists at position 0
1257 if (!joinedArguments.isEmpty() && !joinedArguments.at(0).startsWith("-"))
1258 {
1259 joinedArguments.removeFirst();
1260 } // was cmd line argument
1261 if (!newArgumentsChecked.isEmpty() && !newArgumentsChecked.at(0).startsWith("-"))
1262 {
1263 newArgumentsChecked.removeFirst();
1264 } // was cmd line argument
1265
1266 // remove all values before checking options
1267 static const QRegularExpression regExp("^-");
1268 QStringList toBeRemoved(newArgumentsChecked.filter(regExp));
1269 toBeRemoved.append(removeArguments.filter(regExp));
1270 toBeRemoved.append("--installer");
1271 toBeRemoved.removeDuplicates();
1272
1273 if (!joinedArguments.isEmpty() && !toBeRemoved.isEmpty())
1274 {
1275 // remove all options from removeArguments
1276 // consider alias names, that is why we check on option
1277 for (const QCommandLineOption &option : m_allOptions)
1278 {
1279 const int n = indexOfCommandLineOption(option, toBeRemoved);
1280 if (n >= 0)
1281 {
1282 argumentsWithoutOption(option, joinedArguments);
1283 }
1284 }
1285 }
1286
1287 joinedArguments.append(newArgumentsChecked);
1288 return joinedArguments;
1289 }
1290
1291 // ---------------------------------------------------------------------------------
1292 // Contexts
1293 // ---------------------------------------------------------------------------------
1294
1296
1297 bool CApplication::supportsContexts(bool ignoreShutdownTest) const
1298 {
1299 if (!ignoreShutdownTest && m_shutdown)
1300 {
1301 return false;
1302 }
1303 if (m_coreFacade.isNull())
1304 {
1305 return false;
1306 }
1307 if (!m_coreFacade->getIContextApplication())
1308 {
1309 return false;
1310 }
1311 return (!m_coreFacade->getIContextApplication()->isEmptyObject());
1312 }
1313
1315 {
1316 if (!supportsContexts())
1317 {
1318 return nullptr;
1319 }
1320 return m_coreFacade->getIContextNetwork();
1321 }
1322
1324 {
1325 if (!supportsContexts())
1326 {
1327 return nullptr;
1328 }
1329 return m_coreFacade->getIContextAudio();
1330 }
1331
1333 {
1334 if (!supportsContexts())
1335 {
1336 return nullptr;
1337 }
1338 return m_coreFacade->getCContextAudioBase();
1339 }
1340
1342 {
1343 if (!supportsContexts())
1344 {
1345 return nullptr;
1346 }
1347 return m_coreFacade->getIContextApplication();
1348 }
1349
1351 {
1352 if (!supportsContexts())
1353 {
1354 return nullptr;
1355 }
1356 return m_coreFacade->getIContextOwnAircraft();
1357 }
1358
1360 {
1361 if (!supportsContexts())
1362 {
1363 return nullptr;
1364 }
1365 return m_coreFacade->getIContextSimulator();
1366 }
1367
1369 {
1370 if (!supportsContexts())
1371 {
1372 return nullptr;
1373 }
1374 return m_coreFacade->getIContextNetwork();
1375 }
1376
1378 {
1379 if (!supportsContexts())
1380 {
1381 return nullptr;
1382 }
1383 return m_coreFacade->getIContextAudio();
1384 }
1385
1387 {
1388 if (!supportsContexts())
1389 {
1390 return nullptr;
1391 }
1392 return m_coreFacade->getCContextAudioBase();
1393 }
1394
1396 {
1397 if (!supportsContexts())
1398 {
1399 return nullptr;
1400 }
1401 return m_coreFacade->getIContextApplication();
1402 }
1403
1405 {
1406 if (!supportsContexts())
1407 {
1408 return nullptr;
1409 }
1410 return m_coreFacade->getIContextOwnAircraft();
1411 }
1412
1414 {
1415 if (!supportsContexts())
1416 {
1417 return nullptr;
1418 }
1419 return m_coreFacade->getIContextSimulator();
1420 }
1421
1423 {
1424 // void
1425 }
1426
1427 // ---------------------------------------------------------------------------------
1428 // Setup
1429 // ---------------------------------------------------------------------------------
1430
1431 bool CApplication::hasSetupReader() const { return !m_setupReader.isNull(); }
1432
1433 CSetupReader *CApplication::getSetupReader() const { return m_setupReader.data(); }
1434
1435 CStatusMessageList CApplication::loadSetup()
1436 {
1437 if (m_shutdown)
1438 {
1439 return CStatusMessage(this).warning(u"Shutting down, not reading");
1440 }
1441 if (!m_setupReader)
1442 {
1443 return CStatusMessage(this).error(u"No reader for setup/version");
1444 }
1445 Q_ASSERT_X(m_parsed, Q_FUNC_INFO, "Not yet parsed");
1446 const CStatusMessageList requestMsgs = m_setupReader->loadSetup();
1447 return requestMsgs;
1448 }
1449
1451 {
1452 if (m_shutdown)
1453 {
1454 return {};
1455 }
1456 if (m_webDataServices)
1457 {
1458 const CUrl url(m_webDataServices->getVatsimMetarUrl());
1459 if (!url.isEmpty())
1460 {
1461 return url;
1462 }
1463 }
1464 if (m_setupReader)
1465 {
1466 return m_setupReader->getSetup().getVatsimMetarsUrl();
1467 }
1468 return {};
1469 }
1470
1472 {
1473 if (m_shutdown)
1474 {
1475 return {};
1476 }
1477 if (m_webDataServices)
1478 {
1479 const CUrl url(m_webDataServices->getVatsimDataFileUrl());
1480 if (!url.isEmpty())
1481 {
1482 return url;
1483 }
1484 }
1485 if (m_setupReader)
1486 {
1487 return m_setupReader->getSetup().getVatsimDataFileUrl();
1488 }
1489 return {};
1490 }
1491
1493 {
1494 if (m_shutdown || !m_setupReader)
1495 {
1496 return {};
1497 }
1498
1499 return m_setupReader->getSetup().getVatsimServerFileUrl();
1500 }
1501
1503 {
1504 if (m_shutdown || !m_setupReader)
1505 {
1506 return {};
1507 }
1508
1509 return m_setupReader->getSetup().getVatsimFsdHttpUrl();
1510 }
1511
1512 void CApplication::onCrashDumpUploadEnabledChanged()
1513 {
1514 const bool enabled = CBuildConfig::isReleaseBuild() && m_crashDumpUploadEnabled.getThreadLocal();
1515 this->enableCrashDumpUpload(enabled);
1516 }
1517
1518 void CApplication::simulateCrash() { CCrashHandler::instance()->simulateCrash(); }
1519
1520 void CApplication::simulateAssert() { CCrashHandler::instance()->simulateAssert(); }
1521
1523
1525 {
1526#ifdef SWIFT_USE_CRASHPAD
1527 return true;
1528#else
1529 return false;
1530#endif
1531 }
1532
1533 void CApplication::httpRequestImplInQAMThread(const QNetworkRequest &request, int logId,
1534 const CallbackSlot &callback, const ProgressSlot &progress,
1535 int maxRedirects, NetworkRequestOrPostFunction getPostOrDeleteRequest)
1536 {
1537 // run in QAM thread
1538 if (this->isShuttingDown())
1539 {
1540 return;
1541 }
1542 QTimer::singleShot(0, m_accessManager, [=, this] {
1543 // should be now in QAM thread
1544 if (!sApp || sApp->isShuttingDown())
1545 {
1546 return;
1547 }
1548 Q_ASSERT_X(CThreadUtils::isInThisThread(sApp->m_accessManager), Q_FUNC_INFO,
1549 "Wrong thread, must be QAM thread");
1550 this->httpRequestImpl(request, logId, callback, progress, maxRedirects, getPostOrDeleteRequest);
1551 });
1552 }
1553
1554 QNetworkReply *CApplication::httpRequestImpl(const QNetworkRequest &request, int logId,
1555 const CApplication::CallbackSlot &callback, int maxRedirects,
1556 NetworkRequestOrPostFunction requestOrPostMethod)
1557 {
1558 ProgressSlot progress;
1559 return this->httpRequestImpl(request, logId, callback, progress, maxRedirects, requestOrPostMethod);
1560 }
1561
1562 QNetworkReply *CApplication::httpRequestImpl(const QNetworkRequest &request, int logId,
1563 const CallbackSlot &callback, const ProgressSlot &progress,
1564 int maxRedirects, NetworkRequestOrPostFunction getPostOrDeleteRequest)
1565 {
1566 if (this->isShuttingDown())
1567 {
1568 return nullptr;
1569 }
1570
1571 QWriteLocker locker(&m_accessManagerLock);
1572 Q_ASSERT_X(m_accessManager->thread() == qApp->thread(), Q_FUNC_INFO,
1573 "Network manager supposed to be in main thread");
1574 if (!CThreadUtils::isInThisThread(m_accessManager))
1575 {
1576 this->httpRequestImplInQAMThread(request, logId, callback, progress, maxRedirects, getPostOrDeleteRequest);
1577 return nullptr; // not yet started, will be called again in QAM thread
1578 }
1579
1580 Q_ASSERT_X(CThreadUtils::isInThisThread(m_accessManager), Q_FUNC_INFO, "Network manager thread mismatch");
1581 QNetworkRequest copiedRequest =
1582 CNetworkUtils::getSwiftNetworkRequest(request, this->getApplicationNameAndVersion());
1583
1584 QNetworkReply *reply = getPostOrDeleteRequest(*m_accessManager, copiedRequest);
1585 reply->setProperty("started", QVariant(QDateTime::currentMSecsSinceEpoch()));
1586 reply->setProperty(CUrlLog::propertyNameId(), QVariant(logId));
1587 const QUrl url(reply->url());
1588 QString urlStr = url.toString();
1589
1590 if (progress)
1591 {
1592 connect(reply, &QNetworkReply::downloadProgress, progress.object(),
1593 [=](qint64 current, qint64 max) { progress(logId, current, max, url); });
1594 }
1595
1596 if (callback)
1597 {
1598 Q_ASSERT_X(callback.object(), Q_FUNC_INFO, "Need callback object (to determine thread)");
1599 connect(
1600 reply, &QNetworkReply::finished, callback.object(),
1601 [=, this] {
1602 // Called when finished!
1603 // QNetworkRequest::FollowRedirectsAttribute would allow auto redirect, but we use our approach as
1604 // it gives us better control \fixme: Check again on Qt 5.9: Added redirects policy to
1605 // QNetworkAccessManager (ManualRedirectsPolicy, NoLessSafeRedirectsPolicy,
1606 // SameOriginRedirectsPolicy, UserVerifiedRedirectsPolicy)
1607 const bool isRedirect = CNetworkUtils::isHttpStatusRedirect(reply);
1608 if (isRedirect && maxRedirects > 0)
1609 {
1610 const QUrl redirectUrl = CNetworkUtils::getHttpRedirectUrl(reply);
1611 if (!redirectUrl.isEmpty())
1612 {
1613 QNetworkRequest redirectRequest(redirectUrl);
1614 const int redirectsLeft = maxRedirects - 1;
1615 CLogMessage(sApp).info(u"Redirecting '%1' to '%2'") << urlStr << redirectUrl.toString();
1616 this->httpRequestImplInQAMThread(redirectRequest, logId, callback, progress, redirectsLeft,
1617 getPostOrDeleteRequest);
1618 return;
1619 }
1620 }
1621 // called when there are no more callbacks
1622 callback(reply);
1623 },
1624 Qt::QueuedConnection); // called in callback thread
1625 }
1626 return reply;
1627 }
1628
1629 void CApplication::tagApplicationDataDirectory()
1630 {
1632 const QDir dir(d);
1633 if (!dir.exists() || !dir.isReadable())
1634 {
1635 return;
1636 }
1637 const QString aiStr(this->getApplicationInfo().toJsonString());
1638 const QString filePath(CFileUtils::appendFilePaths(
1639 dir.path(), CApplicationInfo::fileName())); // will be overridden by next swift app
1640 CFileUtils::writeStringToFile(aiStr, filePath);
1641 }
1642} // namespace swift::core
static const QString & getVersionString()
Version as QVersionNumber.
static constexpr bool isReleaseBuild()
Release build?
static constexpr bool isRunningOnUnixPlatform()
Running on Unix (Linux or Mac OS X) platform.
static constexpr bool isRunningOnMacOSPlatform()
Running on MacOS platform?
static bool isLocalDeveloperDebugBuild()
Local build for developers.
static constexpr bool isRunningOnWindowsNtPlatform()
Running on Windows NT platform?
static constexpr bool isRunningOnLinuxPlatform()
Running on Linux platform?
static const QString & compiledWithInfo()
Info string about compilation.
static const QString & getVersionStringPlatform()
Version as QVersionNumber plus platform info.
swift::misc::CStatusMessageList startCoreFacadeWithoutContexts()
Starts the core facade without any contexts.
static void argumentsWithoutOption(const QCommandLineOption &option, QStringList &args)
Arguments without that given option.
void aboutToShutdown()
About to shutdown.
QStringList argumentsJoined(const QStringList &newArguments={}, const QStringList &removeArguments={}) const
Current parameters replaced by new arguments without the cmd line argument.
const QString & versionStringDetailed() const
String with beta, dev. and version.
swift::misc::CSlot< void(QNetworkReply *)> CallbackSlot
The network reply callback when request is completed.
swift::misc::shared_state::CDataLinkDBus * getDataLinkDBus()
Transport mechanism for sharing state between applications.
swift::misc::CStatusMessageList startCoreFacade()
Start the core facade.
const context::IContextAudio * getIContextAudio() const
Direct access to contexts if a CCoreFacade has been initialized.
QString getParserValue(const QString &option) const
Delegates to QCommandLineParser::value.
void addAudioOptions()
Add the audio options.
bool addParserOptions(const QList< QCommandLineOption > &options)
QNetworkReply * getFromNetwork(const swift::misc::network::CUrl &url, const CallbackSlot &callback, int maxRedirects=DefaultMaxRedirects)
Request to get network reply.
QNetworkReply * downloadFromNetwork(const swift::misc::network::CUrl &url, const QString &saveAsFileName, const swift::misc::CSlot< void(const swift::misc::CStatusMessage &)> &callback, int maxRedirects=DefaultMaxRedirects)
Download file from network and store it as passed.
bool hasSetupReader() const
Setup reader?
swift::misc::network::CUrl getVatsimServerFileUrl() const
Get URL to file which contains the list of VATSIM servers.
virtual void displaySetupLoadFailure(swift::misc::CStatusMessageList msgs)
Display the failures caused by loading the setup file.
const context::IContextOwnAircraft * getIContextOwnAircraft() const
Direct access to contexts if a CCoreFacade has been initialized.
std::atomic_bool m_shutdown
Is being shutdown?
QPointer< ISimulator > getISimulator() const
The simulator plugin, if available.
void restartApplication(const QStringList &newArguments={}, const QStringList &removeArguments={})
Stop and restart application.
bool hasSimulator() const
Simulator object available?
bool m_parsed
Parsing accomplished?
swift::misc::network::CUrl getVatsimMetarUrl() const
Consolidated version of METAR URLs, either from CGlobalSetup or CVatsimSetup.
bool isParserOptionSet(const QString &option) const
Delegates to QCommandLineParser::isSet.
static const QString & executable()
executable name
swift::misc::CStatusMessageList startWebDataServices(CWebReaderFlags::WebReader webReader, const db::CDatabaseReaderConfigList &dbReaderConfig)
Start the web data services.
data::CGlobalSetup getGlobalSetup() const
Global setup.
static constexpr int NoLogRequestId
network request without logging
bool isDeveloperFlagSet() const
Running with dev.flag?
swift::misc::db::CDistribution getOwnDistribution() const
Own distribution.
bool m_alreadyRunning
Application already running.
const char * swiftVersionChar()
swift info string
std::atomic_bool m_incognito
Incognito mode?
QCommandLineOption m_cmdClearCache
Clear cache.
const swift::misc::CApplicationInfo & getApplicationInfo() const
swift application running
const context::IContextApplication * getIContextApplication() const
Direct access to contexts if a CCoreFacade has been initialized.
QCommandLineOption m_cmdDBusAddress
DBus address.
virtual void onStartUpCompleted()
Startup completed.
swift::misc::CStatusMessageList initAndStartWebDataServices(CWebReaderFlags::WebReader webReader, const db::CDatabaseReaderConfigList &dbReaderConfig)
Init web data services and start them.
static bool unregisterAsRunning()
Unregister from running.
bool parseCommandLineArgsAndLoadSetup()
Combined function that does a startup check, parses the command line arguments and loads the setup.
QString getCmdDBusAddressValue() const
DBus address from CMD line, otherwise "".
bool skipSingleApplicationCheck() const
Skip the single application check.
QCommandLineParser m_parser
cmd parser
bool isIncognito() const
Is incognito mode?
static void processEventsFor(int milliseconds)
Process all events for some time.
bool hasUnsavedSettings() const
Unsaved settings.
QNetworkReply * postToNetwork(const QNetworkRequest &request, int logId, const QByteArray &data, const CallbackSlot &callback)
Post to network.
virtual void onCoreFacadeStarted()
Called when facade/contexts have been started.
const QString & swiftVersionString() const
swift info string
void coreFacadeStarted()
Facade started.
QList< QCommandLineOption > m_allOptions
All registered options.
void setIncognito(bool incognito)
Set incognito mode.
static QString getTemporaryDirectory()
Directory for temporary files.
void addDBusAddressOption()
CMD line argument for DBus address.
bool hasWebDataServices() const
Web data services available?
static const QStringList & getLogCategories()
Own log categories.
virtual void cmdLineErrorMessage(const QString &text, const QString &informativeText) const
Display error message.
void init(bool withMetadata)
Init class, allows to init from swift::gui::CGuiApplication as well (pseudo virtual).
swift::misc::network::CUrl getVatsimFsdHttpUrl() const
Get VATSIM FSD HTTP URL.
const context::IContextNetwork * getIContextNetwork() const
Direct access to contexts if a CCoreFacade has been initialized.
swift::misc::CStatusMessageList initContextsAndStartCoreFacade(const CCoreFacadeConfig &coreConfig)
Init the contexts part and start core facade.
void updateInfoAvailable(bool success)
Update info available (cache, web load).
swift::misc::CStatusMessage saveSettingsByKey(const QStringList &keys)
Save all settings.
CApplication(swift::misc::CApplicationInfo::Application application, bool init=true)
Constructor.
static void exit(int retcode=EXIT_SUCCESS)
Exit application, perform graceful shutdown and exit.
void deleteAllCookies()
Delete all cookies from cookie manager.
bool addParserOption(const QCommandLineOption &option)
bool isDBusContext() const
DBus application? (not Local).
QString getInfoString(const QString &separator) const
Comprehensive info.
bool isShuttingDown() const
Is application shutting down?
QNetworkReply * deleteResourceFromNetwork(const QNetworkRequest &request, int logId, const CallbackSlot &callback, int maxRedirects=DefaultMaxRedirects)
Request to delete a network resource from network, supporting swift::misc::network::CUrlLog.
static constexpr int NoRedirects
network request not allowing redirects
QCommandLineOption m_cmdDevelopment
Development flag.
const context::IContextSimulator * getIContextSimulator() const
Direct access to contexts if a CCoreFacade has been initialized.
bool isSet(const QCommandLineOption &option) const
Flag set or explicitly set to true.
std::atomic_bool m_shutdownInProgress
shutdown in progress?
static swift::misc::CApplicationInfoList getRunningApplications()
Information about all running apps (including this one only if exec() has already been called).
QStringList getUnsavedSettingsKeys() const
All unsaved settings.
const QString & getApplicationNameVersionDetailed() const
Version, name beta and dev info.
void toggleIncognito()
Toggle incognito mode.
virtual swift::misc::CStatusMessageList startHookIn()
Can be used to start special services.
CSetupReader * getSetupReader() const
Access to setup reader.
static bool isApplicationRunning(swift::misc::CApplicationInfo::Application application)
Is application running?
CCoreFacade * getCoreFacade()
Get the facade.
bool m_started
Started with success?
swift::misc::db::CUpdateInfo getUpdateInfo() const
Update info.
swift::misc::network::CUrl getVatsimDataFileUrl() const
Consolidated version of data file URL, either from CGlobalSetup or CVatsimSetup.
QCommandLineOption m_cmdSkipSingleApp
Skip test for single application.
bool isSetupAvailable() const
Setup already synchronized.
static QStringList clearCaches()
Clear the caches.
void webDataServicesStarted(bool success)
Web data services started.
virtual bool start()
Start services, if not yet parsed call CApplication::parse.
const context::CContextAudioBase * getCContextAudioBase() const
Direct access to contexts if a CCoreFacade has been initialized.
bool supportsContexts(bool ignoreShutdownTest=false) const
Supports contexts.
static int indexOfCommandLineOption(const QCommandLineOption &option, const QStringList &args=CApplication::arguments())
Is the command line option represented in the given arguments?
void reloadUpdateInfo()
Reload update info.
swift::misc::CSlot< void(int, qint64, qint64, const QUrl &)> ProgressSlot
The progress slot.
CWebDataServices * getWebDataServices() const
Get the web data services.
int exec()
Finishes initialization and executes the event loop.
const QString & getApplicationNameAndVersion() const
Application name and version.
bool isLocalContext() const
Local application? (not DBus).
virtual void gracefulShutdown()
Graceful shutdown.
void enableCrashDumpUpload(bool enable)
Enable crash upload.
static QStringList arguments()
Similar to QCoreApplication::arguments.
void saveSettingsOnShutdown(bool saveSettings)
Save settings on shutdown.
QCommandLineOption m_cmdTestCrashpad
Test a crasphpad upload.
static void registerMetadata()
Register metadata.
bool isAlreadyRunning() const
True if this swift application is already running (including different versions).
virtual bool hasMinimumMappingVersion() const
Minimum mapping version check.
bool isSupportingCrashpad() const
Has crashpad support?
void startUpCompleted(bool success)
Startup has been completed Will be triggered shortly before starting the event loop.
QNetworkReply * headerFromNetwork(const swift::misc::network::CUrl &url, const CallbackSlot &callback, int maxRedirects=NoRedirects)
Request to get network repy using HTTP's HEADER method.
static CApplication * instance()
Similar to.
static bool registerAsRunning()
Register as running.
Configuration object for the contexts.
@ NotUsed
during shutdown or not used at all
@ Remote
context runs in a different process.
The class providing facades (the contexts) for all DBus relevant operations.
Definition corefacade.h:57
Read available updates from GitHub Packages REST API.
void updateInfoAvailable(bool available)
Updates have been received from GitHub Packages.
Input manager handling hotkey function calls.
Read the central URLs / locations of our data, setup and versions.
Definition setupreader.h:36
data::CGlobalSetup getSetup() const
Current setup (reader URLs, DB location, crash server).
Encapsulates reading data from web sources.
static const QList< QCommandLineOption > & getCmdLineOptions()
Cmd.line arguments.
virtual misc::CStatusMessage saveSettingsByKey(const QStringList &keys)=0
Save core settings to disk.
virtual QStringList getUnsavedSettingsKeys() const =0
Get keys of all unsaved settings currently in core settings cache.
Audio context interface.
const IContextSimulator * getIContextSimulator() const
Context for simulator.
Definition context.cpp:72
IContextNetwork * getIContextNetwork()
Context for network.
Definition context.cpp:29
const IContextApplication * getIContextApplication() const
Context for application.
Definition context.cpp:39
IContextAudio * getIContextAudio()
Context for network.
Definition context.cpp:33
IContextOwnAircraft * getIContextOwnAircraft()
Context for own aircraft.
Definition context.cpp:44
Global settings for readers, debug flags, etc.
Definition globalsetup.h:31
Value object encapsulating a list of reader configs.
static CDatabaseReaderConfigList forPilotClient()
Init for pilot client.
Description of a swift application.
Application getApplication() const
Get application.
static const QString & fileName()
File name of the application info file.
Application
Enumeration of application roles.
const CProcessInfo & getProcessInfo() const
Get process info.
List of swift application descriptions.
bool containsApplication(CApplicationInfo::Application application) const
List containing entry for CApplicationInfo::Application ?
QString toJsonString(QJsonDocument::JsonFormat format=QJsonDocument::Indented) const
Convenience function JSON as string.
CStatusMessage convertFromJsonNoThrow(const QJsonObject &json, const CLogCategoryList &categories, const QString &prefix)
Call convertFromJson, catch any CJsonException that is thrown and return it as CStatusMessage.
static CCrashHandler * instance()
Get singleton instance.
void setUploadsEnabled(bool enable)
Enable/disable automatic uploading.
void simulateAssert()
Simulate an ASSERT.
void simulateCrash()
Simulate a crash.
static QString normalizeAddress(const QString &address)
Turn something like 127.0.0.1:45000 into "tcp:host=127.0.0.1,port=45000".
static CDataCache * instance()
Return the singleton instance.
Class to write log messages to file.
Definition filelogger.h:22
void writeStatusMessageToFile(const swift::misc::CStatusMessage &statusMessage)
Write single status message to file.
static QString readLockedFileToString(const QString &fileNameAndPath)
Read file into string, with a lock so two applications can't access at the same time.
Definition fileutils.cpp:96
static bool writeStringToFile(const QString &content, const QString &fileNameAndPath)
Write string to text file.
Definition fileutils.cpp:40
static bool writeByteArrayToFile(const QByteArray &data, const QString &fileNameAndPath)
Write byte array to file.
Definition fileutils.cpp:57
static bool writeStringToLockedFile(const QString &content, const QString &fileNameAndPath)
Write string to file, with a lock so two applications can't access at the same time.
Definition fileutils.cpp:73
static QString appendFilePaths(const QString &path1, const QString &path2)
Append file paths.
CIdentifiable(const QString &objectName)
Use literal based object name.
A sequence of log categories.
void localMessageLogged(const swift::misc::CStatusMessage &message)
Emitted when a message is logged in this process.
static CLogHandler * instance()
Return pointer to the CLogHandler singleton.
void remoteMessageLogged(const swift::misc::CStatusMessage &message)
Emitted when a log message is relayed from a different process.
void install(bool skipIfAlreadyInstalled=false)
Tell the CLogHandler to install itself with qInstallMessageHandler.
Class for emitting a log message.
Definition logmessage.h:27
static void preformatted(const CStatusMessage &statusMessage)
Sends a verbatim, preformatted message to the log.
Value class for matching log messages based on their categories.
Definition logpattern.h:49
Derived & debug()
Set the severity to debug.
Derived & warning(const char16_t(&format)[N])
Set the severity to warning, providing a format string.
Derived & error(const char16_t(&format)[N])
Set the severity to error, providing a format string.
Derived & info(const char16_t(&format)[N])
Set the severity to info, providing a format string.
bool exists() const
True if this object identifies a process that exists.
Definition processinfo.h:37
bool containsBy(Predicate p) const
Return true if there is an element for which a given predicate returns true.
Definition range.h:101
bool contains(const T &object) const
Return true if there is an element equal to given object. Uses the most efficient implementation avai...
Definition range.h:109
int removeIf(Predicate p)
Remove elements for which a given predicate returns true.
Definition sequence.h:458
void push_back(const T &value)
Appends an element at the end of the sequence.
Definition sequence.h:308
int remove(const T &object)
Remove all elements equal to the given object, if it is contained.
Definition sequence.h:447
bool isEmpty() const
Synonym for empty.
Definition sequence.h:285
CStatusMessage loadFromStore()
Load settings from disk.
void enableLocalSave()
Connects signal CValueCache::valuesSaveRequested to a private slot that saves the values....
static CSettingsCache * instance()
Return the singleton instance.
CStatusMessage saveToStore(const QString &keyPrefix={})
Save settings to disk.
Callable wrapper for a member function with function signature F.
Definition slot.h:65
Streamable status message, e.g.
static constexpr auto SeverityInfo
Status severities.
static constexpr auto SeverityError
Status severities.
bool isFailure() const
Operation considered unsuccessful.
static constexpr auto SeverityDebug
Status severities.
Status messages, e.g. from Core -> GUI.
bool isFailure() const
Any message is marked as failure.
bool hasErrorMessages() const
Error messages.
bool isSuccess() const
All messages are marked as success.
static const QString & normalizedApplicationDataDirectory()
swift application data directory for one specific installation (a version)
static QStringList verifyRuntimeDirectoriesAndFiles()
Check if the (most important) runtime directories are available.
static bool isInThisThread(const QObject *toBeTested)
Is the current thread the object's thread?
void clearAllValues(const QString &keyPrefix={})
Clear all values from the cache.
QStringList getAllUnsavedKeys(const QString &keyPrefix={}) const
Return keys of all values which have been changed but not saved.
Base class for CWorker and CContinuousWorker.
Definition worker.h:72
static const QSet< CWorkerBase * > & allWorkers()
All workers currently existing.
Definition worker.h:181
Distributions for channel.
static const CDistribution & localDeveloperBuild()
Pseudo distribution for local builds.
Update info, i.e. artifacts and distributions.
Definition updateinfo.h:24
CDistribution anticipateOwnDistribution() const
Own distribution.
QString toQString(bool i18n=false) const
Cast as QString.
Definition mixinstring.h:74
static QNetworkRequest getSwiftNetworkRequest(const QUrl &url, RequestType type=Get, const QString &userAgentDetails={})
Our tweaked network request with swift header.
Value object encapsulating information of a location, kind of simplified CValueObject compliant versi...
Definition url.h:27
bool isEmpty() const
Empty.
Definition url.cpp:63
QNetworkRequest toNetworkRequest() const
To request.
Definition url.cpp:149
QString getFullUrl(bool withQuery=true) const
Qualified name.
Definition url.cpp:102
static const char * propertyNameId()
Property name used for request.
Definition urllog.cpp:87
Core data traits (aka cached values) and classes.
Classes interacting with the swift database (aka "datastore").
Backend services of the swift project, like dealing with the network or the simulators.
Definition actionbind.cpp:7
void registerMetadata()
Register all relevant metadata in swift::core.
Free functions in swift::misc.
SWIFT_MISC_EXPORT const QString & boolToYesNo(bool v)
Bool to yes/no.
SWIFT_MISC_EXPORT void setMockCacheRootDirectory(const QString &path)
Overwrite the default root directory for cache and settings, for testing purposes.
void registerMetadata()
Register all relevant metadata in Misc.
QString applicationName()
Get application name.
const char * constData() const const
QStringList names() const const
QString valueName() const const
QString applicationFilePath()
void setApplicationName(const QString &application)
void setApplicationVersion(const QString &version)
QStringList arguments()
void exit(int returnCode)
QCoreApplication * instance()
QString translate(const char *context, const char *sourceText, const char *disambiguation, int n)
qint64 currentMSecsSinceEpoch()
bool exists() const const
QString tempPath()
int exec(QEventLoop::ProcessEventsFlags flags)
void quit()
QDir dir() const const
QByteArray readAll()
void append(QList< T > &&value)
QList< T >::const_reference at(qsizetype i) const const
bool isEmpty() const const
void removeAt(qsizetype i)
void removeFirst()
qsizetype size() const const
bool startsWith(QList< T >::parameter_type value) const const
QNetworkReply * deleteResource(const QNetworkRequest &request)
QNetworkReply * get(const QNetworkRequest &request)
QNetworkReply * head(const QNetworkRequest &request)
QNetworkReply * post(const QNetworkRequest &request, QHttpMultiPart *multiPart)
void downloadProgress(qint64 bytesReceived, qint64 bytesTotal)
QNetworkReply::NetworkError error() const const
QUrl url() const const
QMetaObject::Connection connect(const QObject *sender, PointerToMemberFunction signal, Functor functor)
void destroyed(QObject *obj)
bool disconnect(const QMetaObject::Connection &connection)
bool moveToThread(QThread *targetThread)
void setObjectName(QAnyStringView name)
void setParent(QObject *parent)
bool setProperty(const char *name, QVariant &&value)
QThread * thread() const const
bool startDetached(const QString &program, const QStringList &arguments, const QString &workingDirectory, qint64 *pid)
bool supportsSsl()
QString writableLocation(QStandardPaths::StandardLocation type)
bool isEmpty() const const
QString mid(qsizetype position, qsizetype n) &&
bool startsWith(QChar c, Qt::CaseSensitivity cs) const const
bool contains(QLatin1StringView str, Qt::CaseSensitivity cs) const const
QStringList filter(QLatin1StringView str, Qt::CaseSensitivity cs) const const
QString join(QChar separator) const const
qsizetype removeDuplicates()
QString buildAbi()
QString buildCpuArchitecture()
CaseInsensitive
QueuedConnection
bool isValid() const const
QString path() const const
QFuture< QtFuture::ArgsType< Signal > > connect(Sender *sender, Signal signal)
#define SWIFT_VERIFY_X(COND, WHERE, WHAT)
A weaker kind of assert.
Definition verify.h:26