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 QSettings::setDefaultFormat(QSettings::IniFormat);
383 QSettings::setPath(QSettings::IniFormat, QSettings::UserScope,
384 QString::fromStdString(globals->get_fg_home()));
386 QApplication* app = new QApplication(s_argc, argv);
387 app->setOrganizationName("FlightGear");
388 app->setApplicationName("FlightGear");
389 app->setOrganizationDomain("flightgear.org");
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.str());
663 void QtLauncher::setInAppMode()
666 m_ui->tabWidget->removeTab(2);
667 m_ui->runButton->setText(tr("Apply"));
668 m_ui->quitButton->setText(tr("Cancel"));
670 disconnect(m_ui->runButton, SIGNAL(clicked()), this, SLOT(onRun()));
671 connect(m_ui->runButton, SIGNAL(clicked()), this, SLOT(onApply()));
674 void QtLauncher::restoreSettings()
677 m_ui->rembrandtCheckbox->setChecked(settings.value("enable-rembrandt", false).toBool());
678 m_ui->terrasyncCheck->setChecked(settings.value("enable-terrasync", true).toBool());
679 m_ui->fullScreenCheckbox->setChecked(settings.value("start-fullscreen", false).toBool());
680 m_ui->msaaCheckbox->setChecked(settings.value("enable-msaa", false).toBool());
681 m_ui->fetchRealWxrCheckbox->setChecked(settings.value("enable-realwx", true).toBool());
682 m_ui->startPausedCheck->setChecked(settings.value("start-paused", false).toBool());
683 m_ui->timeOfDayCombo->setCurrentIndex(settings.value("timeofday", 0).toInt());
684 m_ui->seasonCombo->setCurrentIndex(settings.value("season", 0).toInt());
686 // full paths to -set.xml files
687 m_recentAircraft = QUrl::fromStringList(settings.value("recent-aircraft").toStringList());
689 if (!m_recentAircraft.empty()) {
690 m_selectedAircraft = m_recentAircraft.front();
692 // select the default C172p
699 m_ui->location->restoreSettings();
702 m_ui->onlyShowInstalledCheck->setChecked(settings.value("only-show-installed", false).toBool());
703 if (m_ui->onlyShowInstalledCheck->isChecked()) {
704 m_ui->ratingsFilterCheck->setEnabled(false);
707 m_ui->ratingsFilterCheck->setChecked(settings.value("ratings-filter", true).toBool());
709 Q_FOREACH(QVariant v, settings.value("min-ratings").toList()) {
710 m_ratingFilters[index++] = v.toInt();
713 m_aircraftProxy->setRatingFilterEnabled(m_ui->ratingsFilterCheck->isChecked());
714 m_aircraftProxy->setRatings(m_ratingFilters);
716 updateSelectedAircraft();
717 maybeRestoreAircraftSelection();
719 m_ui->commandLineArgs->setPlainText(settings.value("additional-args").toString());
722 void QtLauncher::delayedAircraftModelReset()
724 QTimer::singleShot(1, this, SLOT(maybeRestoreAircraftSelection()));
727 void QtLauncher::maybeRestoreAircraftSelection()
729 QModelIndex aircraftIndex = m_aircraftModel->indexOfAircraftURI(m_selectedAircraft);
730 QModelIndex proxyIndex = m_aircraftProxy->mapFromSource(aircraftIndex);
731 if (proxyIndex.isValid()) {
732 m_ui->aircraftList->selectionModel()->setCurrentIndex(proxyIndex,
733 QItemSelectionModel::ClearAndSelect);
734 m_ui->aircraftList->selectionModel()->select(proxyIndex,
735 QItemSelectionModel::ClearAndSelect);
736 m_ui->aircraftList->scrollTo(proxyIndex);
740 void QtLauncher::saveSettings()
743 settings.setValue("enable-rembrandt", m_ui->rembrandtCheckbox->isChecked());
744 settings.setValue("enable-terrasync", m_ui->terrasyncCheck->isChecked());
745 settings.setValue("enable-msaa", m_ui->msaaCheckbox->isChecked());
746 settings.setValue("start-fullscreen", m_ui->fullScreenCheckbox->isChecked());
747 settings.setValue("enable-realwx", m_ui->fetchRealWxrCheckbox->isChecked());
748 settings.setValue("start-paused", m_ui->startPausedCheck->isChecked());
749 settings.setValue("ratings-filter", m_ui->ratingsFilterCheck->isChecked());
750 settings.setValue("only-show-installed", m_ui->onlyShowInstalledCheck->isChecked());
751 settings.setValue("recent-aircraft", QUrl::toStringList(m_recentAircraft));
753 settings.setValue("timeofday", m_ui->timeOfDayCombo->currentIndex());
754 settings.setValue("season", m_ui->seasonCombo->currentIndex());
755 settings.setValue("additional-args", m_ui->commandLineArgs->toPlainText());
757 m_ui->location->saveSettings();
760 void QtLauncher::setEnableDisableOptionFromCheckbox(QCheckBox* cbox, QString name) const
762 flightgear::Options* opt = flightgear::Options::sharedInstance();
763 std::string stdName(name.toStdString());
764 if (cbox->isChecked()) {
765 opt->addOption("enable-" + stdName, "");
767 opt->addOption("disable-" + stdName, "");
771 void QtLauncher::closeEvent(QCloseEvent *event)
776 void QtLauncher::reject()
781 void QtLauncher::onRun()
783 flightgear::Options* opt = flightgear::Options::sharedInstance();
784 setEnableDisableOptionFromCheckbox(m_ui->terrasyncCheck, "terrasync");
785 setEnableDisableOptionFromCheckbox(m_ui->fetchRealWxrCheckbox, "real-weather-fetch");
786 setEnableDisableOptionFromCheckbox(m_ui->rembrandtCheckbox, "rembrandt");
787 setEnableDisableOptionFromCheckbox(m_ui->fullScreenCheckbox, "fullscreen");
788 // setEnableDisableOptionFromCheckbox(m_ui->startPausedCheck, "freeze");
790 bool startPaused = m_ui->startPausedCheck->isChecked() ||
791 m_ui->location->shouldStartPaused();
793 opt->addOption("enable-freeze", "");
796 // MSAA is more complex
797 if (!m_ui->rembrandtCheckbox->isChecked()) {
798 if (m_ui->msaaCheckbox->isChecked()) {
799 globals->get_props()->setIntValue("/sim/rendering/multi-sample-buffers", 1);
800 globals->get_props()->setIntValue("/sim/rendering/multi-samples", 4);
802 globals->get_props()->setIntValue("/sim/rendering/multi-sample-buffers", 0);
807 if (!m_selectedAircraft.isEmpty()) {
808 if (m_selectedAircraft.isLocalFile()) {
809 QFileInfo setFileInfo(m_selectedAircraft.toLocalFile());
810 opt->addOption("aircraft-dir", setFileInfo.dir().absolutePath().toStdString());
811 QString setFile = setFileInfo.fileName();
812 Q_ASSERT(setFile.endsWith("-set.xml"));
813 setFile.truncate(setFile.count() - 8); // drop the '-set.xml' portion
814 opt->addOption("aircraft", setFile.toStdString());
815 } else if (m_selectedAircraft.scheme() == "package") {
816 QString qualifiedId = m_selectedAircraft.path();
817 // no need to set aircraft-dir, handled by the corresponding code
819 opt->addOption("aircraft", qualifiedId.toStdString());
821 qWarning() << "unsupported aircraft launch URL" << m_selectedAircraft;
824 // manage aircraft history
825 if (m_recentAircraft.contains(m_selectedAircraft))
826 m_recentAircraft.removeOne(m_selectedAircraft);
827 m_recentAircraft.prepend(m_selectedAircraft);
828 if (m_recentAircraft.size() > MAX_RECENT_AIRCRAFT)
829 m_recentAircraft.pop_back();
832 m_ui->location->setLocationOptions();
835 if (m_ui->timeOfDayCombo->currentIndex() != 0) {
836 QString dayval = m_ui->timeOfDayCombo->currentText().toLower();
837 opt->addOption("timeofday", dayval.toStdString());
840 if (m_ui->seasonCombo->currentIndex() != 0) {
841 QString seasonName = m_ui->seasonCombo->currentText().toLower();
842 opt->addOption("season", seasonName.toStdString());
846 QString downloadDir = settings.value("download-dir").toString();
847 if (!downloadDir.isEmpty()) {
850 int result = QMessageBox::question(this, tr("Create download folder?"),
851 tr("The selected location for downloads does not exist. Create it?"),
852 QMessageBox::Yes | QMessageBox::No | QMessageBox::Cancel);
853 if (result == QMessageBox::Cancel) {
857 if (result == QMessageBox::Yes) {
858 d.mkpath(downloadDir);
862 opt->addOption("download-dir", downloadDir.toStdString());
866 Q_FOREACH(QString path, settings.value("scenery-paths").toStringList()) {
867 opt->addOption("fg-scenery", path.toStdString());
871 Q_FOREACH(QString path, settings.value("aircraft-paths").toStringList()) {
872 // can't use fg-aircraft for this, as it is processed before the launcher is run
873 globals->append_aircraft_path(path.toStdString());
876 // additional arguments
877 ArgumentsTokenizer tk;
878 Q_FOREACH(ArgumentsTokenizer::Arg a, tk.tokenize(m_ui->commandLineArgs->toPlainText())) {
879 if (a.arg.startsWith("prop:")) {
880 QString v = a.arg.mid(5) + "=" + a.value;
881 opt->addOption("prop", v.toStdString());
883 opt->addOption(a.arg.toStdString(), a.value.toStdString());
887 if (settings.contains("restore-defaults-on-run")) {
888 settings.remove("restore-defaults-on-run");
889 opt->addOption("restore-defaults", "");
898 void QtLauncher::onApply()
903 if (!m_selectedAircraft.isEmpty()) {
904 std::string aircraftPropValue,
907 if (m_selectedAircraft.isLocalFile()) {
908 QFileInfo setFileInfo(m_selectedAircraft.toLocalFile());
909 QString setFile = setFileInfo.fileName();
910 Q_ASSERT(setFile.endsWith("-set.xml"));
911 setFile.truncate(setFile.count() - 8); // drop the '-set.xml' portion
912 aircraftDir = setFileInfo.dir().absolutePath().toStdString();
913 aircraftPropValue = setFile.toStdString();
914 } else if (m_selectedAircraft.scheme() == "package") {
915 // no need to set aircraft-dir, handled by the corresponding code
917 aircraftPropValue = m_selectedAircraft.path().toStdString();
919 qWarning() << "unsupported aircraft launch URL" << m_selectedAircraft;
922 // manage aircraft history
923 if (m_recentAircraft.contains(m_selectedAircraft))
924 m_recentAircraft.removeOne(m_selectedAircraft);
925 m_recentAircraft.prepend(m_selectedAircraft);
926 if (m_recentAircraft.size() > MAX_RECENT_AIRCRAFT)
927 m_recentAircraft.pop_back();
929 globals->get_props()->setStringValue("/sim/aircraft", aircraftPropValue);
930 globals->get_props()->setStringValue("/sim/aircraft-dir", aircraftDir);
937 void QtLauncher::onQuit()
942 void QtLauncher::onToggleTerrasync(bool enabled)
946 QString downloadDir = settings.value("download-dir").toString();
947 if (downloadDir.isEmpty()) {
948 downloadDir = QString::fromStdString(flightgear::defaultDownloadDir());
951 QFileInfo info(downloadDir);
952 if (!info.exists()) {
954 msg.setWindowTitle(tr("Create download folder?"));
955 msg.setText(tr("The download folder '%1' does not exist, create it now?").arg(downloadDir));
956 msg.addButton(QMessageBox::Yes);
957 msg.addButton(QMessageBox::Cancel);
958 int result = msg.exec();
960 if (result == QMessageBox::Cancel) {
961 m_ui->terrasyncCheck->setChecked(false);
966 d.mkpath(downloadDir);
971 void QtLauncher::onAircraftInstalledCompleted(QModelIndex index)
973 maybeUpdateSelectedAircraft(index);
976 void QtLauncher::onRatingsFilterToggled()
978 QModelIndex aircraftIndex = m_aircraftModel->indexOfAircraftURI(m_selectedAircraft);
979 QModelIndex proxyIndex = m_aircraftProxy->mapFromSource(aircraftIndex);
980 if (proxyIndex.isValid()) {
981 m_ui->aircraftList->scrollTo(proxyIndex);
985 void QtLauncher::onAircraftInstallFailed(QModelIndex index, QString errorMessage)
987 qWarning() << Q_FUNC_INFO << index.data(AircraftURIRole) << errorMessage;
990 msg.setWindowTitle(tr("Aircraft installation failed"));
991 msg.setText(tr("An error occurred installing the aircraft %1: %2").
992 arg(index.data(Qt::DisplayRole).toString()).arg(errorMessage));
993 msg.addButton(QMessageBox::Ok);
996 maybeUpdateSelectedAircraft(index);
999 void QtLauncher::onAircraftSelected(const QModelIndex& index)
1001 m_selectedAircraft = index.data(AircraftURIRole).toUrl();
1002 updateSelectedAircraft();
1005 void QtLauncher::onRequestPackageInstall(const QModelIndex& index)
1007 // also select, otherwise UI is confusing
1008 m_selectedAircraft = index.data(AircraftURIRole).toUrl();
1009 updateSelectedAircraft();
1011 QString pkg = index.data(AircraftPackageIdRole).toString();
1012 simgear::pkg::PackageRef pref = globals->packageRoot()->getPackageById(pkg.toStdString());
1013 if (pref->isInstalled()) {
1014 InstallRef install = pref->existingInstall();
1015 if (install && install->hasUpdate()) {
1016 globals->packageRoot()->scheduleToUpdate(install);
1023 void QtLauncher::onCancelDownload(const QModelIndex& index)
1025 QString pkg = index.data(AircraftPackageIdRole).toString();
1026 simgear::pkg::PackageRef pref = globals->packageRoot()->getPackageById(pkg.toStdString());
1027 simgear::pkg::InstallRef i = pref->existingInstall();
1028 i->cancelDownload();
1031 void QtLauncher::onRestoreDefaults()
1033 QMessageBox mbox(this);
1034 mbox.setText(tr("Restore all settings to defaults?"));
1035 mbox.setInformativeText(tr("Restoring settings to their defaults may affect available add-ons such as scenery or aircraft."));
1036 QPushButton* quitButton = mbox.addButton(tr("Restore and restart now"), QMessageBox::YesRole);
1037 mbox.addButton(QMessageBox::Cancel);
1038 mbox.setDefaultButton(QMessageBox::Cancel);
1039 mbox.setIconPixmap(QPixmap(":/app-icon-large"));
1042 if (mbox.clickedButton() != quitButton) {
1049 settings.setValue("restore-defaults-on-run", true);
1052 restartTheApp(QStringList());
1055 void QtLauncher::maybeUpdateSelectedAircraft(QModelIndex index)
1057 QUrl u = index.data(AircraftURIRole).toUrl();
1058 if (u == m_selectedAircraft) {
1059 // potentially enable the run button now!
1060 updateSelectedAircraft();
1064 void QtLauncher::updateSelectedAircraft()
1066 QModelIndex index = m_aircraftModel->indexOfAircraftURI(m_selectedAircraft);
1067 if (index.isValid()) {
1068 QPixmap pm = index.data(Qt::DecorationRole).value<QPixmap>();
1069 m_ui->thumbnail->setPixmap(pm);
1070 m_ui->aircraftDescription->setText(index.data(Qt::DisplayRole).toString());
1072 int status = index.data(AircraftPackageStatusRole).toInt();
1073 bool canRun = (status == PackageInstalled);
1074 m_ui->runButton->setEnabled(canRun);
1076 LauncherAircraftType aircraftType = Airplane;
1077 if (index.data(AircraftIsHelicopterRole).toBool()) {
1078 aircraftType = Helicopter;
1079 } else if (index.data(AircraftIsSeaplaneRole).toBool()) {
1080 aircraftType = Seaplane;
1083 m_ui->location->setAircraftType(aircraftType);
1085 m_ui->thumbnail->setPixmap(QPixmap());
1086 m_ui->aircraftDescription->setText("");
1087 m_ui->runButton->setEnabled(false);
1091 QModelIndex QtLauncher::proxyIndexForAircraftURI(QUrl uri) const
1093 return m_aircraftProxy->mapFromSource(sourceIndexForAircraftURI(uri));
1096 QModelIndex QtLauncher::sourceIndexForAircraftURI(QUrl uri) const
1098 AircraftItemModel* sourceModel = qobject_cast<AircraftItemModel*>(m_aircraftProxy->sourceModel());
1099 Q_ASSERT(sourceModel);
1100 return sourceModel->indexOfAircraftURI(uri);
1103 void QtLauncher::onPopupAircraftHistory()
1105 if (m_recentAircraft.isEmpty()) {
1110 Q_FOREACH(QUrl uri, m_recentAircraft) {
1111 QModelIndex index = sourceIndexForAircraftURI(uri);
1112 if (!index.isValid()) {
1116 QAction* act = m.addAction(index.data(Qt::DisplayRole).toString());
1120 QPoint popupPos = m_ui->aircraftHistory->mapToGlobal(m_ui->aircraftHistory->rect().bottomLeft());
1121 QAction* triggered = m.exec(popupPos);
1123 m_selectedAircraft = triggered->data().toUrl();
1124 QModelIndex index = proxyIndexForAircraftURI(m_selectedAircraft);
1125 m_ui->aircraftList->selectionModel()->setCurrentIndex(index,
1126 QItemSelectionModel::ClearAndSelect);
1127 m_ui->aircraftFilter->clear();
1128 updateSelectedAircraft();
1132 void QtLauncher::onEditRatingsFilter()
1134 EditRatingsFilterDialog dialog(this);
1135 dialog.setRatings(m_ratingFilters);
1138 if (dialog.result() == QDialog::Accepted) {
1140 for (int i=0; i<4; ++i) {
1141 m_ratingFilters[i] = dialog.getRating(i);
1142 vl.append(m_ratingFilters[i]);
1144 m_aircraftProxy->setRatings(m_ratingFilters);
1147 settings.setValue("min-ratings", vl);
1151 void QtLauncher::updateSettingsSummary()
1153 QStringList summary;
1154 if (m_ui->timeOfDayCombo->currentIndex() > 0) {
1155 summary.append(QString(m_ui->timeOfDayCombo->currentText().toLower()));
1158 if (m_ui->seasonCombo->currentIndex() > 0) {
1159 summary.append(QString(m_ui->seasonCombo->currentText().toLower()));
1162 if (m_ui->rembrandtCheckbox->isChecked()) {
1163 summary.append("Rembrandt enabled");
1164 } else if (m_ui->msaaCheckbox->isChecked()) {
1165 summary.append("anti-aliasing");
1168 if (m_ui->fetchRealWxrCheckbox->isChecked()) {
1169 summary.append("live weather");
1172 if (m_ui->terrasyncCheck->isChecked()) {
1173 summary.append("automatic scenery downloads");
1176 if (m_ui->startPausedCheck->isChecked()) {
1177 summary.append("paused");
1180 QString s = summary.join(", ");
1181 s[0] = s[0].toUpper();
1182 m_ui->settingsDescription->setText(s);
1185 void QtLauncher::onRembrandtToggled(bool b)
1187 // Rembrandt and multi-sample are exclusive
1188 m_ui->msaaCheckbox->setEnabled(!b);
1191 void QtLauncher::onShowInstalledAircraftToggled(bool b)
1193 m_ui->ratingsFilterCheck->setEnabled(!b);
1194 maybeRestoreAircraftSelection();
1197 void QtLauncher::onSubsytemIdleTimeout()
1199 globals->get_subsystem_mgr()->update(0.0);
1202 void QtLauncher::onDownloadDirChanged()
1205 // replace existing package root
1206 globals->get_subsystem<FGHTTPClient>()->shutdown();
1207 globals->setPackageRoot(simgear::pkg::RootRef());
1209 // create new root with updated download-dir value
1210 fgInitPackageRoot();
1212 globals->get_subsystem<FGHTTPClient>()->init();
1215 // re-scan the aircraft list
1216 m_aircraftModel->setPackageRoot(globals->packageRoot());
1217 m_aircraftModel->setPaths(settings.value("aircraft-paths").toStringList());
1218 m_aircraftModel->scanDirs();
1220 checkOfficialCatalogMessage();
1222 // re-set scenery dirs
1226 void QtLauncher::checkOfficialCatalogMessage()
1229 bool showOfficialCatalogMesssage = !globals->get_subsystem<FGHTTPClient>()->isDefaultCatalogInstalled();
1230 if (settings.value("hide-official-catalog-message").toBool()) {
1231 showOfficialCatalogMesssage = false;
1234 m_aircraftModel->setOfficialHangarMessageVisible(showOfficialCatalogMesssage);
1235 if (showOfficialCatalogMesssage) {
1236 NoOfficialHangarMessage* messageWidget = new NoOfficialHangarMessage;
1237 connect(messageWidget, &NoOfficialHangarMessage::linkActivated,
1238 this, &QtLauncher::onOfficialCatalogMessageLink);
1240 QModelIndex index = m_aircraftProxy->mapFromSource(m_aircraftModel->officialHangarMessageIndex());
1241 m_ui->aircraftList->setIndexWidget(index, messageWidget);
1245 void QtLauncher::onOfficialCatalogMessageLink(QUrl link)
1247 QString s = link.toString();
1248 if (s == "action:hide") {
1250 settings.setValue("hide-official-catalog-message", true);
1251 } else if (s == "action:add-official") {
1252 AddOnsPage::addDefaultCatalog(this);
1255 checkOfficialCatalogMessage();
1258 simgear::pkg::PackageRef QtLauncher::packageForAircraftURI(QUrl uri) const
1260 if (uri.scheme() != "package") {
1261 qWarning() << "invalid URL scheme:" << uri;
1262 return simgear::pkg::PackageRef();
1265 QString ident = uri.path();
1266 return globals->packageRoot()->getPackageById(ident.toStdString());
1269 void QtLauncher::restartTheApp(QStringList fgArgs)
1271 // Spawn a new instance of myApplication:
1275 #if defined(Q_OS_MAC)
1276 QDir dir(qApp->applicationDirPath()); // returns the 'MacOS' dir
1277 dir.cdUp(); // up to 'contents' dir
1278 dir.cdUp(); // up to .app dir
1279 // see 'man open' for details, but '-n' ensures we launch a new instance,
1280 // and we want to pass remaining arguments to us, not open.
1281 args << "-n" << dir.absolutePath() << "--args" << "--launcher" << fgArgs;
1282 qDebug() << "args" << args;
1283 proc.startDetached("open", args);
1285 args << "--launcher" << fgArgs;
1286 proc.startDetached(qApp->applicationFilePath(), args);
1291 #include "QtLauncher.moc"