Debian Codegraph @

src/GUI/LauncherController.cxx

raw symbols SCIP
1
2 // SPDX-FileCopyrightText: 2018 James Turner
3 // SPDX-License-Identifier: GPL-2.0-or-later
4
5 #include "config.h"
6 #include "simgear/package/Root.hxx"
7
8 #include "LauncherController.hxx"
9
10 // Qt headers
11 #include <QDebug>
12 #include <QDesktopServices>
13 #include <QFileDialog>
14 #include <QJSEngine>
15 #include <QMessageBox>
16 #include <QNetworkAccessManager>
17 #include <QNetworkDiskCache>
18 #include <QPushButton>
19 #include <QQmlComponent>
20 #include <QQuickWindow>
21 #include <QSettings>
22
23 #if (QT_VERSION >= QT_VERSION_CHECK(6, 1, 0))
24 #include <QNetworkInformation>
25 #endif
26
27 // simgear headers
28 #include <simgear/package/Install.hxx>
29 #include <simgear/environment/metar.hxx>
30 #include <simgear/structure/exception.hxx>
31
32 // FlightGear headers
33 #include <Network/HTTPClient.hxx>
34 #include <Main/globals.hxx>
35 #include <Airports/airport.hxx>
36 #include <Main/options.hxx>
37 #include <Main/fg_init.hxx>
38 #include <Main/fg_props.hxx>
39 #include <Main/sentryIntegration.hxx>
40
41 #include "AircraftItemModel.hxx"
42 #include "AircraftProxyModel.hxx"
43 #include "AirportDiagram.hxx"
44 #include "CarrierDiagram.hxx"
45 #include "CarriersLocationModel.hxx"
46 #include "DefaultAircraftLocator.hxx"
47 #include "FlightPlanController.hxx"
48 #include "GettingStartedScope.hxx"
49 #include "GettingStartedTip.hxx"
50 #include "GettingStartedTipsController.hxx"
51 #include "HoverArea.hxx"
52 #include "LaunchConfig.hxx"
53 #include "LauncherArgumentTokenizer.hxx"
54 #include "LauncherNotificationsController.hxx"
55 #include "LocationController.hxx"
56 #include "MPServersModel.h"
57 #include "ModelDataExtractor.hxx"
58 #include "NavaidDiagram.hxx"
59 #include "NavaidSearchModel.hxx"
60 #include "PathUrlHelper.hxx"
61 #include "PixmapImageItem.hxx"
62 #include "PreviewImageItem.hxx"
63 #include "QmlAircraftInfo.hxx"
64 #include "QmlPositioned.hxx"
65 #include "QmlRadioButtonHelper.hxx"
66 #include "QmlStringListModel.hxx"
67 #include "QtLauncher.hxx"
68 #include "RecentAircraftModel.hxx"
69 #include "RecentLocationsModel.hxx"
70 #include "RouteDiagram.hxx"
71 #include "SettingsWrapper.hxx"
72 #include "SetupRootDialog.hxx"
73 #include "StackController.hxx"
74 #include "ThumbnailImageItem.hxx"
75 #include "TipBackgroundBox.hxx"
76 #include "UnitsModel.hxx"
77 #include "UpdateChecker.hxx"
78
79
80 using namespace simgear::pkg;
81 using namespace std::chrono_literals;
82
83 LauncherController::LauncherController(QObject *parent, QWindow* window) :
84 QObject(parent),
85 m_window(window)
86 {
87 m_serversModel = new MPServersModel(this);
88 m_location = new LocationController(this);
89 m_locationHistory = new RecentLocationsModel(this);
90 m_selectedAircraftInfo = new QmlAircraftInfo(this);
91
92 // ensure uninstall disables the fly button
93 connect(m_selectedAircraftInfo, &QmlAircraftInfo::downloadChanged, this, &LauncherController::canFlyChanged);
94
95 m_config = new LaunchConfig(this);
96 connect(m_config, &LaunchConfig::collect, this, &LauncherController::collectAircraftArgs);
97 connect(m_config, &LaunchConfig::save, this, &LauncherController::saveAircraft);
98 connect(m_config, &LaunchConfig::restore, this, &LauncherController::restoreAircraft);
99
100 m_flightPlan = new FlightPlanController(this, m_config);
101
102 m_location->setLaunchConfig(m_config);
103 connect(m_location, &LocationController::descriptionChanged,
104 this, &LauncherController::summaryChanged);
105
106 m_aircraftModel = new AircraftItemModel(this);
107 m_installedAircraftModel = new AircraftProxyModel(this, m_aircraftModel);
108 m_installedAircraftModel->setInstalledFilterEnabled(true);
109
110 m_aircraftWithUpdatesModel = new AircraftProxyModel(this, m_aircraftModel);
111 m_aircraftWithUpdatesModel->setInstalledFilterEnabled(true);
112 m_aircraftWithUpdatesModel->setHaveUpdateFilterEnabled(true);
113
114 m_browseAircraftModel = new AircraftProxyModel(this, m_aircraftModel);
115 m_browseAircraftModel->setRatingFilterEnabled(true);
116
117 m_aircraftSearchModel = new AircraftProxyModel(this, m_aircraftModel);
118
119 m_favouriteAircraftModel = new AircraftProxyModel(this, m_aircraftModel);
120 m_favouriteAircraftModel->setShowFavourites(true);
121
122 m_aircraftHistory = new RecentAircraftModel(m_aircraftModel, this);
123
124 connect(m_aircraftModel, &AircraftItemModel::aircraftInstallCompleted,
125 this, &LauncherController::onAircraftInstalledCompleted);
126 connect(m_aircraftModel, &AircraftItemModel::aircraftInstallFailed,
127 this, &LauncherController::onAircraftInstallFailed);
128
129 connect(LocalAircraftCache::instance(),
130 &LocalAircraftCache::scanCompleted,
131 this, &LauncherController::updateSelectedAircraft);
132
133 auto settings = flightgear::getQSettings();
134 m_aircraftModel->setPackageRoot(globals->packageRoot());
135
136 m_aircraftGridMode = settings.value("aircraftGridMode").toBool();
137
138 m_subsystemIdleTimer = new QTimer(this);
139 m_subsystemIdleTimer->setInterval(5);
140 connect(m_subsystemIdleTimer, &QTimer::timeout, []()
141 {globals->get_subsystem_mgr()->update(0.0);});
142 m_subsystemIdleTimer->start();
143
144 QRect winRect = settings.value("window-geometry").toRect();
145
146 if (winRect.isValid()) {
147 m_window->setGeometry(winRect);
148 } else {
149 m_window->setWidth(600);
150 m_window->setHeight(800);
151 }
152
153 if (settings.contains("window-state")) {
154 const auto ws = static_cast<Qt::WindowState>(settings.value("window-state").toInt());
155 const auto options = flightgear::Options::sharedInstance();
156 if (ws == Qt::WindowState::WindowFullScreen && options->isBoolOptionDisable("fullscreen")) {
157 // Last time we used fullscreen, but now we explicitly turn off fullscreen
158 m_window->setWindowState(Qt::WindowState::WindowNoState);
159 }
160 else {
161 m_window->setWindowState(ws);
162 }
163 }
164
165 // count launches; we use this to trigger first-run and periodic notices
166 // in the UI.
167 m_launchCount = settings.value("launch-count", 0).toInt();
168 settings.setValue("launch-count", m_launchCount + 1);
169
170 std::ostringstream os;
171 string_list versionParts = simgear::strutils::split(FLIGHTGEAR_VERSION, ".");
172 if (versionParts.size() >= 2) {
173 // build a setting key like launch-count-2020-2
174 QString versionedCountKey = QString::fromStdString("launch-count-" + versionParts.at(0) + "-" + versionParts.at(1));
175 m_versionLaunchCount = settings.value(versionedCountKey, 0).toInt();
176 settings.setValue(versionedCountKey, m_versionLaunchCount + 1);
177 }
178
179 #if (QT_VERSION >= QT_VERSION_CHECK(6, 1, 0))
180 if (QNetworkInformation::instance()) {
181 connect(QNetworkInformation::instance(), &QNetworkInformation::reachabilityChanged,
182 this, &LauncherController::onReachabilityChanged);
183 onReachabilityChanged();
184 } else {
185 qWarning() << "No network information available";
186 delayedPackageRefresh();
187 }
188 #else
189 delayedPackageRefresh();
190 #endif
191
192 QTimer::singleShot(2s, this, &LauncherController::checkForOldDownloadDir);
193 }
194
195 void LauncherController::delayedPackageRefresh()
196 {
197 QTimer::singleShot(2s, this, []() {
198 auto pkgRoot = globals->packageRoot();
199 pkgRoot->refresh(true);
200 });
201 }
202
203 void LauncherController::initQML(int& styleTypeId)
204 {
205 qmlRegisterUncreatableType<LauncherController>("FlightGear.Launcher", 1, 0, "LauncherController", "no");
206 qmlRegisterUncreatableType<LocationController>("FlightGear.Launcher", 1, 0, "LocationController", "no");
207 qmlRegisterUncreatableType<FlightPlanController>("FlightGear.Launcher", 1, 0, "FlightPlanController", "no");
208 qmlRegisterUncreatableType<UpdateChecker>("FlightGear.Launcher", 1, 0, "UpdateChecker", "for enums");
209
210 qmlRegisterType<LauncherArgumentTokenizer>("FlightGear.Launcher", 1, 0, "ArgumentTokenizer");
211 qmlRegisterUncreatableType<QAbstractItemModel>("FlightGear.Launcher", 1, 0, "QAIM", "no");
212 qmlRegisterUncreatableType<AircraftProxyModel>("FlightGear.Launcher", 1, 0, "AircraftProxyModel", "no");
213 qmlRegisterUncreatableType<RecentAircraftModel>("FlightGear.Launcher", 1, 0, "RecentAircraftModel", "no");
214 qmlRegisterUncreatableType<RecentLocationsModel>("FlightGear.Launcher", 1, 0, "RecentLocationsModel", "no");
215 qmlRegisterUncreatableType<LaunchConfig>("FlightGear.Launcher", 1, 0, "LaunchConfig", "Singleton API");
216 qmlRegisterUncreatableType<MPServersModel>("FlightGear.Launcher", 1, 0, "MPServers", "Singleton API");
217
218 qmlRegisterType<NavaidSearchModel>("FlightGear", 1, 0, "NavaidSearch");
219 qmlRegisterType<CarriersLocationModel>("FlightGear", 1, 0, "CarriersModel");
220
221 qmlRegisterUncreatableType<Units>("FlightGear", 1, 0, "Units", "Only for enum");
222 qmlRegisterType<UnitsModel>("FlightGear", 1, 0, "UnitsModel");
223
224 qmlRegisterType<FileDialogWrapper>("FlightGear", 1, 0, "FileDialog");
225 qmlRegisterType<QmlAircraftInfo>("FlightGear.Launcher", 1, 0, "AircraftInfo");
226
227 qmlRegisterUncreatableType<LocalAircraftCache>("FlightGear.Launcher", 1, 0, "LocalAircraftCache", "Aircraft cache");
228 qmlRegisterUncreatableType<AircraftItemModel>("FlightGear.Launcher", 1, 0, "AircraftModel", "Built-in model");
229 qmlRegisterType<ThumbnailImageItem>("FlightGear.Launcher", 1, 0, "ThumbnailImage");
230 qmlRegisterType<PreviewImageItem>("FlightGear.Launcher", 1, 0, "PreviewImage");
231
232 qmlRegisterType<QmlPositioned>("FlightGear", 1, 0, "Positioned");
233 // this is a Q_GADGET, but we need to register it for use in return types, etc
234 qRegisterMetaType<QmlGeod>();
235
236 qmlRegisterType<PixmapImageItem>("FlightGear", 1, 0, "PixmapImage");
237 qmlRegisterType<AirportDiagram>("FlightGear", 1, 0, "AirportDiagram");
238 qmlRegisterType<CarrierDiagram>("FlightGear", 1, 0, "CarrierDiagram");
239 qmlRegisterType<NavaidDiagram>("FlightGear", 1, 0, "NavaidDiagram");
240 qmlRegisterType<RouteDiagram>("FlightGear", 1, 0, "RouteDiagram");
241 qmlRegisterType<QmlRadioButtonGroup>("FlightGear", 1, 0, "RadioButtonGroup");
242 qmlRegisterType<HoverArea>("FlightGear", 1, 0, "HoverArea");
243 qmlRegisterType<StackController>("FlightGear", 1, 0, "StackController");
244
245 qmlRegisterType<ModelDataExtractor>("FlightGear", 1, 0, "ModelDataExtractor");
246 qmlRegisterType<QmlStringListModel>("FlightGear", 1, 0, "StringListModel");
247
248
249 qmlRegisterSingletonType(QUrl("qrc:/qml/OverlayShared.qml"), "FlightGear", 1, 0, "OverlayShared");
250 styleTypeId = qmlRegisterSingletonType(QUrl("qrc:/qml/Style.qml"), "FlightGear", 1, 0, "Style");
251
252 qmlRegisterType<GettingStartedScope>("FlightGear", 1, 0, "GettingStartedScope");
253 qmlRegisterType<GettingStartedTipsController>("FlightGear", 1, 0, "GettingStartedController");
254 qmlRegisterType<GettingStartedTip>("FlightGear", 1, 0, "GettingStartedTip");
255 qmlRegisterType<TipBackgroundBox>("FlightGear", 1, 0, "TipBackgroundBox");
256
257 QNetworkDiskCache* diskCache = new QNetworkDiskCache(this);
258 SGPath cachePath = globals->get_fg_home() / "PreviewsCache";
259 diskCache->setCacheDirectory(QString::fromStdString(cachePath.utf8Str()));
260
261 QNetworkAccessManager* netAccess = new QNetworkAccessManager(this);
262 netAccess->setCache(diskCache);
263 PreviewImageItem::setGlobalNetworkAccess(netAccess);
264 }
265
266 void LauncherController::setInAppMode()
267 {
268 m_inAppMode = true;
269 m_keepRunningInAppMode = true;
270 m_appModeResult = true;
271 emit inAppChanged();
272 }
273
274 bool LauncherController::keepRunningInAppMode() const
275 {
276 return m_keepRunningInAppMode;
277 }
278
279 bool LauncherController::inAppResult() const
280 {
281 return m_appModeResult;
282 }
283
284 void LauncherController::initialRestoreSettings()
285 {
286 m_selectedAircraft = m_aircraftHistory->mostRecent();
287 if (m_selectedAircraft.isEmpty()) {
288 // select the default aircraft specified in defaults.xml
289 flightgear::DefaultAircraftLocator da;
290 if (da.foundPath().exists()) {
291 m_selectedAircraft = QUrl::fromLocalFile(QString::fromStdString(da.foundPath().utf8Str()));
292 qDebug() << "Restored default aircraft:" << m_selectedAircraft;
293 } else {
294 qWarning() << "Completely failed to find the default aircraft";
295 }
296 }
297
298 m_location->restoreSearchHistory();
299 QVariantMap currentLocation = m_locationHistory->mostRecent();
300 if (currentLocation.isEmpty()) {
301 // use the default
302 std::string defaultAirport = flightgear::defaultAirportICAO();
303 FGAirportRef apt = FGAirport::findByIdent(defaultAirport);
304 if (apt) {
305 currentLocation["location-id"] = static_cast<qlonglong>(apt->guid());
306 currentLocation["location-apt-runway"] = "ACTIVE";
307 } // otherwise we failed to find the default airport in the nav-db :(
308 }
309 m_location->restoreLocation(currentLocation);
310
311 emit selectedAircraftChanged(m_selectedAircraft);
312
313 updateSelectedAircraft();
314 m_serversModel->requestRestore();
315 m_aircraftState = m_config->getValueForKey("", "selected-aircraft-state", QString()).toString();
316 emit selectedAircraftStateChanged();
317
318 emit summaryChanged();
319 }
320
321 void LauncherController::saveSettings()
322 {
323 auto settings = flightgear::getQSettings();
324 if (m_window->windowState() != Qt::WindowMaximized) {
325 settings.setValue("window-geometry", m_window->geometry());
326 }
327 settings.setValue("window-state", m_window->windowState());
328
329 m_config->saveConfigToINI();
330 m_aircraftHistory->saveToSettings();
331 m_locationHistory->saveToSettings();
332 }
333
334 void LauncherController::collectAircraftArgs()
335 {
336 if (m_skipAircraftFromArgs)
337 return;
338
339 // aircraft
340 if (!m_selectedAircraft.isEmpty()) {
341 if (m_selectedAircraft.isLocalFile()) {
342 QFileInfo setFileInfo(m_selectedAircraft.toLocalFile());
343 m_config->setArg("aircraft-dir", setFileInfo.dir().absolutePath());
344 QString setFile = setFileInfo.fileName();
345 Q_ASSERT(setFile.endsWith("-set.xml"));
346 setFile.truncate(setFile.size() - 8); // drop the '-set.xml' portion
347 m_config->setArg("aircraft", setFile);
348 } else if (m_selectedAircraft.scheme() == "package") {
349 // no need to set aircraft-dir, handled by the corresponding code
350 // in fgInitAircraft
351 m_config->setArg("aircraft", m_selectedAircraft.path());
352 } else {
353 qWarning() << "unsupported aircraft launch URL" << m_selectedAircraft;
354 }
355 }
356
357 if (m_selectedAircraftInfo->hasStates() && !m_aircraftState.isEmpty()) {
358 QString state = m_aircraftState;
359 if ((m_aircraftState == "auto") && !m_selectedAircraftInfo->haveExplicitAutoState()) {
360 state = selectAircraftStateAutomatically();
361 }
362
363 if (!state.isEmpty()) {
364 m_config->setArg("state", state);
365 }
366 }
367 }
368
369 void LauncherController::saveAircraft()
370 {
371 m_config->setValueForKey("", "selected-aircraft", m_selectedAircraft);
372 if (!m_aircraftState.isEmpty()) {
373 m_config->setValueForKey("", "selected-aircraft-state", m_aircraftState);
374 }
375 }
376
377 void LauncherController::restoreAircraft()
378 {
379 m_selectedAircraft = m_config->getValueForKey("", "selected-aircraft", QUrl()).toUrl();
380 m_aircraftState = m_config->getValueForKey("", "selected-aircraft-state", QString()).toString();
381 emit selectedAircraftChanged(m_selectedAircraft);
382 updateSelectedAircraft();
383 emit selectedAircraftStateChanged();
384 }
385
386 void LauncherController::doRun()
387 {
388 flightgear::addSentryBreadcrumb("Launcher: fly!:" + m_selectedAircraft.toString().toStdString(), "info");
389 flightgear::Options* opt = flightgear::Options::sharedInstance();
390 m_config->reset();
391 m_config->collect();
392
393 m_aircraftHistory->insert(m_selectedAircraft);
394
395 QVariant locSet = m_location->saveLocation();
396 m_locationHistory->insert(locSet);
397
398 flightgear::addSentryBreadcrumb("acft path:" + m_selectedAircraftInfo->pathOnDisk().toStdString(), "info");
399
400 // aircraft paths
401 auto settings = flightgear::getQSettings();
402 QString downloadDir = settings.value("downloadSettings/downloadDir").toString();
403 if (!downloadDir.isEmpty()) {
404 QDir d(downloadDir);
405 if (!d.exists()) {
406 int result = QMessageBox::question(nullptr, tr("Create download folder?"),
407 tr("The selected location for downloads does not exist. (%1) Create it?").arg(downloadDir),
408 QMessageBox::Yes | QMessageBox::No | QMessageBox::Cancel);
409 if (result == QMessageBox::Cancel) {
410 return;
411 }
412
413 if (result == QMessageBox::Yes) {
414 d.mkpath(downloadDir);
415 }
416 }
417 }
418
419 if (settings.contains("restore-defaults-on-run")) {
420 settings.remove("restore-defaults-on-run");
421 opt->addOption("restore-defaults", "");
422 }
423
424 m_config->applyToOptions();
425 saveSettings();
426 }
427
428 void LauncherController::doApply()
429 {
430 // aircraft
431 if (!m_selectedAircraft.isEmpty()) {
432 std::string aircraftPropValue,
433 aircraftDir;
434
435 if (m_selectedAircraft.isLocalFile()) {
436 QFileInfo setFileInfo(m_selectedAircraft.toLocalFile());
437 QString setFile = setFileInfo.fileName();
438 Q_ASSERT(setFile.endsWith("-set.xml"));
439 setFile.truncate(setFile.size() - 8); // drop the '-set.xml' portion
440 aircraftDir = setFileInfo.dir().absolutePath().toStdString();
441 aircraftPropValue = setFile.toStdString();
442 } else if (m_selectedAircraft.scheme() == "package") {
443 // no need to set aircraft-dir, handled by the corresponding code
444 // in fgInitAircraft
445 aircraftPropValue = m_selectedAircraft.path().toStdString();
446 } else {
447 qWarning() << "unsupported aircraft launch URL" << m_selectedAircraft;
448 }
449
450 m_aircraftHistory->insert(m_selectedAircraft);
451 globals->get_props()->setStringValue("/sim/aircraft", aircraftPropValue);
452 globals->get_props()->setStringValue("/sim/aircraft-dir", aircraftDir);
453 }
454
455 m_location->setLocationProperties();
456 saveSettings();
457 }
458
459
460 QString LauncherController::selectAircraftStateAutomatically()
461 {
462 if (!m_selectedAircraftInfo)
463 return {};
464
465 if (m_location->isAirborneLocation() && m_selectedAircraftInfo->hasState("cruise")) {
466 const double altitudeFt = m_location->altitude().convertToUnit(Units::FeetMSL).value;
467 if (altitudeFt > 6000) {
468 return "cruise";
469 }
470 }
471
472 if (m_location->isCarrier() && m_location->isAirborneLocation() && m_selectedAircraftInfo->hasState("carrier-approach")) {
473 return "carrier-approach";
474 }
475
476 if (m_location->isAirborneLocation() && m_selectedAircraftInfo->hasState("approach")) {
477 return "approach";
478 }
479
480 if (m_location->isParkedLocation()) {
481 if (m_selectedAircraftInfo->hasState("parked")) {
482 return "parked";
483 }
484 if (m_selectedAircraftInfo->hasState("parking")) {
485 return "parking";
486 }
487 }
488
489 if (m_location->isCarrier() && m_selectedAircraftInfo->hasState("carrier-take-off")) {
490 return "carrier-take-off";
491 }
492
493 if (m_selectedAircraftInfo->hasState("take-off")) {
494 return "take-off";
495 }
496
497 return {}; // failed to compute, give up
498 }
499
500 void LauncherController::maybeUpdateSelectedAircraft(QModelIndex index)
501 {
502 QUrl u = index.data(AircraftURIRole).toUrl();
503 if (u == m_selectedAircraft) {
504 // potentially enable the run button now!
505 updateSelectedAircraft();
506 }
507 }
508
509 void LauncherController::updateSelectedAircraft()
510 {
511 m_selectedAircraftInfo->setUri(m_selectedAircraft);
512 QModelIndex index = m_aircraftModel->indexOfAircraftURI(m_selectedAircraft);
513 if (index.isValid()) {
514 // we have to default to unknown here, until we have an explicit
515 // way to determine if it's a regular aircraft or not
516 m_aircraftType = Unknown;
517 if (index.data(AircraftIsHelicopterRole).toBool()) {
518 m_aircraftType = Helicopter;
519 } else if (index.data(AircraftIsSeaplaneRole).toBool()) {
520 m_aircraftType = Seaplane;
521 }
522 }
523
524 if (!m_aircraftState.isEmpty()) {
525 if (!m_selectedAircraftInfo->hasState(m_aircraftState)) {
526 m_aircraftState.clear();
527 emit selectedAircraftStateChanged();
528 }
529 }
530
531 emit canFlyChanged();
532 }
533
534 bool LauncherController::canFly() const
535 {
536 QModelIndex index = m_aircraftModel->indexOfAircraftURI(m_selectedAircraft);
537 if (!index.isValid()) {
538 return false;
539 }
540
541 int status = index.data(AircraftPackageStatusRole).toInt();
542 bool canRun = (status == LocalAircraftCache::PackageInstalled);
543 return canRun;
544 }
545
546 void LauncherController::downloadDirChanged(QString path)
547 {
548 // this can get run if the UI is disabled, just bail out before doing
549 // anything permanent.
550 if (!m_config->enableDownloadDirUI()) {
551 return;
552 }
553
554 // if the default dir is passed in, map that back to the empty string
555 if (path == m_config->defaultDownloadDir()) {
556 path.clear();
557 }
558
559 auto options = flightgear::Options::sharedInstance();
560 if (options->valueForOption("download-dir") == path.toStdString()) {
561 // this works because we propagate the value from QSettings to
562 // the flightgear::Options object in runLauncherDialog()
563 // so the options object always contains our current idea of this
564 // value
565 return;
566 }
567
568 if (!path.isEmpty()) {
569 options->setOption("download-dir", path.toStdString());
570 } else {
571 options->clearOption("download-dir");
572 }
573
574 m_config->setValueForKey("", "download-dir", path);
575 saveSettings();
576 flightgear::restartTheApp();
577 }
578
579 QmlAircraftInfo *LauncherController::selectedAircraftInfo() const
580 {
581 return m_selectedAircraftInfo;
582 }
583
584 void LauncherController::restoreLocation(QVariant var)
585 {
586 m_location->restoreLocation(var.toMap());
587 }
588
589 QUrl LauncherController::selectedAircraft() const
590 {
591 return m_selectedAircraft;
592 }
593
594 bool LauncherController::matchesSearch(QString term, QStringList keywords) const
595 {
596 Q_FOREACH(QString s, keywords) {
597 if (s.contains(term, Qt::CaseInsensitive)) {
598 return true;
599 }
600 }
601
602 return false;
603 }
604
605 bool LauncherController::isSearchActive() const
606 {
607 return !m_settingsSearchTerm.isEmpty();
608 }
609
610 QStringList LauncherController::settingsSummary() const
611 {
612 return m_settingsSummary;
613 }
614
615 QStringList LauncherController::environmentSummary() const
616 {
617 return m_environmentSummary;
618 }
619
620
621 void LauncherController::setSelectedAircraft(QUrl selectedAircraft)
622 {
623 if (m_selectedAircraft == selectedAircraft)
624 return;
625
626 m_selectedAircraft = selectedAircraft;
627 m_aircraftState.clear();
628
629 updateSelectedAircraft();
630 emit selectedAircraftChanged(m_selectedAircraft);
631 emit selectedAircraftStateChanged();
632 }
633
634 void LauncherController::setSettingsSearchTerm(QString settingsSearchTerm)
635 {
636 if (m_settingsSearchTerm == settingsSearchTerm)
637 return;
638
639 m_settingsSearchTerm = settingsSearchTerm;
640 emit searchChanged();
641 }
642
643 void LauncherController::setSettingsSummary(QStringList settingsSummary)
644 {
645 if (m_settingsSummary == settingsSummary)
646 return;
647
648 m_settingsSummary = settingsSummary;
649 emit summaryChanged();
650 }
651
652 void LauncherController::setEnvironmentSummary(QStringList environmentSummary)
653 {
654 if (m_environmentSummary == environmentSummary)
655 return;
656
657 m_environmentSummary = environmentSummary;
658 emit summaryChanged();
659 }
660
661 void LauncherController::fly()
662 {
663 // avoid duplicate calls to fly, if the user's system is slow, and they
664 // generate multiple clicks / events before the qApp->exit() fires.
665 // without this, we can apply options, etc twice which breaks.
666 if (m_flyRequested)
667 return;
668 m_flyRequested = true;
669
670 if (m_inAppMode) {
671 doApply();
672 m_keepRunningInAppMode = false;
673 m_appModeResult = true;
674 } else {
675 doRun();
676 qApp->exit(1);
677 }
678 }
679
680 void LauncherController::quit()
681 {
682 if (m_inAppMode) {
683 m_keepRunningInAppMode = false;
684 m_appModeResult = false;
685 } else {
686 saveSettings();
687 qApp->exit(0);
688 }
689 }
690
691 QStringList LauncherController::combinedSummary() const
692 {
693 return m_settingsSummary + m_environmentSummary;
694 }
695
696 simgear::pkg::PackageRef LauncherController::packageForAircraftURI(QUrl uri) const
697 {
698 if (uri.scheme() != "package") {
699 qWarning() << "invalid URL scheme:" << uri;
700 return simgear::pkg::PackageRef();
701 }
702
703 QString ident = uri.path();
704 return globals->packageRoot()->getPackageById(ident.toStdString());
705 }
706
707 bool LauncherController::validateMetarString(QString metar)
708 {
709 if (metar.isEmpty()) {
710 return true;
711 }
712
713 try {
714 std::string s = metar.toStdString();
715 SGMetar theMetar(s);
716 } catch (sg_io_exception&) {
717 return false;
718 }
719
720 return true;
721 }
722
723 void LauncherController::requestInstallUpdate(QUrl aircraftUri)
724 {
725 simgear::pkg::PackageRef pref = packageForAircraftURI(aircraftUri);
726 if (pref) {
727 if (pref->isInstalled()) {
728 InstallRef install = pref->existingInstall();
729 if (install->hasUpdate()) {
730 globals->packageRoot()->scheduleToUpdate(install);
731 }
732 } else {
733 pref->install();
734 }
735 }
736 }
737
738 void LauncherController::requestUninstall(QUrl aircraftUri)
739 {
740 simgear::pkg::PackageRef pref = packageForAircraftURI(aircraftUri);
741 if (pref) {
742 simgear::pkg::InstallRef i = pref->existingInstall();
743 if (i) {
744 i->uninstall();
745 }
746 }
747 }
748
749 void LauncherController::requestInstallCancel(QUrl aircraftUri)
750 {
751 simgear::pkg::PackageRef pref = packageForAircraftURI(aircraftUri);
752 if (pref) {
753 simgear::pkg::InstallRef i = pref->existingInstall();
754 if (i) {
755 i->cancelDownload();
756 }
757 }
758 }
759
760 void LauncherController::requestUpdateAllAircraft()
761 {
762 const auto pkgRoot = globals->packageRoot();
763 const PackageList& toBeUpdated = pkgRoot->packagesNeedingUpdate();
764 std::for_each(toBeUpdated.begin(), toBeUpdated.end(), [pkgRoot](PackageRef pkg) {
765 const auto ins = pkg->install();
766 if (!pkgRoot->isInstallQueued(ins)) {
767 pkgRoot->scheduleToUpdate(ins);
768 }
769 });
770 }
771
772 void LauncherController::queryMPServers()
773 {
774 m_serversModel->refresh();
775 }
776
777 QString LauncherController::versionString() const
778 {
779 return FLIGHTGEAR_VERSION;
780 }
781
782 RecentAircraftModel *LauncherController::aircraftHistory()
783 {
784 return m_aircraftHistory;
785 }
786
787 RecentLocationsModel *LauncherController::locationHistory()
788 {
789 return m_locationHistory;
790 }
791
792 void LauncherController::launchUrl(QUrl url)
793 {
794 QDesktopServices::openUrl(url);
795 }
796
797 QVariantList LauncherController::defaultSplashUrls() const
798 {
799 QVariantList urls;
800
801 for (auto path : flightgear::defaultSplashScreenPaths()) {
802 QUrl url = QUrl::fromLocalFile(QString::fromStdString(path));
803 urls.append(url);
804 }
805
806 return urls;
807 }
808
809 QVariant LauncherController::loadUISetting(QString name, QVariant defaultValue) const
810 {
811 auto settings = flightgear::getQSettings();
812 if (!settings.contains(name))
813 return defaultValue;
814 return settings.value(name);
815 }
816
817 void LauncherController::saveUISetting(QString name, QVariant value) const
818 {
819 auto settings = flightgear::getQSettings();
820 settings.setValue(name, value);
821 }
822
823 void LauncherController::onAircraftInstalledCompleted(QModelIndex index)
824 {
825 maybeUpdateSelectedAircraft(index);
826 }
827
828 void LauncherController::onAircraftInstallFailed(QModelIndex index, QString errorMessage)
829 {
830 qWarning() << Q_FUNC_INFO << index.data(AircraftURIRole) << errorMessage;
831
832 QMessageBox msg;
833 msg.setWindowTitle(tr("Aircraft installation failed"));
834 msg.setText(tr("An error occurred installing the aircraft %1: %2").
835 arg(index.data(Qt::DisplayRole).toString()).arg(errorMessage));
836 msg.addButton(QMessageBox::Ok);
837 msg.exec();
838
839 maybeUpdateSelectedAircraft(index);
840 }
841
842
843 QPointF LauncherController::mapToGlobal(QQuickItem *item, const QPointF &pos) const
844 {
845 QPointF scenePos = item->mapToScene(pos);
846 QQuickWindow* win = item->window();
847 return win->mapToGlobal(scenePos.toPoint());
848 }
849
850 void LauncherController::requestRestoreDefaults()
851 {
852 QMessageBox mbox;
853 mbox.setText(tr("Restore all settings to defaults?"));
854 mbox.setInformativeText(tr("Restoring settings to their defaults may affect available add-ons such as scenery or aircraft."));
855 QPushButton* quitButton = mbox.addButton(tr("Restore and restart now"), QMessageBox::YesRole);
856 mbox.addButton(QMessageBox::Cancel);
857 mbox.setDefaultButton(QMessageBox::Cancel);
858 mbox.setIconPixmap(QPixmap(":/app-icon-large"));
859
860 mbox.exec();
861 if (mbox.clickedButton() != quitButton) {
862 return;
863 }
864
865 {
866 auto settings = flightgear::getQSettings();
867 settings.clear();
868 settings.setValue("restore-defaults-on-run", true);
869 }
870
871 flightgear::restartTheApp();
872 }
873
874 void LauncherController::requestChangeDataPath()
875 {
876 QString currentLocText;
877 auto settings = flightgear::getQSettings();
878 QString root = settings.value(SetupRootDialog::rootPathKey()).toString();
879 if (root.isNull()) {
880 currentLocText = tr("Currently the built-in data files are being used");
881 }
882 else {
883 currentLocText = tr("Currently using location: %1").arg(root);
884 }
885
886 QMessageBox mbox;
887 mbox.setText(tr("Change the data files used by FlightGear?"));
888 mbox.setInformativeText(tr("FlightGear requires additional files to operate. "
889 "(Also called the base package, or fg-data) "
890 "You can restart FlightGear and choose a "
891 "different data files location, or restore the default setting. %1").arg(currentLocText));
892 QPushButton* quitButton = mbox.addButton(tr("Restart FlightGear now"), QMessageBox::YesRole);
893 mbox.addButton(QMessageBox::Cancel);
894 mbox.setDefaultButton(QMessageBox::Cancel);
895 mbox.setIconPixmap(QPixmap(":/app-icon-large"));
896
897 mbox.exec();
898 if (mbox.clickedButton() != quitButton) {
899 return;
900 }
901
902 SetupRootDialog::askRootOnNextLaunch();
903 flightgear::restartTheApp();
904 }
905
906 void LauncherController::openConfig()
907 {
908 QString file = QFileDialog::getOpenFileName(nullptr, tr("Choose a saved configuration"),
909 {}, "*.fglaunch");
910 if (file.isEmpty())
911 return;
912
913 m_config->loadConfigFromFile(file);
914 }
915
916 void LauncherController::saveConfigAs()
917 {
918 QString file = QFileDialog::getSaveFileName(nullptr, tr("Save the current configuration"),
919 {}, "*.fglaunch");
920 if (file.isEmpty())
921 return;
922 if (!file.endsWith(".fglaunch")) {
923 file += ".fglaunch";
924 }
925
926 m_config->saveConfigToFile(file);
927 }
928
929 void LauncherController::setAircraftGridMode(bool aircraftGridMode)
930 {
931 if (m_aircraftGridMode == aircraftGridMode)
932 return;
933
934 auto settings = flightgear::getQSettings();
935 settings.setValue("aircraftGridMode", aircraftGridMode);
936 m_aircraftGridMode = aircraftGridMode;
937 emit aircraftGridModeChanged(m_aircraftGridMode);
938 }
939
940 void LauncherController::resetGettingStartedTips()
941 {
942 {
943 auto settings = flightgear::getQSettings();
944 settings.beginGroup("GettingStarted-DontShow");
945 settings.remove(""); // remove all keys in the current group
946 settings.endGroup();
947 } // ensure settings are written, before we emit the signal
948
949 emit didResetGettingStartedTips();
950 }
951
952 void LauncherController::setMinWindowSize(QSize sz)
953 {
954 if (sz == m_minWindowSize)
955 return;
956
957 m_window->setMinimumSize(sz);
958 emit minWindowSizeChanged();
959 }
960
961 QUrl LauncherController::flyIconUrl() const
962 {
963 if (m_aircraftType == Helicopter) {
964 return QUrl{"image://colored-icon/toolbox-fly-heli"};
965 } else if (m_selectedAircraftInfo) {
966 if (m_selectedAircraftInfo->hasTag("spaceship")) {
967 return QUrl{"image://colored-icon/toolbox-fly-alt"};
968 }
969 }
970
971 return QUrl{"image://colored-icon/toolbox-fly"};
972 }
973
974 QString LauncherController::flyButtonLabel() const
975 {
976 if (m_aircraftType == Helicopter) {
977 return tr("Fly!", "For a helicopter");
978 } else if (m_selectedAircraftInfo) {
979 if (m_selectedAircraftInfo->hasTag("spaceship")) {
980 return tr("Fly!", "For a spaceship");
981 }
982 }
983
984 return tr("Fly!");
985 }
986
987 QUrl LauncherController::urlToDataPath(QString relPath) const
988 {
989 QString absFilePath = QString::fromStdString(globals->get_fg_root().utf8Str());
990 if (!relPath.startsWith("/")) {
991 relPath.prepend("/");
992 }
993 return QUrl::fromLocalFile(absFilePath + relPath);
994 }
995
996 void LauncherController::checkForOldDownloadDir()
997 {
998 #if defined(Q_OS_WIN)
999 auto options = flightgear::Options::sharedInstance();
1000 if (options->valueForOption("download-dir") != std::string{}) {
1001 return; // if we're using a custom value, nothing to do
1002 }
1003
1004 if (haveOldWindowsDownloadDir()) {
1005 // the notifications logic handles 'don't show again' lgoic internally,
1006 // so we can always trigger this check
1007 auto nc = LauncherNotificationsController::instance();
1008 QJSValue args = nc->jsEngine()->newObject();
1009
1010 const auto oldPath = SGPath::documents() / "FlightGear";
1011 const auto newPath = flightgear::defaultDownloadDir();
1012
1013 const QUrl oldLocURI = QUrl::fromLocalFile(QString::fromStdString(oldPath.utf8Str()));
1014 const QUrl newLocURI = QUrl::fromLocalFile(QString::fromStdString(newPath.utf8Str()));
1015
1016 args.setProperty("oldLocation", oldLocURI.toString());
1017 args.setProperty("newLocation", newLocURI.toString());
1018 args.setProperty("persistent-dismiss", true);
1019
1020 nc->postNotification("have-old-downloads-location", QUrl{"qrc:///qml/DownloadsInDocumentsWarning.qml"}, args);
1021 }
1022 #endif
1023 }
1024
1025 bool LauncherController::haveOldWindowsDownloadDir() const
1026 {
1027 const SGPath p = SGPath::documents() / "FlightGear";
1028 if ((p / "TerraSync").exists() || (p / "Aircraft").exists()) {
1029 return true;
1030 }
1031
1032 // tex-cache dir is created by default, so check if it's populated
1033 simgear::Dir texCacheDir(p / "TextureCache");
1034 return (texCacheDir.exists() && !texCacheDir.isEmpty());
1035 }
1036
1037 bool LauncherController::isNetworkAvailable() const
1038 {
1039 #if (QT_VERSION >= QT_VERSION_CHECK(6, 1, 0))
1040 return QNetworkInformation::instance()->reachability() == QNetworkInformation::Reachability::Online;
1041 #else
1042 return true;
1043 #endif
1044 }
1045
1046 void LauncherController::onReachabilityChanged()
1047 {
1048 #if (QT_VERSION >= QT_VERSION_CHECK(6, 1, 0))
1049 const auto online = (QNetworkInformation::instance()->reachability() == QNetworkInformation::Reachability::Online);
1050 auto pkgRoot = globals->packageRoot();
1051 pkgRoot->setOnlineMode(online);
1052
1053 if (online) {
1054 pkgRoot->refresh(true);
1055 }
1056
1057 emit networkAvailableChanged();
1058 #endif
1059 }