1 // QtLauncher.cxx - GUI launcher dialog using Qt5
3 // Written by James Turner, started December 2014.
5 // Copyright (C) 2014 James Turner <zakalawe@mac.com>
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.
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.
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.
21 #include "QtLauncher.hxx"
22 #include "QtLauncher_private.hxx"
27 #include <QProgressDialog>
28 #include <QCoreApplication>
29 #include <QAbstractListModel>
38 #include <QSortFilterProxyModel>
40 #include <QDesktopServices>
43 #include <QFileDialog>
44 #include <QMessageBox>
46 #include <QApplication>
48 #include <QDoubleSpinBox>
52 #include <simgear/timing/timestamp.hxx>
53 #include <simgear/props/props_io.hxx>
54 #include <simgear/structure/exception.hxx>
55 #include <simgear/structure/subsystem_mgr.hxx>
56 #include <simgear/misc/sg_path.hxx>
57 #include <simgear/package/Catalog.hxx>
58 #include <simgear/package/Package.hxx>
59 #include <simgear/package/Install.hxx>
61 #include "ui_Launcher.h"
62 #include "ui_NoOfficialHangar.h"
64 #include "EditRatingsFilterDialog.hxx"
65 #include "AircraftItemDelegate.hxx"
66 #include "AircraftModel.hxx"
67 #include "PathsDialog.hxx"
69 #include <Main/globals.hxx>
70 #include <Navaids/NavDataCache.hxx>
71 #include <Navaids/navrecord.hxx>
72 #include <Navaids/SHPParser.hxx>
74 #include <Main/options.hxx>
75 #include <Main/fg_init.hxx>
76 #include <Viewer/WindowBuilder.hxx>
77 #include <Network/HTTPClient.hxx>
79 using namespace flightgear;
80 using namespace simgear::pkg;
82 const int MAX_RECENT_AIRCRAFT = 20;
84 namespace { // anonymous namespace
88 QString baseLabel = QT_TR_NOOP("Initialising navigation data, this may take several minutes");
89 NavDataCache* cache = NavDataCache::createInstance();
90 if (cache->isRebuildRequired()) {
91 QProgressDialog rebuildProgress(baseLabel,
92 QString() /* cancel text */,
95 | Qt::CustomizeWindowHint
97 | Qt::WindowSystemMenuHint
98 | Qt::MSWindowsFixedSizeDialogHint);
99 rebuildProgress.setWindowModality(Qt::WindowModal);
100 rebuildProgress.show();
102 NavDataCache::RebuildPhase phase = cache->rebuild();
104 while (phase != NavDataCache::REBUILD_DONE) {
105 // sleep to give the rebuild thread more time
106 SGTimeStamp::sleepForMSec(50);
107 phase = cache->rebuild();
110 case NavDataCache::REBUILD_AIRPORTS:
111 rebuildProgress.setLabelText(QT_TR_NOOP("Loading airport data"));
114 case NavDataCache::REBUILD_FIXES:
115 rebuildProgress.setLabelText(QT_TR_NOOP("Loading waypoint data"));
118 case NavDataCache::REBUILD_NAVAIDS:
119 rebuildProgress.setLabelText(QT_TR_NOOP("Loading navigation data"));
123 case NavDataCache::REBUILD_POIS:
124 rebuildProgress.setLabelText(QT_TR_NOOP("Loading point-of-interest data"));
128 rebuildProgress.setLabelText(baseLabel);
131 if (phase == NavDataCache::REBUILD_UNKNOWN) {
132 rebuildProgress.setValue(0);
133 rebuildProgress.setMaximum(0);
135 rebuildProgress.setValue(cache->rebuildPhaseCompletionPercentage());
136 rebuildProgress.setMaximum(100);
139 QCoreApplication::processEvents();
144 class ArgumentsTokenizer
150 explicit Arg(QString k, QString v = QString()) : arg(k), value(v) {}
156 QList<Arg> tokenize(QString in) const
159 const int len = in.count();
165 for (; index < len; ++index) {
167 nc = index < (len - 1) ? in.at(index + 1) : QChar();
171 if (c == QChar('-')) {
172 if (nc == QChar('-')) {
177 // should we pemit single hyphen arguments?
178 // choosing to fail for now
181 } else if (c == QChar('#')) {
184 } else if (c.isSpace()) {
190 if (c == QChar('=')) {
193 } else if (c.isSpace()) {
195 result.append(Arg(key));
197 // could check for illegal charatcers here
203 if (c == QChar('"')) {
205 } else if (c.isSpace()) {
207 result.append(Arg(key, value));
214 if (c == QChar('\\')) {
215 // check for escaped double-quote inside quoted value
216 if (nc == QChar('"')) {
219 } else if (c == QChar('"')) {
227 if ((c == QChar('\n')) || (c == QChar('\r'))) {
231 // nothing to do, eat comment chars
235 } // of character loop
237 // ensure last argument isn't lost
239 result.append(Arg(key));
240 } else if (state == Value) {
241 result.append(Arg(key, value));
257 } // of anonymous namespace
259 class AircraftProxyModel : public QSortFilterProxyModel
263 AircraftProxyModel(QObject* pr) :
264 QSortFilterProxyModel(pr),
265 m_ratingsFilter(true),
266 m_onlyShowInstalled(false)
268 for (int i=0; i<4; ++i) {
273 void setRatings(int* ratings)
275 ::memcpy(m_ratings, ratings, sizeof(int) * 4);
280 void setRatingFilterEnabled(bool e)
282 if (e == m_ratingsFilter) {
290 void setInstalledFilterEnabled(bool e)
292 if (e == m_onlyShowInstalled) {
296 m_onlyShowInstalled = e;
301 bool filterAcceptsRow(int sourceRow, const QModelIndex &sourceParent) const
303 QModelIndex index = sourceModel()->index(sourceRow, 0, sourceParent);
304 QVariant v = index.data(AircraftPackageStatusRole);
305 AircraftItemStatus status = static_cast<AircraftItemStatus>(v.toInt());
306 if (status == NoOfficialCatalogMessage) {
310 if (!QSortFilterProxyModel::filterAcceptsRow(sourceRow, sourceParent)) {
314 if (m_onlyShowInstalled) {
315 QVariant v = index.data(AircraftPackageStatusRole);
316 AircraftItemStatus status = static_cast<AircraftItemStatus>(v.toInt());
317 if (status == PackageNotInstalled) {
322 if (!m_onlyShowInstalled && m_ratingsFilter) {
323 for (int i=0; i<4; ++i) {
324 if (m_ratings[i] > index.data(AircraftRatingRole + i).toInt()) {
334 bool m_ratingsFilter;
335 bool m_onlyShowInstalled;
339 class NoOfficialHangarMessage : public QWidget
343 NoOfficialHangarMessage() :
344 m_ui(new Ui::NoOfficialHangarMessage)
347 // proxy this signal upwards
348 connect(m_ui->label, &QLabel::linkActivated,
349 this, &NoOfficialHangarMessage::linkActivated);
353 void linkActivated(QUrl link);
356 Ui::NoOfficialHangarMessage* m_ui;
359 static void initQtResources()
361 Q_INIT_RESOURCE(resources);
367 void initApp(int& argc, char** argv)
369 static bool qtInitDone = false;
375 sglog().setLogLevels( SG_ALL, SG_INFO );
376 initQtResources(); // can't be called from a namespace
378 s_argc = argc; // QApplication only stores a reference to argc,
379 // and may crash if it is freed
380 // http://doc.qt.io/qt-5/qguiapplication.html#QGuiApplication
383 QSettings::setDefaultFormat(QSettings::IniFormat);
384 QSettings::setPath(QSettings::IniFormat, QSettings::UserScope,
385 QString::fromStdString(globals->get_fg_home()));
387 QApplication* app = new QApplication(s_argc, argv);
388 app->setOrganizationName("FlightGear");
389 app->setApplicationName("FlightGear");
390 app->setOrganizationDomain("flightgear.org");
392 // reset numeric / collation locales as described at:
393 // http://doc.qt.io/qt-5/qcoreapplication.html#details
394 ::setlocale(LC_NUMERIC, "C");
395 ::setlocale(LC_COLLATE, "C");
397 Qt::KeyboardModifiers mods = app->queryKeyboardModifiers();
398 if (mods & (Qt::AltModifier | Qt::ShiftModifier)) {
399 qWarning() << "Alt/shift pressed during launch";
401 settings.setValue("fg-root", "!ask");
406 void loadNaturalEarthFile(const std::string& aFileName,
407 flightgear::PolyLine::Type aType,
410 SGPath path(globals->get_fg_root());
411 path.append( "Geodata" );
412 path.append(aFileName);
414 return; // silently fail for now
416 flightgear::PolyLineList lines;
417 flightgear::SHPParser::parsePolyLines(path, aType, lines, areClosed);
418 flightgear::PolyLine::bulkAddToSpatialIndex(lines);
421 void loadNaturalEarthData()
426 loadNaturalEarthFile("ne_10m_coastline.shp", flightgear::PolyLine::COASTLINE, false);
427 loadNaturalEarthFile("ne_10m_rivers_lake_centerlines.shp", flightgear::PolyLine::RIVER, false);
428 loadNaturalEarthFile("ne_10m_lakes.shp", flightgear::PolyLine::LAKE, true);
430 qDebug() << "load basic data took" << st.elapsedMSec();
434 loadNaturalEarthFile("ne_10m_urban_areas.shp", flightgear::PolyLine::URBAN, true);
436 qDebug() << "loading urban areas took:" << st.elapsedMSec();
439 bool runLauncherDialog()
441 // startup the nav-cache now. This pre-empts normal startup of
442 // the cache, but no harm done. (Providing scenery paths are consistent)
447 QString downloadDir = settings.value("download-dir").toString();
448 if (!downloadDir.isEmpty()) {
449 flightgear::Options::sharedInstance()->setOption("download-dir", downloadDir.toStdString());
454 // startup the HTTP system now since packages needs it
455 FGHTTPClient* http = globals->add_new_subsystem<FGHTTPClient>();
457 // we guard against re-init in the global phase; bind and postinit
458 // will happen as normal
461 loadNaturalEarthData();
463 // avoid double Apple menu and other weirdness if both Qt and OSG
464 // try to initialise various Cocoa structures.
465 flightgear::WindowBuilder::setPoseAsStandaloneApp(false);
470 int appResult = qApp->exec();
472 return false; // quit
475 // don't set scenery paths twice
476 globals->clear_fg_scenery();
481 bool runInAppLauncherDialog()
486 if (dlg.result() != QDialog::Accepted) {
493 } // of namespace flightgear
495 QtLauncher::QtLauncher() :
498 m_subsystemIdleTimer(NULL),
501 m_ui.reset(new Ui::Launcher);
504 #if QT_VERSION >= 0x050300
505 // don't require Qt 5.3
506 m_ui->commandLineArgs->setPlaceholderText("--option=value --prop:/sim/name=value");
509 #if QT_VERSION >= 0x050200
510 m_ui->aircraftFilter->setClearButtonEnabled(true);
513 for (int i=0; i<4; ++i) {
514 m_ratingFilters[i] = 3;
517 m_subsystemIdleTimer = new QTimer(this);
518 m_subsystemIdleTimer->setInterval(0);
519 connect(m_subsystemIdleTimer, &QTimer::timeout,
520 this, &QtLauncher::onSubsytemIdleTimeout);
521 m_subsystemIdleTimer->start();
523 // create and configure the proxy model
524 m_aircraftProxy = new AircraftProxyModel(this);
525 connect(m_ui->ratingsFilterCheck, &QAbstractButton::toggled,
526 m_aircraftProxy, &AircraftProxyModel::setRatingFilterEnabled);
527 connect(m_ui->ratingsFilterCheck, &QAbstractButton::toggled,
528 this, &QtLauncher::maybeRestoreAircraftSelection);
530 connect(m_ui->onlyShowInstalledCheck, &QAbstractButton::toggled,
531 m_aircraftProxy, &AircraftProxyModel::setInstalledFilterEnabled);
532 connect(m_ui->aircraftFilter, &QLineEdit::textChanged,
533 m_aircraftProxy, &QSortFilterProxyModel::setFilterFixedString);
535 connect(m_ui->runButton, SIGNAL(clicked()), this, SLOT(onRun()));
536 connect(m_ui->quitButton, SIGNAL(clicked()), this, SLOT(onQuit()));
538 connect(m_ui->aircraftHistory, &QPushButton::clicked,
539 this, &QtLauncher::onPopupAircraftHistory);
541 connect(m_ui->location, &LocationWidget::descriptionChanged,
542 m_ui->locationDescription, &QLabel::setText);
544 QAction* qa = new QAction(this);
545 qa->setShortcut(QKeySequence("Ctrl+Q"));
546 connect(qa, &QAction::triggered, this, &QtLauncher::onQuit);
549 connect(m_ui->editRatingFilter, &QPushButton::clicked,
550 this, &QtLauncher::onEditRatingsFilter);
551 connect(m_ui->onlyShowInstalledCheck, &QCheckBox::toggled,
552 this, &QtLauncher::onShowInstalledAircraftToggled);
554 QIcon historyIcon(":/history-icon");
555 m_ui->aircraftHistory->setIcon(historyIcon);
557 connect(m_ui->timeOfDayCombo, SIGNAL(currentIndexChanged(int)),
558 this, SLOT(updateSettingsSummary()));
559 connect(m_ui->seasonCombo, SIGNAL(currentIndexChanged(int)),
560 this, SLOT(updateSettingsSummary()));
561 connect(m_ui->fetchRealWxrCheckbox, SIGNAL(toggled(bool)),
562 this, SLOT(updateSettingsSummary()));
563 connect(m_ui->rembrandtCheckbox, SIGNAL(toggled(bool)),
564 this, SLOT(updateSettingsSummary()));
565 connect(m_ui->terrasyncCheck, SIGNAL(toggled(bool)),
566 this, SLOT(updateSettingsSummary()));
567 connect(m_ui->startPausedCheck, SIGNAL(toggled(bool)),
568 this, SLOT(updateSettingsSummary()));
569 connect(m_ui->msaaCheckbox, SIGNAL(toggled(bool)),
570 this, SLOT(updateSettingsSummary()));
572 connect(m_ui->rembrandtCheckbox, SIGNAL(toggled(bool)),
573 this, SLOT(onRembrandtToggled(bool)));
574 connect(m_ui->terrasyncCheck, &QCheckBox::toggled,
575 this, &QtLauncher::onToggleTerrasync);
576 updateSettingsSummary();
578 m_aircraftModel = new AircraftItemModel(this);
579 m_aircraftProxy->setSourceModel(m_aircraftModel);
581 m_aircraftProxy->setFilterCaseSensitivity(Qt::CaseInsensitive);
582 m_aircraftProxy->setSortCaseSensitivity(Qt::CaseInsensitive);
583 m_aircraftProxy->setSortRole(Qt::DisplayRole);
584 m_aircraftProxy->setDynamicSortFilter(true);
586 m_ui->aircraftList->setModel(m_aircraftProxy);
587 m_ui->aircraftList->setHorizontalScrollBarPolicy(Qt::ScrollBarAlwaysOff);
588 AircraftItemDelegate* delegate = new AircraftItemDelegate(m_ui->aircraftList);
589 m_ui->aircraftList->setItemDelegate(delegate);
590 m_ui->aircraftList->setSelectionMode(QAbstractItemView::SingleSelection);
591 connect(m_ui->aircraftList, &QListView::clicked,
592 this, &QtLauncher::onAircraftSelected);
593 connect(delegate, &AircraftItemDelegate::variantChanged,
594 this, &QtLauncher::onAircraftSelected);
595 connect(delegate, &AircraftItemDelegate::requestInstall,
596 this, &QtLauncher::onRequestPackageInstall);
597 connect(delegate, &AircraftItemDelegate::cancelDownload,
598 this, &QtLauncher::onCancelDownload);
600 connect(m_aircraftModel, &AircraftItemModel::aircraftInstallCompleted,
601 this, &QtLauncher::onAircraftInstalledCompleted);
602 connect(m_aircraftModel, &AircraftItemModel::aircraftInstallFailed,
603 this, &QtLauncher::onAircraftInstallFailed);
604 connect(m_aircraftModel, &AircraftItemModel::scanCompleted,
605 this, &QtLauncher::updateSelectedAircraft);
606 connect(m_ui->restoreDefaultsButton, &QPushButton::clicked,
607 this, &QtLauncher::onRestoreDefaults);
610 AddOnsPage* addOnsPage = new AddOnsPage(NULL, globals->packageRoot());
611 connect(addOnsPage, &AddOnsPage::downloadDirChanged,
612 this, &QtLauncher::onDownloadDirChanged);
613 connect(addOnsPage, &AddOnsPage::sceneryPathsChanged,
614 this, &QtLauncher::setSceneryPaths);
616 m_ui->tabWidget->addTab(addOnsPage, tr("Add-ons"));
617 // after any kind of reset, try to restore selection and scroll
618 // to match the m_selectedAircraft. This needs to be delayed
619 // fractionally otherwise the scrollTo seems to be ignored,
621 connect(m_aircraftProxy, &AircraftProxyModel::modelReset,
622 this, &QtLauncher::delayedAircraftModelReset);
625 m_aircraftModel->setPaths(settings.value("aircraft-paths").toStringList());
626 m_aircraftModel->setPackageRoot(globals->packageRoot());
627 m_aircraftModel->scanDirs();
629 checkOfficialCatalogMessage();
633 QtLauncher::~QtLauncher()
638 void QtLauncher::setSceneryPaths()
640 globals->clear_fg_scenery();
642 // mimic what optionss.cxx does, so we can find airport data for parking
645 // append explicit scenery paths
646 Q_FOREACH(QString path, settings.value("scenery-paths").toStringList()) {
647 globals->append_fg_scenery(path.toStdString());
650 // append the TerraSync path
651 QString downloadDir = settings.value("download-dir").toString();
652 if (downloadDir.isEmpty()) {
653 downloadDir = QString::fromStdString(flightgear::defaultDownloadDir());
656 SGPath terraSyncDir(downloadDir.toStdString());
657 terraSyncDir.append("TerraSync");
658 if (terraSyncDir.exists()) {
659 globals->append_fg_scenery(terraSyncDir.str());
664 void QtLauncher::setInAppMode()
667 m_ui->tabWidget->removeTab(2);
668 m_ui->runButton->setText(tr("Apply"));
669 m_ui->quitButton->setText(tr("Cancel"));
671 disconnect(m_ui->runButton, SIGNAL(clicked()), this, SLOT(onRun()));
672 connect(m_ui->runButton, SIGNAL(clicked()), this, SLOT(onApply()));
675 void QtLauncher::restoreSettings()
678 m_ui->rembrandtCheckbox->setChecked(settings.value("enable-rembrandt", false).toBool());
679 m_ui->terrasyncCheck->setChecked(settings.value("enable-terrasync", true).toBool());
680 m_ui->fullScreenCheckbox->setChecked(settings.value("start-fullscreen", false).toBool());
681 m_ui->msaaCheckbox->setChecked(settings.value("enable-msaa", false).toBool());
682 m_ui->fetchRealWxrCheckbox->setChecked(settings.value("enable-realwx", true).toBool());
683 m_ui->startPausedCheck->setChecked(settings.value("start-paused", false).toBool());
684 m_ui->timeOfDayCombo->setCurrentIndex(settings.value("timeofday", 0).toInt());
685 m_ui->seasonCombo->setCurrentIndex(settings.value("season", 0).toInt());
687 // full paths to -set.xml files
688 m_recentAircraft = QUrl::fromStringList(settings.value("recent-aircraft").toStringList());
690 if (!m_recentAircraft.empty()) {
691 m_selectedAircraft = m_recentAircraft.front();
693 // select the default C172p
700 m_ui->location->restoreSettings();
703 m_ui->onlyShowInstalledCheck->setChecked(settings.value("only-show-installed", false).toBool());
704 if (m_ui->onlyShowInstalledCheck->isChecked()) {
705 m_ui->ratingsFilterCheck->setEnabled(false);
708 m_ui->ratingsFilterCheck->setChecked(settings.value("ratings-filter", true).toBool());
710 Q_FOREACH(QVariant v, settings.value("min-ratings").toList()) {
711 m_ratingFilters[index++] = v.toInt();
714 m_aircraftProxy->setRatingFilterEnabled(m_ui->ratingsFilterCheck->isChecked());
715 m_aircraftProxy->setRatings(m_ratingFilters);
717 updateSelectedAircraft();
718 maybeRestoreAircraftSelection();
720 m_ui->commandLineArgs->setPlainText(settings.value("additional-args").toString());
723 void QtLauncher::delayedAircraftModelReset()
725 QTimer::singleShot(1, this, SLOT(maybeRestoreAircraftSelection()));
728 void QtLauncher::maybeRestoreAircraftSelection()
730 QModelIndex aircraftIndex = m_aircraftModel->indexOfAircraftURI(m_selectedAircraft);
731 QModelIndex proxyIndex = m_aircraftProxy->mapFromSource(aircraftIndex);
732 if (proxyIndex.isValid()) {
733 m_ui->aircraftList->selectionModel()->setCurrentIndex(proxyIndex,
734 QItemSelectionModel::ClearAndSelect);
735 m_ui->aircraftList->selectionModel()->select(proxyIndex,
736 QItemSelectionModel::ClearAndSelect);
737 m_ui->aircraftList->scrollTo(proxyIndex);
741 void QtLauncher::saveSettings()
744 settings.setValue("enable-rembrandt", m_ui->rembrandtCheckbox->isChecked());
745 settings.setValue("enable-terrasync", m_ui->terrasyncCheck->isChecked());
746 settings.setValue("enable-msaa", m_ui->msaaCheckbox->isChecked());
747 settings.setValue("start-fullscreen", m_ui->fullScreenCheckbox->isChecked());
748 settings.setValue("enable-realwx", m_ui->fetchRealWxrCheckbox->isChecked());
749 settings.setValue("start-paused", m_ui->startPausedCheck->isChecked());
750 settings.setValue("ratings-filter", m_ui->ratingsFilterCheck->isChecked());
751 settings.setValue("only-show-installed", m_ui->onlyShowInstalledCheck->isChecked());
752 settings.setValue("recent-aircraft", QUrl::toStringList(m_recentAircraft));
754 settings.setValue("timeofday", m_ui->timeOfDayCombo->currentIndex());
755 settings.setValue("season", m_ui->seasonCombo->currentIndex());
756 settings.setValue("additional-args", m_ui->commandLineArgs->toPlainText());
758 m_ui->location->saveSettings();
761 void QtLauncher::setEnableDisableOptionFromCheckbox(QCheckBox* cbox, QString name) const
763 flightgear::Options* opt = flightgear::Options::sharedInstance();
764 std::string stdName(name.toStdString());
765 if (cbox->isChecked()) {
766 opt->addOption("enable-" + stdName, "");
768 opt->addOption("disable-" + stdName, "");
772 void QtLauncher::closeEvent(QCloseEvent *event)
777 void QtLauncher::reject()
782 void QtLauncher::onRun()
784 flightgear::Options* opt = flightgear::Options::sharedInstance();
785 setEnableDisableOptionFromCheckbox(m_ui->terrasyncCheck, "terrasync");
786 setEnableDisableOptionFromCheckbox(m_ui->fetchRealWxrCheckbox, "real-weather-fetch");
787 setEnableDisableOptionFromCheckbox(m_ui->rembrandtCheckbox, "rembrandt");
788 setEnableDisableOptionFromCheckbox(m_ui->fullScreenCheckbox, "fullscreen");
789 // setEnableDisableOptionFromCheckbox(m_ui->startPausedCheck, "freeze");
791 bool startPaused = m_ui->startPausedCheck->isChecked() ||
792 m_ui->location->shouldStartPaused();
794 opt->addOption("enable-freeze", "");
797 // MSAA is more complex
798 if (!m_ui->rembrandtCheckbox->isChecked()) {
799 if (m_ui->msaaCheckbox->isChecked()) {
800 globals->get_props()->setIntValue("/sim/rendering/multi-sample-buffers", 1);
801 globals->get_props()->setIntValue("/sim/rendering/multi-samples", 4);
803 globals->get_props()->setIntValue("/sim/rendering/multi-sample-buffers", 0);
808 if (!m_selectedAircraft.isEmpty()) {
809 if (m_selectedAircraft.isLocalFile()) {
810 QFileInfo setFileInfo(m_selectedAircraft.toLocalFile());
811 opt->addOption("aircraft-dir", setFileInfo.dir().absolutePath().toStdString());
812 QString setFile = setFileInfo.fileName();
813 Q_ASSERT(setFile.endsWith("-set.xml"));
814 setFile.truncate(setFile.count() - 8); // drop the '-set.xml' portion
815 opt->addOption("aircraft", setFile.toStdString());
816 } else if (m_selectedAircraft.scheme() == "package") {
817 QString qualifiedId = m_selectedAircraft.path();
818 // no need to set aircraft-dir, handled by the corresponding code
820 opt->addOption("aircraft", qualifiedId.toStdString());
822 qWarning() << "unsupported aircraft launch URL" << m_selectedAircraft;
825 // manage aircraft history
826 if (m_recentAircraft.contains(m_selectedAircraft))
827 m_recentAircraft.removeOne(m_selectedAircraft);
828 m_recentAircraft.prepend(m_selectedAircraft);
829 if (m_recentAircraft.size() > MAX_RECENT_AIRCRAFT)
830 m_recentAircraft.pop_back();
833 m_ui->location->setLocationOptions();
836 if (m_ui->timeOfDayCombo->currentIndex() != 0) {
837 QString dayval = m_ui->timeOfDayCombo->currentText().toLower();
838 opt->addOption("timeofday", dayval.toStdString());
841 if (m_ui->seasonCombo->currentIndex() != 0) {
842 QString seasonName = m_ui->seasonCombo->currentText().toLower();
843 opt->addOption("season", seasonName.toStdString());
847 QString downloadDir = settings.value("download-dir").toString();
848 if (!downloadDir.isEmpty()) {
851 int result = QMessageBox::question(this, tr("Create download folder?"),
852 tr("The selected location for downloads does not exist. Create it?"),
853 QMessageBox::Yes | QMessageBox::No | QMessageBox::Cancel);
854 if (result == QMessageBox::Cancel) {
858 if (result == QMessageBox::Yes) {
859 d.mkpath(downloadDir);
863 opt->addOption("download-dir", downloadDir.toStdString());
867 Q_FOREACH(QString path, settings.value("scenery-paths").toStringList()) {
868 opt->addOption("fg-scenery", path.toStdString());
872 Q_FOREACH(QString path, settings.value("aircraft-paths").toStringList()) {
873 // can't use fg-aircraft for this, as it is processed before the launcher is run
874 globals->append_aircraft_path(path.toStdString());
877 // additional arguments
878 ArgumentsTokenizer tk;
879 Q_FOREACH(ArgumentsTokenizer::Arg a, tk.tokenize(m_ui->commandLineArgs->toPlainText())) {
880 if (a.arg.startsWith("prop:")) {
881 QString v = a.arg.mid(5) + "=" + a.value;
882 opt->addOption("prop", v.toStdString());
884 opt->addOption(a.arg.toStdString(), a.value.toStdString());
888 if (settings.contains("restore-defaults-on-run")) {
889 settings.remove("restore-defaults-on-run");
890 opt->addOption("restore-defaults", "");
899 void QtLauncher::onApply()
904 if (!m_selectedAircraft.isEmpty()) {
905 std::string aircraftPropValue,
908 if (m_selectedAircraft.isLocalFile()) {
909 QFileInfo setFileInfo(m_selectedAircraft.toLocalFile());
910 QString setFile = setFileInfo.fileName();
911 Q_ASSERT(setFile.endsWith("-set.xml"));
912 setFile.truncate(setFile.count() - 8); // drop the '-set.xml' portion
913 aircraftDir = setFileInfo.dir().absolutePath().toStdString();
914 aircraftPropValue = setFile.toStdString();
915 } else if (m_selectedAircraft.scheme() == "package") {
916 // no need to set aircraft-dir, handled by the corresponding code
918 aircraftPropValue = m_selectedAircraft.path().toStdString();
920 qWarning() << "unsupported aircraft launch URL" << m_selectedAircraft;
923 // manage aircraft history
924 if (m_recentAircraft.contains(m_selectedAircraft))
925 m_recentAircraft.removeOne(m_selectedAircraft);
926 m_recentAircraft.prepend(m_selectedAircraft);
927 if (m_recentAircraft.size() > MAX_RECENT_AIRCRAFT)
928 m_recentAircraft.pop_back();
930 globals->get_props()->setStringValue("/sim/aircraft", aircraftPropValue);
931 globals->get_props()->setStringValue("/sim/aircraft-dir", aircraftDir);
938 void QtLauncher::onQuit()
943 void QtLauncher::onToggleTerrasync(bool enabled)
947 QString downloadDir = settings.value("download-dir").toString();
948 if (downloadDir.isEmpty()) {
949 downloadDir = QString::fromStdString(flightgear::defaultDownloadDir());
952 QFileInfo info(downloadDir);
953 if (!info.exists()) {
955 msg.setWindowTitle(tr("Create download folder?"));
956 msg.setText(tr("The download folder '%1' does not exist, create it now?").arg(downloadDir));
957 msg.addButton(QMessageBox::Yes);
958 msg.addButton(QMessageBox::Cancel);
959 int result = msg.exec();
961 if (result == QMessageBox::Cancel) {
962 m_ui->terrasyncCheck->setChecked(false);
967 d.mkpath(downloadDir);
972 void QtLauncher::onAircraftInstalledCompleted(QModelIndex index)
974 maybeUpdateSelectedAircraft(index);
977 void QtLauncher::onRatingsFilterToggled()
979 QModelIndex aircraftIndex = m_aircraftModel->indexOfAircraftURI(m_selectedAircraft);
980 QModelIndex proxyIndex = m_aircraftProxy->mapFromSource(aircraftIndex);
981 if (proxyIndex.isValid()) {
982 m_ui->aircraftList->scrollTo(proxyIndex);
986 void QtLauncher::onAircraftInstallFailed(QModelIndex index, QString errorMessage)
988 qWarning() << Q_FUNC_INFO << index.data(AircraftURIRole) << errorMessage;
991 msg.setWindowTitle(tr("Aircraft installation failed"));
992 msg.setText(tr("An error occurred installing the aircraft %1: %2").
993 arg(index.data(Qt::DisplayRole).toString()).arg(errorMessage));
994 msg.addButton(QMessageBox::Ok);
997 maybeUpdateSelectedAircraft(index);
1000 void QtLauncher::onAircraftSelected(const QModelIndex& index)
1002 m_selectedAircraft = index.data(AircraftURIRole).toUrl();
1003 updateSelectedAircraft();
1006 void QtLauncher::onRequestPackageInstall(const QModelIndex& index)
1008 // also select, otherwise UI is confusing
1009 m_selectedAircraft = index.data(AircraftURIRole).toUrl();
1010 updateSelectedAircraft();
1012 QString pkg = index.data(AircraftPackageIdRole).toString();
1013 simgear::pkg::PackageRef pref = globals->packageRoot()->getPackageById(pkg.toStdString());
1014 if (pref->isInstalled()) {
1015 InstallRef install = pref->existingInstall();
1016 if (install && install->hasUpdate()) {
1017 globals->packageRoot()->scheduleToUpdate(install);
1024 void QtLauncher::onCancelDownload(const QModelIndex& index)
1026 QString pkg = index.data(AircraftPackageIdRole).toString();
1027 simgear::pkg::PackageRef pref = globals->packageRoot()->getPackageById(pkg.toStdString());
1028 simgear::pkg::InstallRef i = pref->existingInstall();
1029 i->cancelDownload();
1032 void QtLauncher::onRestoreDefaults()
1034 QMessageBox mbox(this);
1035 mbox.setText(tr("Restore all settings to defaults?"));
1036 mbox.setInformativeText(tr("Restoring settings to their defaults may affect available add-ons such as scenery or aircraft."));
1037 QPushButton* quitButton = mbox.addButton(tr("Restore and restart now"), QMessageBox::YesRole);
1038 mbox.addButton(QMessageBox::Cancel);
1039 mbox.setDefaultButton(QMessageBox::Cancel);
1040 mbox.setIconPixmap(QPixmap(":/app-icon-large"));
1043 if (mbox.clickedButton() != quitButton) {
1050 settings.setValue("restore-defaults-on-run", true);
1053 restartTheApp(QStringList());
1056 void QtLauncher::maybeUpdateSelectedAircraft(QModelIndex index)
1058 QUrl u = index.data(AircraftURIRole).toUrl();
1059 if (u == m_selectedAircraft) {
1060 // potentially enable the run button now!
1061 updateSelectedAircraft();
1065 void QtLauncher::updateSelectedAircraft()
1067 QModelIndex index = m_aircraftModel->indexOfAircraftURI(m_selectedAircraft);
1068 if (index.isValid()) {
1069 QPixmap pm = index.data(Qt::DecorationRole).value<QPixmap>();
1070 m_ui->thumbnail->setPixmap(pm);
1071 m_ui->aircraftDescription->setText(index.data(Qt::DisplayRole).toString());
1073 int status = index.data(AircraftPackageStatusRole).toInt();
1074 bool canRun = (status == PackageInstalled);
1075 m_ui->runButton->setEnabled(canRun);
1077 LauncherAircraftType aircraftType = Airplane;
1078 if (index.data(AircraftIsHelicopterRole).toBool()) {
1079 aircraftType = Helicopter;
1080 } else if (index.data(AircraftIsSeaplaneRole).toBool()) {
1081 aircraftType = Seaplane;
1084 m_ui->location->setAircraftType(aircraftType);
1086 m_ui->thumbnail->setPixmap(QPixmap());
1087 m_ui->aircraftDescription->setText("");
1088 m_ui->runButton->setEnabled(false);
1092 QModelIndex QtLauncher::proxyIndexForAircraftURI(QUrl uri) const
1094 return m_aircraftProxy->mapFromSource(sourceIndexForAircraftURI(uri));
1097 QModelIndex QtLauncher::sourceIndexForAircraftURI(QUrl uri) const
1099 AircraftItemModel* sourceModel = qobject_cast<AircraftItemModel*>(m_aircraftProxy->sourceModel());
1100 Q_ASSERT(sourceModel);
1101 return sourceModel->indexOfAircraftURI(uri);
1104 void QtLauncher::onPopupAircraftHistory()
1106 if (m_recentAircraft.isEmpty()) {
1111 Q_FOREACH(QUrl uri, m_recentAircraft) {
1112 QModelIndex index = sourceIndexForAircraftURI(uri);
1113 if (!index.isValid()) {
1117 QAction* act = m.addAction(index.data(Qt::DisplayRole).toString());
1121 QPoint popupPos = m_ui->aircraftHistory->mapToGlobal(m_ui->aircraftHistory->rect().bottomLeft());
1122 QAction* triggered = m.exec(popupPos);
1124 m_selectedAircraft = triggered->data().toUrl();
1125 QModelIndex index = proxyIndexForAircraftURI(m_selectedAircraft);
1126 m_ui->aircraftList->selectionModel()->setCurrentIndex(index,
1127 QItemSelectionModel::ClearAndSelect);
1128 m_ui->aircraftFilter->clear();
1129 updateSelectedAircraft();
1133 void QtLauncher::onEditRatingsFilter()
1135 EditRatingsFilterDialog dialog(this);
1136 dialog.setRatings(m_ratingFilters);
1139 if (dialog.result() == QDialog::Accepted) {
1141 for (int i=0; i<4; ++i) {
1142 m_ratingFilters[i] = dialog.getRating(i);
1143 vl.append(m_ratingFilters[i]);
1145 m_aircraftProxy->setRatings(m_ratingFilters);
1148 settings.setValue("min-ratings", vl);
1152 void QtLauncher::updateSettingsSummary()
1154 QStringList summary;
1155 if (m_ui->timeOfDayCombo->currentIndex() > 0) {
1156 summary.append(QString(m_ui->timeOfDayCombo->currentText().toLower()));
1159 if (m_ui->seasonCombo->currentIndex() > 0) {
1160 summary.append(QString(m_ui->seasonCombo->currentText().toLower()));
1163 if (m_ui->rembrandtCheckbox->isChecked()) {
1164 summary.append("Rembrandt enabled");
1165 } else if (m_ui->msaaCheckbox->isChecked()) {
1166 summary.append("anti-aliasing");
1169 if (m_ui->fetchRealWxrCheckbox->isChecked()) {
1170 summary.append("live weather");
1173 if (m_ui->terrasyncCheck->isChecked()) {
1174 summary.append("automatic scenery downloads");
1177 if (m_ui->startPausedCheck->isChecked()) {
1178 summary.append("paused");
1181 QString s = summary.join(", ");
1182 s[0] = s[0].toUpper();
1183 m_ui->settingsDescription->setText(s);
1186 void QtLauncher::onRembrandtToggled(bool b)
1188 // Rembrandt and multi-sample are exclusive
1189 m_ui->msaaCheckbox->setEnabled(!b);
1192 void QtLauncher::onShowInstalledAircraftToggled(bool b)
1194 m_ui->ratingsFilterCheck->setEnabled(!b);
1195 maybeRestoreAircraftSelection();
1198 void QtLauncher::onSubsytemIdleTimeout()
1200 globals->get_subsystem_mgr()->update(0.0);
1203 void QtLauncher::onDownloadDirChanged()
1206 // replace existing package root
1207 globals->get_subsystem<FGHTTPClient>()->shutdown();
1208 globals->setPackageRoot(simgear::pkg::RootRef());
1210 // create new root with updated download-dir value
1211 fgInitPackageRoot();
1213 globals->get_subsystem<FGHTTPClient>()->init();
1216 // re-scan the aircraft list
1217 m_aircraftModel->setPackageRoot(globals->packageRoot());
1218 m_aircraftModel->setPaths(settings.value("aircraft-paths").toStringList());
1219 m_aircraftModel->scanDirs();
1221 checkOfficialCatalogMessage();
1223 // re-set scenery dirs
1227 void QtLauncher::checkOfficialCatalogMessage()
1230 bool showOfficialCatalogMesssage = !globals->get_subsystem<FGHTTPClient>()->isDefaultCatalogInstalled();
1231 if (settings.value("hide-official-catalog-message").toBool()) {
1232 showOfficialCatalogMesssage = false;
1235 m_aircraftModel->setOfficialHangarMessageVisible(showOfficialCatalogMesssage);
1236 if (showOfficialCatalogMesssage) {
1237 NoOfficialHangarMessage* messageWidget = new NoOfficialHangarMessage;
1238 connect(messageWidget, &NoOfficialHangarMessage::linkActivated,
1239 this, &QtLauncher::onOfficialCatalogMessageLink);
1241 QModelIndex index = m_aircraftProxy->mapFromSource(m_aircraftModel->officialHangarMessageIndex());
1242 m_ui->aircraftList->setIndexWidget(index, messageWidget);
1246 void QtLauncher::onOfficialCatalogMessageLink(QUrl link)
1248 QString s = link.toString();
1249 if (s == "action:hide") {
1251 settings.setValue("hide-official-catalog-message", true);
1252 } else if (s == "action:add-official") {
1253 AddOnsPage::addDefaultCatalog(this);
1256 checkOfficialCatalogMessage();
1259 simgear::pkg::PackageRef QtLauncher::packageForAircraftURI(QUrl uri) const
1261 if (uri.scheme() != "package") {
1262 qWarning() << "invalid URL scheme:" << uri;
1263 return simgear::pkg::PackageRef();
1266 QString ident = uri.path();
1267 return globals->packageRoot()->getPackageById(ident.toStdString());
1270 void QtLauncher::restartTheApp(QStringList fgArgs)
1272 // Spawn a new instance of myApplication:
1276 #if defined(Q_OS_MAC)
1277 QDir dir(qApp->applicationDirPath()); // returns the 'MacOS' dir
1278 dir.cdUp(); // up to 'contents' dir
1279 dir.cdUp(); // up to .app dir
1280 // see 'man open' for details, but '-n' ensures we launch a new instance,
1281 // and we want to pass remaining arguments to us, not open.
1282 args << "-n" << dir.absolutePath() << "--args" << "--launcher" << fgArgs;
1283 qDebug() << "args" << args;
1284 proc.startDetached("open", args);
1286 args << "--launcher" << fgArgs;
1287 proc.startDetached(qApp->applicationFilePath(), args);
1292 #include "QtLauncher.moc"