QGroundControl
Ground Control Station for MAVLink Drones
Loading...
Searching...
No Matches
QGCApplication.cc
Go to the documentation of this file.
1#include "QGCApplication.h"
2
3#include <QtCore/QEvent>
4#include <QtCore/QFile>
5#include <QtCore/QMetaMethod>
6#include <QtCore/QMetaObject>
7#include <QtCore/private/qthread_p.h>
8#include <QtGui/QFontDatabase>
9#include <QtGui/QIcon>
10#include <QtQml/QQmlApplicationEngine>
11#include <QtQml/QQmlContext>
12#include <QtQuick/QQuickImageProvider>
13#include <QtQuick/QQuickWindow>
14#include <QtQuickControls2/QQuickStyle>
15#include <QtSvg/QSvgRenderer>
16
17#include "AppSettings.h"
18#include "AudioOutput.h"
20#include "FollowMe.h"
21#include "GPSManager.h"
22#include "GraphicsSetup.h"
23#include "JoystickManager.h"
24#include "JsonParsing.h"
25#include "LinkManager.h"
26#include "LogManager.h"
27#include "MAVLinkProtocol.h"
28#include "MavlinkSettings.h"
29#include "MultiVehicleManager.h"
30#include "ParameterManager.h"
32#include "QGCCorePlugin.h"
33#include "QGCImageProvider.h"
34#include "QGCLoggingCategory.h"
36#include "QGCMapEngine.h"
37#include "QGCNetworkHelper.h"
38#include "QGCVersionCheck.h"
39#include "SettingsManager.h"
40#include "Vehicle.h"
41#include "VideoBackend.h"
42#include "VideoManager.h"
43#include "qgc_version.h"
44
45#ifndef QGC_NO_SERIAL_LINK
46#include "SerialLink.h"
47#ifdef Q_OS_ANDROID
48#include "AndroidSerialApp.h"
49#endif
50#endif
51
52QGC_LOGGING_CATEGORY(QGCApplicationLog, "API.QGCApplication")
53QGC_LOGGING_CATEGORY(QGCAppMessageLog, "API.QGCApplication.AppMessage")
54
55namespace {
56
57// A test run has its own application name, which desktop platforms put in the path of the settings and cache
58// locations. Android and iOS do not: there these are the installed application's own directories, as the save path
59// is on iOS, the application's Documents.
60bool isTestRunDirectory(const QDir& dir)
61{
62 return dir.absolutePath().split(QLatin1Char('/')).contains(QCoreApplication::applicationName());
63}
64
65} // namespace
66
68 : QGuiApplication(argc, argv),
69 _runningUnitTests(cli.runningUnitTests),
70 _simpleBootTest(cli.simpleBootTest),
71 _fakeMobile(cli.fakeMobile),
72 _logOutput(cli.logOutput),
73 _systemId(cli.systemId.value_or(0))
74{
75 _msecsElapsedTime.start();
76
77 // Setup for network proxy support
79
80 bool fClearSettingsOptions = cli.clearSettingsOptions; // Clear stored settings
81 const bool fClearCache = cli.clearCache; // Clear parameter/airframe caches
82 const QString loggingOptions = cli.loggingOptions.value_or(QString(""));
83
84 // Set up timer for delayed missing fact display
85 _missingParamsDelayedDisplayTimer.setSingleShot(true);
86 _missingParamsDelayedDisplayTimer.setInterval(_missingParamsDelayedDisplayTimerTimeout);
87 (void) connect(&_missingParamsDelayedDisplayTimer, &QTimer::timeout, this, &QGCApplication::_missingParamsDisplay);
88
89 // Set application information
90 QString applicationName;
91 if (_runningUnitTests || _simpleBootTest) {
92 // We don't want unit tests to use the same QSettings space as the normal app. So we tweak the app
93 // name. Also we want to run unit tests with clean settings every time.
94 // Include test name or PID to prevent settings file conflicts when tests run in parallel
95 if (!cli.unitTests.isEmpty()) {
96 applicationName = QStringLiteral("%1_unittest_%2").arg(QGC_APP_NAME, cli.unitTests.first());
97 if (cli.unitTestShardIndex > 0) {
98 // Shards of one test also run in parallel
99 applicationName += QStringLiteral("_%1").arg(cli.unitTestShardIndex);
100 }
101 } else {
102 applicationName =
103 QStringLiteral("%1_unittest_%2").arg(QGC_APP_NAME).arg(QCoreApplication::applicationPid());
104 }
105 } else {
106#ifdef QGC_DAILY_BUILD
107 // This gives daily builds their own separate settings space. Allowing you to use daily and stable builds
108 // side by side without daily screwing up your stable settings.
109 applicationName = QStringLiteral("%1 Daily").arg(QGC_APP_NAME);
110#else
111 applicationName = QGC_APP_NAME;
112#endif
113 }
114 setApplicationName(applicationName);
115 setDesktopFileName(QGC_PACKAGE_NAME);
116 setOrganizationName(QGC_ORG_NAME);
117 setOrganizationDomain(QGC_ORG_DOMAIN);
118 setApplicationVersion(QString(QGC_APP_VERSION_STR));
119
120 // Set settings format
121 QSettings::setDefaultFormat(QSettings::IniFormat);
122 QSettings settings;
123 qCDebug(QGCApplicationLog) << "Settings location" << settings.fileName()
124 << "Is writable?:" << settings.isWritable();
125
126 if (!settings.isWritable()) {
127 qCWarning(QGCApplicationLog) << "Settings location is not writable";
128 }
129
130 // The setting will delete all settings on this boot
131 fClearSettingsOptions |= settings.value(AppSettings::clearSettingsNextBootKey, false).toBool();
132
133 const bool testRun = _runningUnitTests || _simpleBootTest;
134 if (testRun) {
135 // Unit tests run with clean settings
136 fClearSettingsOptions = true;
137 }
138
139 if (fClearSettingsOptions) {
140 // User requested settings to be cleared on command line
141 settings.clear();
142
143 // Clear parameter cache
145 if (!testRun || isTestRunDirectory(paramDir)) {
146 paramDir.removeRecursively();
147 paramDir.mkpath(paramDir.absolutePath());
148 }
149 } else {
150 // Determine if upgrade message for settings version bump is required. Check and clear must happen before
151 // toolbox is started since that will write some settings.
152 if (settings.contains(_settingsVersionKey)) {
153 if (settings.value(_settingsVersionKey).toInt() != QGC_SETTINGS_VERSION) {
154 settings.clear();
155 _settingsUpgraded = true;
156 }
157 }
158 }
159 settings.setValue(_settingsVersionKey, QGC_SETTINGS_VERSION);
160
161 if (fClearCache) {
163 dir.removeRecursively();
164 QFile parameter(cachedParameterMetaDataFile());
165 parameter.remove();
166 QFile airframe(cachedAirframeMetaDataFile());
167 airframe.remove();
168
169 // Clear versioned parameter metadata cache
170 const QString metaDataCachePath =
171 QStandardPaths::writableLocation(QStandardPaths::CacheLocation) + QStringLiteral("/ParameterMetaData");
172 QDir(metaDataCachePath).removeRecursively();
173 }
174
175 // Set up our logging filters
178
179 if (_runningUnitTests) {
180 // Enable the AppMessage category so showAppMessage() debug logs are visible during unit tests.
181 QGCLoggingCategoryManager::instance()->setCategoryEnabled(QStringLiteral("API.QGCApplication.AppMessage"),
182 true);
183 }
184
185 // We need to set language as early as possible prior to loading on JSON files.
186 setLanguage();
187
188 // Force old SVG Tiny 1.2 behavior for compatibility
189 QSvgRenderer::setDefaultOptions(QtSvg::Tiny12FeaturesOnly);
190}
191
193{
194 _locale = QLocale::system();
195 qCDebug(QGCApplicationLog) << "System reported locale:" << _locale << "; Name" << _locale.name()
196 << "; Preferred (used in maps): "
197 << (QLocale::system().uiLanguages().length() > 0 ? QLocale::system().uiLanguages()[0]
198 : "None");
199
200 QLocale::Language possibleLocale = AppSettings::_qLocaleLanguageEarlyAccess();
201 if (possibleLocale != QLocale::AnyLanguage) {
202 _locale = QLocale(possibleLocale);
203 }
204 //-- We have specific fonts for Korean
205 if (_locale == QLocale::Korean) {
206 qCDebug(QGCApplicationLog) << "Loading Korean fonts" << _locale.name();
207 if (QFontDatabase::addApplicationFont(":/fonts/NanumGothic-Regular") < 0) {
208 qCWarning(QGCApplicationLog) << "Could not load /fonts/NanumGothic-Regular font";
209 }
210 if (QFontDatabase::addApplicationFont(":/fonts/NanumGothic-Bold") < 0) {
211 qCWarning(QGCApplicationLog) << "Could not load /fonts/NanumGothic-Bold font";
212 }
213 }
214 qCDebug(QGCApplicationLog) << "Loading localizations for" << _locale.name();
215 removeTranslator(JsonParsing::translator());
216 removeTranslator(&_qgcTranslatorSourceCode);
217 removeTranslator(&_qgcTranslatorQtLibs);
218 if (_locale.name() != "en_US") {
219 QLocale::setDefault(_locale);
220 if (_qgcTranslatorQtLibs.load("qt_" + _locale.name(), QLibraryInfo::path(QLibraryInfo::TranslationsPath))) {
221 installTranslator(&_qgcTranslatorQtLibs);
222 } else {
223 qCWarning(QGCApplicationLog) << "Qt lib localization for" << _locale.name() << "is not present";
224 }
225 if (_qgcTranslatorSourceCode.load(_locale, QLatin1String("qgc_source_"), "", ":/i18n")) {
226 installTranslator(&_qgcTranslatorSourceCode);
227 } else {
228 qCWarning(QGCApplicationLog) << "Error loading source localization for" << _locale.name();
229 }
230 if (JsonParsing::translator()->load(_locale, QLatin1String("qgc_json_"), "", ":/i18n")) {
231 installTranslator(JsonParsing::translator());
232 } else {
233 qCWarning(QGCApplicationLog) << "Error loading json localization for" << _locale.name();
234 }
235 }
236
237 if (_qmlAppEngine) {
238 _qmlAppEngine->retranslate();
239 }
240
241 emit languageChanged(_locale);
242}
243
245
247{
249 if (_systemId > 0) {
250 qCDebug(QGCApplicationLog) << "Setting MAVLink System ID to:" << _systemId;
251 SettingsManager::instance()->mavlinkSettings()->gcsMavlinkSystemID()->setRawValue(_systemId);
252 }
253
255
256 // Although this should really be in _initForNormalAppBoot putting it here allowws us to create unit tests which pop
257 // up more easily
258 if (QFontDatabase::addApplicationFont(":/fonts/opensans") < 0) {
259 qCWarning(QGCApplicationLog) << "Could not load /fonts/opensans font";
260 }
261
262 if (QFontDatabase::addApplicationFont(":/fonts/opensans-demibold") < 0) {
263 qCWarning(QGCApplicationLog) << "Could not load /fonts/opensans-demibold font";
264 }
265
266 if (_simpleBootTest) {
267 // Since GStreamer builds are so problematic, the simple boot test initializes video and proves that the
268 // packaged runtime decodes and records.
269 const bool videoInitialized = _initVideo() && VideoBackend::instance().selfTest();
270 const bool qmlRootLoaded = _initQmlRootWindow();
271 _bootTestPassed = videoInitialized && qmlRootLoaded;
272#if defined(Q_OS_ANDROID) && !defined(QGC_NO_SERIAL_LINK)
273 // Java and C++ are bound to each other only as the app runs, so the boot test also proves that binding.
274 _bootTestPassed = AndroidSerial::selfTest() && _bootTestPassed;
275#endif
276 } else if (!_runningUnitTests) {
277 _initForNormalAppBoot();
278 }
279}
280
281bool QGCApplication::_initVideo()
282{
283 QGCCorePlugin::instance(); // CorePlugin must be initialized before VideoManager for Video Cleanup
284 VideoManager* videoManager = VideoManager::instance();
285 videoManager->startVideoBackendInit();
286 const bool initSucceeded = !_simpleBootTest || videoManager->waitForVideoBackendReady();
287 _videoManagerInitialized = true;
288 return initSucceeded;
289}
290
291bool QGCApplication::_initQmlRootWindow()
292{
293 QQuickStyle::setStyle("Basic");
298 QObject::connect(_qmlAppEngine, &QQmlApplicationEngine::objectCreationFailed, this, QCoreApplication::quit,
299 Qt::QueuedConnection);
300
301 // Must register before createRootWindow — root QML references QGCColoredImage which resolves image://coloredsvg/...
302 // at load time.
303 _qmlAppEngine->addImageProvider(_qgcImageProviderId, new QGCImageProvider());
304 _qmlAppEngine->addImageProvider(QLatin1String(ColoredSvgImageProvider::ProviderId), new ColoredSvgImageProvider());
305
306 // RHI graphics config / forced device must be applied before the root window's scene graph initializes. Android
307 // exposes the window synchronously when the root QML shows it, so configure it as soon as its surface exists.
310
311 return mainRootWindow() != nullptr;
312}
313
314void QGCApplication::_initForNormalAppBoot()
315{
316 (void) _initVideo();
317
318 (void) _initQmlRootWindow();
319
320 AudioOutput::instance()->init(SettingsManager::instance()->appSettings()->audioVolume(),
321 SettingsManager::instance()->appSettings()->audioMuted());
326
327 // Set the window icon now that custom plugin has a chance to override it
328#ifdef Q_OS_LINUX
329 QUrl windowIcon = QUrl("qrc:/res/qgroundcontrol.ico");
330 windowIcon = _qmlAppEngine->interceptUrl(windowIcon, QQmlAbstractUrlInterceptor::UrlString);
331 // The interceptor needs "qrc:/path" but QIcon expects ":/path"
332 setWindowIcon(QIcon(":" + windowIcon.path()));
333#endif
334
335 // Safe to show popup error messages now that main window is created
336 _showErrorsInToolbar = true;
337
338#ifdef Q_OS_LINUX
339#ifndef Q_OS_ANDROID
340#ifndef QGC_NO_SERIAL_LINK
341 if (!_runningUnitTests) {
342 // Determine if we have the correct permissions to access USB serial devices
343 QFile permFile("/etc/group");
344 if (permFile.open(QIODevice::ReadOnly)) {
345 while (!permFile.atEnd()) {
346 const QString line = permFile.readLine();
347 if (line.contains("dialout") && !line.contains(getenv("USER"))) {
348 permFile.close();
350 tr("The current user does not have the correct permissions to access serial devices. "
351 "You should also remove modemmanager since it also interferes.<br/><br/>"
352 "If you are using Ubuntu, execute the following commands to fix these issues:<br/>"
353 "<pre>sudo usermod -a -G dialout $USER<br/>"
354 "sudo apt-get remove modemmanager</pre>"));
355 break;
356 }
357 }
358 permFile.close();
359 }
360 }
361#endif
362#endif
363#endif
364
365 // Now that main window is up check for lost log files
367
368 // Load known link configurations
371
372 // Probe for joysticks
374
375 if (_settingsUpgraded) {
376 showAppMessage(tr("The format for %1 saved settings has been modified. "
377 "Your saved settings have been reset to defaults.")
378 .arg(applicationName()));
379 }
380
381 // Connect links with flag AutoconnectLink
383
384#ifndef QGC_DAILY_BUILD
386#endif
387}
388
389void QGCApplication::reportMissingParameter(int componentId, const QString& name)
390{
391 const QPair<int, QString> missingParam(componentId, name);
392
393 if (!_missingParams.contains(missingParam)) {
394 _missingParams.append(missingParam);
395 }
396 _missingParamsDelayedDisplayTimer.start();
397}
398
399void QGCApplication::_missingParamsDisplay()
400{
401 if (_missingParams.isEmpty()) {
402 return;
403 }
404
405 QString params;
406 for (QPair<int, QString>& missingParam : _missingParams) {
407 const QString param = QStringLiteral("%1:%2").arg(missingParam.first).arg(missingParam.second);
408 if (params.isEmpty()) {
409 params += param;
410 } else {
411 params += QStringLiteral(", %1").arg(param);
412 }
413 }
414 _missingParams.clear();
415
416 showAppMessage(tr("Parameters are missing from firmware. You may be running a version of firmware which is not "
417 "fully supported or your firmware has a bug in it. Missing params: %1")
418 .arg(params));
419}
420
421QObject* QGCApplication::_rootQmlObject()
422{
423 if (_qmlAppEngine && _qmlAppEngine->rootObjects().size()) {
424 return _qmlAppEngine->rootObjects()[0];
425 }
426
427 return nullptr;
428}
429
431{
432 // PreArm messages are handled by Vehicle and shown in Map
433 if (message.startsWith(QStringLiteral("PreArm")) ||
434 message.startsWith(QStringLiteral("preflight"), Qt::CaseInsensitive)) {
435 return;
436 }
437
438 QObject* const rootQmlObject = _rootQmlObject();
439 if (rootQmlObject && _showErrorsInToolbar) {
440 QVariant varReturn;
441 QVariant varMessage = QVariant::fromValue(message);
442 QMetaObject::invokeMethod(rootQmlObject, "showCriticalVehicleMessage", Q_RETURN_ARG(QVariant, varReturn),
443 Q_ARG(QVariant, varMessage));
444 } else if (runningUnitTests() || !_showErrorsInToolbar) {
445 // Unit tests can run without UI
446 qCDebug(QGCApplicationLog) << "QGCApplication::showCriticalVehicleMessage unittest" << message;
447 } else {
448 qCWarning(QGCApplicationLog) << "Internal error";
449 }
450}
451
452void QGCApplication::showAppMessage(const QString& message, const QString& title)
453{
454 const QString dialogTitle = title.isEmpty() ? applicationName() : title;
455
456 if (runningUnitTests()) {
457 // Logged under QGCAppMessageLog so tests can assert expected dialogs via
458 // expectAppMessage() without matching against the general QGCApplication category.
459 qCDebug(QGCAppMessageLog) << "showAppMessage:" << dialogTitle << "-" << message;
460 if (!_uiTestMode) {
461 // Headless test: there is no QML root to host the dialog and the delayed-message
462 // timer would retry forever, so the log is the only record.
463 return;
464 }
465 // UI tests fall through: the message dialog is a non-blocking QML popup, so show it
466 // for real and let the test handle it the same way a user would.
467 }
468
469 QObject* const rootQmlObject = _rootQmlObject();
470 if (rootQmlObject) {
471 QVariant varReturn;
472 QVariant varMessage = QVariant::fromValue(message);
473 QMetaObject::invokeMethod(rootQmlObject, "_showMessageDialog", Q_RETURN_ARG(QVariant, varReturn),
474 Q_ARG(QVariant, dialogTitle), Q_ARG(QVariant, varMessage));
475 } else {
476 // UI isn't ready yet
477 _delayedAppMessages.append(QPair<QString, QString>(dialogTitle, message));
478 QTimer::singleShot(200, this, &QGCApplication::_showDelayedAppMessages);
479 }
480}
481
482bool QGCApplication::_rebootMessageDebounced()
483{
484 const QTime currentTime = QTime::currentTime();
485 const QTime previousTime = _lastRebootMessageTime;
486 _lastRebootMessageTime = currentTime;
487
488 return previousTime.isValid() && (previousTime.msecsTo(currentTime) < (60 * 1000 * 2));
489}
490
491void QGCApplication::showRebootAppMessage(const QString& message, const QString& title)
492{
493 if (_rebootMessageDebounced()) {
494 return;
495 }
496
497 showAppMessage(message, title);
498}
499
500void QGCApplication::_showDelayedAppMessages()
501{
502 if (_rootQmlObject()) {
503 for (const QPair<QString, QString>& appMsg : _delayedAppMessages) {
504 showAppMessage(appMsg.second, appMsg.first);
505 }
506 _delayedAppMessages.clear();
507 } else {
508 QTimer::singleShot(200, this, &QGCApplication::_showDelayedAppMessages);
509 }
510}
511
513{
514 if (!_mainRootWindow) {
515 _mainRootWindow = qobject_cast<QQuickWindow*>(_rootQmlObject());
516 }
517
518 return _mainRootWindow;
519}
520
522{
523 if (_rootQmlObject()) {
524 QMetaObject::invokeMethod(_rootQmlObject(), "attemptWindowClose");
525 }
526}
527
529{
530 QSettings settings;
531 const QDir parameterDir = QFileInfo(settings.fileName()).dir();
532 return parameterDir.filePath(QStringLiteral("ParameterFactMetaData.json"));
533}
534
536{
537 QSettings settings;
538 const QDir airframeDir = QFileInfo(settings.fileName()).dir();
539 return airframeDir.filePath(QStringLiteral("PX4AirframeFactMetaData.xml"));
540}
541
542int QGCApplication::CompressedSignalList::_signalIndex(const QMetaMethod& method)
543{
544 if (method.methodType() != QMetaMethod::Signal) {
545 qCWarning(QGCApplicationLog) << "Internal error:" << Q_FUNC_INFO << "not a signal" << method.methodType();
546 return -1;
547 }
548
549 int index = -1;
550 const QMetaObject* metaObject = method.enclosingMetaObject();
551 for (int i = 0; i <= method.methodIndex(); i++) {
552 if (metaObject->method(i).methodType() != QMetaMethod::Signal) {
553 continue;
554 }
555 index++;
556 }
557
558 return index;
559}
560
561void QGCApplication::CompressedSignalList::add(const QMetaMethod& method)
562{
563 const QMetaObject* metaObject = method.enclosingMetaObject();
564 const int signalIndex = _signalIndex(method);
565
566 if (signalIndex != -1 && !contains(metaObject, signalIndex)) {
567 _signalMap[method.enclosingMetaObject()].insert(signalIndex);
568 }
569}
570
571void QGCApplication::CompressedSignalList::remove(const QMetaMethod& method)
572{
573 const int signalIndex = _signalIndex(method);
574 const QMetaObject* const metaObject = method.enclosingMetaObject();
575
576 if (signalIndex != -1 && _signalMap.contains(metaObject) && _signalMap[metaObject].contains(signalIndex)) {
577 _signalMap[metaObject].remove(signalIndex);
578 if (_signalMap[metaObject].count() == 0) {
579 _signalMap.remove(metaObject);
580 }
581 }
582}
583
584bool QGCApplication::CompressedSignalList::contains(const QMetaObject* metaObject, int signalIndex)
585{
586 return _signalMap.contains(metaObject) && _signalMap[metaObject].contains(signalIndex);
587}
588
589void QGCApplication::addCompressedSignal(const QMetaMethod& method)
590{
591 _compressedSignals.add(method);
592}
593
594void QGCApplication::removeCompressedSignal(const QMetaMethod& method)
595{
596 _compressedSignals.remove(method);
597}
598
599QT_WARNING_PUSH
600
601QT_WARNING_DISABLE_DEPRECATED
602bool QGCApplication::compressEvent(QEvent* event, QObject* receiver, QPostEventList* postedEvents)
603{
604 if (event->type() != QEvent::MetaCall) {
605 return QGuiApplication::compressEvent(event, receiver, postedEvents);
606 }
607
608 const QMetaCallEvent* mce = static_cast<QMetaCallEvent*>(event);
609 if (!mce->sender() || !_compressedSignals.contains(mce->sender()->metaObject(), mce->signalId())) {
610 return QGuiApplication::compressEvent(event, receiver, postedEvents);
611 }
612
613 for (QPostEventList::iterator it = postedEvents->begin(); it != postedEvents->end(); ++it) {
614 QPostEvent& cur = *it;
615 if (cur.receiver != receiver || cur.event == 0 || cur.event->type() != event->type()) {
616 continue;
617 }
618 const QMetaCallEvent* cur_mce = static_cast<QMetaCallEvent*>(cur.event);
619 if (cur_mce->sender() != mce->sender() || cur_mce->signalId() != mce->signalId() ||
620 cur_mce->id() != mce->id()) {
621 continue;
622 }
623
624 /* Keep The Newest Call */
625 // We can't merely qSwap the existing posted event with the new one, since QEvent
626 // keeps track of whether it has been posted. Deletion of a formerly posted event
627 // takes the posted event list mutex and does a useless search of the posted event
628 // list upon deletion. We thus clear the QEvent::posted flag before deletion.
629 struct EventHelper : private QEvent
630 {
631 static void clearPostedFlag(QEvent* ev)
632 {
633 (&static_cast<EventHelper*>(ev)->t)[1] &= ~0x8001; // Hack to clear QEvent::posted
634 }
635 };
636
637 EventHelper::clearPostedFlag(cur.event);
638 delete cur.event;
639 cur.event = event;
640 return true;
641 }
642
643 return false;
644}
645
646QT_WARNING_POP
647
649{
650 if (e->type() == QEvent::Quit) {
651 if (!_mainRootWindow) {
652 return QGuiApplication::event(e);
653 }
654 // On OSX if the user selects Quit from the menu (or Command-Q) the ApplicationWindow does not signal closing.
655 // Instead you get a Quit event here only. This in turn causes the standard QGC shutdown sequence to not run. So
656 // in this case we close the window ourselves such that the signal is sent and the normal shutdown sequence
657 // runs.
658 const bool forceClose = _mainRootWindow->property("_forceClose").toBool();
659 qCDebug(QGCApplicationLog) << "Quit event" << forceClose;
660 // forceClose
661 // true: Standard QGC shutdown sequence is complete. Let the app quit normally by falling through to the base
662 // class processing. false: QGC shutdown sequence has not been run yet. Don't let this event close the app
663 // yet. Close the main window to kick off the normal shutdown.
664 if (!forceClose) {
665 //
666 _mainRootWindow->close();
667 e->ignore();
668 return true;
669 }
670 }
671
672 return QGuiApplication::event(e);
673}
674
676{
677 return dynamic_cast<QGCImageProvider*>(_qmlAppEngine->imageProvider(_qgcImageProviderId));
678}
679
681{
683 qCDebug(QGCApplicationLog) << "Exit";
684
685 if (_videoManagerInitialized) {
687 }
688
689 // Engines from createQmlApplicationEngine must die through the destroy hook so the plugin
690 // can release per-engine state; parent-based teardown in ~QGCApplication would bypass it.
691 if (_qmlAppEngine) {
693 _qmlAppEngine = nullptr;
694 }
695
697
698 // Close the tile cache database while the application object exists (the map engine is otherwise
699 // destroyed after it) and before test runs remove the cache directory holding it.
701
702 if (_runningUnitTests || _simpleBootTest) {
703 const QSettings settings;
704 const QString settingsFile = settings.fileName();
705 if (QFile::exists(settingsFile)) {
706 if (QFile::remove(settingsFile)) {
707 qCDebug(QGCApplicationLog) << "Removed test run settings file:" << settingsFile;
708 } else {
709 qCWarning(QGCApplicationLog) << "Failed to remove test run settings file:" << settingsFile;
710 }
711 }
712
713 for (const auto location : {QStandardPaths::AppConfigLocation, QStandardPaths::CacheLocation}) {
714 QDir dir(QStandardPaths::writableLocation(location));
715 if (dir.exists() && isTestRunDirectory(dir)) {
716 if (dir.removeRecursively()) {
717 qCDebug(QGCApplicationLog) << "Removed test run directory:" << dir.absolutePath();
718 } else {
719 qCWarning(QGCApplicationLog) << "Failed to remove test run directory:" << dir.absolutePath();
720 }
721 }
722 }
723
724 QDir appDir(SettingsManager::instance()->appSettings()->savePath()->rawValue().toString());
725 if (appDir.exists() && isTestRunDirectory(appDir)) {
726 if (appDir.removeRecursively()) {
727 qCDebug(QGCApplicationLog) << "Removed test run app data directory:" << appDir.absolutePath();
728 } else {
729 qCWarning(QGCApplicationLog)
730 << "Failed to remove test run app data directory:" << appDir.absolutePath();
731 }
732 }
733 }
734
735 // This is bad, but currently qobject inheritances are incorrect and cause crashes on exit without
736 delete _qmlAppEngine;
737}
#define QGC_LOGGING_CATEGORY(name, categoryStr)
static constexpr const char * clearSettingsNextBootKey
Definition AppSettings.h:62
static AudioOutput * instance()
void init(Fact *volumeFact, Fact *mutedFact)
Initialize the Singleton.
static constexpr const char * ProviderId
static FollowMe * instance()
Definition FollowMe.cc:37
void init()
Definition FollowMe.cc:42
void shutdown()
Stops the GPS services, then the position manager.
static GPSManager * instance()
Definition GPSManager.cc:67
void init()
Definition GPSManager.cc:88
static JoystickManager * instance()
void loadLinkConfigurationList()
void startAutoConnectedLinks()
static LinkManager * instance()
void init()
static LogManager * instance()
Definition LogManager.cc:76
static MAVLinkProtocol * instance()
static MultiVehicleManager * instance()
static QDir parameterCacheDir()
void qmlAttemptWindowClose()
void reportMissingParameter(int componentId, const QString &name)
void showRebootAppMessage(const QString &message, const QString &title=QString())
bool logOutput() const
Returns true if Qt debug output should be logged to a file.
void init()
Perform initialize which is common to both normal application running and unit tests.
bool fakeMobile() const
static QString cachedParameterMetaDataFile()
QQuickWindow * mainRootWindow()
void removeCompressedSignal(const QMetaMethod &method)
void languageChanged(const QLocale &locale)
static QString cachedAirframeMetaDataFile()
void addCompressedSignal(const QMetaMethod &method)
Registers the signal such that only the last duplicate signal added is left in the queue.
void showCriticalVehicleMessage(const QString &message)
Show non-modal vehicle message to the user.
QGCApplication(int &argc, char *argv[], const QGCCommandLineParser::CommandLineParseResult &args)
bool runningUnitTests() const
QGCImageProvider * qgcImageProvider()
bool simpleBootTest() const
void showAppMessage(const QString &message, const QString &title=QString())
Show modal application message to the user.
bool event(QEvent *e) final
virtual void linkConfigurationsLoaded(LinkManager *linkManager)
Called at boot after saved link configurations are loaded and before auto-connect links are started.
virtual QQmlApplicationEngine * createQmlApplicationEngine(QObject *parent)
virtual void createRootWindow(QQmlApplicationEngine *qmlEngine)
Allows the plugin to override the creation of the root (native) window.
virtual void init()
virtual void cleanup()
virtual void destroyQmlApplicationEngine(QQmlApplicationEngine *qmlEngine)
static QGCCorePlugin * instance()
This is used to expose images from ImageProtocolHandler.
Q_INVOKABLE void setCategoryEnabled(const QString &fullCategoryName, bool enable)
static QGCLoggingCategoryManager * instance()
void installFilter(const QString &commandLineLoggingOptions=QString())
static void closeInstance()
close() on the application's engine, if one was created.
static QGCVersionCheck * instance()
void start()
Starts the asynchronous download of the stable version file.
static SettingsManager * instance()
MavlinkSettings * mavlinkSettings() const
virtual bool selfTest()
The boot test's check that the initialized backend decodes and records.
static VideoBackend & instance()
void startVideoBackendInit()
Starts the video backend's asynchronous global init. GUI thread only, like everything else here.
static VideoManager * instance()
void init(QQuickWindow *mainWindow)
bool waitForVideoBackendReady()
Blocks until the backend init finishes, starting it if needed. True when the backend is ready.
QByteArray line(std::string_view command)
command as one CR/LF-terminated line.
void configureMainWindowOnCreation()
QTranslator * translator()
Translator used by openInternalQGCJsonFile for localized strings.
Result of parsing command-line arguments.
uint unitTestShardIndex
1-based shard of the test's functions to run (0 = all functions)