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 QApplication* app = new QApplication(s_argc, argv);
351 app->setOrganizationName("FlightGear");
352 app->setApplicationName("FlightGear");
353 app->setOrganizationDomain("flightgear.org");
355 // reset numeric / collation locales as described at:
356 // http://doc.qt.io/qt-5/qcoreapplication.html#details
357 ::setlocale(LC_NUMERIC, "C");
358 ::setlocale(LC_COLLATE, "C");
360 Qt::KeyboardModifiers mods = app->queryKeyboardModifiers();
361 if (mods & (Qt::AltModifier | Qt::ShiftModifier)) {
362 qWarning() << "Alt/shift pressed during launch";
364 // wipe out our settings
368 settings.setValue("fg-root", "!ask");
370 Options::sharedInstance()->addOption("restore-defaults", "");
375 void loadNaturalEarthFile(const std::string& aFileName,
376 flightgear::PolyLine::Type aType,
379 SGPath path(globals->get_fg_root());
380 path.append( "Geodata" );
381 path.append(aFileName);
383 return; // silently fail for now
385 flightgear::PolyLineList lines;
386 flightgear::SHPParser::parsePolyLines(path, aType, lines, areClosed);
387 flightgear::PolyLine::bulkAddToSpatialIndex(lines);
390 void loadNaturalEarthData()
395 loadNaturalEarthFile("ne_10m_coastline.shp", flightgear::PolyLine::COASTLINE, false);
396 loadNaturalEarthFile("ne_10m_rivers_lake_centerlines.shp", flightgear::PolyLine::RIVER, false);
397 loadNaturalEarthFile("ne_10m_lakes.shp", flightgear::PolyLine::LAKE, true);
399 qDebug() << "load basic data took" << st.elapsedMSec();
403 loadNaturalEarthFile("ne_10m_urban_areas.shp", flightgear::PolyLine::URBAN, true);
405 qDebug() << "loading urban areas took:" << st.elapsedMSec();
408 bool runLauncherDialog()
410 // startup the nav-cache now. This pre-empts normal startup of
411 // the cache, but no harm done. (Providing scenery paths are consistent)
416 QString downloadDir = settings.value("download-dir").toString();
417 if (!downloadDir.isEmpty()) {
418 flightgear::Options::sharedInstance()->setOption("download-dir", downloadDir.toStdString());
423 // startup the HTTP system now since packages needs it
424 FGHTTPClient* http = globals->add_new_subsystem<FGHTTPClient>();
426 // we guard against re-init in the global phase; bind and postinit
427 // will happen as normal
430 loadNaturalEarthData();
432 // avoid double Apple menu and other weirdness if both Qt and OSG
433 // try to initialise various Cocoa structures.
434 flightgear::WindowBuilder::setPoseAsStandaloneApp(false);
439 int appResult = qApp->exec();
441 return false; // quit
444 // don't set scenery paths twice
445 globals->clear_fg_scenery();
450 bool runInAppLauncherDialog()
455 if (dlg.result() != QDialog::Accepted) {
462 } // of namespace flightgear
464 QtLauncher::QtLauncher() :
467 m_subsystemIdleTimer(NULL),
470 m_ui.reset(new Ui::Launcher);
473 #if QT_VERSION >= 0x050300
474 // don't require Qt 5.3
475 m_ui->commandLineArgs->setPlaceholderText("--option=value --prop:/sim/name=value");
478 #if QT_VERSION >= 0x050200
479 m_ui->aircraftFilter->setClearButtonEnabled(true);
482 for (int i=0; i<4; ++i) {
483 m_ratingFilters[i] = 3;
486 m_subsystemIdleTimer = new QTimer(this);
487 m_subsystemIdleTimer->setInterval(0);
488 connect(m_subsystemIdleTimer, &QTimer::timeout,
489 this, &QtLauncher::onSubsytemIdleTimeout);
490 m_subsystemIdleTimer->start();
492 // create and configure the proxy model
493 m_aircraftProxy = new AircraftProxyModel(this);
494 connect(m_ui->ratingsFilterCheck, &QAbstractButton::toggled,
495 m_aircraftProxy, &AircraftProxyModel::setRatingFilterEnabled);
496 connect(m_ui->ratingsFilterCheck, &QAbstractButton::toggled,
497 this, &QtLauncher::maybeRestoreAircraftSelection);
499 connect(m_ui->onlyShowInstalledCheck, &QAbstractButton::toggled,
500 m_aircraftProxy, &AircraftProxyModel::setInstalledFilterEnabled);
501 connect(m_ui->aircraftFilter, &QLineEdit::textChanged,
502 m_aircraftProxy, &QSortFilterProxyModel::setFilterFixedString);
504 connect(m_ui->runButton, SIGNAL(clicked()), this, SLOT(onRun()));
505 connect(m_ui->quitButton, SIGNAL(clicked()), this, SLOT(onQuit()));
507 connect(m_ui->changeRootButton, SIGNAL(clicked()), this, SLOT(onChangeRoot()));
509 connect(m_ui->aircraftHistory, &QPushButton::clicked,
510 this, &QtLauncher::onPopupAircraftHistory);
512 connect(m_ui->location, &LocationWidget::descriptionChanged,
513 m_ui->locationDescription, &QLabel::setText);
515 QAction* qa = new QAction(this);
516 qa->setShortcut(QKeySequence("Ctrl+Q"));
517 connect(qa, &QAction::triggered, this, &QtLauncher::onQuit);
520 connect(m_ui->editRatingFilter, &QPushButton::clicked,
521 this, &QtLauncher::onEditRatingsFilter);
522 connect(m_ui->onlyShowInstalledCheck, &QCheckBox::toggled,
523 this, &QtLauncher::onShowInstalledAircraftToggled);
525 QIcon historyIcon(":/history-icon");
526 m_ui->aircraftHistory->setIcon(historyIcon);
528 connect(m_ui->timeOfDayCombo, SIGNAL(currentIndexChanged(int)),
529 this, SLOT(updateSettingsSummary()));
530 connect(m_ui->seasonCombo, SIGNAL(currentIndexChanged(int)),
531 this, SLOT(updateSettingsSummary()));
532 connect(m_ui->fetchRealWxrCheckbox, SIGNAL(toggled(bool)),
533 this, SLOT(updateSettingsSummary()));
534 connect(m_ui->rembrandtCheckbox, SIGNAL(toggled(bool)),
535 this, SLOT(updateSettingsSummary()));
536 connect(m_ui->terrasyncCheck, SIGNAL(toggled(bool)),
537 this, SLOT(updateSettingsSummary()));
538 connect(m_ui->startPausedCheck, SIGNAL(toggled(bool)),
539 this, SLOT(updateSettingsSummary()));
540 connect(m_ui->msaaCheckbox, SIGNAL(toggled(bool)),
541 this, SLOT(updateSettingsSummary()));
543 connect(m_ui->rembrandtCheckbox, SIGNAL(toggled(bool)),
544 this, SLOT(onRembrandtToggled(bool)));
545 connect(m_ui->terrasyncCheck, &QCheckBox::toggled,
546 this, &QtLauncher::onToggleTerrasync);
547 updateSettingsSummary();
549 m_aircraftModel = new AircraftItemModel(this);
550 m_aircraftProxy->setSourceModel(m_aircraftModel);
552 m_aircraftProxy->setFilterCaseSensitivity(Qt::CaseInsensitive);
553 m_aircraftProxy->setSortCaseSensitivity(Qt::CaseInsensitive);
554 m_aircraftProxy->setSortRole(Qt::DisplayRole);
555 m_aircraftProxy->setDynamicSortFilter(true);
557 m_ui->aircraftList->setModel(m_aircraftProxy);
558 m_ui->aircraftList->setHorizontalScrollBarPolicy(Qt::ScrollBarAlwaysOff);
559 AircraftItemDelegate* delegate = new AircraftItemDelegate(m_ui->aircraftList);
560 m_ui->aircraftList->setItemDelegate(delegate);
561 m_ui->aircraftList->setSelectionMode(QAbstractItemView::SingleSelection);
562 connect(m_ui->aircraftList, &QListView::clicked,
563 this, &QtLauncher::onAircraftSelected);
564 connect(delegate, &AircraftItemDelegate::variantChanged,
565 this, &QtLauncher::onAircraftSelected);
566 connect(delegate, &AircraftItemDelegate::requestInstall,
567 this, &QtLauncher::onRequestPackageInstall);
568 connect(delegate, &AircraftItemDelegate::cancelDownload,
569 this, &QtLauncher::onCancelDownload);
571 connect(m_aircraftModel, &AircraftItemModel::aircraftInstallCompleted,
572 this, &QtLauncher::onAircraftInstalledCompleted);
573 connect(m_aircraftModel, &AircraftItemModel::aircraftInstallFailed,
574 this, &QtLauncher::onAircraftInstallFailed);
575 connect(m_aircraftModel, &AircraftItemModel::scanCompleted,
576 this, &QtLauncher::updateSelectedAircraft);
577 connect(m_ui->pathsButton, &QPushButton::clicked,
578 this, &QtLauncher::onEditPaths);
580 // after any kind of reset, try to restore selection and scroll
581 // to match the m_selectedAircraft. This needs to be delayed
582 // fractionally otherwise the scrollTo seems to be ignored,
584 connect(m_aircraftProxy, &AircraftProxyModel::modelReset,
585 this, &QtLauncher::delayedAircraftModelReset);
588 m_aircraftModel->setPaths(settings.value("aircraft-paths").toStringList());
589 m_aircraftModel->setPackageRoot(globals->packageRoot());
590 m_aircraftModel->scanDirs();
595 QtLauncher::~QtLauncher()
600 void QtLauncher::setSceneryPaths()
602 globals->clear_fg_scenery();
604 // mimic what optionss.cxx does, so we can find airport data for parking
607 // append explicit scenery paths
608 Q_FOREACH(QString path, settings.value("scenery-paths").toStringList()) {
609 globals->append_fg_scenery(path.toStdString());
612 // append the TerraSync path
613 QString downloadDir = settings.value("download-dir").toString();
614 if (downloadDir.isEmpty()) {
615 downloadDir = QString::fromStdString(flightgear::defaultDownloadDir());
618 SGPath terraSyncDir(downloadDir.toStdString());
619 terraSyncDir.append("TerraSync");
620 if (terraSyncDir.exists()) {
621 globals->append_fg_scenery(terraSyncDir.str());
626 void QtLauncher::setInAppMode()
629 m_ui->tabWidget->removeTab(2);
630 m_ui->runButton->setText(tr("Apply"));
631 m_ui->quitButton->setText(tr("Cancel"));
633 disconnect(m_ui->runButton, SIGNAL(clicked()), this, SLOT(onRun()));
634 connect(m_ui->runButton, SIGNAL(clicked()), this, SLOT(onApply()));
637 void QtLauncher::restoreSettings()
640 m_ui->rembrandtCheckbox->setChecked(settings.value("enable-rembrandt", false).toBool());
641 m_ui->terrasyncCheck->setChecked(settings.value("enable-terrasync", true).toBool());
642 m_ui->fullScreenCheckbox->setChecked(settings.value("start-fullscreen", false).toBool());
643 m_ui->msaaCheckbox->setChecked(settings.value("enable-msaa", false).toBool());
644 m_ui->fetchRealWxrCheckbox->setChecked(settings.value("enable-realwx", true).toBool());
645 m_ui->startPausedCheck->setChecked(settings.value("start-paused", false).toBool());
646 m_ui->timeOfDayCombo->setCurrentIndex(settings.value("timeofday", 0).toInt());
647 m_ui->seasonCombo->setCurrentIndex(settings.value("season", 0).toInt());
649 // full paths to -set.xml files
650 m_recentAircraft = QUrl::fromStringList(settings.value("recent-aircraft").toStringList());
652 if (!m_recentAircraft.empty()) {
653 m_selectedAircraft = m_recentAircraft.front();
655 // select the default C172p
662 m_ui->location->restoreSettings();
665 m_ui->onlyShowInstalledCheck->setChecked(settings.value("only-show-installed", false).toBool());
666 if (m_ui->onlyShowInstalledCheck->isChecked()) {
667 m_ui->ratingsFilterCheck->setEnabled(false);
670 m_ui->ratingsFilterCheck->setChecked(settings.value("ratings-filter", true).toBool());
672 Q_FOREACH(QVariant v, settings.value("min-ratings").toList()) {
673 m_ratingFilters[index++] = v.toInt();
676 m_aircraftProxy->setRatingFilterEnabled(m_ui->ratingsFilterCheck->isChecked());
677 m_aircraftProxy->setRatings(m_ratingFilters);
679 updateSelectedAircraft();
680 maybeRestoreAircraftSelection();
682 m_ui->commandLineArgs->setPlainText(settings.value("additional-args").toString());
685 void QtLauncher::delayedAircraftModelReset()
687 QTimer::singleShot(1, this, SLOT(maybeRestoreAircraftSelection()));
690 void QtLauncher::maybeRestoreAircraftSelection()
692 QModelIndex aircraftIndex = m_aircraftModel->indexOfAircraftURI(m_selectedAircraft);
693 QModelIndex proxyIndex = m_aircraftProxy->mapFromSource(aircraftIndex);
694 if (proxyIndex.isValid()) {
695 m_ui->aircraftList->selectionModel()->setCurrentIndex(proxyIndex,
696 QItemSelectionModel::ClearAndSelect);
697 m_ui->aircraftList->selectionModel()->select(proxyIndex,
698 QItemSelectionModel::ClearAndSelect);
699 m_ui->aircraftList->scrollTo(proxyIndex);
703 void QtLauncher::saveSettings()
706 settings.setValue("enable-rembrandt", m_ui->rembrandtCheckbox->isChecked());
707 settings.setValue("enable-terrasync", m_ui->terrasyncCheck->isChecked());
708 settings.setValue("enable-msaa", m_ui->msaaCheckbox->isChecked());
709 settings.setValue("start-fullscreen", m_ui->fullScreenCheckbox->isChecked());
710 settings.setValue("enable-realwx", m_ui->fetchRealWxrCheckbox->isChecked());
711 settings.setValue("start-paused", m_ui->startPausedCheck->isChecked());
712 settings.setValue("ratings-filter", m_ui->ratingsFilterCheck->isChecked());
713 settings.setValue("only-show-installed", m_ui->onlyShowInstalledCheck->isChecked());
714 settings.setValue("recent-aircraft", QUrl::toStringList(m_recentAircraft));
716 settings.setValue("timeofday", m_ui->timeOfDayCombo->currentIndex());
717 settings.setValue("season", m_ui->seasonCombo->currentIndex());
718 settings.setValue("additional-args", m_ui->commandLineArgs->toPlainText());
720 m_ui->location->saveSettings();
723 void QtLauncher::setEnableDisableOptionFromCheckbox(QCheckBox* cbox, QString name) const
725 flightgear::Options* opt = flightgear::Options::sharedInstance();
726 std::string stdName(name.toStdString());
727 if (cbox->isChecked()) {
728 opt->addOption("enable-" + stdName, "");
730 opt->addOption("disable-" + stdName, "");
734 void QtLauncher::closeEvent(QCloseEvent *event)
739 void QtLauncher::onRun()
741 flightgear::Options* opt = flightgear::Options::sharedInstance();
742 setEnableDisableOptionFromCheckbox(m_ui->terrasyncCheck, "terrasync");
743 setEnableDisableOptionFromCheckbox(m_ui->fetchRealWxrCheckbox, "real-weather-fetch");
744 setEnableDisableOptionFromCheckbox(m_ui->rembrandtCheckbox, "rembrandt");
745 setEnableDisableOptionFromCheckbox(m_ui->fullScreenCheckbox, "fullscreen");
746 // setEnableDisableOptionFromCheckbox(m_ui->startPausedCheck, "freeze");
748 bool startPaused = m_ui->startPausedCheck->isChecked() ||
749 m_ui->location->shouldStartPaused();
751 opt->addOption("enable-freeze", "");
754 // MSAA is more complex
755 if (!m_ui->rembrandtCheckbox->isChecked()) {
756 if (m_ui->msaaCheckbox->isChecked()) {
757 globals->get_props()->setIntValue("/sim/rendering/multi-sample-buffers", 1);
758 globals->get_props()->setIntValue("/sim/rendering/multi-samples", 4);
760 globals->get_props()->setIntValue("/sim/rendering/multi-sample-buffers", 0);
765 if (!m_selectedAircraft.isEmpty()) {
766 if (m_selectedAircraft.isLocalFile()) {
767 QFileInfo setFileInfo(m_selectedAircraft.toLocalFile());
768 opt->addOption("aircraft-dir", setFileInfo.dir().absolutePath().toStdString());
769 QString setFile = setFileInfo.fileName();
770 Q_ASSERT(setFile.endsWith("-set.xml"));
771 setFile.truncate(setFile.count() - 8); // drop the '-set.xml' portion
772 opt->addOption("aircraft", setFile.toStdString());
773 } else if (m_selectedAircraft.scheme() == "package") {
774 QString qualifiedId = m_selectedAircraft.path();
775 // no need to set aircraft-dir, handled by the corresponding code
777 opt->addOption("aircraft", qualifiedId.toStdString());
779 qWarning() << "unsupported aircraft launch URL" << m_selectedAircraft;
782 // manage aircraft history
783 if (m_recentAircraft.contains(m_selectedAircraft))
784 m_recentAircraft.removeOne(m_selectedAircraft);
785 m_recentAircraft.prepend(m_selectedAircraft);
786 if (m_recentAircraft.size() > MAX_RECENT_AIRCRAFT)
787 m_recentAircraft.pop_back();
790 m_ui->location->setLocationOptions();
793 if (m_ui->timeOfDayCombo->currentIndex() != 0) {
794 QString dayval = m_ui->timeOfDayCombo->currentText().toLower();
795 opt->addOption("timeofday", dayval.toStdString());
798 if (m_ui->seasonCombo->currentIndex() != 0) {
799 QString seasonName = m_ui->seasonCombo->currentText().toLower();
800 opt->addOption("season", seasonName.toStdString());
804 QString downloadDir = settings.value("download-dir").toString();
805 if (!downloadDir.isEmpty()) {
808 int result = QMessageBox::question(this, tr("Create download folder?"),
809 tr("The selected location for downloads does not exist. Create it?"),
810 QMessageBox::Yes | QMessageBox::No | QMessageBox::Cancel);
811 if (result == QMessageBox::Cancel) {
815 if (result == QMessageBox::Yes) {
816 d.mkpath(downloadDir);
820 opt->addOption("download-dir", downloadDir.toStdString());
824 Q_FOREACH(QString path, settings.value("scenery-paths").toStringList()) {
825 opt->addOption("fg-scenery", path.toStdString());
829 Q_FOREACH(QString path, settings.value("aircraft-paths").toStringList()) {
830 // can't use fg-aircraft for this, as it is processed before the launcher is run
831 globals->append_aircraft_path(path.toStdString());
834 // additional arguments
835 ArgumentsTokenizer tk;
836 Q_FOREACH(ArgumentsTokenizer::Arg a, tk.tokenize(m_ui->commandLineArgs->toPlainText())) {
837 if (a.arg.startsWith("prop:")) {
838 QString v = a.arg.mid(5) + "=" + a.value;
839 opt->addOption("prop", v.toStdString());
841 opt->addOption(a.arg.toStdString(), a.value.toStdString());
851 void QtLauncher::onApply()
856 if (!m_selectedAircraft.isEmpty()) {
857 std::string aircraftPropValue,
860 if (m_selectedAircraft.isLocalFile()) {
861 QFileInfo setFileInfo(m_selectedAircraft.toLocalFile());
862 QString setFile = setFileInfo.fileName();
863 Q_ASSERT(setFile.endsWith("-set.xml"));
864 setFile.truncate(setFile.count() - 8); // drop the '-set.xml' portion
865 aircraftDir = setFileInfo.dir().absolutePath().toStdString();
866 aircraftPropValue = setFile.toStdString();
867 } else if (m_selectedAircraft.scheme() == "package") {
868 // no need to set aircraft-dir, handled by the corresponding code
870 aircraftPropValue = m_selectedAircraft.path().toStdString();
872 qWarning() << "unsupported aircraft launch URL" << m_selectedAircraft;
875 // manage aircraft history
876 if (m_recentAircraft.contains(m_selectedAircraft))
877 m_recentAircraft.removeOne(m_selectedAircraft);
878 m_recentAircraft.prepend(m_selectedAircraft);
879 if (m_recentAircraft.size() > MAX_RECENT_AIRCRAFT)
880 m_recentAircraft.pop_back();
882 globals->get_props()->setStringValue("/sim/aircraft", aircraftPropValue);
883 globals->get_props()->setStringValue("/sim/aircraft-dir", aircraftDir);
890 void QtLauncher::onQuit()
895 void QtLauncher::onToggleTerrasync(bool enabled)
899 QString downloadDir = settings.value("download-dir").toString();
900 if (downloadDir.isEmpty()) {
901 downloadDir = QString::fromStdString(flightgear::defaultDownloadDir());
904 QFileInfo info(downloadDir);
905 if (!info.exists()) {
907 msg.setWindowTitle(tr("Create download folder?"));
908 msg.setText(tr("The download folder '%1' does not exist, create it now? "
909 "Click 'change location' to choose another folder "
910 "to store downloaded files").arg(downloadDir));
911 msg.addButton(QMessageBox::Yes);
912 msg.addButton(QMessageBox::Cancel);
913 msg.addButton(tr("Change location"), QMessageBox::ActionRole);
914 int result = msg.exec();
916 if (result == QMessageBox::Cancel) {
917 m_ui->terrasyncCheck->setChecked(false);
921 if (result == QMessageBox::ActionRole) {
927 d.mkpath(downloadDir);
932 void QtLauncher::onAircraftInstalledCompleted(QModelIndex index)
934 maybeUpdateSelectedAircraft(index);
937 void QtLauncher::onRatingsFilterToggled()
939 QModelIndex aircraftIndex = m_aircraftModel->indexOfAircraftURI(m_selectedAircraft);
940 QModelIndex proxyIndex = m_aircraftProxy->mapFromSource(aircraftIndex);
941 if (proxyIndex.isValid()) {
942 m_ui->aircraftList->scrollTo(proxyIndex);
946 void QtLauncher::onAircraftInstallFailed(QModelIndex index, QString errorMessage)
948 qWarning() << Q_FUNC_INFO << index.data(AircraftURIRole) << errorMessage;
951 msg.setWindowTitle(tr("Aircraft installation failed"));
952 msg.setText(tr("An error occurred installing the aircraft %1: %2").
953 arg(index.data(Qt::DisplayRole).toString()).arg(errorMessage));
954 msg.addButton(QMessageBox::Ok);
957 maybeUpdateSelectedAircraft(index);
960 void QtLauncher::onAircraftSelected(const QModelIndex& index)
962 m_selectedAircraft = index.data(AircraftURIRole).toUrl();
963 updateSelectedAircraft();
966 void QtLauncher::onRequestPackageInstall(const QModelIndex& index)
968 // also select, otherwise UI is confusing
969 m_selectedAircraft = index.data(AircraftURIRole).toUrl();
970 updateSelectedAircraft();
972 QString pkg = index.data(AircraftPackageIdRole).toString();
973 simgear::pkg::PackageRef pref = globals->packageRoot()->getPackageById(pkg.toStdString());
974 if (pref->isInstalled()) {
975 InstallRef install = pref->existingInstall();
976 if (install && install->hasUpdate()) {
977 globals->packageRoot()->scheduleToUpdate(install);
984 void QtLauncher::onCancelDownload(const QModelIndex& index)
986 QString pkg = index.data(AircraftPackageIdRole).toString();
987 simgear::pkg::PackageRef pref = globals->packageRoot()->getPackageById(pkg.toStdString());
988 simgear::pkg::InstallRef i = pref->existingInstall();
992 void QtLauncher::maybeUpdateSelectedAircraft(QModelIndex index)
994 QUrl u = index.data(AircraftURIRole).toUrl();
995 if (u == m_selectedAircraft) {
996 // potentially enable the run button now!
997 updateSelectedAircraft();
1001 void QtLauncher::updateSelectedAircraft()
1003 QModelIndex index = m_aircraftModel->indexOfAircraftURI(m_selectedAircraft);
1004 if (index.isValid()) {
1005 QPixmap pm = index.data(Qt::DecorationRole).value<QPixmap>();
1006 m_ui->thumbnail->setPixmap(pm);
1007 m_ui->aircraftDescription->setText(index.data(Qt::DisplayRole).toString());
1009 int status = index.data(AircraftPackageStatusRole).toInt();
1010 bool canRun = (status == PackageInstalled);
1011 m_ui->runButton->setEnabled(canRun);
1013 LauncherAircraftType aircraftType = Airplane;
1014 if (index.data(AircraftIsHelicopterRole).toBool()) {
1015 aircraftType = Helicopter;
1016 } else if (index.data(AircraftIsSeaplaneRole).toBool()) {
1017 aircraftType = Seaplane;
1020 m_ui->location->setAircraftType(aircraftType);
1022 m_ui->thumbnail->setPixmap(QPixmap());
1023 m_ui->aircraftDescription->setText("");
1024 m_ui->runButton->setEnabled(false);
1028 QModelIndex QtLauncher::proxyIndexForAircraftURI(QUrl uri) const
1030 return m_aircraftProxy->mapFromSource(sourceIndexForAircraftURI(uri));
1033 QModelIndex QtLauncher::sourceIndexForAircraftURI(QUrl uri) const
1035 AircraftItemModel* sourceModel = qobject_cast<AircraftItemModel*>(m_aircraftProxy->sourceModel());
1036 Q_ASSERT(sourceModel);
1037 return sourceModel->indexOfAircraftURI(uri);
1040 void QtLauncher::onPopupAircraftHistory()
1042 if (m_recentAircraft.isEmpty()) {
1047 Q_FOREACH(QUrl uri, m_recentAircraft) {
1048 QModelIndex index = sourceIndexForAircraftURI(uri);
1049 if (!index.isValid()) {
1053 QAction* act = m.addAction(index.data(Qt::DisplayRole).toString());
1057 QPoint popupPos = m_ui->aircraftHistory->mapToGlobal(m_ui->aircraftHistory->rect().bottomLeft());
1058 QAction* triggered = m.exec(popupPos);
1060 m_selectedAircraft = triggered->data().toUrl();
1061 QModelIndex index = proxyIndexForAircraftURI(m_selectedAircraft);
1062 m_ui->aircraftList->selectionModel()->setCurrentIndex(index,
1063 QItemSelectionModel::ClearAndSelect);
1064 m_ui->aircraftFilter->clear();
1065 updateSelectedAircraft();
1069 void QtLauncher::onEditRatingsFilter()
1071 EditRatingsFilterDialog dialog(this);
1072 dialog.setRatings(m_ratingFilters);
1075 if (dialog.result() == QDialog::Accepted) {
1077 for (int i=0; i<4; ++i) {
1078 m_ratingFilters[i] = dialog.getRating(i);
1079 vl.append(m_ratingFilters[i]);
1081 m_aircraftProxy->setRatings(m_ratingFilters);
1084 settings.setValue("min-ratings", vl);
1088 void QtLauncher::updateSettingsSummary()
1090 QStringList summary;
1091 if (m_ui->timeOfDayCombo->currentIndex() > 0) {
1092 summary.append(QString(m_ui->timeOfDayCombo->currentText().toLower()));
1095 if (m_ui->seasonCombo->currentIndex() > 0) {
1096 summary.append(QString(m_ui->seasonCombo->currentText().toLower()));
1099 if (m_ui->rembrandtCheckbox->isChecked()) {
1100 summary.append("Rembrandt enabled");
1101 } else if (m_ui->msaaCheckbox->isChecked()) {
1102 summary.append("anti-aliasing");
1105 if (m_ui->fetchRealWxrCheckbox->isChecked()) {
1106 summary.append("live weather");
1109 if (m_ui->terrasyncCheck->isChecked()) {
1110 summary.append("automatic scenery downloads");
1113 if (m_ui->startPausedCheck->isChecked()) {
1114 summary.append("paused");
1117 QString s = summary.join(", ");
1118 s[0] = s[0].toUpper();
1119 m_ui->settingsDescription->setText(s);
1122 void QtLauncher::onRembrandtToggled(bool b)
1124 // Rembrandt and multi-sample are exclusive
1125 m_ui->msaaCheckbox->setEnabled(!b);
1128 void QtLauncher::onShowInstalledAircraftToggled(bool b)
1130 m_ui->ratingsFilterCheck->setEnabled(!b);
1131 maybeRestoreAircraftSelection();
1134 void QtLauncher::onSubsytemIdleTimeout()
1136 globals->get_subsystem_mgr()->update(0.0);
1139 void QtLauncher::onEditPaths()
1142 QString previousDownloadDir = settings.value("download-dir").toString();
1144 PathsDialog dlg(this, globals->packageRoot());
1146 if (dlg.result() == QDialog::Accepted) {
1147 QString dd = settings.value("download-dir").toString();
1148 bool downloadDirChanged = (previousDownloadDir != dd);
1149 if (downloadDirChanged) {
1150 qDebug() << "download dir changed, resetting package root";
1153 flightgear::Options::sharedInstance()->clearOption("download-dir");
1155 flightgear::Options::sharedInstance()->setOption("download-dir", dd.toStdString());
1158 // replace existing package root
1159 globals->get_subsystem<FGHTTPClient>()->shutdown();
1160 globals->setPackageRoot(simgear::pkg::RootRef());
1162 // create new root with updated download-dir value
1163 fgInitPackageRoot();
1165 globals->get_subsystem<FGHTTPClient>()->init();
1168 // re-scan the aircraft list
1169 m_aircraftModel->setPackageRoot(globals->packageRoot());
1170 m_aircraftModel->setPaths(settings.value("aircraft-paths").toStringList());
1171 m_aircraftModel->scanDirs();
1173 // re-set scenery dirs
1178 void QtLauncher::onChangeRoot()
1180 QMessageBox mbox(this);
1181 mbox.setText(tr("Change the data files location used by FlightGear?"));
1182 mbox.setInformativeText(tr("FlightGear cannot work without its data files. "
1183 "(Also called the base package) "
1184 "To change which files are used, quit FlightGear and open it again, "
1185 "while holding down the 'shift' key, and you will be able to choose a "
1186 "different data files location, or restore the default setting."));
1187 QPushButton* quitButton = mbox.addButton(tr("Quit FlightGear now"), QMessageBox::YesRole);
1188 mbox.addButton(QMessageBox::Cancel);
1189 mbox.setDefaultButton(QMessageBox::Cancel);
1190 mbox.setIconPixmap(QPixmap(":/app-icon-large"));
1193 if (mbox.clickedButton() != quitButton) {
1197 // following code doesn't work reliably, so we take the simpler
1198 // option of asking the user to re-launch us while holding down
1199 // the hot-key (shift)
1203 // set the option to the magic marker value
1204 settings.setValue("fg-root", "!ask");
1205 } // scope the ensure settings are written nicel
1207 // Spawn a new instance of myApplication:
1209 #if defined(Q_OS_MAC)
1212 QDir dir(qApp->applicationDirPath()); // returns the 'MacOS' dir
1213 dir.cdUp(); // up to 'contents' dir
1214 dir.cdUp(); // up to .app dir
1215 args << dir.absolutePath();
1216 proc.startDetached("open", args);
1218 proc.startDetached(qApp->applicationFilePath());
1222 qDebug() << "doing app exit";
1226 simgear::pkg::PackageRef QtLauncher::packageForAircraftURI(QUrl uri) const
1228 if (uri.scheme() != "package") {
1229 qWarning() << "invalid URL scheme:" << uri;
1230 return simgear::pkg::PackageRef();
1233 QString ident = uri.path();
1234 return globals->packageRoot()->getPackageById(ident.toStdString());
1238 #include "QtLauncher.moc"