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 <Main/fg_props.hxx>
71 #include <Navaids/NavDataCache.hxx>
72 #include <Navaids/navrecord.hxx>
73 #include <Navaids/SHPParser.hxx>
75 #include <Main/options.hxx>
76 #include <Main/fg_init.hxx>
77 #include <Viewer/WindowBuilder.hxx>
78 #include <Network/HTTPClient.hxx>
79 #include <Network/RemoteXMLRequest.hxx>
81 using namespace flightgear;
82 using namespace simgear::pkg;
84 const int MAX_RECENT_AIRCRAFT = 20;
86 namespace { // anonymous namespace
90 QString baseLabel = QT_TR_NOOP("Initialising navigation data, this may take several minutes");
91 NavDataCache* cache = NavDataCache::createInstance();
92 if (cache->isRebuildRequired()) {
93 QProgressDialog rebuildProgress(baseLabel,
94 QString() /* cancel text */,
97 | Qt::CustomizeWindowHint
99 | Qt::WindowSystemMenuHint
100 | Qt::MSWindowsFixedSizeDialogHint);
101 rebuildProgress.setWindowModality(Qt::WindowModal);
102 rebuildProgress.show();
104 NavDataCache::RebuildPhase phase = cache->rebuild();
106 while (phase != NavDataCache::REBUILD_DONE) {
107 // sleep to give the rebuild thread more time
108 SGTimeStamp::sleepForMSec(50);
109 phase = cache->rebuild();
112 case NavDataCache::REBUILD_AIRPORTS:
113 rebuildProgress.setLabelText(QT_TR_NOOP("Loading airport data"));
116 case NavDataCache::REBUILD_FIXES:
117 rebuildProgress.setLabelText(QT_TR_NOOP("Loading waypoint data"));
120 case NavDataCache::REBUILD_NAVAIDS:
121 rebuildProgress.setLabelText(QT_TR_NOOP("Loading navigation data"));
125 case NavDataCache::REBUILD_POIS:
126 rebuildProgress.setLabelText(QT_TR_NOOP("Loading point-of-interest data"));
130 rebuildProgress.setLabelText(baseLabel);
133 if (phase == NavDataCache::REBUILD_UNKNOWN) {
134 rebuildProgress.setValue(0);
135 rebuildProgress.setMaximum(0);
137 rebuildProgress.setValue(cache->rebuildPhaseCompletionPercentage());
138 rebuildProgress.setMaximum(100);
141 QCoreApplication::processEvents();
146 class ArgumentsTokenizer
152 explicit Arg(QString k, QString v = QString()) : arg(k), value(v) {}
158 QList<Arg> tokenize(QString in) const
161 const int len = in.count();
167 for (; index < len; ++index) {
169 nc = index < (len - 1) ? in.at(index + 1) : QChar();
173 if (c == QChar('-')) {
174 if (nc == QChar('-')) {
179 // should we pemit single hyphen arguments?
180 // choosing to fail for now
183 } else if (c == QChar('#')) {
186 } else if (c.isSpace()) {
192 if (c == QChar('=')) {
195 } else if (c.isSpace()) {
197 result.append(Arg(key));
199 // could check for illegal charatcers here
205 if (c == QChar('"')) {
207 } else if (c.isSpace()) {
209 result.append(Arg(key, value));
216 if (c == QChar('\\')) {
217 // check for escaped double-quote inside quoted value
218 if (nc == QChar('"')) {
221 } else if (c == QChar('"')) {
229 if ((c == QChar('\n')) || (c == QChar('\r'))) {
233 // nothing to do, eat comment chars
237 } // of character loop
239 // ensure last argument isn't lost
241 result.append(Arg(key));
242 } else if (state == Value) {
243 result.append(Arg(key, value));
259 } // of anonymous namespace
261 class AircraftProxyModel : public QSortFilterProxyModel
265 AircraftProxyModel(QObject* pr) :
266 QSortFilterProxyModel(pr),
267 m_ratingsFilter(true),
268 m_onlyShowInstalled(false)
270 for (int i=0; i<4; ++i) {
275 void setRatings(int* ratings)
277 ::memcpy(m_ratings, ratings, sizeof(int) * 4);
282 void setRatingFilterEnabled(bool e)
284 if (e == m_ratingsFilter) {
292 void setInstalledFilterEnabled(bool e)
294 if (e == m_onlyShowInstalled) {
298 m_onlyShowInstalled = e;
303 bool filterAcceptsRow(int sourceRow, const QModelIndex &sourceParent) const
305 QModelIndex index = sourceModel()->index(sourceRow, 0, sourceParent);
306 QVariant v = index.data(AircraftPackageStatusRole);
307 AircraftItemStatus status = static_cast<AircraftItemStatus>(v.toInt());
308 if (status == NoOfficialCatalogMessage) {
312 if (!QSortFilterProxyModel::filterAcceptsRow(sourceRow, sourceParent)) {
316 if (m_onlyShowInstalled) {
317 QVariant v = index.data(AircraftPackageStatusRole);
318 AircraftItemStatus status = static_cast<AircraftItemStatus>(v.toInt());
319 if (status == PackageNotInstalled) {
324 if (!m_onlyShowInstalled && m_ratingsFilter) {
325 for (int i=0; i<4; ++i) {
326 if (m_ratings[i] > index.data(AircraftRatingRole + i).toInt()) {
336 bool m_ratingsFilter;
337 bool m_onlyShowInstalled;
341 class NoOfficialHangarMessage : public QWidget
345 NoOfficialHangarMessage() :
346 m_ui(new Ui::NoOfficialHangarMessage)
349 // proxy this signal upwards
350 connect(m_ui->label, &QLabel::linkActivated,
351 this, &NoOfficialHangarMessage::linkActivated);
355 void linkActivated(QUrl link);
358 Ui::NoOfficialHangarMessage* m_ui;
361 static void initQtResources()
363 Q_INIT_RESOURCE(resources);
369 void initApp(int& argc, char** argv)
371 static bool qtInitDone = false;
377 sglog().setLogLevels( SG_ALL, SG_INFO );
378 initQtResources(); // can't be called from a namespace
380 s_argc = argc; // QApplication only stores a reference to argc,
381 // and may crash if it is freed
382 // http://doc.qt.io/qt-5/qguiapplication.html#QGuiApplication
384 QApplication* app = new QApplication(s_argc, argv);
385 app->setOrganizationName("FlightGear");
386 app->setApplicationName("FlightGear");
387 app->setOrganizationDomain("flightgear.org");
389 QSettings::setDefaultFormat(QSettings::IniFormat);
390 QSettings::setPath(QSettings::IniFormat, QSettings::UserScope,
391 QString::fromStdString(globals->get_fg_home().utf8Str()));
393 // reset numeric / collation locales as described at:
394 // http://doc.qt.io/qt-5/qcoreapplication.html#details
395 ::setlocale(LC_NUMERIC, "C");
396 ::setlocale(LC_COLLATE, "C");
398 Qt::KeyboardModifiers mods = app->queryKeyboardModifiers();
399 if (mods & (Qt::AltModifier | Qt::ShiftModifier)) {
400 qWarning() << "Alt/shift pressed during launch";
402 settings.setValue("fg-root", "!ask");
407 void loadNaturalEarthFile(const std::string& aFileName,
408 flightgear::PolyLine::Type aType,
411 SGPath path(globals->get_fg_root());
412 path.append( "Geodata" );
413 path.append(aFileName);
415 return; // silently fail for now
417 flightgear::PolyLineList lines;
418 flightgear::SHPParser::parsePolyLines(path, aType, lines, areClosed);
419 flightgear::PolyLine::bulkAddToSpatialIndex(lines);
422 void loadNaturalEarthData()
427 loadNaturalEarthFile("ne_10m_coastline.shp", flightgear::PolyLine::COASTLINE, false);
428 loadNaturalEarthFile("ne_10m_rivers_lake_centerlines.shp", flightgear::PolyLine::RIVER, false);
429 loadNaturalEarthFile("ne_10m_lakes.shp", flightgear::PolyLine::LAKE, true);
431 qDebug() << "load basic data took" << st.elapsedMSec();
435 loadNaturalEarthFile("ne_10m_urban_areas.shp", flightgear::PolyLine::URBAN, true);
437 qDebug() << "loading urban areas took:" << st.elapsedMSec();
440 bool runLauncherDialog()
442 // startup the nav-cache now. This pre-empts normal startup of
443 // the cache, but no harm done. (Providing scenery paths are consistent)
448 QString downloadDir = settings.value("download-dir").toString();
449 if (!downloadDir.isEmpty()) {
450 flightgear::Options::sharedInstance()->setOption("download-dir", downloadDir.toStdString());
455 // startup the HTTP system now since packages needs it
456 FGHTTPClient* http = globals->add_new_subsystem<FGHTTPClient>();
458 // we guard against re-init in the global phase; bind and postinit
459 // will happen as normal
462 loadNaturalEarthData();
464 // avoid double Apple menu and other weirdness if both Qt and OSG
465 // try to initialise various Cocoa structures.
466 flightgear::WindowBuilder::setPoseAsStandaloneApp(false);
471 int appResult = qApp->exec();
473 return false; // quit
476 // don't set scenery paths twice
477 globals->clear_fg_scenery();
482 bool runInAppLauncherDialog()
487 if (dlg.result() != QDialog::Accepted) {
494 } // of namespace flightgear
496 QtLauncher::QtLauncher() :
499 m_subsystemIdleTimer(NULL),
501 m_doRestoreMPServer(false)
503 m_ui.reset(new Ui::Launcher);
506 #if QT_VERSION >= 0x050300
507 // don't require Qt 5.3
508 m_ui->commandLineArgs->setPlaceholderText("--option=value --prop:/sim/name=value");
511 #if QT_VERSION >= 0x050200
512 m_ui->aircraftFilter->setClearButtonEnabled(true);
515 for (int i=0; i<4; ++i) {
516 m_ratingFilters[i] = 3;
519 m_subsystemIdleTimer = new QTimer(this);
520 m_subsystemIdleTimer->setInterval(0);
521 connect(m_subsystemIdleTimer, &QTimer::timeout,
522 this, &QtLauncher::onSubsytemIdleTimeout);
523 m_subsystemIdleTimer->start();
525 // create and configure the proxy model
526 m_aircraftProxy = new AircraftProxyModel(this);
527 connect(m_ui->ratingsFilterCheck, &QAbstractButton::toggled,
528 m_aircraftProxy, &AircraftProxyModel::setRatingFilterEnabled);
529 connect(m_ui->ratingsFilterCheck, &QAbstractButton::toggled,
530 this, &QtLauncher::maybeRestoreAircraftSelection);
532 connect(m_ui->onlyShowInstalledCheck, &QAbstractButton::toggled,
533 m_aircraftProxy, &AircraftProxyModel::setInstalledFilterEnabled);
534 connect(m_ui->aircraftFilter, &QLineEdit::textChanged,
535 m_aircraftProxy, &QSortFilterProxyModel::setFilterFixedString);
537 connect(m_ui->runButton, SIGNAL(clicked()), this, SLOT(onRun()));
538 connect(m_ui->quitButton, SIGNAL(clicked()), this, SLOT(onQuit()));
540 connect(m_ui->aircraftHistory, &QPushButton::clicked,
541 this, &QtLauncher::onPopupAircraftHistory);
543 connect(m_ui->location, &LocationWidget::descriptionChanged,
544 m_ui->locationDescription, &QLabel::setText);
546 QAction* qa = new QAction(this);
547 qa->setShortcut(QKeySequence("Ctrl+Q"));
548 connect(qa, &QAction::triggered, this, &QtLauncher::onQuit);
551 connect(m_ui->editRatingFilter, &QPushButton::clicked,
552 this, &QtLauncher::onEditRatingsFilter);
553 connect(m_ui->onlyShowInstalledCheck, &QCheckBox::toggled,
554 this, &QtLauncher::onShowInstalledAircraftToggled);
556 QIcon historyIcon(":/history-icon");
557 m_ui->aircraftHistory->setIcon(historyIcon);
559 connect(m_ui->timeOfDayCombo, SIGNAL(currentIndexChanged(int)),
560 this, SLOT(updateSettingsSummary()));
561 connect(m_ui->seasonCombo, SIGNAL(currentIndexChanged(int)),
562 this, SLOT(updateSettingsSummary()));
563 connect(m_ui->fetchRealWxrCheckbox, SIGNAL(toggled(bool)),
564 this, SLOT(updateSettingsSummary()));
565 connect(m_ui->rembrandtCheckbox, SIGNAL(toggled(bool)),
566 this, SLOT(updateSettingsSummary()));
567 connect(m_ui->terrasyncCheck, SIGNAL(toggled(bool)),
568 this, SLOT(updateSettingsSummary()));
569 connect(m_ui->startPausedCheck, SIGNAL(toggled(bool)),
570 this, SLOT(updateSettingsSummary()));
571 connect(m_ui->msaaCheckbox, SIGNAL(toggled(bool)),
572 this, SLOT(updateSettingsSummary()));
574 connect(m_ui->rembrandtCheckbox, SIGNAL(toggled(bool)),
575 this, SLOT(onRembrandtToggled(bool)));
576 connect(m_ui->terrasyncCheck, &QCheckBox::toggled,
577 this, &QtLauncher::onToggleTerrasync);
578 updateSettingsSummary();
580 m_aircraftModel = new AircraftItemModel(this);
581 m_aircraftProxy->setSourceModel(m_aircraftModel);
583 m_aircraftProxy->setFilterCaseSensitivity(Qt::CaseInsensitive);
584 m_aircraftProxy->setSortCaseSensitivity(Qt::CaseInsensitive);
585 m_aircraftProxy->setSortRole(Qt::DisplayRole);
586 m_aircraftProxy->setDynamicSortFilter(true);
588 m_ui->aircraftList->setModel(m_aircraftProxy);
589 m_ui->aircraftList->setHorizontalScrollBarPolicy(Qt::ScrollBarAlwaysOff);
590 AircraftItemDelegate* delegate = new AircraftItemDelegate(m_ui->aircraftList);
591 m_ui->aircraftList->setItemDelegate(delegate);
592 m_ui->aircraftList->setSelectionMode(QAbstractItemView::SingleSelection);
593 connect(m_ui->aircraftList, &QListView::clicked,
594 this, &QtLauncher::onAircraftSelected);
595 connect(delegate, &AircraftItemDelegate::variantChanged,
596 this, &QtLauncher::onAircraftSelected);
597 connect(delegate, &AircraftItemDelegate::requestInstall,
598 this, &QtLauncher::onRequestPackageInstall);
599 connect(delegate, &AircraftItemDelegate::cancelDownload,
600 this, &QtLauncher::onCancelDownload);
602 connect(m_aircraftModel, &AircraftItemModel::aircraftInstallCompleted,
603 this, &QtLauncher::onAircraftInstalledCompleted);
604 connect(m_aircraftModel, &AircraftItemModel::aircraftInstallFailed,
605 this, &QtLauncher::onAircraftInstallFailed);
606 connect(m_aircraftModel, &AircraftItemModel::scanCompleted,
607 this, &QtLauncher::updateSelectedAircraft);
608 connect(m_ui->restoreDefaultsButton, &QPushButton::clicked,
609 this, &QtLauncher::onRestoreDefaults);
612 AddOnsPage* addOnsPage = new AddOnsPage(NULL, globals->packageRoot());
613 connect(addOnsPage, &AddOnsPage::downloadDirChanged,
614 this, &QtLauncher::onDownloadDirChanged);
615 connect(addOnsPage, &AddOnsPage::sceneryPathsChanged,
616 this, &QtLauncher::setSceneryPaths);
618 m_ui->tabWidget->addTab(addOnsPage, tr("Add-ons"));
619 // after any kind of reset, try to restore selection and scroll
620 // to match the m_selectedAircraft. This needs to be delayed
621 // fractionally otherwise the scrollTo seems to be ignored,
623 connect(m_aircraftProxy, &AircraftProxyModel::modelReset,
624 this, &QtLauncher::delayedAircraftModelReset);
627 m_aircraftModel->setPaths(settings.value("aircraft-paths").toStringList());
628 m_aircraftModel->setPackageRoot(globals->packageRoot());
629 m_aircraftModel->scanDirs();
631 checkOfficialCatalogMessage();
634 onRefreshMPServers();
637 QtLauncher::~QtLauncher()
642 void QtLauncher::setSceneryPaths()
644 globals->clear_fg_scenery();
646 // mimic what optionss.cxx does, so we can find airport data for parking
649 // append explicit scenery paths
650 Q_FOREACH(QString path, settings.value("scenery-paths").toStringList()) {
651 globals->append_fg_scenery(path.toStdString());
654 // append the TerraSync path
655 QString downloadDir = settings.value("download-dir").toString();
656 if (downloadDir.isEmpty()) {
657 downloadDir = QString::fromStdString(flightgear::defaultDownloadDir().utf8Str());
660 SGPath terraSyncDir(downloadDir.toStdString());
661 terraSyncDir.append("TerraSync");
662 if (terraSyncDir.exists()) {
663 globals->append_fg_scenery(terraSyncDir);
668 void QtLauncher::setInAppMode()
671 m_ui->tabWidget->removeTab(2);
672 m_ui->tabWidget->removeTab(2);
674 m_ui->runButton->setText(tr("Apply"));
675 m_ui->quitButton->setText(tr("Cancel"));
677 disconnect(m_ui->runButton, SIGNAL(clicked()), this, SLOT(onRun()));
678 connect(m_ui->runButton, SIGNAL(clicked()), this, SLOT(onApply()));
681 void QtLauncher::restoreSettings()
684 m_ui->rembrandtCheckbox->setChecked(settings.value("enable-rembrandt", false).toBool());
685 m_ui->terrasyncCheck->setChecked(settings.value("enable-terrasync", true).toBool());
686 m_ui->fullScreenCheckbox->setChecked(settings.value("start-fullscreen", false).toBool());
687 m_ui->msaaCheckbox->setChecked(settings.value("enable-msaa", false).toBool());
688 m_ui->fetchRealWxrCheckbox->setChecked(settings.value("enable-realwx", true).toBool());
689 m_ui->startPausedCheck->setChecked(settings.value("start-paused", false).toBool());
690 m_ui->timeOfDayCombo->setCurrentIndex(settings.value("timeofday", 0).toInt());
691 m_ui->seasonCombo->setCurrentIndex(settings.value("season", 0).toInt());
693 // full paths to -set.xml files
694 m_recentAircraft = QUrl::fromStringList(settings.value("recent-aircraft").toStringList());
696 if (!m_recentAircraft.empty()) {
697 m_selectedAircraft = m_recentAircraft.front();
699 // select the default C172p
706 m_ui->location->restoreSettings();
709 m_ui->onlyShowInstalledCheck->setChecked(settings.value("only-show-installed", false).toBool());
710 if (m_ui->onlyShowInstalledCheck->isChecked()) {
711 m_ui->ratingsFilterCheck->setEnabled(false);
714 m_ui->ratingsFilterCheck->setChecked(settings.value("ratings-filter", true).toBool());
716 Q_FOREACH(QVariant v, settings.value("min-ratings").toList()) {
717 m_ratingFilters[index++] = v.toInt();
720 m_aircraftProxy->setRatingFilterEnabled(m_ui->ratingsFilterCheck->isChecked());
721 m_aircraftProxy->setRatings(m_ratingFilters);
723 updateSelectedAircraft();
724 maybeRestoreAircraftSelection();
726 m_ui->commandLineArgs->setPlainText(settings.value("additional-args").toString());
728 m_ui->mpCallsign->setText(settings.value("mp-callsign").toString());
729 // don't restore MP server here, we do it after a refresh
730 m_doRestoreMPServer = true;
733 void QtLauncher::delayedAircraftModelReset()
735 QTimer::singleShot(1, this, SLOT(maybeRestoreAircraftSelection()));
738 void QtLauncher::maybeRestoreAircraftSelection()
740 QModelIndex aircraftIndex = m_aircraftModel->indexOfAircraftURI(m_selectedAircraft);
741 QModelIndex proxyIndex = m_aircraftProxy->mapFromSource(aircraftIndex);
742 if (proxyIndex.isValid()) {
743 m_ui->aircraftList->selectionModel()->setCurrentIndex(proxyIndex,
744 QItemSelectionModel::ClearAndSelect);
745 m_ui->aircraftList->selectionModel()->select(proxyIndex,
746 QItemSelectionModel::ClearAndSelect);
747 m_ui->aircraftList->scrollTo(proxyIndex);
751 void QtLauncher::saveSettings()
754 settings.setValue("enable-rembrandt", m_ui->rembrandtCheckbox->isChecked());
755 settings.setValue("enable-terrasync", m_ui->terrasyncCheck->isChecked());
756 settings.setValue("enable-msaa", m_ui->msaaCheckbox->isChecked());
757 settings.setValue("start-fullscreen", m_ui->fullScreenCheckbox->isChecked());
758 settings.setValue("enable-realwx", m_ui->fetchRealWxrCheckbox->isChecked());
759 settings.setValue("start-paused", m_ui->startPausedCheck->isChecked());
760 settings.setValue("ratings-filter", m_ui->ratingsFilterCheck->isChecked());
761 settings.setValue("only-show-installed", m_ui->onlyShowInstalledCheck->isChecked());
762 settings.setValue("recent-aircraft", QUrl::toStringList(m_recentAircraft));
764 settings.setValue("timeofday", m_ui->timeOfDayCombo->currentIndex());
765 settings.setValue("season", m_ui->seasonCombo->currentIndex());
766 settings.setValue("additional-args", m_ui->commandLineArgs->toPlainText());
768 m_ui->location->saveSettings();
770 settings.setValue("mp-callsign", m_ui->mpCallsign->text());
771 settings.setValue("mp-server", m_ui->mpServerCombo->currentData());
774 void QtLauncher::setEnableDisableOptionFromCheckbox(QCheckBox* cbox, QString name) const
776 flightgear::Options* opt = flightgear::Options::sharedInstance();
777 std::string stdName(name.toStdString());
778 if (cbox->isChecked()) {
779 opt->addOption("enable-" + stdName, "");
781 opt->addOption("disable-" + stdName, "");
785 void QtLauncher::closeEvent(QCloseEvent *event)
790 void QtLauncher::reject()
795 void QtLauncher::onRun()
797 flightgear::Options* opt = flightgear::Options::sharedInstance();
798 setEnableDisableOptionFromCheckbox(m_ui->terrasyncCheck, "terrasync");
799 setEnableDisableOptionFromCheckbox(m_ui->fetchRealWxrCheckbox, "real-weather-fetch");
800 setEnableDisableOptionFromCheckbox(m_ui->rembrandtCheckbox, "rembrandt");
801 setEnableDisableOptionFromCheckbox(m_ui->fullScreenCheckbox, "fullscreen");
802 // setEnableDisableOptionFromCheckbox(m_ui->startPausedCheck, "freeze");
804 bool startPaused = m_ui->startPausedCheck->isChecked() ||
805 m_ui->location->shouldStartPaused();
807 opt->addOption("enable-freeze", "");
810 // MSAA is more complex
811 if (!m_ui->rembrandtCheckbox->isChecked()) {
812 if (m_ui->msaaCheckbox->isChecked()) {
813 globals->get_props()->setIntValue("/sim/rendering/multi-sample-buffers", 1);
814 globals->get_props()->setIntValue("/sim/rendering/multi-samples", 4);
816 globals->get_props()->setIntValue("/sim/rendering/multi-sample-buffers", 0);
821 if (!m_selectedAircraft.isEmpty()) {
822 if (m_selectedAircraft.isLocalFile()) {
823 QFileInfo setFileInfo(m_selectedAircraft.toLocalFile());
824 opt->addOption("aircraft-dir", setFileInfo.dir().absolutePath().toStdString());
825 QString setFile = setFileInfo.fileName();
826 Q_ASSERT(setFile.endsWith("-set.xml"));
827 setFile.truncate(setFile.count() - 8); // drop the '-set.xml' portion
828 opt->addOption("aircraft", setFile.toStdString());
829 } else if (m_selectedAircraft.scheme() == "package") {
830 QString qualifiedId = m_selectedAircraft.path();
831 // no need to set aircraft-dir, handled by the corresponding code
833 opt->addOption("aircraft", qualifiedId.toStdString());
835 qWarning() << "unsupported aircraft launch URL" << m_selectedAircraft;
838 // manage aircraft history
839 if (m_recentAircraft.contains(m_selectedAircraft))
840 m_recentAircraft.removeOne(m_selectedAircraft);
841 m_recentAircraft.prepend(m_selectedAircraft);
842 if (m_recentAircraft.size() > MAX_RECENT_AIRCRAFT)
843 m_recentAircraft.pop_back();
846 if (m_ui->mpBox->isChecked()) {
847 opt->addOption("callsign", m_ui->mpCallsign->text().toStdString());
848 QString host = m_ui->mpServerCombo->currentData().toString();
849 globals->get_props()->setStringValue("/sim/multiplay/txhost", host.toStdString());
850 int port = findMPServerPort(host.toStdString());
851 globals->get_props()->setIntValue("/sim/multiplay/txport", port);
854 m_ui->location->setLocationOptions();
857 if (m_ui->timeOfDayCombo->currentIndex() != 0) {
858 QString dayval = m_ui->timeOfDayCombo->currentText().toLower();
859 opt->addOption("timeofday", dayval.toStdString());
862 if (m_ui->seasonCombo->currentIndex() != 0) {
863 QString seasonName = m_ui->seasonCombo->currentText().toLower();
864 opt->addOption("season", seasonName.toStdString());
868 QString downloadDir = settings.value("download-dir").toString();
869 if (!downloadDir.isEmpty()) {
872 int result = QMessageBox::question(this, tr("Create download folder?"),
873 tr("The selected location for downloads does not exist. Create it?"),
874 QMessageBox::Yes | QMessageBox::No | QMessageBox::Cancel);
875 if (result == QMessageBox::Cancel) {
879 if (result == QMessageBox::Yes) {
880 d.mkpath(downloadDir);
884 opt->addOption("download-dir", downloadDir.toStdString());
888 Q_FOREACH(QString path, settings.value("scenery-paths").toStringList()) {
889 opt->addOption("fg-scenery", path.toStdString());
893 Q_FOREACH(QString path, settings.value("aircraft-paths").toStringList()) {
894 // can't use fg-aircraft for this, as it is processed before the launcher is run
895 globals->append_aircraft_path(path.toStdString());
898 // additional arguments
899 ArgumentsTokenizer tk;
900 Q_FOREACH(ArgumentsTokenizer::Arg a, tk.tokenize(m_ui->commandLineArgs->toPlainText())) {
901 if (a.arg.startsWith("prop:")) {
902 QString v = a.arg.mid(5) + "=" + a.value;
903 opt->addOption("prop", v.toStdString());
905 opt->addOption(a.arg.toStdString(), a.value.toStdString());
909 if (settings.contains("restore-defaults-on-run")) {
910 settings.remove("restore-defaults-on-run");
911 opt->addOption("restore-defaults", "");
920 void QtLauncher::onApply()
925 if (!m_selectedAircraft.isEmpty()) {
926 std::string aircraftPropValue,
929 if (m_selectedAircraft.isLocalFile()) {
930 QFileInfo setFileInfo(m_selectedAircraft.toLocalFile());
931 QString setFile = setFileInfo.fileName();
932 Q_ASSERT(setFile.endsWith("-set.xml"));
933 setFile.truncate(setFile.count() - 8); // drop the '-set.xml' portion
934 aircraftDir = setFileInfo.dir().absolutePath().toStdString();
935 aircraftPropValue = setFile.toStdString();
936 } else if (m_selectedAircraft.scheme() == "package") {
937 // no need to set aircraft-dir, handled by the corresponding code
939 aircraftPropValue = m_selectedAircraft.path().toStdString();
941 qWarning() << "unsupported aircraft launch URL" << m_selectedAircraft;
944 // manage aircraft history
945 if (m_recentAircraft.contains(m_selectedAircraft))
946 m_recentAircraft.removeOne(m_selectedAircraft);
947 m_recentAircraft.prepend(m_selectedAircraft);
948 if (m_recentAircraft.size() > MAX_RECENT_AIRCRAFT)
949 m_recentAircraft.pop_back();
951 globals->get_props()->setStringValue("/sim/aircraft", aircraftPropValue);
952 globals->get_props()->setStringValue("/sim/aircraft-dir", aircraftDir);
959 void QtLauncher::onQuit()
964 void QtLauncher::onToggleTerrasync(bool enabled)
968 QString downloadDir = settings.value("download-dir").toString();
969 if (downloadDir.isEmpty()) {
970 downloadDir = QString::fromStdString(flightgear::defaultDownloadDir().utf8Str());
973 QFileInfo info(downloadDir);
974 if (!info.exists()) {
976 msg.setWindowTitle(tr("Create download folder?"));
977 msg.setText(tr("The download folder '%1' does not exist, create it now?").arg(downloadDir));
978 msg.addButton(QMessageBox::Yes);
979 msg.addButton(QMessageBox::Cancel);
980 int result = msg.exec();
982 if (result == QMessageBox::Cancel) {
983 m_ui->terrasyncCheck->setChecked(false);
988 d.mkpath(downloadDir);
993 void QtLauncher::onAircraftInstalledCompleted(QModelIndex index)
995 maybeUpdateSelectedAircraft(index);
998 void QtLauncher::onRatingsFilterToggled()
1000 QModelIndex aircraftIndex = m_aircraftModel->indexOfAircraftURI(m_selectedAircraft);
1001 QModelIndex proxyIndex = m_aircraftProxy->mapFromSource(aircraftIndex);
1002 if (proxyIndex.isValid()) {
1003 m_ui->aircraftList->scrollTo(proxyIndex);
1007 void QtLauncher::onAircraftInstallFailed(QModelIndex index, QString errorMessage)
1009 qWarning() << Q_FUNC_INFO << index.data(AircraftURIRole) << errorMessage;
1012 msg.setWindowTitle(tr("Aircraft installation failed"));
1013 msg.setText(tr("An error occurred installing the aircraft %1: %2").
1014 arg(index.data(Qt::DisplayRole).toString()).arg(errorMessage));
1015 msg.addButton(QMessageBox::Ok);
1018 maybeUpdateSelectedAircraft(index);
1021 void QtLauncher::onAircraftSelected(const QModelIndex& index)
1023 m_selectedAircraft = index.data(AircraftURIRole).toUrl();
1024 updateSelectedAircraft();
1027 void QtLauncher::onRequestPackageInstall(const QModelIndex& index)
1029 // also select, otherwise UI is confusing
1030 m_selectedAircraft = index.data(AircraftURIRole).toUrl();
1031 updateSelectedAircraft();
1033 QString pkg = index.data(AircraftPackageIdRole).toString();
1034 simgear::pkg::PackageRef pref = globals->packageRoot()->getPackageById(pkg.toStdString());
1035 if (pref->isInstalled()) {
1036 InstallRef install = pref->existingInstall();
1037 if (install && install->hasUpdate()) {
1038 globals->packageRoot()->scheduleToUpdate(install);
1045 void QtLauncher::onCancelDownload(const QModelIndex& index)
1047 QString pkg = index.data(AircraftPackageIdRole).toString();
1048 simgear::pkg::PackageRef pref = globals->packageRoot()->getPackageById(pkg.toStdString());
1049 simgear::pkg::InstallRef i = pref->existingInstall();
1050 i->cancelDownload();
1053 void QtLauncher::onRestoreDefaults()
1055 QMessageBox mbox(this);
1056 mbox.setText(tr("Restore all settings to defaults?"));
1057 mbox.setInformativeText(tr("Restoring settings to their defaults may affect available add-ons such as scenery or aircraft."));
1058 QPushButton* quitButton = mbox.addButton(tr("Restore and restart now"), QMessageBox::YesRole);
1059 mbox.addButton(QMessageBox::Cancel);
1060 mbox.setDefaultButton(QMessageBox::Cancel);
1061 mbox.setIconPixmap(QPixmap(":/app-icon-large"));
1064 if (mbox.clickedButton() != quitButton) {
1071 settings.setValue("restore-defaults-on-run", true);
1074 restartTheApp(QStringList());
1077 void QtLauncher::maybeUpdateSelectedAircraft(QModelIndex index)
1079 QUrl u = index.data(AircraftURIRole).toUrl();
1080 if (u == m_selectedAircraft) {
1081 // potentially enable the run button now!
1082 updateSelectedAircraft();
1086 void QtLauncher::updateSelectedAircraft()
1088 QModelIndex index = m_aircraftModel->indexOfAircraftURI(m_selectedAircraft);
1089 if (index.isValid()) {
1090 QPixmap pm = index.data(Qt::DecorationRole).value<QPixmap>();
1091 m_ui->thumbnail->setPixmap(pm);
1092 m_ui->aircraftDescription->setText(index.data(Qt::DisplayRole).toString());
1094 int status = index.data(AircraftPackageStatusRole).toInt();
1095 bool canRun = (status == PackageInstalled);
1096 m_ui->runButton->setEnabled(canRun);
1098 LauncherAircraftType aircraftType = Airplane;
1099 if (index.data(AircraftIsHelicopterRole).toBool()) {
1100 aircraftType = Helicopter;
1101 } else if (index.data(AircraftIsSeaplaneRole).toBool()) {
1102 aircraftType = Seaplane;
1105 m_ui->location->setAircraftType(aircraftType);
1107 m_ui->thumbnail->setPixmap(QPixmap());
1108 m_ui->aircraftDescription->setText("");
1109 m_ui->runButton->setEnabled(false);
1113 QModelIndex QtLauncher::proxyIndexForAircraftURI(QUrl uri) const
1115 return m_aircraftProxy->mapFromSource(sourceIndexForAircraftURI(uri));
1118 QModelIndex QtLauncher::sourceIndexForAircraftURI(QUrl uri) const
1120 AircraftItemModel* sourceModel = qobject_cast<AircraftItemModel*>(m_aircraftProxy->sourceModel());
1121 Q_ASSERT(sourceModel);
1122 return sourceModel->indexOfAircraftURI(uri);
1125 void QtLauncher::onPopupAircraftHistory()
1127 if (m_recentAircraft.isEmpty()) {
1132 Q_FOREACH(QUrl uri, m_recentAircraft) {
1133 QModelIndex index = sourceIndexForAircraftURI(uri);
1134 if (!index.isValid()) {
1138 QAction* act = m.addAction(index.data(Qt::DisplayRole).toString());
1142 QPoint popupPos = m_ui->aircraftHistory->mapToGlobal(m_ui->aircraftHistory->rect().bottomLeft());
1143 QAction* triggered = m.exec(popupPos);
1145 m_selectedAircraft = triggered->data().toUrl();
1146 QModelIndex index = proxyIndexForAircraftURI(m_selectedAircraft);
1147 m_ui->aircraftList->selectionModel()->setCurrentIndex(index,
1148 QItemSelectionModel::ClearAndSelect);
1149 m_ui->aircraftFilter->clear();
1150 updateSelectedAircraft();
1154 void QtLauncher::onEditRatingsFilter()
1156 EditRatingsFilterDialog dialog(this);
1157 dialog.setRatings(m_ratingFilters);
1160 if (dialog.result() == QDialog::Accepted) {
1162 for (int i=0; i<4; ++i) {
1163 m_ratingFilters[i] = dialog.getRating(i);
1164 vl.append(m_ratingFilters[i]);
1166 m_aircraftProxy->setRatings(m_ratingFilters);
1169 settings.setValue("min-ratings", vl);
1173 void QtLauncher::updateSettingsSummary()
1175 QStringList summary;
1176 if (m_ui->timeOfDayCombo->currentIndex() > 0) {
1177 summary.append(QString(m_ui->timeOfDayCombo->currentText().toLower()));
1180 if (m_ui->seasonCombo->currentIndex() > 0) {
1181 summary.append(QString(m_ui->seasonCombo->currentText().toLower()));
1184 if (m_ui->rembrandtCheckbox->isChecked()) {
1185 summary.append("Rembrandt enabled");
1186 } else if (m_ui->msaaCheckbox->isChecked()) {
1187 summary.append("anti-aliasing");
1190 if (m_ui->fetchRealWxrCheckbox->isChecked()) {
1191 summary.append("live weather");
1194 if (m_ui->terrasyncCheck->isChecked()) {
1195 summary.append("automatic scenery downloads");
1198 if (m_ui->startPausedCheck->isChecked()) {
1199 summary.append("paused");
1202 QString s = summary.join(", ");
1203 s[0] = s[0].toUpper();
1204 m_ui->settingsDescription->setText(s);
1207 void QtLauncher::onRembrandtToggled(bool b)
1209 // Rembrandt and multi-sample are exclusive
1210 m_ui->msaaCheckbox->setEnabled(!b);
1213 void QtLauncher::onShowInstalledAircraftToggled(bool b)
1215 m_ui->ratingsFilterCheck->setEnabled(!b);
1216 maybeRestoreAircraftSelection();
1219 void QtLauncher::onSubsytemIdleTimeout()
1221 globals->get_subsystem_mgr()->update(0.0);
1224 void QtLauncher::onDownloadDirChanged()
1227 // replace existing package root
1228 globals->get_subsystem<FGHTTPClient>()->shutdown();
1229 globals->setPackageRoot(simgear::pkg::RootRef());
1231 // create new root with updated download-dir value
1232 fgInitPackageRoot();
1234 globals->get_subsystem<FGHTTPClient>()->init();
1237 // re-scan the aircraft list
1238 m_aircraftModel->setPackageRoot(globals->packageRoot());
1239 m_aircraftModel->setPaths(settings.value("aircraft-paths").toStringList());
1240 m_aircraftModel->scanDirs();
1242 checkOfficialCatalogMessage();
1244 // re-set scenery dirs
1248 void QtLauncher::checkOfficialCatalogMessage()
1251 bool showOfficialCatalogMesssage = !globals->get_subsystem<FGHTTPClient>()->isDefaultCatalogInstalled();
1252 if (settings.value("hide-official-catalog-message").toBool()) {
1253 showOfficialCatalogMesssage = false;
1256 m_aircraftModel->setOfficialHangarMessageVisible(showOfficialCatalogMesssage);
1257 if (showOfficialCatalogMesssage) {
1258 NoOfficialHangarMessage* messageWidget = new NoOfficialHangarMessage;
1259 connect(messageWidget, &NoOfficialHangarMessage::linkActivated,
1260 this, &QtLauncher::onOfficialCatalogMessageLink);
1262 QModelIndex index = m_aircraftProxy->mapFromSource(m_aircraftModel->officialHangarMessageIndex());
1263 m_ui->aircraftList->setIndexWidget(index, messageWidget);
1267 void QtLauncher::onOfficialCatalogMessageLink(QUrl link)
1269 QString s = link.toString();
1270 if (s == "action:hide") {
1272 settings.setValue("hide-official-catalog-message", true);
1273 } else if (s == "action:add-official") {
1274 AddOnsPage::addDefaultCatalog(this);
1277 checkOfficialCatalogMessage();
1280 void QtLauncher::onRefreshMPServers()
1282 if (m_mpServerRequest.get()) {
1283 return; // in-progress
1286 string url(fgGetString("/sim/multiplay/serverlist-url",
1287 "http://liveries.flightgear.org/mpstatus/mpservers.xml"));
1290 SG_LOG(SG_IO, SG_ALERT, "do_multiplayer.refreshserverlist: no URL given");
1294 SGPropertyNode *targetnode = fgGetNode("/sim/multiplay/server-list", true);
1295 m_mpServerRequest.reset(new RemoteXMLRequest(url, targetnode));
1296 m_mpServerRequest->done(this, &QtLauncher::onRefreshMPServersDone);
1297 m_mpServerRequest->fail(this, &QtLauncher::onRefreshMPServersFailed);
1298 globals->get_subsystem<FGHTTPClient>()->makeRequest(m_mpServerRequest);
1301 void QtLauncher::onRefreshMPServersDone(simgear::HTTP::Request*)
1303 // parse the properties
1304 SGPropertyNode *targetnode = fgGetNode("/sim/multiplay/server-list", true);
1307 m_ui->mpServerCombo->clear();
1309 for (int i=0; i<targetnode->nChildren(); ++i) {
1310 SGPropertyNode* c = targetnode->getChild(i);
1311 if (c->getName() != std::string("server")) {
1315 QString name = QString::fromStdString(c->getStringValue("name"));
1316 QString loc = QString::fromStdString(c->getStringValue("location"));
1317 QString host = QString::fromStdString(c->getStringValue("hostname"));
1318 m_ui->mpServerCombo->addItem(tr("%1 - %2").arg(name,loc), host);
1321 if (m_doRestoreMPServer) {
1323 int index = m_ui->mpServerCombo->findData(settings.value("mp-server"));
1325 m_ui->mpServerCombo->setCurrentIndex(index);
1329 m_mpServerRequest.clear();
1332 void QtLauncher::onRefreshMPServersFailed(simgear::HTTP::Request*)
1334 qWarning() << "refreshing MP servers failed:" << QString::fromStdString(m_mpServerRequest->responseReason());
1335 m_mpServerRequest.clear();
1338 void QtLauncher::onMPServerEdited(QString text)
1340 // parse as server hostname + optional URL
1343 int QtLauncher::findMPServerPort(const std::string& host)
1345 SGPropertyNode *targetnode = fgGetNode("/sim/multiplay/server-list", true);
1346 for (int i=0; i<targetnode->nChildren(); ++i) {
1347 SGPropertyNode* c = targetnode->getChild(i);
1348 if (c->getName() != std::string("server")) {
1352 if (c->getStringValue("hostname") == host) {
1353 return c->getIntValue("port");
1360 simgear::pkg::PackageRef QtLauncher::packageForAircraftURI(QUrl uri) const
1362 if (uri.scheme() != "package") {
1363 qWarning() << "invalid URL scheme:" << uri;
1364 return simgear::pkg::PackageRef();
1367 QString ident = uri.path();
1368 return globals->packageRoot()->getPackageById(ident.toStdString());
1371 void QtLauncher::restartTheApp(QStringList fgArgs)
1373 // Spawn a new instance of myApplication:
1377 #if defined(Q_OS_MAC)
1378 QDir dir(qApp->applicationDirPath()); // returns the 'MacOS' dir
1379 dir.cdUp(); // up to 'contents' dir
1380 dir.cdUp(); // up to .app dir
1381 // see 'man open' for details, but '-n' ensures we launch a new instance,
1382 // and we want to pass remaining arguments to us, not open.
1383 args << "-n" << dir.absolutePath() << "--args" << "--launcher" << fgArgs;
1384 qDebug() << "args" << args;
1385 proc.startDetached("open", args);
1387 args << "--launcher" << fgArgs;
1388 proc.startDetached(qApp->applicationFilePath(), args);
1393 #include "QtLauncher.moc"