Debian Codegraph @

src/GUI/QtLauncher.cxx

raw symbols SCIP
1 // QtLauncher.cxx - GUI launcher dialog using Qt5
2 //
3 // Written by James Turner, started December 2014.
4 //
5 // Copyright (C) 2014 James Turner <[email protected]>
6 //
7 // This program is free software; you can redistribute it and/or
8 // modify it under the terms of the GNU General Public License as
9 // published by the Free Software Foundation; either version 2 of the
10 // License, or (at your option) any later version.
11 //
12 // This program is distributed in the hope that it will be useful, but
13 // WITHOUT ANY WARRANTY; without even the implied warranty of
14 // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
15 // General Public License for more details.
16 //
17 // You should have received a copy of the GNU General Public License
18 // along with this program; if not, write to the Free Software
19 // Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
20
21 #include "config.h"
22
23 #include "QtLauncher.hxx"
24
25 #include <locale.h>
26
27 // Qt
28 #include <QApplication>
29 #include <QDebug>
30 #include <QDir>
31 #include <QFileInfo>
32 #include <QMessageBox>
33 #include <QOffscreenSurface>
34 #include <QOpenGLContext>
35 #include <QPointer>
36 #include <QProcess>
37 #include <QProgressDialog>
38 #include <QSettings>
39 #include <QString>
40 #include <QThread>
41 #include <QTimer>
42 #include <QTranslator>
43 #include <QUrl>
44 #include <QtGlobal>
45
46 #if (QT_VERSION >= QT_VERSION_CHECK(6, 1, 0))
47 #include <QNetworkInformation>
48 #endif
49
50 // Simgear
51 #include <simgear/timing/timestamp.hxx>
52 #include <simgear/props/props_io.hxx>
53 #include <simgear/structure/exception.hxx>
54 #include <simgear/structure/subsystem_mgr.hxx>
55 #include <simgear/misc/sg_path.hxx>
56 #include <simgear/misc/strutils.hxx>
57 #include <simgear/package/Root.hxx>
58 #include <simgear/package/Catalog.hxx>
59 #include <simgear/package/Package.hxx>
60 #include <simgear/package/Install.hxx>
61 #include <simgear/debug/logstream.hxx>
62
63 #include <Add-ons/AddonManager.hxx>
64 #include <Airports/airport.hxx>
65 #include <Main/fg_props.hxx>
66 #include <Main/globals.hxx>
67 #include <Main/sentryIntegration.hxx>
68 #include <Navaids/NavDataCache.hxx>
69 #include <Navaids/SHPParser.hxx>
70 #include <Navaids/navrecord.hxx>
71
72
73 #include <Main/MultipleInstanceLock.hxx>
74 #include <Main/fg_init.hxx>
75 #include <Main/locale.hxx>
76 #include <Main/options.hxx>
77 #include <Network/HTTPClient.hxx>
78 #include <Viewer/WindowBuilder.hxx>
79
80 #include "LaunchConfig.hxx"
81 #include "LauncherMainWindow.hxx"
82 #include "LocalAircraftCache.hxx"
83 #include "PathListModel.hxx"
84 #include "SettingsWrapper.hxx"
85 #include "SetupRootDialog.hxx"
86 #include "UnitsModel.hxx"
87
88 #if defined(SG_MAC)
89 #include <GUI/CocoaHelpers.h>
90 #endif
91
92 #if defined(Q_OS_WIN)
93 #include <windows.h> // for GetAsyncKeyState and VK_ constants
94 #endif
95
96 using namespace flightgear;
97 using namespace simgear::pkg;
98 using std::string;
99 using namespace std::chrono_literals;
100
101 namespace { // anonymous namespace
102
103 struct ProgressLabel {
104 NavDataCache::RebuildPhase phase;
105 const char* label;
106 };
107
108 static std::initializer_list<ProgressLabel> progressStrings = {
109 {NavDataCache::REBUILD_READING_APT_DAT_FILES, QT_TRANSLATE_NOOP("initNavCache","Reading airport data")},
110 {NavDataCache::REBUILD_LOADING_AIRPORTS, QT_TRANSLATE_NOOP("initNavCache","Loading airports")},
111 {NavDataCache::REBUILD_FIXES, QT_TRANSLATE_NOOP("initNavCache","Loading waypoint data")},
112 {NavDataCache::REBUILD_NAVAIDS, QT_TRANSLATE_NOOP("initNavCache","Loading navigation data")},
113 {NavDataCache::REBUILD_POIS, QT_TRANSLATE_NOOP("initNavCache","Loading point-of-interest data")}
114 };
115
116 bool initNavCache()
117 {
118 const char* baseLabelKey = QT_TRANSLATE_NOOP("initNavCache", "Initialising navigation data, this may take several minutes");
119 QString baseLabel= qApp->translate("initNavCache", baseLabelKey);
120
121 const auto wflags = Qt::Dialog | Qt::CustomizeWindowHint | Qt::WindowTitleHint | Qt::WindowSystemMenuHint | Qt::MSWindowsFixedSizeDialogHint;
122
123 if (flightgear::ExclusiveInstanceLock::isLocked()) {
124 bool ok = flightgear::ExclusiveInstanceLock::showWaitDialog();
125 if (!ok) {
126 return false;
127 }
128 }
129
130 NavDataCache* cache = NavDataCache::createInstance();
131 if (cache->isRebuildRequired()) {
132 // start the rebuild right now, before showing the dialog
133 cache->rebuild();
134
135 QProgressDialog rebuildProgress(baseLabel,
136 QString() /* cancel text */,
137 0, 100, Q_NULLPTR,
138 wflags);
139 rebuildProgress.setWindowModality(Qt::WindowModal);
140 rebuildProgress.setMinimumWidth(600);
141 rebuildProgress.setAutoReset(false);
142 rebuildProgress.setAutoClose(false);
143 rebuildProgress.show();
144
145 QTimer updateTimer;
146 updateTimer.setInterval(100);
147
148 bool didComplete = false;
149
150 QObject::connect(&updateTimer, &QTimer::timeout, [&cache, &rebuildProgress, &baseLabel, &didComplete]() {
151 auto phase = cache->rebuild();
152 if (phase == NavDataCache::REBUILD_DONE) {
153 rebuildProgress.done(0);
154 didComplete = true;
155 return;
156 }
157
158 auto it = std::find_if(progressStrings.begin(), progressStrings.end(), [phase]
159 (const ProgressLabel& l) { return l.phase == phase; });
160 if (it == progressStrings.end()) {
161 rebuildProgress.setLabelText(baseLabel);
162 } else {
163 QString trans = qApp->translate("initNavCache", it->label);
164 rebuildProgress.setLabelText(trans);
165 }
166
167 if (phase == NavDataCache::REBUILD_UNKNOWN) {
168 rebuildProgress.setValue(0);
169 rebuildProgress.setMaximum(0);
170 } else {
171 rebuildProgress.setValue(static_cast<int>(cache->rebuildPhaseCompletionPercentage()));
172 rebuildProgress.setMaximum(100);
173 }
174 });
175
176 updateTimer.start(); // timer won't actually run until we process events
177 rebuildProgress.exec();
178 updateTimer.stop();
179
180 if (!didComplete) {
181 flightgear::addSentryBreadcrumb("Launcher nav-cache rebuild abandoned by user", "info");
182 return false;
183 }
184
185 flightgear::addSentryBreadcrumb("Launcher nav-cache rebuild complete", "info");
186 }
187
188
189 // if using the launcher, this is when we're done with our exclusive section
190 // from now on, multiple copies can access FG_HOME / the nav-cache
191 flightgear::ExclusiveInstanceLock::destroyInstance();
192 return true;
193 }
194
195 class NaturalEarthDataLoaderThread : public QThread
196 {
197 Q_OBJECT
198 public:
199
200 NaturalEarthDataLoaderThread()
201 {
202 connect(this, &QThread::finished, this, &NaturalEarthDataLoaderThread::onFinished);
203 }
204
205 void abandon()
206 {
207 m_abandoned = true;
208 }
209 protected:
210 void run() override
211 {
212 struct FileAndType {
213 std::string file;
214 flightgear::PolyLine::Type type;
215 bool closed = false;
216 };
217
218 const std::initializer_list<FileAndType> files = {
219 {"ne_10m_coastline.shp", flightgear::PolyLine::COASTLINE, false},
220 {"ne_10m_rivers_lake_centerlines.shp", flightgear::PolyLine::RIVER, false},
221 {"ne_10m_lakes.shp", flightgear::PolyLine::LAKE, true},
222 {"ne_10m_urban_areas.shp", flightgear::PolyLine::URBAN, true}
223 };
224
225 for (const auto& d : files) {
226 if (m_abandoned) {
227 break;
228 }
229
230 loadNaturalEarthFile(d.file, d.type, d.closed);
231 }
232 }
233
234 private:
235 Q_SLOT void onFinished()
236 {
237 if (m_abandoned)
238 return;
239
240
241 flightgear::PolyLine::bulkAddToSpatialIndex(m_parsedLines.begin(), m_parsedLines.end());
242 deleteLater(); // commit suicide
243 }
244
245 void loadNaturalEarthFile(const std::string& aFileName,
246 flightgear::PolyLine::Type aType,
247 bool areClosed)
248 {
249 SGPath path(globals->get_fg_root());
250 path.append( "Geodata" );
251 path.append(aFileName);
252 if (!path.exists())
253 return; // silently fail for now
254
255 flightgear::SHPParser::parsePolyLines(path, aType, m_parsedLines, areClosed);
256 }
257
258 flightgear::PolyLineList m_parsedLines;
259 bool m_abandoned = false;
260 };
261
262 enum class OpenGLStatus
263 {
264 OpenGL21,
265 Unknown,
266 GDIGeneric,
267 Intel14
268 };
269
270 OpenGLStatus checkForWorkingOpenGL()
271 {
272 // request an OpenGL comptability profile, version 2.1
273 // anything lower and we'll crash
274 QSurfaceFormat fmt;
275 fmt.setProfile(QSurfaceFormat::CompatibilityProfile);
276 fmt.setMajorVersion(2);
277 fmt.setMinorVersion(1);
278
279 QOpenGLContext ctx;
280 ctx.setFormat(fmt);
281 if (!ctx.create()) {
282 return OpenGLStatus::Unknown;
283 }
284
285 // from here on, we need to ensure orderly cleanup or some drivers
286 // crash. So we can't early return.
287
288 OpenGLStatus result = OpenGLStatus::Unknown;
289 QOffscreenSurface offSurface;
290 offSurface.setFormat(ctx.format()); // ensure it's compatible
291 offSurface.create();
292
293 if (ctx.makeCurrent(&offSurface)) {
294 result = OpenGLStatus::OpenGL21;
295 std::string renderer = (char*)glGetString(GL_RENDERER);
296 if (renderer == "GDI Generic") {
297 flightgear::addSentryBreadcrumb("Detected GDI generic renderer", "info");
298 result = OpenGLStatus::GDIGeneric;
299 } else if (simgear::strutils::starts_with(renderer, "Intel")) {
300 if (ctx.format().majorVersion() < 2) {
301 flightgear::addSentryBreadcrumb("Detected Intel < 2.1 renderer", "info");
302 result = OpenGLStatus::Intel14;
303 }
304 }
305
306 // ensure the context is no longer current on the offscreen
307 ctx.doneCurrent();
308 }
309
310 offSurface.destroy();
311 return result;
312 }
313
314 } // of anonymous namespace
315
316 static void initQtResources()
317 {
318 Q_INIT_RESOURCE(resources);
319 #if defined(HAVE_QRC_TRANSLATIONS)
320 Q_INIT_RESOURCE(translations);
321 #endif
322 }
323
324 static void simgearMessageOutput(QtMsgType type, const QMessageLogContext &context, const QString &msg)
325 {
326 sgDebugPriority mappedPriority = SG_WARN;
327 switch (type) {
328 case QtDebugMsg: mappedPriority = SG_DEBUG; break;
329 case QtInfoMsg: mappedPriority = SG_INFO; break;
330 case QtWarningMsg: mappedPriority = SG_WARN; break;
331 case QtCriticalMsg: mappedPriority = SG_ALERT; break;
332 case QtFatalMsg: mappedPriority = SG_POPUP; break;
333 }
334
335 static const char* nullFile = "";
336 const char* file = context.file ? context.file : nullFile;
337 const auto s = msg.toStdString();
338 // important we copy the file name here, since QMessageLogContext doesn't
339 sglog().logCopyingFilename(SG_GUI, mappedPriority, file, context.line, "" /*function*/, s);
340 if (type == QtFatalMsg) {
341 // if we abort() here, we get a thread crash which prevents
342 // us actually seeing the error
343 // we'll attempt to continue so we do the SG_POPUP dialog, maybe it works
344 // if it crashes we're no worse off than calling abort() here
345 }
346 }
347
348 namespace flightgear
349 {
350
351 // making this a unique ptr ensures the QApplication will be deleted
352 // event if we forget to call shutdownQtApp. Cleanly destroying this is
353 // important so QPA resources, in particular the XCB thread, are exited
354 // cleanly on quit. However, at present, the official policy is that static
355 // destruction is too late to call this, hence why we have shutdownQtApp()
356
357 static std::unique_ptr<QApplication> static_qApp;
358
359
360 // becuase QTranslator::load (find_translation, internally) doesn't handle the
361 // sciprt part of a language code like: zh-Hans-CN, use this code borrowed from
362 // Qt Creator to do the search manually.
363 void selectUITranslation()
364 {
365 QStringList uiLanguages = QLocale::system().uiLanguages();
366 //qWarning() << "UI languages:" << uiLanguages;
367
368 for (QString locale : std::as_const(uiLanguages)) {
369 // remove script if it exists, eg zh-Hans-CN -> zh-CN
370 locale = QLocale(locale).name();
371 locale.replace('-', '_');
372
373 QTranslator* translator = new QTranslator;
374 ;
375
376 if (translator->load("FlightGear_" + locale, QLatin1String(":/"))) {
377 static_qApp->installTranslator(translator);
378 return;
379 }
380
381 delete translator;
382 }
383 }
384
385 // Only requires FGGlobals to be initialized if 'doInitQSettings' is true.
386 // Safe to call several times.
387 void initApp(int& argc, char** argv, bool doInitQSettings)
388 {
389 static bool qtInitDone = false;
390 static int s_argc;
391
392 if (!qtInitDone) {
393 qtInitDone = true;
394
395 initQtResources(); // can't be called from a namespace
396
397 s_argc = argc; // QApplication only stores a reference to argc,
398 // and may crash if it is freed
399 // http://doc.qt.io/qt-5/qguiapplication.html#QGuiApplication
400
401 // log to simgear instead of the console from Qt, so we go to
402 // whichever log locations SimGear has configured
403 qInstallMessageHandler(simgearMessageOutput);
404
405 // ensure we use desktop OpenGL, don't even fall back to ANGLE, since
406 // this gets into a knot on Optimus setups (since we export the magic
407 // Optimus / AMD symbols in main.cxx).
408 QCoreApplication::setAttribute(Qt::AA_UseDesktopOpenGL);
409
410 // becuase on Windows, Qt only supports integer scaling factors,
411 // forceibly enabling HighDpiScaling is controversial.
412 // leave things unset here, so users can use env var
413 // QT_AUTO_SCREEN_SCALE_FACTOR=1 to enable it at runtime
414
415 #if QT_VERSION < QT_VERSION_CHECK(6, 0, 0)
416 #if !defined (SG_WINDOWS)
417 QCoreApplication::setAttribute(Qt::AA_EnableHighDpiScaling);
418 #endif
419 #endif
420 static_qApp.reset(new QApplication(s_argc, argv));
421 // This processEvents() call prevents a crash when FG is started
422 // under X11 without the built-in launcher and a Qt dialog is
423 // opened (SIGPIPE received as Qt calls IceProcessMessages()).
424 // See https://stackoverflow.com/a/56687321 and
425 // https://bugreports.qt.io/browse/QTBUG-58709 for more info.
426 static_qApp->processEvents();
427 static_qApp->setOrganizationName("FlightGear");
428 static_qApp->setApplicationName("FlightGear");
429 static_qApp->setOrganizationDomain("flightgear.org");
430
431 static_qApp->setDesktopFileName(
432 QStringLiteral("org.flightgear.FlightGear.desktop"));
433
434 QTranslator* fallbackTranslator = new QTranslator(static_qApp.get());
435 if (!fallbackTranslator->load(QLatin1String(":/FlightGear_en_US.qm"))) {
436 qWarning() << "Failed to load the built-in launcher fallback"
437 << "translation (English). If you compiled FlightGear"
438 << "yourself, you may want to pass -DFG_DATA_DIR to"
439 << "CMake so as to allow the FlightGear build system"
440 << "to find FGData.";
441 delete fallbackTranslator;
442 } else {
443 static_qApp->installTranslator(fallbackTranslator);
444 }
445
446 // check for --language=xx option and prefer that over QLocale
447 // detection of the locale if it exists
448 auto lang = simgear::strutils::replace(
449 Options::getArgValue(argc, argv, "--language"),
450 "-",
451 "_");
452 if (!lang.empty()) {
453 QTranslator* translator = new QTranslator(static_qApp.get());
454 QString localeFile = "FlightGear_" + QString::fromStdString(lang);
455 if (translator->load(localeFile, QLatin1String(":/"))) {
456 qInfo() << "Loaded translations based on --language from:" << localeFile;
457 static_qApp->installTranslator(translator);
458 } else {
459 qInfo() << "--language was set, but no translations found at:" << localeFile;
460 delete translator;
461 }
462 } else {
463 selectUITranslation();
464 }
465
466 // reset numeric / collation locales as described at:
467 // http://doc.qt.io/qt-5/qcoreapplication.html#details
468 ::setlocale(LC_NUMERIC, "C");
469 ::setlocale(LC_COLLATE, "C");
470
471
472 #if defined(SG_MAC)
473 if (cocoaIsRunningTranslocated()) {
474 addSentryBreadcrumb("did show translocation warning", "info");
475 const char* titleKey = QT_TRANSLATE_NOOP("macTranslationWarning", "Application running from download location");
476 const char* key = QT_TRANSLATE_NOOP("macTranslationWarning", "FlightGear is running from the download image. For better performance and to avoid potential problems, "
477 "please copy FlightGear to some other location, such as your desktop or Applications folder.");
478 QString msg = qApp->translate("macTranslationWarning", key);
479 QString title = qApp->translate("macTranslationWarning", titleKey);
480
481 QMessageBox::warning(nullptr, title, msg);
482 }
483 #endif
484 }
485
486 #if (QT_VERSION >= QT_VERSION_CHECK(6, 3, 0))
487 QNetworkInformation::loadDefaultBackend();
488 #elif (QT_VERSION >= QT_VERSION_CHECK(6,1,0))
489 bool ok = QNetworkInformation::load(QNetworkInformation::Feature::Reachability);
490 if (!ok) {
491 qInfo() << "network information plugins:" << QNetworkInformation::availableBackends();
492 }
493 #endif
494
495 if (doInitQSettings) {
496 initQSettings();
497 }
498 }
499
500 void shutdownQtApp()
501 {
502 // restore default message handler, otherwise Qt logging on
503 // shutdown crashes once sglog is killed
504 qInstallMessageHandler(nullptr);
505 static_qApp.reset();
506 }
507
508 // Requires FGGlobals to be initialized. Safe to call several times.
509 void initQSettings()
510 {
511 static bool qSettingsInitDone = false;
512
513 if (!qSettingsInitDone) {
514 qRegisterMetaType<QuantityValue>();
515 #if QT_VERSION < QT_VERSION_CHECK(6, 0, 0)
516 qRegisterMetaTypeStreamOperators<QuantityValue>("QuantityValue");
517 #endif
518
519 qSettingsInitDone = true;
520 string fgHome = globals->get_fg_home().utf8Str();
521
522 QSettings::setDefaultFormat(QSettings::IniFormat);
523 QSettings::setPath(QSettings::IniFormat, QSettings::UserScope,
524 QString::fromStdString(fgHome));
525 }
526 }
527
528 QSettings getQSettings()
529 {
530 #if defined(SG_MAC)
531 return QSettings(QSettings::IniFormat, QSettings::UserScope, QCoreApplication::organizationDomain(),
532 "FlightGear_" FLIGHTGEAR_MAJOR_MINOR_VERSION);
533 #else
534 return QSettings(QSettings::IniFormat, QSettings::UserScope, QCoreApplication::organizationName(),
535 "FlightGear_" FLIGHTGEAR_MAJOR_MINOR_VERSION);
536 #endif
537 }
538
539 std::unique_ptr<QSettings> createQSettings()
540 {
541 #if defined(SG_MAC)
542 return std::make_unique<QSettings>(QSettings::IniFormat, QSettings::UserScope, QCoreApplication::organizationDomain(),
543 "FlightGear_" FLIGHTGEAR_MAJOR_MINOR_VERSION);
544 #else
545 return std::make_unique<QSettings>(QSettings::IniFormat, QSettings::UserScope, QCoreApplication::organizationName(),
546 "FlightGear_" FLIGHTGEAR_MAJOR_MINOR_VERSION);
547 #endif
548 }
549
550 bool checkKeyboardModifiersForSettingFGRoot()
551 {
552 initQSettings();
553 #if defined(Q_OS_WIN)
554 const auto altState = GetAsyncKeyState(VK_MENU);
555 const auto shiftState = GetAsyncKeyState(VK_SHIFT);
556 if ((altState < 0) || (shiftState < 0))
557 #else
558 Qt::KeyboardModifiers mods = qApp->queryKeyboardModifiers();
559 if (mods & (Qt::AltModifier | Qt::ShiftModifier))
560 #endif
561 {
562 qWarning() << "Alt/shift pressed during launch";
563 return true;
564 }
565
566 return false;
567 }
568
569 void restartTheApp()
570 {
571 QStringList fgArgs;
572
573 // Spawn a new instance of myApplication:
574 QProcess proc;
575 QStringList args;
576
577 // ensure we release whatever mutex/lock file we have in home,
578 // so the new instance runs in writeable mode
579 fgShutdownHome();
580
581 #if defined(Q_OS_MAC)
582 QDir dir(qApp->applicationDirPath()); // returns the 'MacOS' dir
583 dir.cdUp(); // up to 'contents' dir
584 dir.cdUp(); // up to .app dir
585 // see 'man open' for details, but '-n' ensures we launch a new instance,
586 // and we want to pass remaining arguments to us, not open.
587 args << "-n" << dir.absolutePath() << "--args" << "--launcher" << fgArgs;
588 proc.startDetached("open", args);
589 #else
590 args << "--launcher" << fgArgs;
591 proc.startDetached(qApp->applicationFilePath(), args);
592 #endif
593 qApp->exit(-1);
594 }
595
596 void startLaunchOnExit(const std::vector<std::string>& originalCommandLine)
597 {
598 QStringList fgArgs;
599 for (const auto& arg : originalCommandLine) {
600 fgArgs.append(QString::fromStdString(arg));
601 }
602
603 QProcess proc;
604 #if defined(Q_OS_MAC)
605 QDir dir(qApp->applicationDirPath()); // returns the 'MacOS' dir
606 dir.cdUp(); // up to 'contents' dir
607 dir.cdUp(); // up to .app dir
608
609 QStringList args;
610 // see 'man open' for details, but '-n' ensures we launch a new instance,
611 // and we want to pass remaining arguments to us, not open.
612 args << "-n" << dir.absolutePath() << "--args" << fgArgs;
613 qDebug() << "args" << args;
614 proc.startDetached("open", args);
615 #else
616 proc.startDetached(qApp->applicationFilePath(), fgArgs);
617 #endif
618 }
619
620 void launcherSetSceneryPaths()
621 {
622 globals->clear_fg_scenery();
623
624 // process path sthe user supplied on the existing command line
625 const auto commandLineSceneryPaths = flightgear::Options::sharedInstance()->valuesForOption("fg-scenery");
626 for (const auto& arg : commandLineSceneryPaths) {
627 // each arg can be multiple paths
628 globals->append_fg_scenery(SGPath::pathsFromUtf8(arg));
629 }
630
631 // mimic what options.cxx does, so we can find airport data for parking
632 // positions
633 auto settings = flightgear::getQSettings();
634 // append explicit scenery paths
635 Q_FOREACH(QString path, PathListModel::readEnabledPaths("scenery-paths-v2")) {
636 globals->append_fg_scenery(path.toStdString());
637 }
638
639 // append the TerraSync path
640 QString downloadDir = settings.value("download-dir").toString();
641 if (downloadDir.isEmpty()) {
642 downloadDir = QString::fromStdString(flightgear::defaultDownloadDir().utf8Str());
643 }
644
645 SGPath terraSyncDir(downloadDir.toStdString());
646 terraSyncDir.append("TerraSync");
647 if (terraSyncDir.exists()) {
648 globals->append_fg_scenery(terraSyncDir);
649 }
650
651 // add the installation path since it contains default airport data,
652 // if terrasync is disabled or on first-launch
653 const SGPath rootScenery = globals->get_fg_root() / "Scenery";
654 if (rootScenery.exists()) {
655 globals->append_fg_scenery(rootScenery);
656 }
657 }
658
659 bool runLauncherDialog()
660 {
661 auto glCheckResult = checkForWorkingOpenGL();
662 if (glCheckResult != OpenGLStatus::OpenGL21) {
663 QMessageBox::critical(nullptr, "Failed to find graphics drivers",
664 "This computer is missing suitable graphics drivers (OpenGL) to run FlightGear. "
665 "Please download and install drivers from your graphics card vendor.");
666 return false;
667 }
668
669 // Used for NavDataCache initialization: needed to find the apt.dat files
670 launcherSetSceneryPaths();
671 // startup the nav-cache now. This pre-empts normal startup of
672 // the cache, but no harm done. (Providing scenery paths are consistent)
673
674 bool ok = initNavCache();
675 if (!ok) {
676 return false;
677 }
678
679 auto options = flightgear::Options::sharedInstance();
680 if (options->isOptionSet("download-dir")) {
681 // user set download-dir on command line, don't mess with it in the
682 // launcher GUI. We'll disable the UI.
683 LaunchConfig::setEnableDownloadDirUI(false);
684 } else {
685 auto settings = flightgear::getQSettings();
686 QString downloadDir = settings.value("download-dir").toString();
687 if (!downloadDir.isEmpty()) {
688 options->setOption("download-dir", downloadDir.toStdString());
689 }
690 }
691
692 fgInitPackageRoot();
693
694 // setup package language
695 auto lang = options->valueForOption("language");
696 if (lang.empty()) {
697 const auto langName = QLocale::languageToString(QLocale{}.language());
698 lang = langName.toStdString();
699 }
700
701 // we will re-do this later, but we want to access translated strings
702 // from within the launcher
703 globals->get_locale()->selectLanguage(lang);
704 globals->packageRoot()->setLocale(globals->get_locale()->getPreferredLanguage());
705
706 QPointer<NaturalEarthDataLoaderThread> naturalEarthLoader = new NaturalEarthDataLoaderThread;
707 naturalEarthLoader->start();
708
709 // avoid double Apple menu and other weirdness if both Qt and OSG
710 // try to initialise various Cocoa structures.
711 flightgear::WindowBuilder::setPoseAsStandaloneApp(false);
712
713
714 FGHTTPClient::getOrCreate();
715
716 LauncherMainWindow dlg(false);
717
718 if (options->isOptionSet("fullscreen")) {
719 dlg.showFullScreen();
720 } else {
721 dlg.setVisible(true);
722 }
723
724 int appResult = qApp->exec();
725 // avoid crashes / NavCache races if the loader is still running after
726 // the launcher exits
727 if (naturalEarthLoader) {
728 naturalEarthLoader->abandon();
729 }
730
731 // avoid a race-y crash on the locale, if a scan thread is
732 // still running: this reset will cancel any running scan
733 LocalAircraftCache::reset();
734
735 // don't set scenery paths twice
736 globals->clear_fg_scenery();
737 globals->get_locale()->clear();
738
739 if (appResult <= 0) {
740 return false; // quit
741 }
742
743 return true;
744 }
745
746 bool runInAppLauncherDialog()
747 {
748 LauncherMainWindow dlg(true);
749 bool accepted = dlg.execInApp();
750 if (!accepted) {
751 return false;
752 }
753
754 return true;
755 }
756
757 static const char* static_lockFileDialog_Title =
758 QT_TRANSLATE_NOOP("LockFileDialog", "Multiple copies of FlightGear running");
759 static const char* static_lockFileDialog_Text =
760 QT_TRANSLATE_NOOP("LockFileDialog",
761 "FlightGear has detected another copy is already running. "
762 "This copy will run in read-only mode, so downloads will not be possible, "
763 "and settings will not be saved.");
764 static const char* static_lockFileDialog_Info =
765 QT_TRANSLATE_NOOP("LockFileDialog",
766 "If you are sure another copy is not running on this computer, "
767 "you can choose to reset the lock file, and run this copy as normal. "
768 "Alternatively, you can close this copy of the software.");
769
770 LockFileDialogResult showLockFileDialog()
771 {
772 flightgear::addSentryBreadcrumb("showing lock-file dialog", "info");
773
774 QString title = qApp->translate("LockFileDialog", static_lockFileDialog_Title);
775 QString text = qApp->translate("LockFileDialog", static_lockFileDialog_Text);
776 QString infoText = qApp->translate("LockFileDialog", static_lockFileDialog_Info);
777
778 QMessageBox mb;
779 mb.setIconPixmap(QPixmap(":/app-icon-large"));
780 mb.setWindowTitle(title);
781 mb.setText(text);
782 mb.addButton(QMessageBox::Ok);
783 mb.setDefaultButton(QMessageBox::Ok);
784 #if !defined(SG_WINDOWS)
785 mb.addButton(QMessageBox::Reset);
786 mb.setInformativeText(infoText);
787 #endif
788 mb.addButton(QMessageBox::Close);
789
790 // no lock file on Windows, so don't show the reset text/button. Enabling it
791 // causes more errors due to people clicking it erroneously
792 #if !defined(SG_WINDOWS)
793 mb.setInformativeText(infoText);
794 mb.addButton(QMessageBox::Reset);
795 #endif
796
797 int r = mb.exec();
798 if (r == QMessageBox::Reset)
799 return LockFileReset;
800 if (r == QMessageBox::Close)
801 return LockFileQuit;
802 return LockFileContinue;
803 }
804
805 bool showSetupRootDialog(SetupRootReason r)
806 {
807 return SetupRootDialog::runDialog(r);
808 }
809
810 bool showUpdateRootDialog(SetupRootReason r)
811 {
812 return SetupRootDialog::runUpdateDialog(r);
813 }
814
815
816 SetupRootResult restoreUserSelectedRoot(SGPath& path)
817 {
818 return SetupRootDialog::restoreUserSelectedRoot(path);
819 }
820
821 // defined here since it uses QWidgets
822 bool ExclusiveInstanceLock::showWaitDialog()
823 {
824 const char* waitForOtherMsg = QT_TRANSLATE_NOOP("initNavCache", "Another copy of FlightGear is preparing data files. Waiting for it to finish.");
825 QString m = qApp->translate("initNavCache", waitForOtherMsg);
826
827 const auto wflags = Qt::Dialog | Qt::CustomizeWindowHint | Qt::WindowTitleHint | Qt::WindowSystemMenuHint | Qt::MSWindowsFixedSizeDialogHint;
828
829 addSentryBreadcrumb("showing wait for other process dialog", "info");
830
831 QProgressDialog waitDialog(m,
832 QString() /* cancel text */,
833 0, 0, Q_NULLPTR,
834 wflags);
835 waitDialog.setWindowModality(Qt::WindowModal);
836 waitDialog.setMinimumWidth(600);
837 waitDialog.setAutoReset(false);
838 waitDialog.setAutoClose(false);
839 waitDialog.show();
840
841 QTimer updateTimer;
842 updateTimer.setInterval(500);
843 bool done = false;
844
845 QObject::connect(&updateTimer, &QTimer::timeout, [&waitDialog, &done]() {
846 auto lockedReason = isLocked();
847 if (!lockedReason.has_value()) {
848 waitDialog.done(0);
849 done = true;
850 return;
851 }
852 });
853
854 updateTimer.start(); // timer won't actually run until we process events
855 waitDialog.exec();
856 updateTimer.stop();
857
858 if (!done) {
859 addSentryBreadcrumb("wait on other process abandoned by user", "info");
860 return false;
861 }
862
863 addSentryBreadcrumb("done waiting for other process lock dialog", "info");
864 return true;
865 }
866
867 } // of namespace flightgear
868
869 #include "QtLauncher.moc"