3#include <QtCore/QEvent>
5#include <QtCore/QMetaMethod>
6#include <QtCore/QMetaObject>
7#include <QtCore/private/qthread_p.h>
8#include <QtGui/QFontDatabase>
10#include <QtQml/QQmlApplicationEngine>
11#include <QtQml/QQmlContext>
12#include <QtQuick/QQuickImageProvider>
13#include <QtQuick/QQuickWindow>
14#include <QtQuickControls2/QQuickStyle>
15#include <QtSvg/QSvgRenderer>
43#include "qgc_version.h"
45#ifndef QGC_NO_SERIAL_LINK
60bool isTestRunDirectory(
const QDir& dir)
62 return dir.absolutePath().split(QLatin1Char(
'/')).contains(QCoreApplication::applicationName());
68 : QGuiApplication(argc, argv),
73 _systemId(cli.systemId.value_or(0))
75 _msecsElapsedTime.start();
82 const QString loggingOptions = cli.
loggingOptions.value_or(QString(
""));
85 _missingParamsDelayedDisplayTimer.setSingleShot(
true);
86 _missingParamsDelayedDisplayTimer.setInterval(_missingParamsDelayedDisplayTimerTimeout);
87 (void) connect(&_missingParamsDelayedDisplayTimer, &QTimer::timeout,
this, &QGCApplication::_missingParamsDisplay);
90 QString applicationName;
91 if (_runningUnitTests || _simpleBootTest) {
96 applicationName = QStringLiteral(
"%1_unittest_%2").arg(QGC_APP_NAME, cli.
unitTests.first());
103 QStringLiteral(
"%1_unittest_%2").arg(QGC_APP_NAME).arg(QCoreApplication::applicationPid());
106#ifdef QGC_DAILY_BUILD
109 applicationName = QStringLiteral(
"%1 Daily").arg(QGC_APP_NAME);
111 applicationName = QGC_APP_NAME;
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));
121 QSettings::setDefaultFormat(QSettings::IniFormat);
123 qCDebug(QGCApplicationLog) <<
"Settings location" << settings.fileName()
124 <<
"Is writable?:" << settings.isWritable();
126 if (!settings.isWritable()) {
127 qCWarning(QGCApplicationLog) <<
"Settings location is not writable";
133 const bool testRun = _runningUnitTests || _simpleBootTest;
136 fClearSettingsOptions =
true;
139 if (fClearSettingsOptions) {
145 if (!testRun || isTestRunDirectory(paramDir)) {
146 paramDir.removeRecursively();
147 paramDir.mkpath(paramDir.absolutePath());
152 if (settings.contains(_settingsVersionKey)) {
153 if (settings.value(_settingsVersionKey).toInt() != QGC_SETTINGS_VERSION) {
155 _settingsUpgraded =
true;
159 settings.setValue(_settingsVersionKey, QGC_SETTINGS_VERSION);
163 dir.removeRecursively();
170 const QString metaDataCachePath =
171 QStandardPaths::writableLocation(QStandardPaths::CacheLocation) + QStringLiteral(
"/ParameterMetaData");
172 QDir(metaDataCachePath).removeRecursively();
179 if (_runningUnitTests) {
189 QSvgRenderer::setDefaultOptions(QtSvg::Tiny12FeaturesOnly);
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]
200 QLocale::Language possibleLocale = AppSettings::_qLocaleLanguageEarlyAccess();
201 if (possibleLocale != QLocale::AnyLanguage) {
202 _locale = QLocale(possibleLocale);
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";
210 if (QFontDatabase::addApplicationFont(
":/fonts/NanumGothic-Bold") < 0) {
211 qCWarning(QGCApplicationLog) <<
"Could not load /fonts/NanumGothic-Bold font";
214 qCDebug(QGCApplicationLog) <<
"Loading localizations for" << _locale.name();
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);
223 qCWarning(QGCApplicationLog) <<
"Qt lib localization for" << _locale.name() <<
"is not present";
225 if (_qgcTranslatorSourceCode.load(_locale, QLatin1String(
"qgc_source_"),
"",
":/i18n")) {
226 installTranslator(&_qgcTranslatorSourceCode);
228 qCWarning(QGCApplicationLog) <<
"Error loading source localization for" << _locale.name();
233 qCWarning(QGCApplicationLog) <<
"Error loading json localization for" << _locale.name();
238 _qmlAppEngine->retranslate();
250 qCDebug(QGCApplicationLog) <<
"Setting MAVLink System ID to:" << _systemId;
258 if (QFontDatabase::addApplicationFont(
":/fonts/opensans") < 0) {
259 qCWarning(QGCApplicationLog) <<
"Could not load /fonts/opensans font";
262 if (QFontDatabase::addApplicationFont(
":/fonts/opensans-demibold") < 0) {
263 qCWarning(QGCApplicationLog) <<
"Could not load /fonts/opensans-demibold font";
266 if (_simpleBootTest) {
270 const bool qmlRootLoaded = _initQmlRootWindow();
271 _bootTestPassed = videoInitialized && qmlRootLoaded;
272#if defined(Q_OS_ANDROID) && !defined(QGC_NO_SERIAL_LINK)
276 }
else if (!_runningUnitTests) {
277 _initForNormalAppBoot();
281bool QGCApplication::_initVideo()
287 _videoManagerInitialized =
true;
288 return initSucceeded;
291bool QGCApplication::_initQmlRootWindow()
293 QQuickStyle::setStyle(
"Basic");
298 QObject::connect(_qmlAppEngine, &QQmlApplicationEngine::objectCreationFailed,
this, QCoreApplication::quit,
299 Qt::QueuedConnection);
303 _qmlAppEngine->addImageProvider(_qgcImageProviderId,
new QGCImageProvider());
314void QGCApplication::_initForNormalAppBoot()
318 (void) _initQmlRootWindow();
329 QUrl windowIcon = QUrl(
"qrc:/res/qgroundcontrol.ico");
330 windowIcon = _qmlAppEngine->interceptUrl(windowIcon, QQmlAbstractUrlInterceptor::UrlString);
332 setWindowIcon(QIcon(
":" + windowIcon.path()));
336 _showErrorsInToolbar =
true;
340#ifndef QGC_NO_SERIAL_LINK
341 if (!_runningUnitTests) {
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"))) {
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>"));
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()));
384#ifndef QGC_DAILY_BUILD
391 const QPair<int, QString> missingParam(componentId, name);
393 if (!_missingParams.contains(missingParam)) {
394 _missingParams.append(missingParam);
396 _missingParamsDelayedDisplayTimer.start();
399void QGCApplication::_missingParamsDisplay()
401 if (_missingParams.isEmpty()) {
406 for (QPair<int, QString>& missingParam : _missingParams) {
407 const QString param = QStringLiteral(
"%1:%2").arg(missingParam.first).arg(missingParam.second);
408 if (params.isEmpty()) {
411 params += QStringLiteral(
", %1").arg(param);
414 _missingParams.clear();
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")
421QObject* QGCApplication::_rootQmlObject()
423 if (_qmlAppEngine && _qmlAppEngine->rootObjects().size()) {
424 return _qmlAppEngine->rootObjects()[0];
433 if (message.startsWith(QStringLiteral(
"PreArm")) ||
434 message.startsWith(QStringLiteral(
"preflight"), Qt::CaseInsensitive)) {
438 QObject*
const rootQmlObject = _rootQmlObject();
439 if (rootQmlObject && _showErrorsInToolbar) {
441 QVariant varMessage = QVariant::fromValue(message);
442 QMetaObject::invokeMethod(rootQmlObject,
"showCriticalVehicleMessage", Q_RETURN_ARG(QVariant, varReturn),
443 Q_ARG(QVariant, varMessage));
446 qCDebug(QGCApplicationLog) <<
"QGCApplication::showCriticalVehicleMessage unittest" << message;
448 qCWarning(QGCApplicationLog) <<
"Internal error";
454 const QString dialogTitle = title.isEmpty() ? applicationName() : title;
459 qCDebug(QGCAppMessageLog) <<
"showAppMessage:" << dialogTitle <<
"-" << message;
469 QObject*
const rootQmlObject = _rootQmlObject();
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));
477 _delayedAppMessages.append(QPair<QString, QString>(dialogTitle, message));
478 QTimer::singleShot(200,
this, &QGCApplication::_showDelayedAppMessages);
482bool QGCApplication::_rebootMessageDebounced()
484 const QTime currentTime = QTime::currentTime();
485 const QTime previousTime = _lastRebootMessageTime;
486 _lastRebootMessageTime = currentTime;
488 return previousTime.isValid() && (previousTime.msecsTo(currentTime) < (60 * 1000 * 2));
493 if (_rebootMessageDebounced()) {
500void QGCApplication::_showDelayedAppMessages()
502 if (_rootQmlObject()) {
503 for (
const QPair<QString, QString>& appMsg : _delayedAppMessages) {
506 _delayedAppMessages.clear();
508 QTimer::singleShot(200,
this, &QGCApplication::_showDelayedAppMessages);
514 if (!_mainRootWindow) {
515 _mainRootWindow = qobject_cast<QQuickWindow*>(_rootQmlObject());
518 return _mainRootWindow;
523 if (_rootQmlObject()) {
524 QMetaObject::invokeMethod(_rootQmlObject(),
"attemptWindowClose");
531 const QDir parameterDir = QFileInfo(settings.fileName()).dir();
532 return parameterDir.filePath(QStringLiteral(
"ParameterFactMetaData.json"));
538 const QDir airframeDir = QFileInfo(settings.fileName()).dir();
539 return airframeDir.filePath(QStringLiteral(
"PX4AirframeFactMetaData.xml"));
542int QGCApplication::CompressedSignalList::_signalIndex(
const QMetaMethod& method)
544 if (method.methodType() != QMetaMethod::Signal) {
545 qCWarning(QGCApplicationLog) <<
"Internal error:" << Q_FUNC_INFO <<
"not a signal" << method.methodType();
550 const QMetaObject* metaObject = method.enclosingMetaObject();
551 for (
int i = 0; i <= method.methodIndex(); i++) {
552 if (metaObject->method(i).methodType() != QMetaMethod::Signal) {
561void QGCApplication::CompressedSignalList::add(
const QMetaMethod& method)
563 const QMetaObject* metaObject = method.enclosingMetaObject();
564 const int signalIndex = _signalIndex(method);
566 if (signalIndex != -1 && !contains(metaObject, signalIndex)) {
567 _signalMap[method.enclosingMetaObject()].insert(signalIndex);
571void QGCApplication::CompressedSignalList::remove(
const QMetaMethod& method)
573 const int signalIndex = _signalIndex(method);
574 const QMetaObject*
const metaObject = method.enclosingMetaObject();
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);
584bool QGCApplication::CompressedSignalList::contains(
const QMetaObject* metaObject,
int signalIndex)
586 return _signalMap.contains(metaObject) && _signalMap[metaObject].contains(signalIndex);
591 _compressedSignals.add(method);
596 _compressedSignals.remove(method);
601QT_WARNING_DISABLE_DEPRECATED
602bool QGCApplication::compressEvent(QEvent*
event, QObject* receiver, QPostEventList* postedEvents)
604 if (
event->type() != QEvent::MetaCall) {
605 return QGuiApplication::compressEvent(
event, receiver, postedEvents);
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);
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()) {
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()) {
629 struct EventHelper :
private QEvent
631 static void clearPostedFlag(QEvent* ev)
633 (&
static_cast<EventHelper*
>(ev)->t)[1] &= ~0x8001;
637 EventHelper::clearPostedFlag(cur.event);
650 if (e->type() == QEvent::Quit) {
651 if (!_mainRootWindow) {
652 return QGuiApplication::event(e);
658 const bool forceClose = _mainRootWindow->property(
"_forceClose").toBool();
659 qCDebug(QGCApplicationLog) <<
"Quit event" << forceClose;
666 _mainRootWindow->close();
672 return QGuiApplication::event(e);
677 return dynamic_cast<QGCImageProvider*
>(_qmlAppEngine->imageProvider(_qgcImageProviderId));
683 qCDebug(QGCApplicationLog) <<
"Exit";
685 if (_videoManagerInitialized) {
693 _qmlAppEngine =
nullptr;
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;
709 qCWarning(QGCApplicationLog) <<
"Failed to remove test run settings file:" << settingsFile;
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();
719 qCWarning(QGCApplicationLog) <<
"Failed to remove test run directory:" << dir.absolutePath();
725 if (appDir.exists() && isTestRunDirectory(appDir)) {
726 if (appDir.removeRecursively()) {
727 qCDebug(QGCApplicationLog) <<
"Removed test run app data directory:" << appDir.absolutePath();
729 qCWarning(QGCApplicationLog)
730 <<
"Failed to remove test run app data directory:" << appDir.absolutePath();
736 delete _qmlAppEngine;
#define QGC_LOGGING_CATEGORY(name, categoryStr)
static constexpr const char * clearSettingsNextBootKey
static AudioOutput * instance()
void init(Fact *volumeFact, Fact *mutedFact)
Initialize the Singleton.
static constexpr const char * ProviderId
static FollowMe * instance()
void shutdown()
Stops the GPS services, then the position manager.
static GPSManager * instance()
static JoystickManager * instance()
void loadLinkConfigurationList()
void startAutoConnectedLinks()
static LinkManager * instance()
static LogManager * instance()
void checkForLostLogFiles()
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.
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 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.
void initializeProxySupport()
Result of parsing command-line arguments.
std::optional< QString > loggingOptions
bool clearSettingsOptions
uint unitTestShardIndex
1-based shard of the test's functions to run (0 = all functions)