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"
25 #include <QProgressDialog>
26 #include <QCoreApplication>
27 #include <QAbstractListModel>
36 #include <QSortFilterProxyModel>
38 #include <QDesktopServices>
41 #include <QFileDialog>
42 #include <QMessageBox>
44 #include <QApplication>
46 #include <QDoubleSpinBox>
49 #include <simgear/timing/timestamp.hxx>
50 #include <simgear/props/props_io.hxx>
51 #include <simgear/structure/exception.hxx>
52 #include <simgear/structure/subsystem_mgr.hxx>
53 #include <simgear/misc/sg_path.hxx>
54 #include <simgear/package/Catalog.hxx>
55 #include <simgear/package/Package.hxx>
56 #include <simgear/package/Install.hxx>
58 #include "ui_Launcher.h"
59 #include "EditRatingsFilterDialog.hxx"
60 #include "AircraftItemDelegate.hxx"
61 #include "AircraftModel.hxx"
62 #include "PathsDialog.hxx"
64 #include <Main/globals.hxx>
65 #include <Navaids/NavDataCache.hxx>
66 #include <Navaids/navrecord.hxx>
67 #include <Navaids/SHPParser.hxx>
69 #include <Main/options.hxx>
70 #include <Main/fg_init.hxx>
71 #include <Viewer/WindowBuilder.hxx>
72 #include <Network/HTTPClient.hxx>
74 using namespace flightgear;
75 using namespace simgear::pkg;
77 const int MAX_RECENT_AIRCRAFT = 20;
79 namespace { // anonymous namespace
83 QString baseLabel = QT_TR_NOOP("Initialising navigation data, this may take several minutes");
84 NavDataCache* cache = NavDataCache::createInstance();
85 if (cache->isRebuildRequired()) {
86 QProgressDialog rebuildProgress(baseLabel,
87 QString() /* cancel text */,
89 rebuildProgress.setWindowModality(Qt::WindowModal);
90 rebuildProgress.show();
92 NavDataCache::RebuildPhase phase = cache->rebuild();
94 while (phase != NavDataCache::REBUILD_DONE) {
95 // sleep to give the rebuild thread more time
96 SGTimeStamp::sleepForMSec(50);
97 phase = cache->rebuild();
100 case NavDataCache::REBUILD_AIRPORTS:
101 rebuildProgress.setLabelText(QT_TR_NOOP("Loading airport data"));
104 case NavDataCache::REBUILD_FIXES:
105 rebuildProgress.setLabelText(QT_TR_NOOP("Loading waypoint data"));
108 case NavDataCache::REBUILD_NAVAIDS:
109 rebuildProgress.setLabelText(QT_TR_NOOP("Loading navigation data"));
113 case NavDataCache::REBUILD_POIS:
114 rebuildProgress.setLabelText(QT_TR_NOOP("Loading point-of-interest data"));
118 rebuildProgress.setLabelText(baseLabel);
121 if (phase == NavDataCache::REBUILD_UNKNOWN) {
122 rebuildProgress.setValue(0);
123 rebuildProgress.setMaximum(0);
125 rebuildProgress.setValue(cache->rebuildPhaseCompletionPercentage());
126 rebuildProgress.setMaximum(100);
129 QCoreApplication::processEvents();
134 class ArgumentsTokenizer
140 explicit Arg(QString k, QString v = QString()) : arg(k), value(v) {}
146 QList<Arg> tokenize(QString in) const
149 const int len = in.count();
155 for (; index < len; ++index) {
157 nc = index < (len - 1) ? in.at(index + 1) : QChar();
161 if (c == QChar('-')) {
162 if (nc == QChar('-')) {
167 // should we pemit single hyphen arguments?
168 // choosing to fail for now
171 } else if (c == QChar('#')) {
174 } else if (c.isSpace()) {
180 if (c == QChar('=')) {
183 } else if (c.isSpace()) {
185 result.append(Arg(key));
187 // could check for illegal charatcers here
193 if (c == QChar('"')) {
195 } else if (c.isSpace()) {
197 result.append(Arg(key, value));
204 if (c == QChar('\\')) {
205 // check for escaped double-quote inside quoted value
206 if (nc == QChar('"')) {
209 } else if (c == QChar('"')) {
217 if ((c == QChar('\n')) || (c == QChar('\r'))) {
221 // nothing to do, eat comment chars
225 } // of character loop
227 // ensure last argument isn't lost
229 result.append(Arg(key));
230 } else if (state == Value) {
231 result.append(Arg(key, value));
247 } // of anonymous namespace
249 class AircraftProxyModel : public QSortFilterProxyModel
253 AircraftProxyModel(QObject* pr) :
254 QSortFilterProxyModel(pr),
255 m_ratingsFilter(true),
256 m_onlyShowInstalled(false)
258 for (int i=0; i<4; ++i) {
263 void setRatings(int* ratings)
265 ::memcpy(m_ratings, ratings, sizeof(int) * 4);
270 void setRatingFilterEnabled(bool e)
272 if (e == m_ratingsFilter) {
280 void setInstalledFilterEnabled(bool e)
282 if (e == m_onlyShowInstalled) {
286 m_onlyShowInstalled = e;
291 bool filterAcceptsRow(int sourceRow, const QModelIndex &sourceParent) const
293 if (!QSortFilterProxyModel::filterAcceptsRow(sourceRow, sourceParent)) {
297 if (m_onlyShowInstalled) {
298 QModelIndex index = sourceModel()->index(sourceRow, 0, sourceParent);
299 QVariant v = index.data(AircraftPackageStatusRole);
300 AircraftItemStatus status = static_cast<AircraftItemStatus>(v.toInt());
301 if (status == PackageNotInstalled) {
306 if (!m_onlyShowInstalled && m_ratingsFilter) {
307 QModelIndex index = sourceModel()->index(sourceRow, 0, sourceParent);
308 for (int i=0; i<4; ++i) {
309 if (m_ratings[i] > index.data(AircraftRatingRole + i).toInt()) {
319 bool m_ratingsFilter;
320 bool m_onlyShowInstalled;
324 static void initQtResources()
326 Q_INIT_RESOURCE(resources);
332 void initApp(int& argc, char** argv)
334 sglog().setLogLevels( SG_ALL, SG_INFO );
335 initQtResources(); // can't be called from a namespace
337 static bool qtInitDone = false;
342 s_argc = argc; // QApplication only stores a reference to argc,
343 // and may crash if it is freed
344 // http://doc.qt.io/qt-5/qguiapplication.html#QGuiApplication
346 QApplication* app = new QApplication(s_argc, argv);
347 app->setOrganizationName("FlightGear");
348 app->setApplicationName("FlightGear");
349 app->setOrganizationDomain("flightgear.org");
351 // avoid double Apple menu and other weirdness if both Qt and OSG
352 // try to initialise various Cocoa structures.
353 flightgear::WindowBuilder::setPoseAsStandaloneApp(false);
355 Qt::KeyboardModifiers mods = app->queryKeyboardModifiers();
356 if (mods & Qt::AltModifier) {
357 qWarning() << "Alt pressed during launch";
359 // wipe out our settings
364 Options::sharedInstance()->addOption("restore-defaults", "");
369 void loadNaturalEarthFile(const std::string& aFileName,
370 flightgear::PolyLine::Type aType,
373 SGPath path(globals->get_fg_root());
374 path.append( "Geodata" );
375 path.append(aFileName);
377 return; // silently fail for now
379 flightgear::PolyLineList lines;
380 flightgear::SHPParser::parsePolyLines(path, aType, lines, areClosed);
381 flightgear::PolyLine::bulkAddToSpatialIndex(lines);
384 void loadNaturalEarthData()
389 loadNaturalEarthFile("ne_10m_coastline.shp", flightgear::PolyLine::COASTLINE, false);
390 loadNaturalEarthFile("ne_10m_rivers_lake_centerlines.shp", flightgear::PolyLine::RIVER, false);
391 loadNaturalEarthFile("ne_10m_lakes.shp", flightgear::PolyLine::LAKE, true);
393 qDebug() << "load basic data took" << st.elapsedMSec();
397 loadNaturalEarthFile("ne_10m_urban_areas.shp", flightgear::PolyLine::URBAN, true);
399 qDebug() << "loading urban areas took:" << st.elapsedMSec();
402 bool runLauncherDialog()
404 // startup the nav-cache now. This pre-empts normal startup of
405 // the cache, but no harm done. (Providing scenery paths are consistent)
411 // startup the HTTP system now since packages needs it
412 FGHTTPClient* http = new FGHTTPClient;
413 globals->add_subsystem("http", http);
414 // we guard against re-init in the global phase; bind and postinit
415 // will happen as normal
418 loadNaturalEarthData();
420 // setup scenery paths now, especially TerraSync path for airport
421 // parking locations (after they're downloaded)
425 if (dlg.result() != QDialog::Accepted) {
432 bool runInAppLauncherDialog()
437 if (dlg.result() != QDialog::Accepted) {
444 } // of namespace flightgear
446 QtLauncher::QtLauncher() :
449 m_subsystemIdleTimer(NULL),
452 m_ui.reset(new Ui::Launcher);
455 #if QT_VERSION >= 0x050300
456 // don't require Qt 5.3
457 m_ui->commandLineArgs->setPlaceholderText("--option=value --prop:/sim/name=value");
460 #if QT_VERSION >= 0x050200
461 m_ui->aircraftFilter->setClearButtonEnabled(true);
464 for (int i=0; i<4; ++i) {
465 m_ratingFilters[i] = 3;
468 m_subsystemIdleTimer = new QTimer(this);
469 m_subsystemIdleTimer->setInterval(0);
470 connect(m_subsystemIdleTimer, &QTimer::timeout,
471 this, &QtLauncher::onSubsytemIdleTimeout);
472 m_subsystemIdleTimer->start();
474 // create and configure the proxy model
475 m_aircraftProxy = new AircraftProxyModel(this);
476 connect(m_ui->ratingsFilterCheck, &QAbstractButton::toggled,
477 m_aircraftProxy, &AircraftProxyModel::setRatingFilterEnabled);
478 connect(m_ui->ratingsFilterCheck, &QAbstractButton::toggled,
479 this, &QtLauncher::maybeRestoreAircraftSelection);
481 connect(m_ui->onlyShowInstalledCheck, &QAbstractButton::toggled,
482 m_aircraftProxy, &AircraftProxyModel::setInstalledFilterEnabled);
483 connect(m_ui->aircraftFilter, &QLineEdit::textChanged,
484 m_aircraftProxy, &QSortFilterProxyModel::setFilterFixedString);
486 connect(m_ui->runButton, SIGNAL(clicked()), this, SLOT(onRun()));
487 connect(m_ui->quitButton, SIGNAL(clicked()), this, SLOT(onQuit()));
489 connect(m_ui->aircraftHistory, &QPushButton::clicked,
490 this, &QtLauncher::onPopupAircraftHistory);
492 connect(m_ui->location, &LocationWidget::descriptionChanged,
493 m_ui->locationDescription, &QLabel::setText);
495 QAction* qa = new QAction(this);
496 qa->setShortcut(QKeySequence("Ctrl+Q"));
497 connect(qa, &QAction::triggered, this, &QtLauncher::onQuit);
500 connect(m_ui->editRatingFilter, &QPushButton::clicked,
501 this, &QtLauncher::onEditRatingsFilter);
502 connect(m_ui->onlyShowInstalledCheck, &QCheckBox::toggled,
503 this, &QtLauncher::onShowInstalledAircraftToggled);
505 QIcon historyIcon(":/history-icon");
506 m_ui->aircraftHistory->setIcon(historyIcon);
508 connect(m_ui->timeOfDayCombo, SIGNAL(currentIndexChanged(int)),
509 this, SLOT(updateSettingsSummary()));
510 connect(m_ui->seasonCombo, SIGNAL(currentIndexChanged(int)),
511 this, SLOT(updateSettingsSummary()));
512 connect(m_ui->fetchRealWxrCheckbox, SIGNAL(toggled(bool)),
513 this, SLOT(updateSettingsSummary()));
514 connect(m_ui->rembrandtCheckbox, SIGNAL(toggled(bool)),
515 this, SLOT(updateSettingsSummary()));
516 connect(m_ui->terrasyncCheck, SIGNAL(toggled(bool)),
517 this, SLOT(updateSettingsSummary()));
518 connect(m_ui->startPausedCheck, SIGNAL(toggled(bool)),
519 this, SLOT(updateSettingsSummary()));
520 connect(m_ui->msaaCheckbox, SIGNAL(toggled(bool)),
521 this, SLOT(updateSettingsSummary()));
523 connect(m_ui->rembrandtCheckbox, SIGNAL(toggled(bool)),
524 this, SLOT(onRembrandtToggled(bool)));
525 connect(m_ui->terrasyncCheck, &QCheckBox::toggled,
526 this, &QtLauncher::onToggleTerrasync);
527 updateSettingsSummary();
529 m_aircraftModel = new AircraftItemModel(this, RootRef(globals->packageRoot()));
530 m_aircraftProxy->setSourceModel(m_aircraftModel);
532 m_aircraftProxy->setFilterCaseSensitivity(Qt::CaseInsensitive);
533 m_aircraftProxy->setSortCaseSensitivity(Qt::CaseInsensitive);
534 m_aircraftProxy->setSortRole(Qt::DisplayRole);
535 m_aircraftProxy->setDynamicSortFilter(true);
537 m_ui->aircraftList->setModel(m_aircraftProxy);
538 m_ui->aircraftList->setHorizontalScrollBarPolicy(Qt::ScrollBarAlwaysOff);
539 AircraftItemDelegate* delegate = new AircraftItemDelegate(m_ui->aircraftList);
540 m_ui->aircraftList->setItemDelegate(delegate);
541 m_ui->aircraftList->setSelectionMode(QAbstractItemView::SingleSelection);
542 connect(m_ui->aircraftList, &QListView::clicked,
543 this, &QtLauncher::onAircraftSelected);
544 connect(delegate, &AircraftItemDelegate::variantChanged,
545 this, &QtLauncher::onAircraftSelected);
546 connect(delegate, &AircraftItemDelegate::requestInstall,
547 this, &QtLauncher::onRequestPackageInstall);
548 connect(delegate, &AircraftItemDelegate::cancelDownload,
549 this, &QtLauncher::onCancelDownload);
551 connect(m_aircraftModel, &AircraftItemModel::aircraftInstallCompleted,
552 this, &QtLauncher::onAircraftInstalledCompleted);
553 connect(m_aircraftModel, &AircraftItemModel::aircraftInstallFailed,
554 this, &QtLauncher::onAircraftInstallFailed);
555 connect(m_aircraftModel, &AircraftItemModel::scanCompleted,
556 this, &QtLauncher::updateSelectedAircraft);
557 connect(m_ui->pathsButton, &QPushButton::clicked,
558 this, &QtLauncher::onEditPaths);
560 // after any kind of reset, try to restore selection and scroll
561 // to match the m_selectedAircraft. This needs to be delayed
562 // fractionally otherwise the scrollTo seems to be ignored,
564 connect(m_aircraftProxy, &AircraftProxyModel::modelReset,
565 this, &QtLauncher::delayedAircraftModelReset);
570 m_aircraftModel->setPaths(settings.value("aircraft-paths").toStringList());
571 m_aircraftModel->scanDirs();
574 QtLauncher::~QtLauncher()
579 void QtLauncher::setInAppMode()
582 m_ui->tabWidget->removeTab(2);
583 m_ui->runButton->setText(tr("Apply"));
584 m_ui->quitButton->setText(tr("Cancel"));
586 disconnect(m_ui->runButton, SIGNAL(clicked()), this, SLOT(onRun()));
587 connect(m_ui->runButton, SIGNAL(clicked()), this, SLOT(onApply()));
590 void QtLauncher::restoreSettings()
593 m_ui->rembrandtCheckbox->setChecked(settings.value("enable-rembrandt", false).toBool());
594 m_ui->terrasyncCheck->setChecked(settings.value("enable-terrasync", true).toBool());
595 m_ui->fullScreenCheckbox->setChecked(settings.value("start-fullscreen", false).toBool());
596 m_ui->msaaCheckbox->setChecked(settings.value("enable-msaa", false).toBool());
597 m_ui->fetchRealWxrCheckbox->setChecked(settings.value("enable-realwx", true).toBool());
598 m_ui->startPausedCheck->setChecked(settings.value("start-paused", false).toBool());
599 m_ui->timeOfDayCombo->setCurrentIndex(settings.value("timeofday", 0).toInt());
600 m_ui->seasonCombo->setCurrentIndex(settings.value("season", 0).toInt());
602 // full paths to -set.xml files
603 m_recentAircraft = QUrl::fromStringList(settings.value("recent-aircraft").toStringList());
605 if (!m_recentAircraft.empty()) {
606 m_selectedAircraft = m_recentAircraft.front();
608 // select the default C172p
611 updateSelectedAircraft();
612 m_ui->location->restoreSettings();
615 m_ui->onlyShowInstalledCheck->setChecked(settings.value("only-show-installed", false).toBool());
616 if (m_ui->onlyShowInstalledCheck->isChecked()) {
617 m_ui->ratingsFilterCheck->setEnabled(false);
620 m_ui->ratingsFilterCheck->setChecked(settings.value("ratings-filter", true).toBool());
622 Q_FOREACH(QVariant v, settings.value("min-ratings").toList()) {
623 m_ratingFilters[index++] = v.toInt();
626 m_aircraftProxy->setRatingFilterEnabled(m_ui->ratingsFilterCheck->isChecked());
627 m_aircraftProxy->setRatings(m_ratingFilters);
629 updateSelectedAircraft();
630 maybeRestoreAircraftSelection();
632 m_ui->commandLineArgs->setPlainText(settings.value("additional-args").toString());
635 void QtLauncher::delayedAircraftModelReset()
637 QTimer::singleShot(1, this, &QtLauncher::maybeRestoreAircraftSelection);
640 void QtLauncher::maybeRestoreAircraftSelection()
642 QModelIndex aircraftIndex = m_aircraftModel->indexOfAircraftURI(m_selectedAircraft);
643 QModelIndex proxyIndex = m_aircraftProxy->mapFromSource(aircraftIndex);
644 if (proxyIndex.isValid()) {
645 m_ui->aircraftList->selectionModel()->setCurrentIndex(proxyIndex,
646 QItemSelectionModel::ClearAndSelect);
647 m_ui->aircraftList->selectionModel()->select(proxyIndex,
648 QItemSelectionModel::ClearAndSelect);
649 m_ui->aircraftList->scrollTo(proxyIndex);
653 void QtLauncher::saveSettings()
656 settings.setValue("enable-rembrandt", m_ui->rembrandtCheckbox->isChecked());
657 settings.setValue("enable-terrasync", m_ui->terrasyncCheck->isChecked());
658 settings.setValue("enable-msaa", m_ui->msaaCheckbox->isChecked());
659 settings.setValue("start-fullscreen", m_ui->fullScreenCheckbox->isChecked());
660 settings.setValue("enable-realwx", m_ui->fetchRealWxrCheckbox->isChecked());
661 settings.setValue("start-paused", m_ui->startPausedCheck->isChecked());
662 settings.setValue("ratings-filter", m_ui->ratingsFilterCheck->isChecked());
663 settings.setValue("only-show-installed", m_ui->onlyShowInstalledCheck->isChecked());
664 settings.setValue("recent-aircraft", QUrl::toStringList(m_recentAircraft));
666 settings.setValue("timeofday", m_ui->timeOfDayCombo->currentIndex());
667 settings.setValue("season", m_ui->seasonCombo->currentIndex());
668 settings.setValue("additional-args", m_ui->commandLineArgs->toPlainText());
670 m_ui->location->saveSettings();
673 void QtLauncher::setEnableDisableOptionFromCheckbox(QCheckBox* cbox, QString name) const
675 flightgear::Options* opt = flightgear::Options::sharedInstance();
676 std::string stdName(name.toStdString());
677 if (cbox->isChecked()) {
678 opt->addOption("enable-" + stdName, "");
680 opt->addOption("disable-" + stdName, "");
684 void QtLauncher::onRun()
688 flightgear::Options* opt = flightgear::Options::sharedInstance();
689 setEnableDisableOptionFromCheckbox(m_ui->terrasyncCheck, "terrasync");
690 setEnableDisableOptionFromCheckbox(m_ui->fetchRealWxrCheckbox, "real-weather-fetch");
691 setEnableDisableOptionFromCheckbox(m_ui->rembrandtCheckbox, "rembrandt");
692 setEnableDisableOptionFromCheckbox(m_ui->fullScreenCheckbox, "fullscreen");
693 // setEnableDisableOptionFromCheckbox(m_ui->startPausedCheck, "freeze");
695 bool startPaused = m_ui->startPausedCheck->isChecked() ||
696 m_ui->location->shouldStartPaused();
698 opt->addOption("enable-freeze", "");
701 // MSAA is more complex
702 if (!m_ui->rembrandtCheckbox->isChecked()) {
703 if (m_ui->msaaCheckbox->isChecked()) {
704 globals->get_props()->setIntValue("/sim/rendering/multi-sample-buffers", 1);
705 globals->get_props()->setIntValue("/sim/rendering/multi-samples", 4);
707 globals->get_props()->setIntValue("/sim/rendering/multi-sample-buffers", 0);
712 if (!m_selectedAircraft.isEmpty()) {
713 if (m_selectedAircraft.isLocalFile()) {
714 QFileInfo setFileInfo(m_selectedAircraft.toLocalFile());
715 opt->addOption("aircraft-dir", setFileInfo.dir().absolutePath().toStdString());
716 QString setFile = setFileInfo.fileName();
717 Q_ASSERT(setFile.endsWith("-set.xml"));
718 setFile.truncate(setFile.count() - 8); // drop the '-set.xml' portion
719 opt->addOption("aircraft", setFile.toStdString());
720 } else if (m_selectedAircraft.scheme() == "package") {
721 QString qualifiedId = m_selectedAircraft.path();
722 // no need to set aircraft-dir, handled by the corresponding code
724 opt->addOption("aircraft", qualifiedId.toStdString());
726 qWarning() << "unsupported aircraft launch URL" << m_selectedAircraft;
729 // manage aircraft history
730 if (m_recentAircraft.contains(m_selectedAircraft))
731 m_recentAircraft.removeOne(m_selectedAircraft);
732 m_recentAircraft.prepend(m_selectedAircraft);
733 if (m_recentAircraft.size() > MAX_RECENT_AIRCRAFT)
734 m_recentAircraft.pop_back();
737 m_ui->location->setLocationOptions();
740 if (m_ui->timeOfDayCombo->currentIndex() != 0) {
741 QString dayval = m_ui->timeOfDayCombo->currentText().toLower();
742 opt->addOption("timeofday", dayval.toStdString());
745 if (m_ui->seasonCombo->currentIndex() != 0) {
746 QString dayval = m_ui->timeOfDayCombo->currentText().toLower();
747 opt->addOption("season", dayval.toStdString());
751 QString downloadDir = settings.value("download-dir").toString();
752 if (!downloadDir.isEmpty()) {
755 int result = QMessageBox::question(this, tr("Create download folder?"),
756 tr("The selected location for downloads does not exist. Create it?"),
757 QMessageBox::Yes | QMessageBox::No | QMessageBox::Cancel);
758 if (result == QMessageBox::Cancel) {
762 if (result == QMessageBox::Yes) {
763 d.mkpath(downloadDir);
767 opt->addOption("download-dir", downloadDir.toStdString());
771 Q_FOREACH(QString path, settings.value("scenery-paths").toStringList()) {
772 opt->addOption("fg-scenery", path.toStdString());
776 Q_FOREACH(QString path, settings.value("aircraft-paths").toStringList()) {
777 // can't use fg-aircraft for this, as it is processed before the launcher is run
778 globals->append_aircraft_path(path.toStdString());
781 // additional arguments
782 ArgumentsTokenizer tk;
783 Q_FOREACH(ArgumentsTokenizer::Arg a, tk.tokenize(m_ui->commandLineArgs->toPlainText())) {
784 if (a.arg.startsWith("prop:")) {
785 QString v = a.arg.mid(5) + "=" + a.value;
786 opt->addOption("prop", v.toStdString());
788 opt->addOption(a.arg.toStdString(), a.value.toStdString());
796 void QtLauncher::onApply()
801 if (!m_selectedAircraft.isEmpty()) {
802 std::string aircraftPropValue,
805 if (m_selectedAircraft.isLocalFile()) {
806 QFileInfo setFileInfo(m_selectedAircraft.toLocalFile());
807 QString setFile = setFileInfo.fileName();
808 Q_ASSERT(setFile.endsWith("-set.xml"));
809 setFile.truncate(setFile.count() - 8); // drop the '-set.xml' portion
810 aircraftDir = setFileInfo.dir().absolutePath().toStdString();
811 aircraftPropValue = setFile.toStdString();
812 } else if (m_selectedAircraft.scheme() == "package") {
813 // no need to set aircraft-dir, handled by the corresponding code
815 aircraftPropValue = m_selectedAircraft.path().toStdString();
817 qWarning() << "unsupported aircraft launch URL" << m_selectedAircraft;
820 // manage aircraft history
821 if (m_recentAircraft.contains(m_selectedAircraft))
822 m_recentAircraft.removeOne(m_selectedAircraft);
823 m_recentAircraft.prepend(m_selectedAircraft);
824 if (m_recentAircraft.size() > MAX_RECENT_AIRCRAFT)
825 m_recentAircraft.pop_back();
827 globals->get_props()->setStringValue("/sim/aircraft", aircraftPropValue);
828 globals->get_props()->setStringValue("/sim/aircraft-dir", aircraftDir);
835 void QtLauncher::onQuit()
840 void QtLauncher::onToggleTerrasync(bool enabled)
844 QString downloadDir = settings.value("download-dir").toString();
845 if (downloadDir.isEmpty()) {
846 downloadDir = QString::fromStdString(flightgear::defaultDownloadDir());
849 QFileInfo info(downloadDir);
850 if (!info.exists()) {
852 msg.setWindowTitle(tr("Create download folder?"));
853 msg.setText(tr("The download folder '%1' does not exist, create it now? "
854 "Click 'change location' to choose another folder "
855 "to store downloaded files").arg(downloadDir));
856 msg.addButton(QMessageBox::Yes);
857 msg.addButton(QMessageBox::Cancel);
858 msg.addButton(tr("Change location"), QMessageBox::ActionRole);
859 int result = msg.exec();
861 if (result == QMessageBox::Cancel) {
862 m_ui->terrasyncCheck->setChecked(false);
866 if (result == QMessageBox::ActionRole) {
872 d.mkpath(downloadDir);
877 void QtLauncher::onAircraftInstalledCompleted(QModelIndex index)
879 maybeUpdateSelectedAircraft(index);
882 void QtLauncher::onRatingsFilterToggled()
884 QModelIndex aircraftIndex = m_aircraftModel->indexOfAircraftURI(m_selectedAircraft);
885 QModelIndex proxyIndex = m_aircraftProxy->mapFromSource(aircraftIndex);
886 if (proxyIndex.isValid()) {
887 m_ui->aircraftList->scrollTo(proxyIndex);
891 void QtLauncher::onAircraftInstallFailed(QModelIndex index, QString errorMessage)
893 qWarning() << Q_FUNC_INFO << index.data(AircraftURIRole) << errorMessage;
896 msg.setWindowTitle(tr("Aircraft installation failed"));
897 msg.setText(tr("An error occurred installing the aircraft %1: %2").
898 arg(index.data(Qt::DisplayRole).toString()).arg(errorMessage));
899 msg.addButton(QMessageBox::Ok);
902 maybeUpdateSelectedAircraft(index);
905 void QtLauncher::onAircraftSelected(const QModelIndex& index)
907 m_selectedAircraft = index.data(AircraftURIRole).toUrl();
908 updateSelectedAircraft();
911 void QtLauncher::onRequestPackageInstall(const QModelIndex& index)
913 // also select, otherwise UI is confusing
914 m_selectedAircraft = index.data(AircraftURIRole).toUrl();
915 updateSelectedAircraft();
917 QString pkg = index.data(AircraftPackageIdRole).toString();
918 simgear::pkg::PackageRef pref = globals->packageRoot()->getPackageById(pkg.toStdString());
919 if (pref->isInstalled()) {
920 InstallRef install = pref->existingInstall();
921 if (install && install->hasUpdate()) {
922 globals->packageRoot()->scheduleToUpdate(install);
929 void QtLauncher::onCancelDownload(const QModelIndex& index)
931 QString pkg = index.data(AircraftPackageIdRole).toString();
932 simgear::pkg::PackageRef pref = globals->packageRoot()->getPackageById(pkg.toStdString());
933 simgear::pkg::InstallRef i = pref->existingInstall();
937 void QtLauncher::maybeUpdateSelectedAircraft(QModelIndex index)
939 QUrl u = index.data(AircraftURIRole).toUrl();
940 if (u == m_selectedAircraft) {
941 // potentially enable the run button now!
942 updateSelectedAircraft();
946 void QtLauncher::updateSelectedAircraft()
948 QModelIndex index = m_aircraftModel->indexOfAircraftURI(m_selectedAircraft);
949 if (index.isValid()) {
950 QPixmap pm = index.data(Qt::DecorationRole).value<QPixmap>();
951 m_ui->thumbnail->setPixmap(pm);
952 m_ui->aircraftDescription->setText(index.data(Qt::DisplayRole).toString());
954 int status = index.data(AircraftPackageStatusRole).toInt();
955 bool canRun = (status == PackageInstalled);
956 m_ui->runButton->setEnabled(canRun);
958 LauncherAircraftType aircraftType = Airplane;
959 if (index.data(AircraftIsHelicopterRole).toBool()) {
960 aircraftType = Helicopter;
961 } else if (index.data(AircraftIsSeaplaneRole).toBool()) {
962 aircraftType = Seaplane;
965 m_ui->location->setAircraftType(aircraftType);
967 m_ui->thumbnail->setPixmap(QPixmap());
968 m_ui->aircraftDescription->setText("");
969 m_ui->runButton->setEnabled(false);
973 QModelIndex QtLauncher::proxyIndexForAircraftURI(QUrl uri) const
975 return m_aircraftProxy->mapFromSource(sourceIndexForAircraftURI(uri));
978 QModelIndex QtLauncher::sourceIndexForAircraftURI(QUrl uri) const
980 AircraftItemModel* sourceModel = qobject_cast<AircraftItemModel*>(m_aircraftProxy->sourceModel());
981 Q_ASSERT(sourceModel);
982 return sourceModel->indexOfAircraftURI(uri);
985 void QtLauncher::onPopupAircraftHistory()
987 if (m_recentAircraft.isEmpty()) {
992 Q_FOREACH(QUrl uri, m_recentAircraft) {
993 QModelIndex index = sourceIndexForAircraftURI(uri);
994 if (!index.isValid()) {
998 QAction* act = m.addAction(index.data(Qt::DisplayRole).toString());
1002 QPoint popupPos = m_ui->aircraftHistory->mapToGlobal(m_ui->aircraftHistory->rect().bottomLeft());
1003 QAction* triggered = m.exec(popupPos);
1005 m_selectedAircraft = triggered->data().toUrl();
1006 QModelIndex index = proxyIndexForAircraftURI(m_selectedAircraft);
1007 m_ui->aircraftList->selectionModel()->setCurrentIndex(index,
1008 QItemSelectionModel::ClearAndSelect);
1009 m_ui->aircraftFilter->clear();
1010 updateSelectedAircraft();
1014 void QtLauncher::onEditRatingsFilter()
1016 EditRatingsFilterDialog dialog(this);
1017 dialog.setRatings(m_ratingFilters);
1020 if (dialog.result() == QDialog::Accepted) {
1022 for (int i=0; i<4; ++i) {
1023 m_ratingFilters[i] = dialog.getRating(i);
1024 vl.append(m_ratingFilters[i]);
1026 m_aircraftProxy->setRatings(m_ratingFilters);
1029 settings.setValue("min-ratings", vl);
1033 void QtLauncher::updateSettingsSummary()
1035 QStringList summary;
1036 if (m_ui->timeOfDayCombo->currentIndex() > 0) {
1037 summary.append(QString(m_ui->timeOfDayCombo->currentText().toLower()));
1040 if (m_ui->seasonCombo->currentIndex() > 0) {
1041 summary.append(QString(m_ui->seasonCombo->currentText().toLower()));
1044 if (m_ui->rembrandtCheckbox->isChecked()) {
1045 summary.append("Rembrandt enabled");
1046 } else if (m_ui->msaaCheckbox->isChecked()) {
1047 summary.append("anti-aliasing");
1050 if (m_ui->fetchRealWxrCheckbox->isChecked()) {
1051 summary.append("live weather");
1054 if (m_ui->terrasyncCheck->isChecked()) {
1055 summary.append("automatic scenery downloads");
1058 if (m_ui->startPausedCheck->isChecked()) {
1059 summary.append("paused");
1062 QString s = summary.join(", ");
1063 s[0] = s[0].toUpper();
1064 m_ui->settingsDescription->setText(s);
1067 void QtLauncher::onRembrandtToggled(bool b)
1069 // Rembrandt and multi-sample are exclusive
1070 m_ui->msaaCheckbox->setEnabled(!b);
1073 void QtLauncher::onShowInstalledAircraftToggled(bool b)
1075 m_ui->ratingsFilterCheck->setEnabled(!b);
1076 maybeRestoreAircraftSelection();
1079 void QtLauncher::onSubsytemIdleTimeout()
1081 globals->get_subsystem_mgr()->update(0.0);
1084 void QtLauncher::onEditPaths()
1086 PathsDialog dlg(this, globals->packageRoot());
1088 if (dlg.result() == QDialog::Accepted) {
1089 // re-scan the aircraft list
1091 m_aircraftModel->setPaths(settings.value("aircraft-paths").toStringList());
1092 m_aircraftModel->scanDirs();
1096 simgear::pkg::PackageRef QtLauncher::packageForAircraftURI(QUrl uri) const
1098 if (uri.scheme() != "package") {
1099 qWarning() << "invalid URL scheme:" << uri;
1100 return simgear::pkg::PackageRef();
1103 QString ident = uri.path();
1104 return globals->packageRoot()->getPackageById(ident.toStdString());
1108 #include "QtLauncher.moc"