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 "EditRatingsFilterDialog.hxx"
63 #include "AircraftItemDelegate.hxx"
64 #include "AircraftModel.hxx"
65 #include "PathsDialog.hxx"
67 #include <Main/globals.hxx>
68 #include <Navaids/NavDataCache.hxx>
69 #include <Navaids/navrecord.hxx>
70 #include <Navaids/SHPParser.hxx>
72 #include <Main/options.hxx>
73 #include <Main/fg_init.hxx>
74 #include <Viewer/WindowBuilder.hxx>
75 #include <Network/HTTPClient.hxx>
77 using namespace flightgear;
78 using namespace simgear::pkg;
80 const int MAX_RECENT_AIRCRAFT = 20;
82 namespace { // anonymous namespace
86 QString baseLabel = QT_TR_NOOP("Initialising navigation data, this may take several minutes");
87 NavDataCache* cache = NavDataCache::createInstance();
88 if (cache->isRebuildRequired()) {
89 QProgressDialog rebuildProgress(baseLabel,
90 QString() /* cancel text */,
92 rebuildProgress.setWindowModality(Qt::WindowModal);
93 rebuildProgress.show();
95 NavDataCache::RebuildPhase phase = cache->rebuild();
97 while (phase != NavDataCache::REBUILD_DONE) {
98 // sleep to give the rebuild thread more time
99 SGTimeStamp::sleepForMSec(50);
100 phase = cache->rebuild();
103 case NavDataCache::REBUILD_AIRPORTS:
104 rebuildProgress.setLabelText(QT_TR_NOOP("Loading airport data"));
107 case NavDataCache::REBUILD_FIXES:
108 rebuildProgress.setLabelText(QT_TR_NOOP("Loading waypoint data"));
111 case NavDataCache::REBUILD_NAVAIDS:
112 rebuildProgress.setLabelText(QT_TR_NOOP("Loading navigation data"));
116 case NavDataCache::REBUILD_POIS:
117 rebuildProgress.setLabelText(QT_TR_NOOP("Loading point-of-interest data"));
121 rebuildProgress.setLabelText(baseLabel);
124 if (phase == NavDataCache::REBUILD_UNKNOWN) {
125 rebuildProgress.setValue(0);
126 rebuildProgress.setMaximum(0);
128 rebuildProgress.setValue(cache->rebuildPhaseCompletionPercentage());
129 rebuildProgress.setMaximum(100);
132 QCoreApplication::processEvents();
137 class ArgumentsTokenizer
143 explicit Arg(QString k, QString v = QString()) : arg(k), value(v) {}
149 QList<Arg> tokenize(QString in) const
152 const int len = in.count();
158 for (; index < len; ++index) {
160 nc = index < (len - 1) ? in.at(index + 1) : QChar();
164 if (c == QChar('-')) {
165 if (nc == QChar('-')) {
170 // should we pemit single hyphen arguments?
171 // choosing to fail for now
174 } else if (c == QChar('#')) {
177 } else if (c.isSpace()) {
183 if (c == QChar('=')) {
186 } else if (c.isSpace()) {
188 result.append(Arg(key));
190 // could check for illegal charatcers here
196 if (c == QChar('"')) {
198 } else if (c.isSpace()) {
200 result.append(Arg(key, value));
207 if (c == QChar('\\')) {
208 // check for escaped double-quote inside quoted value
209 if (nc == QChar('"')) {
212 } else if (c == QChar('"')) {
220 if ((c == QChar('\n')) || (c == QChar('\r'))) {
224 // nothing to do, eat comment chars
228 } // of character loop
230 // ensure last argument isn't lost
232 result.append(Arg(key));
233 } else if (state == Value) {
234 result.append(Arg(key, value));
250 } // of anonymous namespace
252 class AircraftProxyModel : public QSortFilterProxyModel
256 AircraftProxyModel(QObject* pr) :
257 QSortFilterProxyModel(pr),
258 m_ratingsFilter(true),
259 m_onlyShowInstalled(false)
261 for (int i=0; i<4; ++i) {
266 void setRatings(int* ratings)
268 ::memcpy(m_ratings, ratings, sizeof(int) * 4);
273 void setRatingFilterEnabled(bool e)
275 if (e == m_ratingsFilter) {
283 void setInstalledFilterEnabled(bool e)
285 if (e == m_onlyShowInstalled) {
289 m_onlyShowInstalled = e;
294 bool filterAcceptsRow(int sourceRow, const QModelIndex &sourceParent) const
296 if (!QSortFilterProxyModel::filterAcceptsRow(sourceRow, sourceParent)) {
300 if (m_onlyShowInstalled) {
301 QModelIndex index = sourceModel()->index(sourceRow, 0, sourceParent);
302 QVariant v = index.data(AircraftPackageStatusRole);
303 AircraftItemStatus status = static_cast<AircraftItemStatus>(v.toInt());
304 if (status == PackageNotInstalled) {
309 if (!m_onlyShowInstalled && m_ratingsFilter) {
310 QModelIndex index = sourceModel()->index(sourceRow, 0, sourceParent);
311 for (int i=0; i<4; ++i) {
312 if (m_ratings[i] > index.data(AircraftRatingRole + i).toInt()) {
322 bool m_ratingsFilter;
323 bool m_onlyShowInstalled;
327 static void initQtResources()
329 Q_INIT_RESOURCE(resources);
335 void initApp(int& argc, char** argv)
337 static bool qtInitDone = false;
343 sglog().setLogLevels( SG_ALL, SG_INFO );
344 initQtResources(); // can't be called from a namespace
346 s_argc = argc; // QApplication only stores a reference to argc,
347 // and may crash if it is freed
348 // http://doc.qt.io/qt-5/qguiapplication.html#QGuiApplication
350 QSettings::setDefaultFormat(QSettings::IniFormat);
351 QSettings::setPath(QSettings::IniFormat, QSettings::UserScope,
352 QString::fromStdString(globals->get_fg_home()));
354 QApplication* app = new QApplication(s_argc, argv);
355 app->setOrganizationName("FlightGear");
356 app->setApplicationName("FlightGear");
357 app->setOrganizationDomain("flightgear.org");
359 // reset numeric / collation locales as described at:
360 // http://doc.qt.io/qt-5/qcoreapplication.html#details
361 ::setlocale(LC_NUMERIC, "C");
362 ::setlocale(LC_COLLATE, "C");
364 Qt::KeyboardModifiers mods = app->queryKeyboardModifiers();
365 if (mods & (Qt::AltModifier | Qt::ShiftModifier)) {
366 qWarning() << "Alt/shift pressed during launch";
368 settings.setValue("fg-root", "!ask");
373 void loadNaturalEarthFile(const std::string& aFileName,
374 flightgear::PolyLine::Type aType,
377 SGPath path(globals->get_fg_root());
378 path.append( "Geodata" );
379 path.append(aFileName);
381 return; // silently fail for now
383 flightgear::PolyLineList lines;
384 flightgear::SHPParser::parsePolyLines(path, aType, lines, areClosed);
385 flightgear::PolyLine::bulkAddToSpatialIndex(lines);
388 void loadNaturalEarthData()
393 loadNaturalEarthFile("ne_10m_coastline.shp", flightgear::PolyLine::COASTLINE, false);
394 loadNaturalEarthFile("ne_10m_rivers_lake_centerlines.shp", flightgear::PolyLine::RIVER, false);
395 loadNaturalEarthFile("ne_10m_lakes.shp", flightgear::PolyLine::LAKE, true);
397 qDebug() << "load basic data took" << st.elapsedMSec();
401 loadNaturalEarthFile("ne_10m_urban_areas.shp", flightgear::PolyLine::URBAN, true);
403 qDebug() << "loading urban areas took:" << st.elapsedMSec();
406 bool runLauncherDialog()
408 // startup the nav-cache now. This pre-empts normal startup of
409 // the cache, but no harm done. (Providing scenery paths are consistent)
414 QString downloadDir = settings.value("download-dir").toString();
415 if (!downloadDir.isEmpty()) {
416 flightgear::Options::sharedInstance()->setOption("download-dir", downloadDir.toStdString());
421 // startup the HTTP system now since packages needs it
422 FGHTTPClient* http = globals->add_new_subsystem<FGHTTPClient>();
424 // we guard against re-init in the global phase; bind and postinit
425 // will happen as normal
428 loadNaturalEarthData();
430 // avoid double Apple menu and other weirdness if both Qt and OSG
431 // try to initialise various Cocoa structures.
432 flightgear::WindowBuilder::setPoseAsStandaloneApp(false);
437 int appResult = qApp->exec();
439 return false; // quit
442 // don't set scenery paths twice
443 globals->clear_fg_scenery();
448 bool runInAppLauncherDialog()
453 if (dlg.result() != QDialog::Accepted) {
460 } // of namespace flightgear
462 QtLauncher::QtLauncher() :
465 m_subsystemIdleTimer(NULL),
468 m_ui.reset(new Ui::Launcher);
471 #if QT_VERSION >= 0x050300
472 // don't require Qt 5.3
473 m_ui->commandLineArgs->setPlaceholderText("--option=value --prop:/sim/name=value");
476 #if QT_VERSION >= 0x050200
477 m_ui->aircraftFilter->setClearButtonEnabled(true);
480 for (int i=0; i<4; ++i) {
481 m_ratingFilters[i] = 3;
484 m_subsystemIdleTimer = new QTimer(this);
485 m_subsystemIdleTimer->setInterval(0);
486 connect(m_subsystemIdleTimer, &QTimer::timeout,
487 this, &QtLauncher::onSubsytemIdleTimeout);
488 m_subsystemIdleTimer->start();
490 // create and configure the proxy model
491 m_aircraftProxy = new AircraftProxyModel(this);
492 connect(m_ui->ratingsFilterCheck, &QAbstractButton::toggled,
493 m_aircraftProxy, &AircraftProxyModel::setRatingFilterEnabled);
494 connect(m_ui->ratingsFilterCheck, &QAbstractButton::toggled,
495 this, &QtLauncher::maybeRestoreAircraftSelection);
497 connect(m_ui->onlyShowInstalledCheck, &QAbstractButton::toggled,
498 m_aircraftProxy, &AircraftProxyModel::setInstalledFilterEnabled);
499 connect(m_ui->aircraftFilter, &QLineEdit::textChanged,
500 m_aircraftProxy, &QSortFilterProxyModel::setFilterFixedString);
502 connect(m_ui->runButton, SIGNAL(clicked()), this, SLOT(onRun()));
503 connect(m_ui->quitButton, SIGNAL(clicked()), this, SLOT(onQuit()));
505 connect(m_ui->aircraftHistory, &QPushButton::clicked,
506 this, &QtLauncher::onPopupAircraftHistory);
508 connect(m_ui->location, &LocationWidget::descriptionChanged,
509 m_ui->locationDescription, &QLabel::setText);
511 QAction* qa = new QAction(this);
512 qa->setShortcut(QKeySequence("Ctrl+Q"));
513 connect(qa, &QAction::triggered, this, &QtLauncher::onQuit);
516 connect(m_ui->editRatingFilter, &QPushButton::clicked,
517 this, &QtLauncher::onEditRatingsFilter);
518 connect(m_ui->onlyShowInstalledCheck, &QCheckBox::toggled,
519 this, &QtLauncher::onShowInstalledAircraftToggled);
521 QIcon historyIcon(":/history-icon");
522 m_ui->aircraftHistory->setIcon(historyIcon);
524 connect(m_ui->timeOfDayCombo, SIGNAL(currentIndexChanged(int)),
525 this, SLOT(updateSettingsSummary()));
526 connect(m_ui->seasonCombo, SIGNAL(currentIndexChanged(int)),
527 this, SLOT(updateSettingsSummary()));
528 connect(m_ui->fetchRealWxrCheckbox, SIGNAL(toggled(bool)),
529 this, SLOT(updateSettingsSummary()));
530 connect(m_ui->rembrandtCheckbox, SIGNAL(toggled(bool)),
531 this, SLOT(updateSettingsSummary()));
532 connect(m_ui->terrasyncCheck, SIGNAL(toggled(bool)),
533 this, SLOT(updateSettingsSummary()));
534 connect(m_ui->startPausedCheck, SIGNAL(toggled(bool)),
535 this, SLOT(updateSettingsSummary()));
536 connect(m_ui->msaaCheckbox, SIGNAL(toggled(bool)),
537 this, SLOT(updateSettingsSummary()));
539 connect(m_ui->rembrandtCheckbox, SIGNAL(toggled(bool)),
540 this, SLOT(onRembrandtToggled(bool)));
541 connect(m_ui->terrasyncCheck, &QCheckBox::toggled,
542 this, &QtLauncher::onToggleTerrasync);
543 updateSettingsSummary();
545 m_aircraftModel = new AircraftItemModel(this);
546 m_aircraftProxy->setSourceModel(m_aircraftModel);
548 m_aircraftProxy->setFilterCaseSensitivity(Qt::CaseInsensitive);
549 m_aircraftProxy->setSortCaseSensitivity(Qt::CaseInsensitive);
550 m_aircraftProxy->setSortRole(Qt::DisplayRole);
551 m_aircraftProxy->setDynamicSortFilter(true);
553 m_ui->aircraftList->setModel(m_aircraftProxy);
554 m_ui->aircraftList->setHorizontalScrollBarPolicy(Qt::ScrollBarAlwaysOff);
555 AircraftItemDelegate* delegate = new AircraftItemDelegate(m_ui->aircraftList);
556 m_ui->aircraftList->setItemDelegate(delegate);
557 m_ui->aircraftList->setSelectionMode(QAbstractItemView::SingleSelection);
558 connect(m_ui->aircraftList, &QListView::clicked,
559 this, &QtLauncher::onAircraftSelected);
560 connect(delegate, &AircraftItemDelegate::variantChanged,
561 this, &QtLauncher::onAircraftSelected);
562 connect(delegate, &AircraftItemDelegate::requestInstall,
563 this, &QtLauncher::onRequestPackageInstall);
564 connect(delegate, &AircraftItemDelegate::cancelDownload,
565 this, &QtLauncher::onCancelDownload);
567 connect(m_aircraftModel, &AircraftItemModel::aircraftInstallCompleted,
568 this, &QtLauncher::onAircraftInstalledCompleted);
569 connect(m_aircraftModel, &AircraftItemModel::aircraftInstallFailed,
570 this, &QtLauncher::onAircraftInstallFailed);
571 connect(m_aircraftModel, &AircraftItemModel::scanCompleted,
572 this, &QtLauncher::updateSelectedAircraft);
573 connect(m_ui->restoreDefaultsButton, &QPushButton::clicked,
574 this, &QtLauncher::onRestoreDefaults);
577 AddOnsPage* addOnsPage = new AddOnsPage(NULL, globals->packageRoot());
578 connect(addOnsPage, &AddOnsPage::downloadDirChanged,
579 this, &QtLauncher::onDownloadDirChanged);
580 connect(addOnsPage, &AddOnsPage::sceneryPathsChanged,
581 this, &QtLauncher::setSceneryPaths);
583 m_ui->tabWidget->addTab(addOnsPage, tr("Add-ons"));
584 // after any kind of reset, try to restore selection and scroll
585 // to match the m_selectedAircraft. This needs to be delayed
586 // fractionally otherwise the scrollTo seems to be ignored,
588 connect(m_aircraftProxy, &AircraftProxyModel::modelReset,
589 this, &QtLauncher::delayedAircraftModelReset);
592 m_aircraftModel->setPaths(settings.value("aircraft-paths").toStringList());
593 m_aircraftModel->setPackageRoot(globals->packageRoot());
594 m_aircraftModel->scanDirs();
599 QtLauncher::~QtLauncher()
604 void QtLauncher::setSceneryPaths()
606 globals->clear_fg_scenery();
608 // mimic what optionss.cxx does, so we can find airport data for parking
611 // append explicit scenery paths
612 Q_FOREACH(QString path, settings.value("scenery-paths").toStringList()) {
613 globals->append_fg_scenery(path.toStdString());
616 // append the TerraSync path
617 QString downloadDir = settings.value("download-dir").toString();
618 if (downloadDir.isEmpty()) {
619 downloadDir = QString::fromStdString(flightgear::defaultDownloadDir());
622 SGPath terraSyncDir(downloadDir.toStdString());
623 terraSyncDir.append("TerraSync");
624 if (terraSyncDir.exists()) {
625 globals->append_fg_scenery(terraSyncDir.str());
630 void QtLauncher::setInAppMode()
633 m_ui->tabWidget->removeTab(2);
634 m_ui->runButton->setText(tr("Apply"));
635 m_ui->quitButton->setText(tr("Cancel"));
637 disconnect(m_ui->runButton, SIGNAL(clicked()), this, SLOT(onRun()));
638 connect(m_ui->runButton, SIGNAL(clicked()), this, SLOT(onApply()));
641 void QtLauncher::restoreSettings()
644 m_ui->rembrandtCheckbox->setChecked(settings.value("enable-rembrandt", false).toBool());
645 m_ui->terrasyncCheck->setChecked(settings.value("enable-terrasync", true).toBool());
646 m_ui->fullScreenCheckbox->setChecked(settings.value("start-fullscreen", false).toBool());
647 m_ui->msaaCheckbox->setChecked(settings.value("enable-msaa", false).toBool());
648 m_ui->fetchRealWxrCheckbox->setChecked(settings.value("enable-realwx", true).toBool());
649 m_ui->startPausedCheck->setChecked(settings.value("start-paused", false).toBool());
650 m_ui->timeOfDayCombo->setCurrentIndex(settings.value("timeofday", 0).toInt());
651 m_ui->seasonCombo->setCurrentIndex(settings.value("season", 0).toInt());
653 // full paths to -set.xml files
654 m_recentAircraft = QUrl::fromStringList(settings.value("recent-aircraft").toStringList());
656 if (!m_recentAircraft.empty()) {
657 m_selectedAircraft = m_recentAircraft.front();
659 // select the default C172p
666 m_ui->location->restoreSettings();
669 m_ui->onlyShowInstalledCheck->setChecked(settings.value("only-show-installed", false).toBool());
670 if (m_ui->onlyShowInstalledCheck->isChecked()) {
671 m_ui->ratingsFilterCheck->setEnabled(false);
674 m_ui->ratingsFilterCheck->setChecked(settings.value("ratings-filter", true).toBool());
676 Q_FOREACH(QVariant v, settings.value("min-ratings").toList()) {
677 m_ratingFilters[index++] = v.toInt();
680 m_aircraftProxy->setRatingFilterEnabled(m_ui->ratingsFilterCheck->isChecked());
681 m_aircraftProxy->setRatings(m_ratingFilters);
683 updateSelectedAircraft();
684 maybeRestoreAircraftSelection();
686 m_ui->commandLineArgs->setPlainText(settings.value("additional-args").toString());
689 void QtLauncher::delayedAircraftModelReset()
691 QTimer::singleShot(1, this, SLOT(maybeRestoreAircraftSelection()));
694 void QtLauncher::maybeRestoreAircraftSelection()
696 QModelIndex aircraftIndex = m_aircraftModel->indexOfAircraftURI(m_selectedAircraft);
697 QModelIndex proxyIndex = m_aircraftProxy->mapFromSource(aircraftIndex);
698 if (proxyIndex.isValid()) {
699 m_ui->aircraftList->selectionModel()->setCurrentIndex(proxyIndex,
700 QItemSelectionModel::ClearAndSelect);
701 m_ui->aircraftList->selectionModel()->select(proxyIndex,
702 QItemSelectionModel::ClearAndSelect);
703 m_ui->aircraftList->scrollTo(proxyIndex);
707 void QtLauncher::saveSettings()
710 settings.setValue("enable-rembrandt", m_ui->rembrandtCheckbox->isChecked());
711 settings.setValue("enable-terrasync", m_ui->terrasyncCheck->isChecked());
712 settings.setValue("enable-msaa", m_ui->msaaCheckbox->isChecked());
713 settings.setValue("start-fullscreen", m_ui->fullScreenCheckbox->isChecked());
714 settings.setValue("enable-realwx", m_ui->fetchRealWxrCheckbox->isChecked());
715 settings.setValue("start-paused", m_ui->startPausedCheck->isChecked());
716 settings.setValue("ratings-filter", m_ui->ratingsFilterCheck->isChecked());
717 settings.setValue("only-show-installed", m_ui->onlyShowInstalledCheck->isChecked());
718 settings.setValue("recent-aircraft", QUrl::toStringList(m_recentAircraft));
720 settings.setValue("timeofday", m_ui->timeOfDayCombo->currentIndex());
721 settings.setValue("season", m_ui->seasonCombo->currentIndex());
722 settings.setValue("additional-args", m_ui->commandLineArgs->toPlainText());
724 m_ui->location->saveSettings();
727 void QtLauncher::setEnableDisableOptionFromCheckbox(QCheckBox* cbox, QString name) const
729 flightgear::Options* opt = flightgear::Options::sharedInstance();
730 std::string stdName(name.toStdString());
731 if (cbox->isChecked()) {
732 opt->addOption("enable-" + stdName, "");
734 opt->addOption("disable-" + stdName, "");
738 void QtLauncher::closeEvent(QCloseEvent *event)
743 void QtLauncher::onRun()
745 flightgear::Options* opt = flightgear::Options::sharedInstance();
746 setEnableDisableOptionFromCheckbox(m_ui->terrasyncCheck, "terrasync");
747 setEnableDisableOptionFromCheckbox(m_ui->fetchRealWxrCheckbox, "real-weather-fetch");
748 setEnableDisableOptionFromCheckbox(m_ui->rembrandtCheckbox, "rembrandt");
749 setEnableDisableOptionFromCheckbox(m_ui->fullScreenCheckbox, "fullscreen");
750 // setEnableDisableOptionFromCheckbox(m_ui->startPausedCheck, "freeze");
752 bool startPaused = m_ui->startPausedCheck->isChecked() ||
753 m_ui->location->shouldStartPaused();
755 opt->addOption("enable-freeze", "");
758 // MSAA is more complex
759 if (!m_ui->rembrandtCheckbox->isChecked()) {
760 if (m_ui->msaaCheckbox->isChecked()) {
761 globals->get_props()->setIntValue("/sim/rendering/multi-sample-buffers", 1);
762 globals->get_props()->setIntValue("/sim/rendering/multi-samples", 4);
764 globals->get_props()->setIntValue("/sim/rendering/multi-sample-buffers", 0);
769 if (!m_selectedAircraft.isEmpty()) {
770 if (m_selectedAircraft.isLocalFile()) {
771 QFileInfo setFileInfo(m_selectedAircraft.toLocalFile());
772 opt->addOption("aircraft-dir", setFileInfo.dir().absolutePath().toStdString());
773 QString setFile = setFileInfo.fileName();
774 Q_ASSERT(setFile.endsWith("-set.xml"));
775 setFile.truncate(setFile.count() - 8); // drop the '-set.xml' portion
776 opt->addOption("aircraft", setFile.toStdString());
777 } else if (m_selectedAircraft.scheme() == "package") {
778 QString qualifiedId = m_selectedAircraft.path();
779 // no need to set aircraft-dir, handled by the corresponding code
781 opt->addOption("aircraft", qualifiedId.toStdString());
783 qWarning() << "unsupported aircraft launch URL" << m_selectedAircraft;
786 // manage aircraft history
787 if (m_recentAircraft.contains(m_selectedAircraft))
788 m_recentAircraft.removeOne(m_selectedAircraft);
789 m_recentAircraft.prepend(m_selectedAircraft);
790 if (m_recentAircraft.size() > MAX_RECENT_AIRCRAFT)
791 m_recentAircraft.pop_back();
794 m_ui->location->setLocationOptions();
797 if (m_ui->timeOfDayCombo->currentIndex() != 0) {
798 QString dayval = m_ui->timeOfDayCombo->currentText().toLower();
799 opt->addOption("timeofday", dayval.toStdString());
802 if (m_ui->seasonCombo->currentIndex() != 0) {
803 QString seasonName = m_ui->seasonCombo->currentText().toLower();
804 opt->addOption("season", seasonName.toStdString());
808 QString downloadDir = settings.value("download-dir").toString();
809 if (!downloadDir.isEmpty()) {
812 int result = QMessageBox::question(this, tr("Create download folder?"),
813 tr("The selected location for downloads does not exist. Create it?"),
814 QMessageBox::Yes | QMessageBox::No | QMessageBox::Cancel);
815 if (result == QMessageBox::Cancel) {
819 if (result == QMessageBox::Yes) {
820 d.mkpath(downloadDir);
824 opt->addOption("download-dir", downloadDir.toStdString());
828 Q_FOREACH(QString path, settings.value("scenery-paths").toStringList()) {
829 opt->addOption("fg-scenery", path.toStdString());
833 Q_FOREACH(QString path, settings.value("aircraft-paths").toStringList()) {
834 // can't use fg-aircraft for this, as it is processed before the launcher is run
835 globals->append_aircraft_path(path.toStdString());
838 // additional arguments
839 ArgumentsTokenizer tk;
840 Q_FOREACH(ArgumentsTokenizer::Arg a, tk.tokenize(m_ui->commandLineArgs->toPlainText())) {
841 if (a.arg.startsWith("prop:")) {
842 QString v = a.arg.mid(5) + "=" + a.value;
843 opt->addOption("prop", v.toStdString());
845 opt->addOption(a.arg.toStdString(), a.value.toStdString());
849 if (settings.contains("restore-defaults-on-run")) {
850 settings.remove("restore-defaults-on-run");
851 opt->addOption("restore-defaults", "");
860 void QtLauncher::onApply()
865 if (!m_selectedAircraft.isEmpty()) {
866 std::string aircraftPropValue,
869 if (m_selectedAircraft.isLocalFile()) {
870 QFileInfo setFileInfo(m_selectedAircraft.toLocalFile());
871 QString setFile = setFileInfo.fileName();
872 Q_ASSERT(setFile.endsWith("-set.xml"));
873 setFile.truncate(setFile.count() - 8); // drop the '-set.xml' portion
874 aircraftDir = setFileInfo.dir().absolutePath().toStdString();
875 aircraftPropValue = setFile.toStdString();
876 } else if (m_selectedAircraft.scheme() == "package") {
877 // no need to set aircraft-dir, handled by the corresponding code
879 aircraftPropValue = m_selectedAircraft.path().toStdString();
881 qWarning() << "unsupported aircraft launch URL" << m_selectedAircraft;
884 // manage aircraft history
885 if (m_recentAircraft.contains(m_selectedAircraft))
886 m_recentAircraft.removeOne(m_selectedAircraft);
887 m_recentAircraft.prepend(m_selectedAircraft);
888 if (m_recentAircraft.size() > MAX_RECENT_AIRCRAFT)
889 m_recentAircraft.pop_back();
891 globals->get_props()->setStringValue("/sim/aircraft", aircraftPropValue);
892 globals->get_props()->setStringValue("/sim/aircraft-dir", aircraftDir);
899 void QtLauncher::onQuit()
904 void QtLauncher::onToggleTerrasync(bool enabled)
908 QString downloadDir = settings.value("download-dir").toString();
909 if (downloadDir.isEmpty()) {
910 downloadDir = QString::fromStdString(flightgear::defaultDownloadDir());
913 QFileInfo info(downloadDir);
914 if (!info.exists()) {
916 msg.setWindowTitle(tr("Create download folder?"));
917 msg.setText(tr("The download folder '%1' does not exist, create it now?").arg(downloadDir));
918 msg.addButton(QMessageBox::Yes);
919 msg.addButton(QMessageBox::Cancel);
920 int result = msg.exec();
922 if (result == QMessageBox::Cancel) {
923 m_ui->terrasyncCheck->setChecked(false);
928 d.mkpath(downloadDir);
933 void QtLauncher::onAircraftInstalledCompleted(QModelIndex index)
935 maybeUpdateSelectedAircraft(index);
938 void QtLauncher::onRatingsFilterToggled()
940 QModelIndex aircraftIndex = m_aircraftModel->indexOfAircraftURI(m_selectedAircraft);
941 QModelIndex proxyIndex = m_aircraftProxy->mapFromSource(aircraftIndex);
942 if (proxyIndex.isValid()) {
943 m_ui->aircraftList->scrollTo(proxyIndex);
947 void QtLauncher::onAircraftInstallFailed(QModelIndex index, QString errorMessage)
949 qWarning() << Q_FUNC_INFO << index.data(AircraftURIRole) << errorMessage;
952 msg.setWindowTitle(tr("Aircraft installation failed"));
953 msg.setText(tr("An error occurred installing the aircraft %1: %2").
954 arg(index.data(Qt::DisplayRole).toString()).arg(errorMessage));
955 msg.addButton(QMessageBox::Ok);
958 maybeUpdateSelectedAircraft(index);
961 void QtLauncher::onAircraftSelected(const QModelIndex& index)
963 m_selectedAircraft = index.data(AircraftURIRole).toUrl();
964 updateSelectedAircraft();
967 void QtLauncher::onRequestPackageInstall(const QModelIndex& index)
969 // also select, otherwise UI is confusing
970 m_selectedAircraft = index.data(AircraftURIRole).toUrl();
971 updateSelectedAircraft();
973 QString pkg = index.data(AircraftPackageIdRole).toString();
974 simgear::pkg::PackageRef pref = globals->packageRoot()->getPackageById(pkg.toStdString());
975 if (pref->isInstalled()) {
976 InstallRef install = pref->existingInstall();
977 if (install && install->hasUpdate()) {
978 globals->packageRoot()->scheduleToUpdate(install);
985 void QtLauncher::onCancelDownload(const QModelIndex& index)
987 QString pkg = index.data(AircraftPackageIdRole).toString();
988 simgear::pkg::PackageRef pref = globals->packageRoot()->getPackageById(pkg.toStdString());
989 simgear::pkg::InstallRef i = pref->existingInstall();
993 void QtLauncher::onRestoreDefaults()
995 QMessageBox mbox(this);
996 mbox.setText(tr("Restore all settings to defaults?"));
997 mbox.setInformativeText(tr("Restoring settings to their defaults may affect available add-ons such as scenery or aircraft."));
998 QPushButton* quitButton = mbox.addButton(tr("Restore and restart now"), QMessageBox::YesRole);
999 mbox.addButton(QMessageBox::Cancel);
1000 mbox.setDefaultButton(QMessageBox::Cancel);
1001 mbox.setIconPixmap(QPixmap(":/app-icon-large"));
1004 if (mbox.clickedButton() != quitButton) {
1011 settings.setValue("restore-defaults-on-run", true);
1014 restartTheApp(QStringList());
1017 void QtLauncher::maybeUpdateSelectedAircraft(QModelIndex index)
1019 QUrl u = index.data(AircraftURIRole).toUrl();
1020 if (u == m_selectedAircraft) {
1021 // potentially enable the run button now!
1022 updateSelectedAircraft();
1026 void QtLauncher::updateSelectedAircraft()
1028 QModelIndex index = m_aircraftModel->indexOfAircraftURI(m_selectedAircraft);
1029 if (index.isValid()) {
1030 QPixmap pm = index.data(Qt::DecorationRole).value<QPixmap>();
1031 m_ui->thumbnail->setPixmap(pm);
1032 m_ui->aircraftDescription->setText(index.data(Qt::DisplayRole).toString());
1034 int status = index.data(AircraftPackageStatusRole).toInt();
1035 bool canRun = (status == PackageInstalled);
1036 m_ui->runButton->setEnabled(canRun);
1038 LauncherAircraftType aircraftType = Airplane;
1039 if (index.data(AircraftIsHelicopterRole).toBool()) {
1040 aircraftType = Helicopter;
1041 } else if (index.data(AircraftIsSeaplaneRole).toBool()) {
1042 aircraftType = Seaplane;
1045 m_ui->location->setAircraftType(aircraftType);
1047 m_ui->thumbnail->setPixmap(QPixmap());
1048 m_ui->aircraftDescription->setText("");
1049 m_ui->runButton->setEnabled(false);
1053 QModelIndex QtLauncher::proxyIndexForAircraftURI(QUrl uri) const
1055 return m_aircraftProxy->mapFromSource(sourceIndexForAircraftURI(uri));
1058 QModelIndex QtLauncher::sourceIndexForAircraftURI(QUrl uri) const
1060 AircraftItemModel* sourceModel = qobject_cast<AircraftItemModel*>(m_aircraftProxy->sourceModel());
1061 Q_ASSERT(sourceModel);
1062 return sourceModel->indexOfAircraftURI(uri);
1065 void QtLauncher::onPopupAircraftHistory()
1067 if (m_recentAircraft.isEmpty()) {
1072 Q_FOREACH(QUrl uri, m_recentAircraft) {
1073 QModelIndex index = sourceIndexForAircraftURI(uri);
1074 if (!index.isValid()) {
1078 QAction* act = m.addAction(index.data(Qt::DisplayRole).toString());
1082 QPoint popupPos = m_ui->aircraftHistory->mapToGlobal(m_ui->aircraftHistory->rect().bottomLeft());
1083 QAction* triggered = m.exec(popupPos);
1085 m_selectedAircraft = triggered->data().toUrl();
1086 QModelIndex index = proxyIndexForAircraftURI(m_selectedAircraft);
1087 m_ui->aircraftList->selectionModel()->setCurrentIndex(index,
1088 QItemSelectionModel::ClearAndSelect);
1089 m_ui->aircraftFilter->clear();
1090 updateSelectedAircraft();
1094 void QtLauncher::onEditRatingsFilter()
1096 EditRatingsFilterDialog dialog(this);
1097 dialog.setRatings(m_ratingFilters);
1100 if (dialog.result() == QDialog::Accepted) {
1102 for (int i=0; i<4; ++i) {
1103 m_ratingFilters[i] = dialog.getRating(i);
1104 vl.append(m_ratingFilters[i]);
1106 m_aircraftProxy->setRatings(m_ratingFilters);
1109 settings.setValue("min-ratings", vl);
1113 void QtLauncher::updateSettingsSummary()
1115 QStringList summary;
1116 if (m_ui->timeOfDayCombo->currentIndex() > 0) {
1117 summary.append(QString(m_ui->timeOfDayCombo->currentText().toLower()));
1120 if (m_ui->seasonCombo->currentIndex() > 0) {
1121 summary.append(QString(m_ui->seasonCombo->currentText().toLower()));
1124 if (m_ui->rembrandtCheckbox->isChecked()) {
1125 summary.append("Rembrandt enabled");
1126 } else if (m_ui->msaaCheckbox->isChecked()) {
1127 summary.append("anti-aliasing");
1130 if (m_ui->fetchRealWxrCheckbox->isChecked()) {
1131 summary.append("live weather");
1134 if (m_ui->terrasyncCheck->isChecked()) {
1135 summary.append("automatic scenery downloads");
1138 if (m_ui->startPausedCheck->isChecked()) {
1139 summary.append("paused");
1142 QString s = summary.join(", ");
1143 s[0] = s[0].toUpper();
1144 m_ui->settingsDescription->setText(s);
1147 void QtLauncher::onRembrandtToggled(bool b)
1149 // Rembrandt and multi-sample are exclusive
1150 m_ui->msaaCheckbox->setEnabled(!b);
1153 void QtLauncher::onShowInstalledAircraftToggled(bool b)
1155 m_ui->ratingsFilterCheck->setEnabled(!b);
1156 maybeRestoreAircraftSelection();
1159 void QtLauncher::onSubsytemIdleTimeout()
1161 globals->get_subsystem_mgr()->update(0.0);
1164 void QtLauncher::onDownloadDirChanged()
1166 // replace existing package root
1167 globals->get_subsystem<FGHTTPClient>()->shutdown();
1168 globals->setPackageRoot(simgear::pkg::RootRef());
1170 // create new root with updated download-dir value
1171 fgInitPackageRoot();
1173 globals->get_subsystem<FGHTTPClient>()->init();
1175 // re-scan the aircraft list
1177 m_aircraftModel->setPackageRoot(globals->packageRoot());
1178 m_aircraftModel->setPaths(settings.value("aircraft-paths").toStringList());
1179 m_aircraftModel->scanDirs();
1181 // re-set scenery dirs
1185 simgear::pkg::PackageRef QtLauncher::packageForAircraftURI(QUrl uri) const
1187 if (uri.scheme() != "package") {
1188 qWarning() << "invalid URL scheme:" << uri;
1189 return simgear::pkg::PackageRef();
1192 QString ident = uri.path();
1193 return globals->packageRoot()->getPackageById(ident.toStdString());
1196 void QtLauncher::restartTheApp(QStringList fgArgs)
1198 // Spawn a new instance of myApplication:
1202 #if defined(Q_OS_MAC)
1203 QDir dir(qApp->applicationDirPath()); // returns the 'MacOS' dir
1204 dir.cdUp(); // up to 'contents' dir
1205 dir.cdUp(); // up to .app dir
1206 // see 'man open' for details, but '-n' ensures we launch a new instance,
1207 // and we want to pass remaining arguments to us, not open.
1208 args << "-n" << dir.absolutePath() << "--args" << "--launcher" << fgArgs;
1209 qDebug() << "args" << args;
1210 proc.startDetached("open", args);
1212 args << "--launcher" << fgArgs;
1213 proc.startDetached(qApp->applicationFilePath(), args);
1218 #include "QtLauncher.moc"