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
382 QApplication* app = new QApplication(s_argc, argv);
383 app->setOrganizationName("FlightGear");
384 app->setApplicationName("FlightGear");
385 app->setOrganizationDomain("flightgear.org");
387 QSettings::setDefaultFormat(QSettings::IniFormat);
388 QSettings::setPath(QSettings::IniFormat, QSettings::UserScope,
389 QString::fromStdString(globals->get_fg_home()));
391 // reset numeric / collation locales as described at:
392 // http://doc.qt.io/qt-5/qcoreapplication.html#details
393 ::setlocale(LC_NUMERIC, "C");
394 ::setlocale(LC_COLLATE, "C");
396 Qt::KeyboardModifiers mods = app->queryKeyboardModifiers();
397 if (mods & (Qt::AltModifier | Qt::ShiftModifier)) {
398 qWarning() << "Alt/shift pressed during launch";
400 settings.setValue("fg-root", "!ask");
405 void loadNaturalEarthFile(const std::string& aFileName,
406 flightgear::PolyLine::Type aType,
409 SGPath path(globals->get_fg_root());
410 path.append( "Geodata" );
411 path.append(aFileName);
413 return; // silently fail for now
415 flightgear::PolyLineList lines;
416 flightgear::SHPParser::parsePolyLines(path, aType, lines, areClosed);
417 flightgear::PolyLine::bulkAddToSpatialIndex(lines);
420 void loadNaturalEarthData()
425 loadNaturalEarthFile("ne_10m_coastline.shp", flightgear::PolyLine::COASTLINE, false);
426 loadNaturalEarthFile("ne_10m_rivers_lake_centerlines.shp", flightgear::PolyLine::RIVER, false);
427 loadNaturalEarthFile("ne_10m_lakes.shp", flightgear::PolyLine::LAKE, true);
429 qDebug() << "load basic data took" << st.elapsedMSec();
433 loadNaturalEarthFile("ne_10m_urban_areas.shp", flightgear::PolyLine::URBAN, true);
435 qDebug() << "loading urban areas took:" << st.elapsedMSec();
438 bool runLauncherDialog()
440 // startup the nav-cache now. This pre-empts normal startup of
441 // the cache, but no harm done. (Providing scenery paths are consistent)
446 QString downloadDir = settings.value("download-dir").toString();
447 if (!downloadDir.isEmpty()) {
448 flightgear::Options::sharedInstance()->setOption("download-dir", downloadDir.toStdString());
453 // startup the HTTP system now since packages needs it
454 FGHTTPClient* http = globals->add_new_subsystem<FGHTTPClient>();
456 // we guard against re-init in the global phase; bind and postinit
457 // will happen as normal
460 loadNaturalEarthData();
462 // avoid double Apple menu and other weirdness if both Qt and OSG
463 // try to initialise various Cocoa structures.
464 flightgear::WindowBuilder::setPoseAsStandaloneApp(false);
469 int appResult = qApp->exec();
471 return false; // quit
474 // don't set scenery paths twice
475 globals->clear_fg_scenery();
480 bool runInAppLauncherDialog()
485 if (dlg.result() != QDialog::Accepted) {
492 } // of namespace flightgear
494 QtLauncher::QtLauncher() :
497 m_subsystemIdleTimer(NULL),
500 m_ui.reset(new Ui::Launcher);
503 #if QT_VERSION >= 0x050300
504 // don't require Qt 5.3
505 m_ui->commandLineArgs->setPlaceholderText("--option=value --prop:/sim/name=value");
508 #if QT_VERSION >= 0x050200
509 m_ui->aircraftFilter->setClearButtonEnabled(true);
512 for (int i=0; i<4; ++i) {
513 m_ratingFilters[i] = 3;
516 m_subsystemIdleTimer = new QTimer(this);
517 m_subsystemIdleTimer->setInterval(0);
518 connect(m_subsystemIdleTimer, &QTimer::timeout,
519 this, &QtLauncher::onSubsytemIdleTimeout);
520 m_subsystemIdleTimer->start();
522 // create and configure the proxy model
523 m_aircraftProxy = new AircraftProxyModel(this);
524 connect(m_ui->ratingsFilterCheck, &QAbstractButton::toggled,
525 m_aircraftProxy, &AircraftProxyModel::setRatingFilterEnabled);
526 connect(m_ui->ratingsFilterCheck, &QAbstractButton::toggled,
527 this, &QtLauncher::maybeRestoreAircraftSelection);
529 connect(m_ui->onlyShowInstalledCheck, &QAbstractButton::toggled,
530 m_aircraftProxy, &AircraftProxyModel::setInstalledFilterEnabled);
531 connect(m_ui->aircraftFilter, &QLineEdit::textChanged,
532 m_aircraftProxy, &QSortFilterProxyModel::setFilterFixedString);
534 connect(m_ui->runButton, SIGNAL(clicked()), this, SLOT(onRun()));
535 connect(m_ui->quitButton, SIGNAL(clicked()), this, SLOT(onQuit()));
537 connect(m_ui->aircraftHistory, &QPushButton::clicked,
538 this, &QtLauncher::onPopupAircraftHistory);
540 connect(m_ui->location, &LocationWidget::descriptionChanged,
541 m_ui->locationDescription, &QLabel::setText);
543 QAction* qa = new QAction(this);
544 qa->setShortcut(QKeySequence("Ctrl+Q"));
545 connect(qa, &QAction::triggered, this, &QtLauncher::onQuit);
548 connect(m_ui->editRatingFilter, &QPushButton::clicked,
549 this, &QtLauncher::onEditRatingsFilter);
550 connect(m_ui->onlyShowInstalledCheck, &QCheckBox::toggled,
551 this, &QtLauncher::onShowInstalledAircraftToggled);
553 QIcon historyIcon(":/history-icon");
554 m_ui->aircraftHistory->setIcon(historyIcon);
556 connect(m_ui->timeOfDayCombo, SIGNAL(currentIndexChanged(int)),
557 this, SLOT(updateSettingsSummary()));
558 connect(m_ui->seasonCombo, SIGNAL(currentIndexChanged(int)),
559 this, SLOT(updateSettingsSummary()));
560 connect(m_ui->fetchRealWxrCheckbox, SIGNAL(toggled(bool)),
561 this, SLOT(updateSettingsSummary()));
562 connect(m_ui->rembrandtCheckbox, SIGNAL(toggled(bool)),
563 this, SLOT(updateSettingsSummary()));
564 connect(m_ui->terrasyncCheck, SIGNAL(toggled(bool)),
565 this, SLOT(updateSettingsSummary()));
566 connect(m_ui->startPausedCheck, SIGNAL(toggled(bool)),
567 this, SLOT(updateSettingsSummary()));
568 connect(m_ui->msaaCheckbox, SIGNAL(toggled(bool)),
569 this, SLOT(updateSettingsSummary()));
571 connect(m_ui->rembrandtCheckbox, SIGNAL(toggled(bool)),
572 this, SLOT(onRembrandtToggled(bool)));
573 connect(m_ui->terrasyncCheck, &QCheckBox::toggled,
574 this, &QtLauncher::onToggleTerrasync);
575 updateSettingsSummary();
577 m_aircraftModel = new AircraftItemModel(this);
578 m_aircraftProxy->setSourceModel(m_aircraftModel);
580 m_aircraftProxy->setFilterCaseSensitivity(Qt::CaseInsensitive);
581 m_aircraftProxy->setSortCaseSensitivity(Qt::CaseInsensitive);
582 m_aircraftProxy->setSortRole(Qt::DisplayRole);
583 m_aircraftProxy->setDynamicSortFilter(true);
585 m_ui->aircraftList->setModel(m_aircraftProxy);
586 m_ui->aircraftList->setHorizontalScrollBarPolicy(Qt::ScrollBarAlwaysOff);
587 AircraftItemDelegate* delegate = new AircraftItemDelegate(m_ui->aircraftList);
588 m_ui->aircraftList->setItemDelegate(delegate);
589 m_ui->aircraftList->setSelectionMode(QAbstractItemView::SingleSelection);
590 connect(m_ui->aircraftList, &QListView::clicked,
591 this, &QtLauncher::onAircraftSelected);
592 connect(delegate, &AircraftItemDelegate::variantChanged,
593 this, &QtLauncher::onAircraftSelected);
594 connect(delegate, &AircraftItemDelegate::requestInstall,
595 this, &QtLauncher::onRequestPackageInstall);
596 connect(delegate, &AircraftItemDelegate::cancelDownload,
597 this, &QtLauncher::onCancelDownload);
599 connect(m_aircraftModel, &AircraftItemModel::aircraftInstallCompleted,
600 this, &QtLauncher::onAircraftInstalledCompleted);
601 connect(m_aircraftModel, &AircraftItemModel::aircraftInstallFailed,
602 this, &QtLauncher::onAircraftInstallFailed);
603 connect(m_aircraftModel, &AircraftItemModel::scanCompleted,
604 this, &QtLauncher::updateSelectedAircraft);
605 connect(m_ui->restoreDefaultsButton, &QPushButton::clicked,
606 this, &QtLauncher::onRestoreDefaults);
609 AddOnsPage* addOnsPage = new AddOnsPage(NULL, globals->packageRoot());
610 connect(addOnsPage, &AddOnsPage::downloadDirChanged,
611 this, &QtLauncher::onDownloadDirChanged);
612 connect(addOnsPage, &AddOnsPage::sceneryPathsChanged,
613 this, &QtLauncher::setSceneryPaths);
615 m_ui->tabWidget->addTab(addOnsPage, tr("Add-ons"));
616 // after any kind of reset, try to restore selection and scroll
617 // to match the m_selectedAircraft. This needs to be delayed
618 // fractionally otherwise the scrollTo seems to be ignored,
620 connect(m_aircraftProxy, &AircraftProxyModel::modelReset,
621 this, &QtLauncher::delayedAircraftModelReset);
624 m_aircraftModel->setPaths(settings.value("aircraft-paths").toStringList());
625 m_aircraftModel->setPackageRoot(globals->packageRoot());
626 m_aircraftModel->scanDirs();
628 checkOfficialCatalogMessage();
632 QtLauncher::~QtLauncher()
637 void QtLauncher::setSceneryPaths()
639 globals->clear_fg_scenery();
641 // mimic what optionss.cxx does, so we can find airport data for parking
644 // append explicit scenery paths
645 Q_FOREACH(QString path, settings.value("scenery-paths").toStringList()) {
646 globals->append_fg_scenery(path.toStdString());
649 // append the TerraSync path
650 QString downloadDir = settings.value("download-dir").toString();
651 if (downloadDir.isEmpty()) {
652 downloadDir = QString::fromStdString(flightgear::defaultDownloadDir());
655 SGPath terraSyncDir(downloadDir.toStdString());
656 terraSyncDir.append("TerraSync");
657 if (terraSyncDir.exists()) {
658 globals->append_fg_scenery(terraSyncDir.utf8Str());
663 void QtLauncher::setInAppMode()
666 m_ui->tabWidget->removeTab(2);
667 m_ui->tabWidget->removeTab(2);
669 m_ui->runButton->setText(tr("Apply"));
670 m_ui->quitButton->setText(tr("Cancel"));
672 disconnect(m_ui->runButton, SIGNAL(clicked()), this, SLOT(onRun()));
673 connect(m_ui->runButton, SIGNAL(clicked()), this, SLOT(onApply()));
676 void QtLauncher::restoreSettings()
679 m_ui->rembrandtCheckbox->setChecked(settings.value("enable-rembrandt", false).toBool());
680 m_ui->terrasyncCheck->setChecked(settings.value("enable-terrasync", true).toBool());
681 m_ui->fullScreenCheckbox->setChecked(settings.value("start-fullscreen", false).toBool());
682 m_ui->msaaCheckbox->setChecked(settings.value("enable-msaa", false).toBool());
683 m_ui->fetchRealWxrCheckbox->setChecked(settings.value("enable-realwx", true).toBool());
684 m_ui->startPausedCheck->setChecked(settings.value("start-paused", false).toBool());
685 m_ui->timeOfDayCombo->setCurrentIndex(settings.value("timeofday", 0).toInt());
686 m_ui->seasonCombo->setCurrentIndex(settings.value("season", 0).toInt());
688 // full paths to -set.xml files
689 m_recentAircraft = QUrl::fromStringList(settings.value("recent-aircraft").toStringList());
691 if (!m_recentAircraft.empty()) {
692 m_selectedAircraft = m_recentAircraft.front();
694 // select the default C172p
701 m_ui->location->restoreSettings();
704 m_ui->onlyShowInstalledCheck->setChecked(settings.value("only-show-installed", false).toBool());
705 if (m_ui->onlyShowInstalledCheck->isChecked()) {
706 m_ui->ratingsFilterCheck->setEnabled(false);
709 m_ui->ratingsFilterCheck->setChecked(settings.value("ratings-filter", true).toBool());
711 Q_FOREACH(QVariant v, settings.value("min-ratings").toList()) {
712 m_ratingFilters[index++] = v.toInt();
715 m_aircraftProxy->setRatingFilterEnabled(m_ui->ratingsFilterCheck->isChecked());
716 m_aircraftProxy->setRatings(m_ratingFilters);
718 updateSelectedAircraft();
719 maybeRestoreAircraftSelection();
721 m_ui->commandLineArgs->setPlainText(settings.value("additional-args").toString());
724 void QtLauncher::delayedAircraftModelReset()
726 QTimer::singleShot(1, this, SLOT(maybeRestoreAircraftSelection()));
729 void QtLauncher::maybeRestoreAircraftSelection()
731 QModelIndex aircraftIndex = m_aircraftModel->indexOfAircraftURI(m_selectedAircraft);
732 QModelIndex proxyIndex = m_aircraftProxy->mapFromSource(aircraftIndex);
733 if (proxyIndex.isValid()) {
734 m_ui->aircraftList->selectionModel()->setCurrentIndex(proxyIndex,
735 QItemSelectionModel::ClearAndSelect);
736 m_ui->aircraftList->selectionModel()->select(proxyIndex,
737 QItemSelectionModel::ClearAndSelect);
738 m_ui->aircraftList->scrollTo(proxyIndex);
742 void QtLauncher::saveSettings()
745 settings.setValue("enable-rembrandt", m_ui->rembrandtCheckbox->isChecked());
746 settings.setValue("enable-terrasync", m_ui->terrasyncCheck->isChecked());
747 settings.setValue("enable-msaa", m_ui->msaaCheckbox->isChecked());
748 settings.setValue("start-fullscreen", m_ui->fullScreenCheckbox->isChecked());
749 settings.setValue("enable-realwx", m_ui->fetchRealWxrCheckbox->isChecked());
750 settings.setValue("start-paused", m_ui->startPausedCheck->isChecked());
751 settings.setValue("ratings-filter", m_ui->ratingsFilterCheck->isChecked());
752 settings.setValue("only-show-installed", m_ui->onlyShowInstalledCheck->isChecked());
753 settings.setValue("recent-aircraft", QUrl::toStringList(m_recentAircraft));
755 settings.setValue("timeofday", m_ui->timeOfDayCombo->currentIndex());
756 settings.setValue("season", m_ui->seasonCombo->currentIndex());
757 settings.setValue("additional-args", m_ui->commandLineArgs->toPlainText());
759 m_ui->location->saveSettings();
762 void QtLauncher::setEnableDisableOptionFromCheckbox(QCheckBox* cbox, QString name) const
764 flightgear::Options* opt = flightgear::Options::sharedInstance();
765 std::string stdName(name.toStdString());
766 if (cbox->isChecked()) {
767 opt->addOption("enable-" + stdName, "");
769 opt->addOption("disable-" + stdName, "");
773 void QtLauncher::closeEvent(QCloseEvent *event)
778 void QtLauncher::reject()
783 void QtLauncher::onRun()
785 flightgear::Options* opt = flightgear::Options::sharedInstance();
786 setEnableDisableOptionFromCheckbox(m_ui->terrasyncCheck, "terrasync");
787 setEnableDisableOptionFromCheckbox(m_ui->fetchRealWxrCheckbox, "real-weather-fetch");
788 setEnableDisableOptionFromCheckbox(m_ui->rembrandtCheckbox, "rembrandt");
789 setEnableDisableOptionFromCheckbox(m_ui->fullScreenCheckbox, "fullscreen");
790 // setEnableDisableOptionFromCheckbox(m_ui->startPausedCheck, "freeze");
792 bool startPaused = m_ui->startPausedCheck->isChecked() ||
793 m_ui->location->shouldStartPaused();
795 opt->addOption("enable-freeze", "");
798 // MSAA is more complex
799 if (!m_ui->rembrandtCheckbox->isChecked()) {
800 if (m_ui->msaaCheckbox->isChecked()) {
801 globals->get_props()->setIntValue("/sim/rendering/multi-sample-buffers", 1);
802 globals->get_props()->setIntValue("/sim/rendering/multi-samples", 4);
804 globals->get_props()->setIntValue("/sim/rendering/multi-sample-buffers", 0);
809 if (!m_selectedAircraft.isEmpty()) {
810 if (m_selectedAircraft.isLocalFile()) {
811 QFileInfo setFileInfo(m_selectedAircraft.toLocalFile());
812 opt->addOption("aircraft-dir", setFileInfo.dir().absolutePath().toStdString());
813 QString setFile = setFileInfo.fileName();
814 Q_ASSERT(setFile.endsWith("-set.xml"));
815 setFile.truncate(setFile.count() - 8); // drop the '-set.xml' portion
816 opt->addOption("aircraft", setFile.toStdString());
817 } else if (m_selectedAircraft.scheme() == "package") {
818 QString qualifiedId = m_selectedAircraft.path();
819 // no need to set aircraft-dir, handled by the corresponding code
821 opt->addOption("aircraft", qualifiedId.toStdString());
823 qWarning() << "unsupported aircraft launch URL" << m_selectedAircraft;
826 // manage aircraft history
827 if (m_recentAircraft.contains(m_selectedAircraft))
828 m_recentAircraft.removeOne(m_selectedAircraft);
829 m_recentAircraft.prepend(m_selectedAircraft);
830 if (m_recentAircraft.size() > MAX_RECENT_AIRCRAFT)
831 m_recentAircraft.pop_back();
834 m_ui->location->setLocationOptions();
837 if (m_ui->timeOfDayCombo->currentIndex() != 0) {
838 QString dayval = m_ui->timeOfDayCombo->currentText().toLower();
839 opt->addOption("timeofday", dayval.toStdString());
842 if (m_ui->seasonCombo->currentIndex() != 0) {
843 QString seasonName = m_ui->seasonCombo->currentText().toLower();
844 opt->addOption("season", seasonName.toStdString());
848 QString downloadDir = settings.value("download-dir").toString();
849 if (!downloadDir.isEmpty()) {
852 int result = QMessageBox::question(this, tr("Create download folder?"),
853 tr("The selected location for downloads does not exist. Create it?"),
854 QMessageBox::Yes | QMessageBox::No | QMessageBox::Cancel);
855 if (result == QMessageBox::Cancel) {
859 if (result == QMessageBox::Yes) {
860 d.mkpath(downloadDir);
864 opt->addOption("download-dir", downloadDir.toStdString());
868 Q_FOREACH(QString path, settings.value("scenery-paths").toStringList()) {
869 opt->addOption("fg-scenery", path.toStdString());
873 Q_FOREACH(QString path, settings.value("aircraft-paths").toStringList()) {
874 // can't use fg-aircraft for this, as it is processed before the launcher is run
875 globals->append_aircraft_path(path.toStdString());
878 // additional arguments
879 ArgumentsTokenizer tk;
880 Q_FOREACH(ArgumentsTokenizer::Arg a, tk.tokenize(m_ui->commandLineArgs->toPlainText())) {
881 if (a.arg.startsWith("prop:")) {
882 QString v = a.arg.mid(5) + "=" + a.value;
883 opt->addOption("prop", v.toStdString());
885 opt->addOption(a.arg.toStdString(), a.value.toStdString());
889 if (settings.contains("restore-defaults-on-run")) {
890 settings.remove("restore-defaults-on-run");
891 opt->addOption("restore-defaults", "");
900 void QtLauncher::onApply()
905 if (!m_selectedAircraft.isEmpty()) {
906 std::string aircraftPropValue,
909 if (m_selectedAircraft.isLocalFile()) {
910 QFileInfo setFileInfo(m_selectedAircraft.toLocalFile());
911 QString setFile = setFileInfo.fileName();
912 Q_ASSERT(setFile.endsWith("-set.xml"));
913 setFile.truncate(setFile.count() - 8); // drop the '-set.xml' portion
914 aircraftDir = setFileInfo.dir().absolutePath().toStdString();
915 aircraftPropValue = setFile.toStdString();
916 } else if (m_selectedAircraft.scheme() == "package") {
917 // no need to set aircraft-dir, handled by the corresponding code
919 aircraftPropValue = m_selectedAircraft.path().toStdString();
921 qWarning() << "unsupported aircraft launch URL" << m_selectedAircraft;
924 // manage aircraft history
925 if (m_recentAircraft.contains(m_selectedAircraft))
926 m_recentAircraft.removeOne(m_selectedAircraft);
927 m_recentAircraft.prepend(m_selectedAircraft);
928 if (m_recentAircraft.size() > MAX_RECENT_AIRCRAFT)
929 m_recentAircraft.pop_back();
931 globals->get_props()->setStringValue("/sim/aircraft", aircraftPropValue);
932 globals->get_props()->setStringValue("/sim/aircraft-dir", aircraftDir);
939 void QtLauncher::onQuit()
944 void QtLauncher::onToggleTerrasync(bool enabled)
948 QString downloadDir = settings.value("download-dir").toString();
949 if (downloadDir.isEmpty()) {
950 downloadDir = QString::fromStdString(flightgear::defaultDownloadDir());
953 QFileInfo info(downloadDir);
954 if (!info.exists()) {
956 msg.setWindowTitle(tr("Create download folder?"));
957 msg.setText(tr("The download folder '%1' does not exist, create it now?").arg(downloadDir));
958 msg.addButton(QMessageBox::Yes);
959 msg.addButton(QMessageBox::Cancel);
960 int result = msg.exec();
962 if (result == QMessageBox::Cancel) {
963 m_ui->terrasyncCheck->setChecked(false);
968 d.mkpath(downloadDir);
973 void QtLauncher::onAircraftInstalledCompleted(QModelIndex index)
975 maybeUpdateSelectedAircraft(index);
978 void QtLauncher::onRatingsFilterToggled()
980 QModelIndex aircraftIndex = m_aircraftModel->indexOfAircraftURI(m_selectedAircraft);
981 QModelIndex proxyIndex = m_aircraftProxy->mapFromSource(aircraftIndex);
982 if (proxyIndex.isValid()) {
983 m_ui->aircraftList->scrollTo(proxyIndex);
987 void QtLauncher::onAircraftInstallFailed(QModelIndex index, QString errorMessage)
989 qWarning() << Q_FUNC_INFO << index.data(AircraftURIRole) << errorMessage;
992 msg.setWindowTitle(tr("Aircraft installation failed"));
993 msg.setText(tr("An error occurred installing the aircraft %1: %2").
994 arg(index.data(Qt::DisplayRole).toString()).arg(errorMessage));
995 msg.addButton(QMessageBox::Ok);
998 maybeUpdateSelectedAircraft(index);
1001 void QtLauncher::onAircraftSelected(const QModelIndex& index)
1003 m_selectedAircraft = index.data(AircraftURIRole).toUrl();
1004 updateSelectedAircraft();
1007 void QtLauncher::onRequestPackageInstall(const QModelIndex& index)
1009 // also select, otherwise UI is confusing
1010 m_selectedAircraft = index.data(AircraftURIRole).toUrl();
1011 updateSelectedAircraft();
1013 QString pkg = index.data(AircraftPackageIdRole).toString();
1014 simgear::pkg::PackageRef pref = globals->packageRoot()->getPackageById(pkg.toStdString());
1015 if (pref->isInstalled()) {
1016 InstallRef install = pref->existingInstall();
1017 if (install && install->hasUpdate()) {
1018 globals->packageRoot()->scheduleToUpdate(install);
1025 void QtLauncher::onCancelDownload(const QModelIndex& index)
1027 QString pkg = index.data(AircraftPackageIdRole).toString();
1028 simgear::pkg::PackageRef pref = globals->packageRoot()->getPackageById(pkg.toStdString());
1029 simgear::pkg::InstallRef i = pref->existingInstall();
1030 i->cancelDownload();
1033 void QtLauncher::onRestoreDefaults()
1035 QMessageBox mbox(this);
1036 mbox.setText(tr("Restore all settings to defaults?"));
1037 mbox.setInformativeText(tr("Restoring settings to their defaults may affect available add-ons such as scenery or aircraft."));
1038 QPushButton* quitButton = mbox.addButton(tr("Restore and restart now"), QMessageBox::YesRole);
1039 mbox.addButton(QMessageBox::Cancel);
1040 mbox.setDefaultButton(QMessageBox::Cancel);
1041 mbox.setIconPixmap(QPixmap(":/app-icon-large"));
1044 if (mbox.clickedButton() != quitButton) {
1051 settings.setValue("restore-defaults-on-run", true);
1054 restartTheApp(QStringList());
1057 void QtLauncher::maybeUpdateSelectedAircraft(QModelIndex index)
1059 QUrl u = index.data(AircraftURIRole).toUrl();
1060 if (u == m_selectedAircraft) {
1061 // potentially enable the run button now!
1062 updateSelectedAircraft();
1066 void QtLauncher::updateSelectedAircraft()
1068 QModelIndex index = m_aircraftModel->indexOfAircraftURI(m_selectedAircraft);
1069 if (index.isValid()) {
1070 QPixmap pm = index.data(Qt::DecorationRole).value<QPixmap>();
1071 m_ui->thumbnail->setPixmap(pm);
1072 m_ui->aircraftDescription->setText(index.data(Qt::DisplayRole).toString());
1074 int status = index.data(AircraftPackageStatusRole).toInt();
1075 bool canRun = (status == PackageInstalled);
1076 m_ui->runButton->setEnabled(canRun);
1078 LauncherAircraftType aircraftType = Airplane;
1079 if (index.data(AircraftIsHelicopterRole).toBool()) {
1080 aircraftType = Helicopter;
1081 } else if (index.data(AircraftIsSeaplaneRole).toBool()) {
1082 aircraftType = Seaplane;
1085 m_ui->location->setAircraftType(aircraftType);
1087 m_ui->thumbnail->setPixmap(QPixmap());
1088 m_ui->aircraftDescription->setText("");
1089 m_ui->runButton->setEnabled(false);
1093 QModelIndex QtLauncher::proxyIndexForAircraftURI(QUrl uri) const
1095 return m_aircraftProxy->mapFromSource(sourceIndexForAircraftURI(uri));
1098 QModelIndex QtLauncher::sourceIndexForAircraftURI(QUrl uri) const
1100 AircraftItemModel* sourceModel = qobject_cast<AircraftItemModel*>(m_aircraftProxy->sourceModel());
1101 Q_ASSERT(sourceModel);
1102 return sourceModel->indexOfAircraftURI(uri);
1105 void QtLauncher::onPopupAircraftHistory()
1107 if (m_recentAircraft.isEmpty()) {
1112 Q_FOREACH(QUrl uri, m_recentAircraft) {
1113 QModelIndex index = sourceIndexForAircraftURI(uri);
1114 if (!index.isValid()) {
1118 QAction* act = m.addAction(index.data(Qt::DisplayRole).toString());
1122 QPoint popupPos = m_ui->aircraftHistory->mapToGlobal(m_ui->aircraftHistory->rect().bottomLeft());
1123 QAction* triggered = m.exec(popupPos);
1125 m_selectedAircraft = triggered->data().toUrl();
1126 QModelIndex index = proxyIndexForAircraftURI(m_selectedAircraft);
1127 m_ui->aircraftList->selectionModel()->setCurrentIndex(index,
1128 QItemSelectionModel::ClearAndSelect);
1129 m_ui->aircraftFilter->clear();
1130 updateSelectedAircraft();
1134 void QtLauncher::onEditRatingsFilter()
1136 EditRatingsFilterDialog dialog(this);
1137 dialog.setRatings(m_ratingFilters);
1140 if (dialog.result() == QDialog::Accepted) {
1142 for (int i=0; i<4; ++i) {
1143 m_ratingFilters[i] = dialog.getRating(i);
1144 vl.append(m_ratingFilters[i]);
1146 m_aircraftProxy->setRatings(m_ratingFilters);
1149 settings.setValue("min-ratings", vl);
1153 void QtLauncher::updateSettingsSummary()
1155 QStringList summary;
1156 if (m_ui->timeOfDayCombo->currentIndex() > 0) {
1157 summary.append(QString(m_ui->timeOfDayCombo->currentText().toLower()));
1160 if (m_ui->seasonCombo->currentIndex() > 0) {
1161 summary.append(QString(m_ui->seasonCombo->currentText().toLower()));
1164 if (m_ui->rembrandtCheckbox->isChecked()) {
1165 summary.append("Rembrandt enabled");
1166 } else if (m_ui->msaaCheckbox->isChecked()) {
1167 summary.append("anti-aliasing");
1170 if (m_ui->fetchRealWxrCheckbox->isChecked()) {
1171 summary.append("live weather");
1174 if (m_ui->terrasyncCheck->isChecked()) {
1175 summary.append("automatic scenery downloads");
1178 if (m_ui->startPausedCheck->isChecked()) {
1179 summary.append("paused");
1182 QString s = summary.join(", ");
1183 s[0] = s[0].toUpper();
1184 m_ui->settingsDescription->setText(s);
1187 void QtLauncher::onRembrandtToggled(bool b)
1189 // Rembrandt and multi-sample are exclusive
1190 m_ui->msaaCheckbox->setEnabled(!b);
1193 void QtLauncher::onShowInstalledAircraftToggled(bool b)
1195 m_ui->ratingsFilterCheck->setEnabled(!b);
1196 maybeRestoreAircraftSelection();
1199 void QtLauncher::onSubsytemIdleTimeout()
1201 globals->get_subsystem_mgr()->update(0.0);
1204 void QtLauncher::onDownloadDirChanged()
1207 // replace existing package root
1208 globals->get_subsystem<FGHTTPClient>()->shutdown();
1209 globals->setPackageRoot(simgear::pkg::RootRef());
1211 // create new root with updated download-dir value
1212 fgInitPackageRoot();
1214 globals->get_subsystem<FGHTTPClient>()->init();
1217 // re-scan the aircraft list
1218 m_aircraftModel->setPackageRoot(globals->packageRoot());
1219 m_aircraftModel->setPaths(settings.value("aircraft-paths").toStringList());
1220 m_aircraftModel->scanDirs();
1222 checkOfficialCatalogMessage();
1224 // re-set scenery dirs
1228 void QtLauncher::checkOfficialCatalogMessage()
1231 bool showOfficialCatalogMesssage = !globals->get_subsystem<FGHTTPClient>()->isDefaultCatalogInstalled();
1232 if (settings.value("hide-official-catalog-message").toBool()) {
1233 showOfficialCatalogMesssage = false;
1236 m_aircraftModel->setOfficialHangarMessageVisible(showOfficialCatalogMesssage);
1237 if (showOfficialCatalogMesssage) {
1238 NoOfficialHangarMessage* messageWidget = new NoOfficialHangarMessage;
1239 connect(messageWidget, &NoOfficialHangarMessage::linkActivated,
1240 this, &QtLauncher::onOfficialCatalogMessageLink);
1242 QModelIndex index = m_aircraftProxy->mapFromSource(m_aircraftModel->officialHangarMessageIndex());
1243 m_ui->aircraftList->setIndexWidget(index, messageWidget);
1247 void QtLauncher::onOfficialCatalogMessageLink(QUrl link)
1249 QString s = link.toString();
1250 if (s == "action:hide") {
1252 settings.setValue("hide-official-catalog-message", true);
1253 } else if (s == "action:add-official") {
1254 AddOnsPage::addDefaultCatalog(this);
1257 checkOfficialCatalogMessage();
1260 simgear::pkg::PackageRef QtLauncher::packageForAircraftURI(QUrl uri) const
1262 if (uri.scheme() != "package") {
1263 qWarning() << "invalid URL scheme:" << uri;
1264 return simgear::pkg::PackageRef();
1267 QString ident = uri.path();
1268 return globals->packageRoot()->getPackageById(ident.toStdString());
1271 void QtLauncher::restartTheApp(QStringList fgArgs)
1273 // Spawn a new instance of myApplication:
1277 #if defined(Q_OS_MAC)
1278 QDir dir(qApp->applicationDirPath()); // returns the 'MacOS' dir
1279 dir.cdUp(); // up to 'contents' dir
1280 dir.cdUp(); // up to .app dir
1281 // see 'man open' for details, but '-n' ensures we launch a new instance,
1282 // and we want to pass remaining arguments to us, not open.
1283 args << "-n" << dir.absolutePath() << "--args" << "--launcher" << fgArgs;
1284 qDebug() << "args" << args;
1285 proc.startDetached("open", args);
1287 args << "--launcher" << fgArgs;
1288 proc.startDetached(qApp->applicationFilePath(), args);
1293 #include "QtLauncher.moc"