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>
53 #include <simgear/timing/timestamp.hxx>
54 #include <simgear/props/props_io.hxx>
55 #include <simgear/structure/exception.hxx>
56 #include <simgear/structure/subsystem_mgr.hxx>
57 #include <simgear/misc/sg_path.hxx>
58 #include <simgear/package/Catalog.hxx>
59 #include <simgear/package/Package.hxx>
60 #include <simgear/package/Install.hxx>
62 #include "ui_Launcher.h"
63 #include "ui_NoOfficialHangar.h"
65 #include "EditRatingsFilterDialog.hxx"
66 #include "AircraftItemDelegate.hxx"
67 #include "AircraftModel.hxx"
68 #include "PathsDialog.hxx"
69 #include "EditCustomMPServerDialog.hxx"
71 #include <Main/globals.hxx>
72 #include <Main/fg_props.hxx>
73 #include <Navaids/NavDataCache.hxx>
74 #include <Navaids/navrecord.hxx>
75 #include <Navaids/SHPParser.hxx>
77 #include <Main/options.hxx>
78 #include <Main/fg_init.hxx>
79 #include <Viewer/WindowBuilder.hxx>
80 #include <Network/HTTPClient.hxx>
81 #include <Network/RemoteXMLRequest.hxx>
83 using namespace flightgear;
84 using namespace simgear::pkg;
86 const int MAX_RECENT_AIRCRAFT = 20;
88 namespace { // anonymous namespace
92 QString baseLabel = QT_TR_NOOP("Initialising navigation data, this may take several minutes");
93 NavDataCache* cache = NavDataCache::createInstance();
94 if (cache->isRebuildRequired()) {
95 QProgressDialog rebuildProgress(baseLabel,
96 QString() /* cancel text */,
99 | Qt::CustomizeWindowHint
100 | Qt::WindowTitleHint
101 | Qt::WindowSystemMenuHint
102 | Qt::MSWindowsFixedSizeDialogHint);
103 rebuildProgress.setWindowModality(Qt::WindowModal);
104 rebuildProgress.show();
106 NavDataCache::RebuildPhase phase = cache->rebuild();
108 while (phase != NavDataCache::REBUILD_DONE) {
109 // sleep to give the rebuild thread more time
110 SGTimeStamp::sleepForMSec(50);
111 phase = cache->rebuild();
114 case NavDataCache::REBUILD_AIRPORTS:
115 rebuildProgress.setLabelText(QT_TR_NOOP("Loading airport data"));
118 case NavDataCache::REBUILD_FIXES:
119 rebuildProgress.setLabelText(QT_TR_NOOP("Loading waypoint data"));
122 case NavDataCache::REBUILD_NAVAIDS:
123 rebuildProgress.setLabelText(QT_TR_NOOP("Loading navigation data"));
127 case NavDataCache::REBUILD_POIS:
128 rebuildProgress.setLabelText(QT_TR_NOOP("Loading point-of-interest data"));
132 rebuildProgress.setLabelText(baseLabel);
135 if (phase == NavDataCache::REBUILD_UNKNOWN) {
136 rebuildProgress.setValue(0);
137 rebuildProgress.setMaximum(0);
139 rebuildProgress.setValue(cache->rebuildPhaseCompletionPercentage());
140 rebuildProgress.setMaximum(100);
143 QCoreApplication::processEvents();
148 class ArgumentsTokenizer
154 explicit Arg(QString k, QString v = QString()) : arg(k), value(v) {}
160 QList<Arg> tokenize(QString in) const
163 const int len = in.count();
169 for (; index < len; ++index) {
171 nc = index < (len - 1) ? in.at(index + 1) : QChar();
175 if (c == QChar('-')) {
176 if (nc == QChar('-')) {
181 // should we pemit single hyphen arguments?
182 // choosing to fail for now
185 } else if (c == QChar('#')) {
188 } else if (c.isSpace()) {
194 if (c == QChar('=')) {
197 } else if (c.isSpace()) {
199 result.append(Arg(key));
201 // could check for illegal charatcers here
207 if (c == QChar('"')) {
209 } else if (c.isSpace()) {
211 result.append(Arg(key, value));
218 if (c == QChar('\\')) {
219 // check for escaped double-quote inside quoted value
220 if (nc == QChar('"')) {
223 } else if (c == QChar('"')) {
231 if ((c == QChar('\n')) || (c == QChar('\r'))) {
235 // nothing to do, eat comment chars
239 } // of character loop
241 // ensure last argument isn't lost
243 result.append(Arg(key));
244 } else if (state == Value) {
245 result.append(Arg(key, value));
261 class NaturalEarthDataLoaderThread : public QThread
266 NaturalEarthDataLoaderThread()
268 connect(this, &QThread::finished, this, &NaturalEarthDataLoaderThread::onFinished);
272 virtual void run() Q_DECL_OVERRIDE
277 loadNaturalEarthFile("ne_10m_coastline.shp", flightgear::PolyLine::COASTLINE, false);
278 loadNaturalEarthFile("ne_10m_rivers_lake_centerlines.shp", flightgear::PolyLine::RIVER, false);
279 loadNaturalEarthFile("ne_10m_lakes.shp", flightgear::PolyLine::LAKE, true);
281 qDebug() << "load basic data took" << st.elapsedMSec();
284 loadNaturalEarthFile("ne_10m_urban_areas.shp", flightgear::PolyLine::URBAN, true);
286 qDebug() << "loading urban areas took:" << st.elapsedMSec();
293 flightgear::PolyLine::bulkAddToSpatialIndex(m_parsedLines);
294 qDebug() << "finished loading Natural Earth data";
295 deleteLater(); // commit suicide
298 void loadNaturalEarthFile(const std::string& aFileName,
299 flightgear::PolyLine::Type aType,
302 SGPath path(globals->get_fg_root());
303 path.append( "Geodata" );
304 path.append(aFileName);
306 return; // silently fail for now
308 flightgear::PolyLineList lines;
309 flightgear::SHPParser::parsePolyLines(path, aType, m_parsedLines, areClosed);
312 flightgear::PolyLineList m_parsedLines;
315 } // of anonymous namespace
317 class AircraftProxyModel : public QSortFilterProxyModel
321 AircraftProxyModel(QObject* pr) :
322 QSortFilterProxyModel(pr),
323 m_ratingsFilter(true),
324 m_onlyShowInstalled(false)
326 for (int i=0; i<4; ++i) {
331 void setRatings(int* ratings)
333 ::memcpy(m_ratings, ratings, sizeof(int) * 4);
338 void setRatingFilterEnabled(bool e)
340 if (e == m_ratingsFilter) {
348 void setInstalledFilterEnabled(bool e)
350 if (e == m_onlyShowInstalled) {
354 m_onlyShowInstalled = e;
359 bool filterAcceptsRow(int sourceRow, const QModelIndex &sourceParent) const
361 QModelIndex index = sourceModel()->index(sourceRow, 0, sourceParent);
362 QVariant v = index.data(AircraftPackageStatusRole);
363 AircraftItemStatus status = static_cast<AircraftItemStatus>(v.toInt());
364 if (status == NoOfficialCatalogMessage) {
368 if (!QSortFilterProxyModel::filterAcceptsRow(sourceRow, sourceParent)) {
372 if (m_onlyShowInstalled) {
373 QVariant v = index.data(AircraftPackageStatusRole);
374 AircraftItemStatus status = static_cast<AircraftItemStatus>(v.toInt());
375 if (status == PackageNotInstalled) {
380 if (!m_onlyShowInstalled && m_ratingsFilter) {
381 for (int i=0; i<4; ++i) {
382 if (m_ratings[i] > index.data(AircraftRatingRole + i).toInt()) {
392 bool m_ratingsFilter;
393 bool m_onlyShowInstalled;
397 class NoOfficialHangarMessage : public QWidget
401 NoOfficialHangarMessage() :
402 m_ui(new Ui::NoOfficialHangarMessage)
405 // proxy this signal upwards
406 connect(m_ui->label, &QLabel::linkActivated,
407 this, &NoOfficialHangarMessage::linkActivated);
411 void linkActivated(QUrl link);
414 Ui::NoOfficialHangarMessage* m_ui;
417 static void initQtResources()
419 Q_INIT_RESOURCE(resources);
425 void initApp(int& argc, char** argv)
427 static bool qtInitDone = false;
433 sglog().setLogLevels( SG_ALL, SG_INFO );
434 initQtResources(); // can't be called from a namespace
436 s_argc = argc; // QApplication only stores a reference to argc,
437 // and may crash if it is freed
438 // http://doc.qt.io/qt-5/qguiapplication.html#QGuiApplication
440 QApplication* app = new QApplication(s_argc, argv);
441 app->setOrganizationName("FlightGear");
442 app->setApplicationName("FlightGear");
443 app->setOrganizationDomain("flightgear.org");
445 QSettings::setDefaultFormat(QSettings::IniFormat);
446 QSettings::setPath(QSettings::IniFormat, QSettings::UserScope,
447 QString::fromStdString(globals->get_fg_home().utf8Str()));
449 // reset numeric / collation locales as described at:
450 // http://doc.qt.io/qt-5/qcoreapplication.html#details
451 ::setlocale(LC_NUMERIC, "C");
452 ::setlocale(LC_COLLATE, "C");
454 Qt::KeyboardModifiers mods = app->queryKeyboardModifiers();
455 if (mods & (Qt::AltModifier | Qt::ShiftModifier)) {
456 qWarning() << "Alt/shift pressed during launch";
458 settings.setValue("fg-root", "!ask");
463 bool runLauncherDialog()
465 // startup the nav-cache now. This pre-empts normal startup of
466 // the cache, but no harm done. (Providing scenery paths are consistent)
471 QString downloadDir = settings.value("download-dir").toString();
472 if (!downloadDir.isEmpty()) {
473 flightgear::Options::sharedInstance()->setOption("download-dir", downloadDir.toStdString());
478 // startup the HTTP system now since packages needs it
479 FGHTTPClient* http = globals->add_new_subsystem<FGHTTPClient>();
481 // we guard against re-init in the global phase; bind and postinit
482 // will happen as normal
485 NaturalEarthDataLoaderThread* naturalEarthLoader = new NaturalEarthDataLoaderThread;
486 naturalEarthLoader->start();
488 // avoid double Apple menu and other weirdness if both Qt and OSG
489 // try to initialise various Cocoa structures.
490 flightgear::WindowBuilder::setPoseAsStandaloneApp(false);
495 int appResult = qApp->exec();
497 return false; // quit
500 // don't set scenery paths twice
501 globals->clear_fg_scenery();
506 bool runInAppLauncherDialog()
511 if (dlg.result() != QDialog::Accepted) {
518 } // of namespace flightgear
520 QtLauncher::QtLauncher() :
523 m_subsystemIdleTimer(NULL),
525 m_doRestoreMPServer(false)
527 m_ui.reset(new Ui::Launcher);
530 #if QT_VERSION >= 0x050300
531 // don't require Qt 5.3
532 m_ui->commandLineArgs->setPlaceholderText("--option=value --prop:/sim/name=value");
535 #if QT_VERSION >= 0x050200
536 m_ui->aircraftFilter->setClearButtonEnabled(true);
539 for (int i=0; i<4; ++i) {
540 m_ratingFilters[i] = 3;
543 m_subsystemIdleTimer = new QTimer(this);
544 m_subsystemIdleTimer->setInterval(0);
545 connect(m_subsystemIdleTimer, &QTimer::timeout,
546 this, &QtLauncher::onSubsytemIdleTimeout);
547 m_subsystemIdleTimer->start();
549 // create and configure the proxy model
550 m_aircraftProxy = new AircraftProxyModel(this);
551 connect(m_ui->ratingsFilterCheck, &QAbstractButton::toggled,
552 m_aircraftProxy, &AircraftProxyModel::setRatingFilterEnabled);
553 connect(m_ui->ratingsFilterCheck, &QAbstractButton::toggled,
554 this, &QtLauncher::maybeRestoreAircraftSelection);
556 connect(m_ui->onlyShowInstalledCheck, &QAbstractButton::toggled,
557 m_aircraftProxy, &AircraftProxyModel::setInstalledFilterEnabled);
558 connect(m_ui->aircraftFilter, &QLineEdit::textChanged,
559 m_aircraftProxy, &QSortFilterProxyModel::setFilterFixedString);
561 connect(m_ui->runButton, SIGNAL(clicked()), this, SLOT(onRun()));
562 connect(m_ui->quitButton, SIGNAL(clicked()), this, SLOT(onQuit()));
564 connect(m_ui->aircraftHistory, &QPushButton::clicked,
565 this, &QtLauncher::onPopupAircraftHistory);
567 connect(m_ui->location, &LocationWidget::descriptionChanged,
568 m_ui->locationDescription, &QLabel::setText);
570 QAction* qa = new QAction(this);
571 qa->setShortcut(QKeySequence("Ctrl+Q"));
572 connect(qa, &QAction::triggered, this, &QtLauncher::onQuit);
575 connect(m_ui->editRatingFilter, &QPushButton::clicked,
576 this, &QtLauncher::onEditRatingsFilter);
577 connect(m_ui->onlyShowInstalledCheck, &QCheckBox::toggled,
578 this, &QtLauncher::onShowInstalledAircraftToggled);
580 QIcon historyIcon(":/history-icon");
581 m_ui->aircraftHistory->setIcon(historyIcon);
583 connect(m_ui->timeOfDayCombo, SIGNAL(currentIndexChanged(int)),
584 this, SLOT(updateSettingsSummary()));
585 connect(m_ui->seasonCombo, SIGNAL(currentIndexChanged(int)),
586 this, SLOT(updateSettingsSummary()));
587 connect(m_ui->fetchRealWxrCheckbox, SIGNAL(toggled(bool)),
588 this, SLOT(updateSettingsSummary()));
589 connect(m_ui->rembrandtCheckbox, SIGNAL(toggled(bool)),
590 this, SLOT(updateSettingsSummary()));
591 connect(m_ui->terrasyncCheck, SIGNAL(toggled(bool)),
592 this, SLOT(updateSettingsSummary()));
593 connect(m_ui->startPausedCheck, SIGNAL(toggled(bool)),
594 this, SLOT(updateSettingsSummary()));
595 connect(m_ui->msaaCheckbox, SIGNAL(toggled(bool)),
596 this, SLOT(updateSettingsSummary()));
598 connect(m_ui->rembrandtCheckbox, SIGNAL(toggled(bool)),
599 this, SLOT(onRembrandtToggled(bool)));
600 connect(m_ui->terrasyncCheck, &QCheckBox::toggled,
601 this, &QtLauncher::onToggleTerrasync);
602 updateSettingsSummary();
604 connect(m_ui->mpServerCombo, SIGNAL(activated(int)),
605 this, SLOT(onMPServerActivated(int)));
607 m_aircraftModel = new AircraftItemModel(this);
608 m_aircraftProxy->setSourceModel(m_aircraftModel);
610 m_aircraftProxy->setFilterCaseSensitivity(Qt::CaseInsensitive);
611 m_aircraftProxy->setSortCaseSensitivity(Qt::CaseInsensitive);
612 m_aircraftProxy->setSortRole(Qt::DisplayRole);
613 m_aircraftProxy->setDynamicSortFilter(true);
615 m_ui->aircraftList->setModel(m_aircraftProxy);
616 m_ui->aircraftList->setHorizontalScrollBarPolicy(Qt::ScrollBarAlwaysOff);
617 AircraftItemDelegate* delegate = new AircraftItemDelegate(m_ui->aircraftList);
618 m_ui->aircraftList->setItemDelegate(delegate);
619 m_ui->aircraftList->setSelectionMode(QAbstractItemView::SingleSelection);
620 connect(m_ui->aircraftList, &QListView::clicked,
621 this, &QtLauncher::onAircraftSelected);
622 connect(delegate, &AircraftItemDelegate::variantChanged,
623 this, &QtLauncher::onAircraftSelected);
624 connect(delegate, &AircraftItemDelegate::requestInstall,
625 this, &QtLauncher::onRequestPackageInstall);
626 connect(delegate, &AircraftItemDelegate::cancelDownload,
627 this, &QtLauncher::onCancelDownload);
629 connect(m_aircraftModel, &AircraftItemModel::aircraftInstallCompleted,
630 this, &QtLauncher::onAircraftInstalledCompleted);
631 connect(m_aircraftModel, &AircraftItemModel::aircraftInstallFailed,
632 this, &QtLauncher::onAircraftInstallFailed);
633 connect(m_aircraftModel, &AircraftItemModel::scanCompleted,
634 this, &QtLauncher::updateSelectedAircraft);
635 connect(m_ui->restoreDefaultsButton, &QPushButton::clicked,
636 this, &QtLauncher::onRestoreDefaults);
639 AddOnsPage* addOnsPage = new AddOnsPage(NULL, globals->packageRoot());
640 connect(addOnsPage, &AddOnsPage::downloadDirChanged,
641 this, &QtLauncher::onDownloadDirChanged);
642 connect(addOnsPage, &AddOnsPage::sceneryPathsChanged,
643 this, &QtLauncher::setSceneryPaths);
645 m_ui->tabWidget->addTab(addOnsPage, tr("Add-ons"));
646 // after any kind of reset, try to restore selection and scroll
647 // to match the m_selectedAircraft. This needs to be delayed
648 // fractionally otherwise the scrollTo seems to be ignored,
650 connect(m_aircraftProxy, &AircraftProxyModel::modelReset,
651 this, &QtLauncher::delayedAircraftModelReset);
654 m_aircraftModel->setPaths(settings.value("aircraft-paths").toStringList());
655 m_aircraftModel->setPackageRoot(globals->packageRoot());
656 m_aircraftModel->scanDirs();
658 checkOfficialCatalogMessage();
661 onRefreshMPServers();
664 QtLauncher::~QtLauncher()
669 void QtLauncher::setSceneryPaths()
671 globals->clear_fg_scenery();
673 // mimic what optionss.cxx does, so we can find airport data for parking
676 // append explicit scenery paths
677 Q_FOREACH(QString path, settings.value("scenery-paths").toStringList()) {
678 globals->append_fg_scenery(path.toStdString());
681 // append the TerraSync path
682 QString downloadDir = settings.value("download-dir").toString();
683 if (downloadDir.isEmpty()) {
684 downloadDir = QString::fromStdString(flightgear::defaultDownloadDir().utf8Str());
687 SGPath terraSyncDir(downloadDir.toStdString());
688 terraSyncDir.append("TerraSync");
689 if (terraSyncDir.exists()) {
690 globals->append_fg_scenery(terraSyncDir);
695 void QtLauncher::setInAppMode()
698 m_ui->tabWidget->removeTab(2);
699 m_ui->tabWidget->removeTab(2);
701 m_ui->runButton->setText(tr("Apply"));
702 m_ui->quitButton->setText(tr("Cancel"));
704 disconnect(m_ui->runButton, SIGNAL(clicked()), this, SLOT(onRun()));
705 connect(m_ui->runButton, SIGNAL(clicked()), this, SLOT(onApply()));
708 void QtLauncher::restoreSettings()
711 m_ui->rembrandtCheckbox->setChecked(settings.value("enable-rembrandt", false).toBool());
712 m_ui->terrasyncCheck->setChecked(settings.value("enable-terrasync", true).toBool());
713 m_ui->fullScreenCheckbox->setChecked(settings.value("start-fullscreen", false).toBool());
714 m_ui->msaaCheckbox->setChecked(settings.value("enable-msaa", false).toBool());
715 m_ui->fetchRealWxrCheckbox->setChecked(settings.value("enable-realwx", true).toBool());
716 m_ui->startPausedCheck->setChecked(settings.value("start-paused", false).toBool());
717 m_ui->timeOfDayCombo->setCurrentIndex(settings.value("timeofday", 0).toInt());
718 m_ui->seasonCombo->setCurrentIndex(settings.value("season", 0).toInt());
720 // full paths to -set.xml files
721 m_recentAircraft = QUrl::fromStringList(settings.value("recent-aircraft").toStringList());
723 if (!m_recentAircraft.empty()) {
724 m_selectedAircraft = m_recentAircraft.front();
726 // select the default C172p
733 m_ui->location->restoreSettings();
736 m_ui->onlyShowInstalledCheck->setChecked(settings.value("only-show-installed", false).toBool());
737 if (m_ui->onlyShowInstalledCheck->isChecked()) {
738 m_ui->ratingsFilterCheck->setEnabled(false);
741 m_ui->ratingsFilterCheck->setChecked(settings.value("ratings-filter", true).toBool());
743 Q_FOREACH(QVariant v, settings.value("min-ratings").toList()) {
744 m_ratingFilters[index++] = v.toInt();
747 m_aircraftProxy->setRatingFilterEnabled(m_ui->ratingsFilterCheck->isChecked());
748 m_aircraftProxy->setRatings(m_ratingFilters);
750 updateSelectedAircraft();
751 maybeRestoreAircraftSelection();
753 m_ui->commandLineArgs->setPlainText(settings.value("additional-args").toString());
755 m_ui->mpBox->setChecked(settings.value("mp-enabled").toBool());
756 m_ui->mpCallsign->setText(settings.value("mp-callsign").toString());
757 // don't restore MP server here, we do it after a refresh
758 m_doRestoreMPServer = true;
761 void QtLauncher::delayedAircraftModelReset()
763 QTimer::singleShot(1, this, SLOT(maybeRestoreAircraftSelection()));
766 void QtLauncher::maybeRestoreAircraftSelection()
768 QModelIndex aircraftIndex = m_aircraftModel->indexOfAircraftURI(m_selectedAircraft);
769 QModelIndex proxyIndex = m_aircraftProxy->mapFromSource(aircraftIndex);
770 if (proxyIndex.isValid()) {
771 m_ui->aircraftList->selectionModel()->setCurrentIndex(proxyIndex,
772 QItemSelectionModel::ClearAndSelect);
773 m_ui->aircraftList->selectionModel()->select(proxyIndex,
774 QItemSelectionModel::ClearAndSelect);
775 m_ui->aircraftList->scrollTo(proxyIndex);
779 void QtLauncher::saveSettings()
782 settings.setValue("enable-rembrandt", m_ui->rembrandtCheckbox->isChecked());
783 settings.setValue("enable-terrasync", m_ui->terrasyncCheck->isChecked());
784 settings.setValue("enable-msaa", m_ui->msaaCheckbox->isChecked());
785 settings.setValue("start-fullscreen", m_ui->fullScreenCheckbox->isChecked());
786 settings.setValue("enable-realwx", m_ui->fetchRealWxrCheckbox->isChecked());
787 settings.setValue("start-paused", m_ui->startPausedCheck->isChecked());
788 settings.setValue("ratings-filter", m_ui->ratingsFilterCheck->isChecked());
789 settings.setValue("only-show-installed", m_ui->onlyShowInstalledCheck->isChecked());
790 settings.setValue("recent-aircraft", QUrl::toStringList(m_recentAircraft));
792 settings.setValue("timeofday", m_ui->timeOfDayCombo->currentIndex());
793 settings.setValue("season", m_ui->seasonCombo->currentIndex());
794 settings.setValue("additional-args", m_ui->commandLineArgs->toPlainText());
796 m_ui->location->saveSettings();
798 settings.setValue("mp-callsign", m_ui->mpCallsign->text());
799 settings.setValue("mp-server", m_ui->mpServerCombo->currentData());
800 settings.setValue("mp-enabled", m_ui->mpBox->isChecked());
803 void QtLauncher::setEnableDisableOptionFromCheckbox(QCheckBox* cbox, QString name) const
805 flightgear::Options* opt = flightgear::Options::sharedInstance();
806 std::string stdName(name.toStdString());
807 if (cbox->isChecked()) {
808 opt->addOption("enable-" + stdName, "");
810 opt->addOption("disable-" + stdName, "");
814 void QtLauncher::closeEvent(QCloseEvent *event)
819 void QtLauncher::reject()
824 void QtLauncher::onRun()
826 flightgear::Options* opt = flightgear::Options::sharedInstance();
827 setEnableDisableOptionFromCheckbox(m_ui->terrasyncCheck, "terrasync");
828 setEnableDisableOptionFromCheckbox(m_ui->fetchRealWxrCheckbox, "real-weather-fetch");
829 setEnableDisableOptionFromCheckbox(m_ui->rembrandtCheckbox, "rembrandt");
830 setEnableDisableOptionFromCheckbox(m_ui->fullScreenCheckbox, "fullscreen");
831 // setEnableDisableOptionFromCheckbox(m_ui->startPausedCheck, "freeze");
833 bool startPaused = m_ui->startPausedCheck->isChecked() ||
834 m_ui->location->shouldStartPaused();
836 opt->addOption("enable-freeze", "");
839 // MSAA is more complex
840 if (!m_ui->rembrandtCheckbox->isChecked()) {
841 if (m_ui->msaaCheckbox->isChecked()) {
842 globals->get_props()->setIntValue("/sim/rendering/multi-sample-buffers", 1);
843 globals->get_props()->setIntValue("/sim/rendering/multi-samples", 4);
845 globals->get_props()->setIntValue("/sim/rendering/multi-sample-buffers", 0);
850 if (!m_selectedAircraft.isEmpty()) {
851 if (m_selectedAircraft.isLocalFile()) {
852 QFileInfo setFileInfo(m_selectedAircraft.toLocalFile());
853 opt->addOption("aircraft-dir", setFileInfo.dir().absolutePath().toStdString());
854 QString setFile = setFileInfo.fileName();
855 Q_ASSERT(setFile.endsWith("-set.xml"));
856 setFile.truncate(setFile.count() - 8); // drop the '-set.xml' portion
857 opt->addOption("aircraft", setFile.toStdString());
858 } else if (m_selectedAircraft.scheme() == "package") {
859 QString qualifiedId = m_selectedAircraft.path();
860 // no need to set aircraft-dir, handled by the corresponding code
862 opt->addOption("aircraft", qualifiedId.toStdString());
864 qWarning() << "unsupported aircraft launch URL" << m_selectedAircraft;
867 // manage aircraft history
868 if (m_recentAircraft.contains(m_selectedAircraft))
869 m_recentAircraft.removeOne(m_selectedAircraft);
870 m_recentAircraft.prepend(m_selectedAircraft);
871 if (m_recentAircraft.size() > MAX_RECENT_AIRCRAFT)
872 m_recentAircraft.pop_back();
875 if (m_ui->mpBox->isChecked()) {
876 opt->addOption("callsign", m_ui->mpCallsign->text().toStdString());
877 QString host = m_ui->mpServerCombo->currentData().toString();
879 if (host == "custom") {
881 host = settings.value("mp-custom-host").toString();
882 port = settings.value("mp-custom-port").toInt();
884 port = findMPServerPort(host.toStdString());
886 globals->get_props()->setStringValue("/sim/multiplay/txhost", host.toStdString());
887 globals->get_props()->setIntValue("/sim/multiplay/txport", port);
890 m_ui->location->setLocationOptions();
893 if (m_ui->timeOfDayCombo->currentIndex() != 0) {
894 QString dayval = m_ui->timeOfDayCombo->currentText().toLower();
895 opt->addOption("timeofday", dayval.toStdString());
898 if (m_ui->seasonCombo->currentIndex() != 0) {
899 QString seasonName = m_ui->seasonCombo->currentText().toLower();
900 opt->addOption("season", seasonName.toStdString());
904 QString downloadDir = settings.value("download-dir").toString();
905 if (!downloadDir.isEmpty()) {
908 int result = QMessageBox::question(this, tr("Create download folder?"),
909 tr("The selected location for downloads does not exist. Create it?"),
910 QMessageBox::Yes | QMessageBox::No | QMessageBox::Cancel);
911 if (result == QMessageBox::Cancel) {
915 if (result == QMessageBox::Yes) {
916 d.mkpath(downloadDir);
920 opt->addOption("download-dir", downloadDir.toStdString());
924 Q_FOREACH(QString path, settings.value("scenery-paths").toStringList()) {
925 opt->addOption("fg-scenery", path.toStdString());
929 Q_FOREACH(QString path, settings.value("aircraft-paths").toStringList()) {
930 // can't use fg-aircraft for this, as it is processed before the launcher is run
931 globals->append_aircraft_path(path.toStdString());
934 // additional arguments
935 ArgumentsTokenizer tk;
936 Q_FOREACH(ArgumentsTokenizer::Arg a, tk.tokenize(m_ui->commandLineArgs->toPlainText())) {
937 if (a.arg.startsWith("prop:")) {
938 QString v = a.arg.mid(5) + "=" + a.value;
939 opt->addOption("prop", v.toStdString());
941 opt->addOption(a.arg.toStdString(), a.value.toStdString());
945 if (settings.contains("restore-defaults-on-run")) {
946 settings.remove("restore-defaults-on-run");
947 opt->addOption("restore-defaults", "");
956 void QtLauncher::onApply()
961 if (!m_selectedAircraft.isEmpty()) {
962 std::string aircraftPropValue,
965 if (m_selectedAircraft.isLocalFile()) {
966 QFileInfo setFileInfo(m_selectedAircraft.toLocalFile());
967 QString setFile = setFileInfo.fileName();
968 Q_ASSERT(setFile.endsWith("-set.xml"));
969 setFile.truncate(setFile.count() - 8); // drop the '-set.xml' portion
970 aircraftDir = setFileInfo.dir().absolutePath().toStdString();
971 aircraftPropValue = setFile.toStdString();
972 } else if (m_selectedAircraft.scheme() == "package") {
973 // no need to set aircraft-dir, handled by the corresponding code
975 aircraftPropValue = m_selectedAircraft.path().toStdString();
977 qWarning() << "unsupported aircraft launch URL" << m_selectedAircraft;
980 // manage aircraft history
981 if (m_recentAircraft.contains(m_selectedAircraft))
982 m_recentAircraft.removeOne(m_selectedAircraft);
983 m_recentAircraft.prepend(m_selectedAircraft);
984 if (m_recentAircraft.size() > MAX_RECENT_AIRCRAFT)
985 m_recentAircraft.pop_back();
987 globals->get_props()->setStringValue("/sim/aircraft", aircraftPropValue);
988 globals->get_props()->setStringValue("/sim/aircraft-dir", aircraftDir);
995 void QtLauncher::onQuit()
1000 void QtLauncher::onToggleTerrasync(bool enabled)
1004 QString downloadDir = settings.value("download-dir").toString();
1005 if (downloadDir.isEmpty()) {
1006 downloadDir = QString::fromStdString(flightgear::defaultDownloadDir().utf8Str());
1009 QFileInfo info(downloadDir);
1010 if (!info.exists()) {
1012 msg.setWindowTitle(tr("Create download folder?"));
1013 msg.setText(tr("The download folder '%1' does not exist, create it now?").arg(downloadDir));
1014 msg.addButton(QMessageBox::Yes);
1015 msg.addButton(QMessageBox::Cancel);
1016 int result = msg.exec();
1018 if (result == QMessageBox::Cancel) {
1019 m_ui->terrasyncCheck->setChecked(false);
1023 QDir d(downloadDir);
1024 d.mkpath(downloadDir);
1029 void QtLauncher::onAircraftInstalledCompleted(QModelIndex index)
1031 maybeUpdateSelectedAircraft(index);
1034 void QtLauncher::onRatingsFilterToggled()
1036 QModelIndex aircraftIndex = m_aircraftModel->indexOfAircraftURI(m_selectedAircraft);
1037 QModelIndex proxyIndex = m_aircraftProxy->mapFromSource(aircraftIndex);
1038 if (proxyIndex.isValid()) {
1039 m_ui->aircraftList->scrollTo(proxyIndex);
1043 void QtLauncher::onAircraftInstallFailed(QModelIndex index, QString errorMessage)
1045 qWarning() << Q_FUNC_INFO << index.data(AircraftURIRole) << errorMessage;
1048 msg.setWindowTitle(tr("Aircraft installation failed"));
1049 msg.setText(tr("An error occurred installing the aircraft %1: %2").
1050 arg(index.data(Qt::DisplayRole).toString()).arg(errorMessage));
1051 msg.addButton(QMessageBox::Ok);
1054 maybeUpdateSelectedAircraft(index);
1057 void QtLauncher::onAircraftSelected(const QModelIndex& index)
1059 m_selectedAircraft = index.data(AircraftURIRole).toUrl();
1060 updateSelectedAircraft();
1063 void QtLauncher::onRequestPackageInstall(const QModelIndex& index)
1065 // also select, otherwise UI is confusing
1066 m_selectedAircraft = index.data(AircraftURIRole).toUrl();
1067 updateSelectedAircraft();
1069 QString pkg = index.data(AircraftPackageIdRole).toString();
1070 simgear::pkg::PackageRef pref = globals->packageRoot()->getPackageById(pkg.toStdString());
1071 if (pref->isInstalled()) {
1072 InstallRef install = pref->existingInstall();
1073 if (install && install->hasUpdate()) {
1074 globals->packageRoot()->scheduleToUpdate(install);
1081 void QtLauncher::onCancelDownload(const QModelIndex& index)
1083 QString pkg = index.data(AircraftPackageIdRole).toString();
1084 simgear::pkg::PackageRef pref = globals->packageRoot()->getPackageById(pkg.toStdString());
1085 simgear::pkg::InstallRef i = pref->existingInstall();
1086 i->cancelDownload();
1089 void QtLauncher::onRestoreDefaults()
1091 QMessageBox mbox(this);
1092 mbox.setText(tr("Restore all settings to defaults?"));
1093 mbox.setInformativeText(tr("Restoring settings to their defaults may affect available add-ons such as scenery or aircraft."));
1094 QPushButton* quitButton = mbox.addButton(tr("Restore and restart now"), QMessageBox::YesRole);
1095 mbox.addButton(QMessageBox::Cancel);
1096 mbox.setDefaultButton(QMessageBox::Cancel);
1097 mbox.setIconPixmap(QPixmap(":/app-icon-large"));
1100 if (mbox.clickedButton() != quitButton) {
1107 settings.setValue("restore-defaults-on-run", true);
1110 restartTheApp(QStringList());
1113 void QtLauncher::maybeUpdateSelectedAircraft(QModelIndex index)
1115 QUrl u = index.data(AircraftURIRole).toUrl();
1116 if (u == m_selectedAircraft) {
1117 // potentially enable the run button now!
1118 updateSelectedAircraft();
1122 void QtLauncher::updateSelectedAircraft()
1124 QModelIndex index = m_aircraftModel->indexOfAircraftURI(m_selectedAircraft);
1125 if (index.isValid()) {
1126 QPixmap pm = index.data(Qt::DecorationRole).value<QPixmap>();
1127 m_ui->thumbnail->setPixmap(pm);
1128 m_ui->aircraftDescription->setText(index.data(Qt::DisplayRole).toString());
1130 int status = index.data(AircraftPackageStatusRole).toInt();
1131 bool canRun = (status == PackageInstalled);
1132 m_ui->runButton->setEnabled(canRun);
1134 LauncherAircraftType aircraftType = Airplane;
1135 if (index.data(AircraftIsHelicopterRole).toBool()) {
1136 aircraftType = Helicopter;
1137 } else if (index.data(AircraftIsSeaplaneRole).toBool()) {
1138 aircraftType = Seaplane;
1141 m_ui->location->setAircraftType(aircraftType);
1143 m_ui->thumbnail->setPixmap(QPixmap());
1144 m_ui->aircraftDescription->setText("");
1145 m_ui->runButton->setEnabled(false);
1149 QModelIndex QtLauncher::proxyIndexForAircraftURI(QUrl uri) const
1151 return m_aircraftProxy->mapFromSource(sourceIndexForAircraftURI(uri));
1154 QModelIndex QtLauncher::sourceIndexForAircraftURI(QUrl uri) const
1156 AircraftItemModel* sourceModel = qobject_cast<AircraftItemModel*>(m_aircraftProxy->sourceModel());
1157 Q_ASSERT(sourceModel);
1158 return sourceModel->indexOfAircraftURI(uri);
1161 void QtLauncher::onPopupAircraftHistory()
1163 if (m_recentAircraft.isEmpty()) {
1168 Q_FOREACH(QUrl uri, m_recentAircraft) {
1169 QModelIndex index = sourceIndexForAircraftURI(uri);
1170 if (!index.isValid()) {
1174 QAction* act = m.addAction(index.data(Qt::DisplayRole).toString());
1178 QPoint popupPos = m_ui->aircraftHistory->mapToGlobal(m_ui->aircraftHistory->rect().bottomLeft());
1179 QAction* triggered = m.exec(popupPos);
1181 m_selectedAircraft = triggered->data().toUrl();
1182 QModelIndex index = proxyIndexForAircraftURI(m_selectedAircraft);
1183 m_ui->aircraftList->selectionModel()->setCurrentIndex(index,
1184 QItemSelectionModel::ClearAndSelect);
1185 m_ui->aircraftFilter->clear();
1186 updateSelectedAircraft();
1190 void QtLauncher::onEditRatingsFilter()
1192 EditRatingsFilterDialog dialog(this);
1193 dialog.setRatings(m_ratingFilters);
1196 if (dialog.result() == QDialog::Accepted) {
1198 for (int i=0; i<4; ++i) {
1199 m_ratingFilters[i] = dialog.getRating(i);
1200 vl.append(m_ratingFilters[i]);
1202 m_aircraftProxy->setRatings(m_ratingFilters);
1205 settings.setValue("min-ratings", vl);
1209 void QtLauncher::updateSettingsSummary()
1211 QStringList summary;
1212 if (m_ui->timeOfDayCombo->currentIndex() > 0) {
1213 summary.append(QString(m_ui->timeOfDayCombo->currentText().toLower()));
1216 if (m_ui->seasonCombo->currentIndex() > 0) {
1217 summary.append(QString(m_ui->seasonCombo->currentText().toLower()));
1220 if (m_ui->rembrandtCheckbox->isChecked()) {
1221 summary.append("Rembrandt enabled");
1222 } else if (m_ui->msaaCheckbox->isChecked()) {
1223 summary.append("anti-aliasing");
1226 if (m_ui->fetchRealWxrCheckbox->isChecked()) {
1227 summary.append("live weather");
1230 if (m_ui->terrasyncCheck->isChecked()) {
1231 summary.append("automatic scenery downloads");
1234 if (m_ui->startPausedCheck->isChecked()) {
1235 summary.append("paused");
1238 QString s = summary.join(", ");
1239 s[0] = s[0].toUpper();
1240 m_ui->settingsDescription->setText(s);
1243 void QtLauncher::onRembrandtToggled(bool b)
1245 // Rembrandt and multi-sample are exclusive
1246 m_ui->msaaCheckbox->setEnabled(!b);
1249 void QtLauncher::onShowInstalledAircraftToggled(bool b)
1251 m_ui->ratingsFilterCheck->setEnabled(!b);
1252 maybeRestoreAircraftSelection();
1255 void QtLauncher::onSubsytemIdleTimeout()
1257 globals->get_subsystem_mgr()->update(0.0);
1260 void QtLauncher::onDownloadDirChanged()
1263 // replace existing package root
1264 globals->get_subsystem<FGHTTPClient>()->shutdown();
1265 globals->setPackageRoot(simgear::pkg::RootRef());
1267 // create new root with updated download-dir value
1268 fgInitPackageRoot();
1270 globals->get_subsystem<FGHTTPClient>()->init();
1273 // re-scan the aircraft list
1274 m_aircraftModel->setPackageRoot(globals->packageRoot());
1275 m_aircraftModel->setPaths(settings.value("aircraft-paths").toStringList());
1276 m_aircraftModel->scanDirs();
1278 checkOfficialCatalogMessage();
1280 // re-set scenery dirs
1284 void QtLauncher::checkOfficialCatalogMessage()
1287 bool showOfficialCatalogMesssage = !globals->get_subsystem<FGHTTPClient>()->isDefaultCatalogInstalled();
1288 if (settings.value("hide-official-catalog-message").toBool()) {
1289 showOfficialCatalogMesssage = false;
1292 m_aircraftModel->setOfficialHangarMessageVisible(showOfficialCatalogMesssage);
1293 if (showOfficialCatalogMesssage) {
1294 NoOfficialHangarMessage* messageWidget = new NoOfficialHangarMessage;
1295 connect(messageWidget, &NoOfficialHangarMessage::linkActivated,
1296 this, &QtLauncher::onOfficialCatalogMessageLink);
1298 QModelIndex index = m_aircraftProxy->mapFromSource(m_aircraftModel->officialHangarMessageIndex());
1299 m_ui->aircraftList->setIndexWidget(index, messageWidget);
1303 void QtLauncher::onOfficialCatalogMessageLink(QUrl link)
1305 QString s = link.toString();
1306 if (s == "action:hide") {
1308 settings.setValue("hide-official-catalog-message", true);
1309 } else if (s == "action:add-official") {
1310 AddOnsPage::addDefaultCatalog(this);
1313 checkOfficialCatalogMessage();
1316 void QtLauncher::onRefreshMPServers()
1318 if (m_mpServerRequest.get()) {
1319 return; // in-progress
1322 string url(fgGetString("/sim/multiplay/serverlist-url",
1323 "http://liveries.flightgear.org/mpstatus/mpservers.xml"));
1326 SG_LOG(SG_IO, SG_ALERT, "do_multiplayer.refreshserverlist: no URL given");
1330 SGPropertyNode *targetnode = fgGetNode("/sim/multiplay/server-list", true);
1331 m_mpServerRequest.reset(new RemoteXMLRequest(url, targetnode));
1332 m_mpServerRequest->done(this, &QtLauncher::onRefreshMPServersDone);
1333 m_mpServerRequest->fail(this, &QtLauncher::onRefreshMPServersFailed);
1334 globals->get_subsystem<FGHTTPClient>()->makeRequest(m_mpServerRequest);
1337 void QtLauncher::onRefreshMPServersDone(simgear::HTTP::Request*)
1339 // parse the properties
1340 SGPropertyNode *targetnode = fgGetNode("/sim/multiplay/server-list", true);
1341 m_ui->mpServerCombo->clear();
1343 for (int i=0; i<targetnode->nChildren(); ++i) {
1344 SGPropertyNode* c = targetnode->getChild(i);
1345 if (c->getName() != std::string("server")) {
1349 QString name = QString::fromStdString(c->getStringValue("name"));
1350 QString loc = QString::fromStdString(c->getStringValue("location"));
1351 QString host = QString::fromStdString(c->getStringValue("hostname"));
1352 m_ui->mpServerCombo->addItem(tr("%1 - %2").arg(name,loc), host);
1355 EditCustomMPServerDialog::addCustomItem(m_ui->mpServerCombo);
1356 restoreMPServerSelection();
1358 m_mpServerRequest.clear();
1361 void QtLauncher::onRefreshMPServersFailed(simgear::HTTP::Request*)
1363 qWarning() << "refreshing MP servers failed:" << QString::fromStdString(m_mpServerRequest->responseReason());
1364 m_mpServerRequest.clear();
1365 EditCustomMPServerDialog::addCustomItem(m_ui->mpServerCombo);
1366 restoreMPServerSelection();
1369 void QtLauncher::restoreMPServerSelection()
1371 if (m_doRestoreMPServer) {
1373 int index = m_ui->mpServerCombo->findData(settings.value("mp-server"));
1375 m_ui->mpServerCombo->setCurrentIndex(index);
1377 m_doRestoreMPServer = false;
1381 void QtLauncher::onMPServerActivated(int index)
1383 if (m_ui->mpServerCombo->itemData(index) == "custom") {
1384 EditCustomMPServerDialog dlg(this);
1386 if (dlg.result() == QDialog::Accepted) {
1387 m_ui->mpServerCombo->setItemText(index, tr("Custom - %1").arg(dlg.hostname()));
1392 int QtLauncher::findMPServerPort(const std::string& host)
1394 SGPropertyNode *targetnode = fgGetNode("/sim/multiplay/server-list", true);
1395 for (int i=0; i<targetnode->nChildren(); ++i) {
1396 SGPropertyNode* c = targetnode->getChild(i);
1397 if (c->getName() != std::string("server")) {
1401 if (c->getStringValue("hostname") == host) {
1402 return c->getIntValue("port");
1409 simgear::pkg::PackageRef QtLauncher::packageForAircraftURI(QUrl uri) const
1411 if (uri.scheme() != "package") {
1412 qWarning() << "invalid URL scheme:" << uri;
1413 return simgear::pkg::PackageRef();
1416 QString ident = uri.path();
1417 return globals->packageRoot()->getPackageById(ident.toStdString());
1420 void QtLauncher::restartTheApp(QStringList fgArgs)
1422 // Spawn a new instance of myApplication:
1426 #if defined(Q_OS_MAC)
1427 QDir dir(qApp->applicationDirPath()); // returns the 'MacOS' dir
1428 dir.cdUp(); // up to 'contents' dir
1429 dir.cdUp(); // up to .app dir
1430 // see 'man open' for details, but '-n' ensures we launch a new instance,
1431 // and we want to pass remaining arguments to us, not open.
1432 args << "-n" << dir.absolutePath() << "--args" << "--launcher" << fgArgs;
1433 qDebug() << "args" << args;
1434 proc.startDetached("open", args);
1436 args << "--launcher" << fgArgs;
1437 proc.startDetached(qApp->applicationFilePath(), args);
1442 #include "QtLauncher.moc"