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)
417 // startup the HTTP system now since packages needs it
418 FGHTTPClient* http = new FGHTTPClient;
419 globals->add_subsystem("http", http);
420 // we guard against re-init in the global phase; bind and postinit
421 // will happen as normal
424 loadNaturalEarthData();
426 // avoid double Apple menu and other weirdness if both Qt and OSG
427 // try to initialise various Cocoa structures.
428 flightgear::WindowBuilder::setPoseAsStandaloneApp(false);
433 int appResult = qApp->exec();
434 qDebug() << "App result:" << appResult;
436 return false; // quit
439 // don't set scenery paths twice
440 globals->clear_fg_scenery();
445 bool runInAppLauncherDialog()
450 if (dlg.result() != QDialog::Accepted) {
457 } // of namespace flightgear
459 QtLauncher::QtLauncher() :
462 m_subsystemIdleTimer(NULL),
465 m_ui.reset(new Ui::Launcher);
468 #if QT_VERSION >= 0x050300
469 // don't require Qt 5.3
470 m_ui->commandLineArgs->setPlaceholderText("--option=value --prop:/sim/name=value");
473 #if QT_VERSION >= 0x050200
474 m_ui->aircraftFilter->setClearButtonEnabled(true);
477 for (int i=0; i<4; ++i) {
478 m_ratingFilters[i] = 3;
481 m_subsystemIdleTimer = new QTimer(this);
482 m_subsystemIdleTimer->setInterval(0);
483 connect(m_subsystemIdleTimer, &QTimer::timeout,
484 this, &QtLauncher::onSubsytemIdleTimeout);
485 m_subsystemIdleTimer->start();
487 // create and configure the proxy model
488 m_aircraftProxy = new AircraftProxyModel(this);
489 connect(m_ui->ratingsFilterCheck, &QAbstractButton::toggled,
490 m_aircraftProxy, &AircraftProxyModel::setRatingFilterEnabled);
491 connect(m_ui->ratingsFilterCheck, &QAbstractButton::toggled,
492 this, &QtLauncher::maybeRestoreAircraftSelection);
494 connect(m_ui->onlyShowInstalledCheck, &QAbstractButton::toggled,
495 m_aircraftProxy, &AircraftProxyModel::setInstalledFilterEnabled);
496 connect(m_ui->aircraftFilter, &QLineEdit::textChanged,
497 m_aircraftProxy, &QSortFilterProxyModel::setFilterFixedString);
499 connect(m_ui->runButton, SIGNAL(clicked()), this, SLOT(onRun()));
500 connect(m_ui->quitButton, SIGNAL(clicked()), this, SLOT(onQuit()));
502 connect(m_ui->changeRootButton, SIGNAL(clicked()), this, SLOT(onChangeRoot()));
504 connect(m_ui->aircraftHistory, &QPushButton::clicked,
505 this, &QtLauncher::onPopupAircraftHistory);
507 connect(m_ui->location, &LocationWidget::descriptionChanged,
508 m_ui->locationDescription, &QLabel::setText);
510 QAction* qa = new QAction(this);
511 qa->setShortcut(QKeySequence("Ctrl+Q"));
512 connect(qa, &QAction::triggered, this, &QtLauncher::onQuit);
515 connect(m_ui->editRatingFilter, &QPushButton::clicked,
516 this, &QtLauncher::onEditRatingsFilter);
517 connect(m_ui->onlyShowInstalledCheck, &QCheckBox::toggled,
518 this, &QtLauncher::onShowInstalledAircraftToggled);
520 QIcon historyIcon(":/history-icon");
521 m_ui->aircraftHistory->setIcon(historyIcon);
523 connect(m_ui->timeOfDayCombo, SIGNAL(currentIndexChanged(int)),
524 this, SLOT(updateSettingsSummary()));
525 connect(m_ui->seasonCombo, SIGNAL(currentIndexChanged(int)),
526 this, SLOT(updateSettingsSummary()));
527 connect(m_ui->fetchRealWxrCheckbox, SIGNAL(toggled(bool)),
528 this, SLOT(updateSettingsSummary()));
529 connect(m_ui->rembrandtCheckbox, SIGNAL(toggled(bool)),
530 this, SLOT(updateSettingsSummary()));
531 connect(m_ui->terrasyncCheck, SIGNAL(toggled(bool)),
532 this, SLOT(updateSettingsSummary()));
533 connect(m_ui->startPausedCheck, SIGNAL(toggled(bool)),
534 this, SLOT(updateSettingsSummary()));
535 connect(m_ui->msaaCheckbox, SIGNAL(toggled(bool)),
536 this, SLOT(updateSettingsSummary()));
538 connect(m_ui->rembrandtCheckbox, SIGNAL(toggled(bool)),
539 this, SLOT(onRembrandtToggled(bool)));
540 connect(m_ui->terrasyncCheck, &QCheckBox::toggled,
541 this, &QtLauncher::onToggleTerrasync);
542 updateSettingsSummary();
544 m_aircraftModel = new AircraftItemModel(this, RootRef(globals->packageRoot()));
545 m_aircraftProxy->setSourceModel(m_aircraftModel);
547 m_aircraftProxy->setFilterCaseSensitivity(Qt::CaseInsensitive);
548 m_aircraftProxy->setSortCaseSensitivity(Qt::CaseInsensitive);
549 m_aircraftProxy->setSortRole(Qt::DisplayRole);
550 m_aircraftProxy->setDynamicSortFilter(true);
552 m_ui->aircraftList->setModel(m_aircraftProxy);
553 m_ui->aircraftList->setHorizontalScrollBarPolicy(Qt::ScrollBarAlwaysOff);
554 AircraftItemDelegate* delegate = new AircraftItemDelegate(m_ui->aircraftList);
555 m_ui->aircraftList->setItemDelegate(delegate);
556 m_ui->aircraftList->setSelectionMode(QAbstractItemView::SingleSelection);
557 connect(m_ui->aircraftList, &QListView::clicked,
558 this, &QtLauncher::onAircraftSelected);
559 connect(delegate, &AircraftItemDelegate::variantChanged,
560 this, &QtLauncher::onAircraftSelected);
561 connect(delegate, &AircraftItemDelegate::requestInstall,
562 this, &QtLauncher::onRequestPackageInstall);
563 connect(delegate, &AircraftItemDelegate::cancelDownload,
564 this, &QtLauncher::onCancelDownload);
566 connect(m_aircraftModel, &AircraftItemModel::aircraftInstallCompleted,
567 this, &QtLauncher::onAircraftInstalledCompleted);
568 connect(m_aircraftModel, &AircraftItemModel::aircraftInstallFailed,
569 this, &QtLauncher::onAircraftInstallFailed);
570 connect(m_aircraftModel, &AircraftItemModel::scanCompleted,
571 this, &QtLauncher::updateSelectedAircraft);
572 connect(m_ui->pathsButton, &QPushButton::clicked,
573 this, &QtLauncher::onEditPaths);
575 // after any kind of reset, try to restore selection and scroll
576 // to match the m_selectedAircraft. This needs to be delayed
577 // fractionally otherwise the scrollTo seems to be ignored,
579 connect(m_aircraftProxy, &AircraftProxyModel::modelReset,
580 this, &QtLauncher::delayedAircraftModelReset);
585 m_aircraftModel->setPaths(settings.value("aircraft-paths").toStringList());
586 m_aircraftModel->scanDirs();
589 QtLauncher::~QtLauncher()
594 void QtLauncher::setSceneryPaths()
596 globals->clear_fg_scenery();
598 // mimic what optionss.cxx does, so we can find airport data for parking
601 // append explicit scenery paths
602 Q_FOREACH(QString path, settings.value("scenery-paths").toStringList()) {
603 globals->append_fg_scenery(path.toStdString());
606 // append the TerraSync path
607 QString downloadDir = settings.value("download-dir").toString();
608 if (downloadDir.isEmpty()) {
609 downloadDir = QString::fromStdString(flightgear::defaultDownloadDir());
612 SGPath terraSyncDir(downloadDir.toStdString());
613 terraSyncDir.append("TerraSync");
614 if (terraSyncDir.exists()) {
615 globals->append_fg_scenery(terraSyncDir.str());
620 void QtLauncher::setInAppMode()
623 m_ui->tabWidget->removeTab(2);
624 m_ui->runButton->setText(tr("Apply"));
625 m_ui->quitButton->setText(tr("Cancel"));
627 disconnect(m_ui->runButton, SIGNAL(clicked()), this, SLOT(onRun()));
628 connect(m_ui->runButton, SIGNAL(clicked()), this, SLOT(onApply()));
631 void QtLauncher::restoreSettings()
634 m_ui->rembrandtCheckbox->setChecked(settings.value("enable-rembrandt", false).toBool());
635 m_ui->terrasyncCheck->setChecked(settings.value("enable-terrasync", true).toBool());
636 m_ui->fullScreenCheckbox->setChecked(settings.value("start-fullscreen", false).toBool());
637 m_ui->msaaCheckbox->setChecked(settings.value("enable-msaa", false).toBool());
638 m_ui->fetchRealWxrCheckbox->setChecked(settings.value("enable-realwx", true).toBool());
639 m_ui->startPausedCheck->setChecked(settings.value("start-paused", false).toBool());
640 m_ui->timeOfDayCombo->setCurrentIndex(settings.value("timeofday", 0).toInt());
641 m_ui->seasonCombo->setCurrentIndex(settings.value("season", 0).toInt());
643 // full paths to -set.xml files
644 m_recentAircraft = QUrl::fromStringList(settings.value("recent-aircraft").toStringList());
646 if (!m_recentAircraft.empty()) {
647 m_selectedAircraft = m_recentAircraft.front();
649 // select the default C172p
656 m_ui->location->restoreSettings();
659 m_ui->onlyShowInstalledCheck->setChecked(settings.value("only-show-installed", false).toBool());
660 if (m_ui->onlyShowInstalledCheck->isChecked()) {
661 m_ui->ratingsFilterCheck->setEnabled(false);
664 m_ui->ratingsFilterCheck->setChecked(settings.value("ratings-filter", true).toBool());
666 Q_FOREACH(QVariant v, settings.value("min-ratings").toList()) {
667 m_ratingFilters[index++] = v.toInt();
670 m_aircraftProxy->setRatingFilterEnabled(m_ui->ratingsFilterCheck->isChecked());
671 m_aircraftProxy->setRatings(m_ratingFilters);
673 updateSelectedAircraft();
674 maybeRestoreAircraftSelection();
676 m_ui->commandLineArgs->setPlainText(settings.value("additional-args").toString());
679 void QtLauncher::delayedAircraftModelReset()
681 QTimer::singleShot(1, this, SLOT(maybeRestoreAircraftSelection()));
684 void QtLauncher::maybeRestoreAircraftSelection()
686 QModelIndex aircraftIndex = m_aircraftModel->indexOfAircraftURI(m_selectedAircraft);
687 QModelIndex proxyIndex = m_aircraftProxy->mapFromSource(aircraftIndex);
688 if (proxyIndex.isValid()) {
689 m_ui->aircraftList->selectionModel()->setCurrentIndex(proxyIndex,
690 QItemSelectionModel::ClearAndSelect);
691 m_ui->aircraftList->selectionModel()->select(proxyIndex,
692 QItemSelectionModel::ClearAndSelect);
693 m_ui->aircraftList->scrollTo(proxyIndex);
697 void QtLauncher::saveSettings()
700 settings.setValue("enable-rembrandt", m_ui->rembrandtCheckbox->isChecked());
701 settings.setValue("enable-terrasync", m_ui->terrasyncCheck->isChecked());
702 settings.setValue("enable-msaa", m_ui->msaaCheckbox->isChecked());
703 settings.setValue("start-fullscreen", m_ui->fullScreenCheckbox->isChecked());
704 settings.setValue("enable-realwx", m_ui->fetchRealWxrCheckbox->isChecked());
705 settings.setValue("start-paused", m_ui->startPausedCheck->isChecked());
706 settings.setValue("ratings-filter", m_ui->ratingsFilterCheck->isChecked());
707 settings.setValue("only-show-installed", m_ui->onlyShowInstalledCheck->isChecked());
708 settings.setValue("recent-aircraft", QUrl::toStringList(m_recentAircraft));
710 settings.setValue("timeofday", m_ui->timeOfDayCombo->currentIndex());
711 settings.setValue("season", m_ui->seasonCombo->currentIndex());
712 settings.setValue("additional-args", m_ui->commandLineArgs->toPlainText());
714 m_ui->location->saveSettings();
717 void QtLauncher::setEnableDisableOptionFromCheckbox(QCheckBox* cbox, QString name) const
719 flightgear::Options* opt = flightgear::Options::sharedInstance();
720 std::string stdName(name.toStdString());
721 if (cbox->isChecked()) {
722 opt->addOption("enable-" + stdName, "");
724 opt->addOption("disable-" + stdName, "");
728 void QtLauncher::closeEvent(QCloseEvent *event)
733 void QtLauncher::onRun()
735 flightgear::Options* opt = flightgear::Options::sharedInstance();
736 setEnableDisableOptionFromCheckbox(m_ui->terrasyncCheck, "terrasync");
737 setEnableDisableOptionFromCheckbox(m_ui->fetchRealWxrCheckbox, "real-weather-fetch");
738 setEnableDisableOptionFromCheckbox(m_ui->rembrandtCheckbox, "rembrandt");
739 setEnableDisableOptionFromCheckbox(m_ui->fullScreenCheckbox, "fullscreen");
740 // setEnableDisableOptionFromCheckbox(m_ui->startPausedCheck, "freeze");
742 bool startPaused = m_ui->startPausedCheck->isChecked() ||
743 m_ui->location->shouldStartPaused();
745 opt->addOption("enable-freeze", "");
748 // MSAA is more complex
749 if (!m_ui->rembrandtCheckbox->isChecked()) {
750 if (m_ui->msaaCheckbox->isChecked()) {
751 globals->get_props()->setIntValue("/sim/rendering/multi-sample-buffers", 1);
752 globals->get_props()->setIntValue("/sim/rendering/multi-samples", 4);
754 globals->get_props()->setIntValue("/sim/rendering/multi-sample-buffers", 0);
759 if (!m_selectedAircraft.isEmpty()) {
760 if (m_selectedAircraft.isLocalFile()) {
761 QFileInfo setFileInfo(m_selectedAircraft.toLocalFile());
762 opt->addOption("aircraft-dir", setFileInfo.dir().absolutePath().toStdString());
763 QString setFile = setFileInfo.fileName();
764 Q_ASSERT(setFile.endsWith("-set.xml"));
765 setFile.truncate(setFile.count() - 8); // drop the '-set.xml' portion
766 opt->addOption("aircraft", setFile.toStdString());
767 } else if (m_selectedAircraft.scheme() == "package") {
768 QString qualifiedId = m_selectedAircraft.path();
769 // no need to set aircraft-dir, handled by the corresponding code
771 opt->addOption("aircraft", qualifiedId.toStdString());
773 qWarning() << "unsupported aircraft launch URL" << m_selectedAircraft;
776 // manage aircraft history
777 if (m_recentAircraft.contains(m_selectedAircraft))
778 m_recentAircraft.removeOne(m_selectedAircraft);
779 m_recentAircraft.prepend(m_selectedAircraft);
780 if (m_recentAircraft.size() > MAX_RECENT_AIRCRAFT)
781 m_recentAircraft.pop_back();
784 m_ui->location->setLocationOptions();
787 if (m_ui->timeOfDayCombo->currentIndex() != 0) {
788 QString dayval = m_ui->timeOfDayCombo->currentText().toLower();
789 opt->addOption("timeofday", dayval.toStdString());
792 if (m_ui->seasonCombo->currentIndex() != 0) {
793 QString seasonName = m_ui->seasonCombo->currentText().toLower();
794 opt->addOption("season", seasonName.toStdString());
798 QString downloadDir = settings.value("download-dir").toString();
799 if (!downloadDir.isEmpty()) {
802 int result = QMessageBox::question(this, tr("Create download folder?"),
803 tr("The selected location for downloads does not exist. Create it?"),
804 QMessageBox::Yes | QMessageBox::No | QMessageBox::Cancel);
805 if (result == QMessageBox::Cancel) {
809 if (result == QMessageBox::Yes) {
810 d.mkpath(downloadDir);
814 opt->addOption("download-dir", downloadDir.toStdString());
818 Q_FOREACH(QString path, settings.value("scenery-paths").toStringList()) {
819 opt->addOption("fg-scenery", path.toStdString());
823 Q_FOREACH(QString path, settings.value("aircraft-paths").toStringList()) {
824 // can't use fg-aircraft for this, as it is processed before the launcher is run
825 globals->append_aircraft_path(path.toStdString());
828 // additional arguments
829 ArgumentsTokenizer tk;
830 Q_FOREACH(ArgumentsTokenizer::Arg a, tk.tokenize(m_ui->commandLineArgs->toPlainText())) {
831 if (a.arg.startsWith("prop:")) {
832 QString v = a.arg.mid(5) + "=" + a.value;
833 opt->addOption("prop", v.toStdString());
835 opt->addOption(a.arg.toStdString(), a.value.toStdString());
845 void QtLauncher::onApply()
850 if (!m_selectedAircraft.isEmpty()) {
851 std::string aircraftPropValue,
854 if (m_selectedAircraft.isLocalFile()) {
855 QFileInfo setFileInfo(m_selectedAircraft.toLocalFile());
856 QString setFile = setFileInfo.fileName();
857 Q_ASSERT(setFile.endsWith("-set.xml"));
858 setFile.truncate(setFile.count() - 8); // drop the '-set.xml' portion
859 aircraftDir = setFileInfo.dir().absolutePath().toStdString();
860 aircraftPropValue = setFile.toStdString();
861 } else if (m_selectedAircraft.scheme() == "package") {
862 // no need to set aircraft-dir, handled by the corresponding code
864 aircraftPropValue = m_selectedAircraft.path().toStdString();
866 qWarning() << "unsupported aircraft launch URL" << m_selectedAircraft;
869 // manage aircraft history
870 if (m_recentAircraft.contains(m_selectedAircraft))
871 m_recentAircraft.removeOne(m_selectedAircraft);
872 m_recentAircraft.prepend(m_selectedAircraft);
873 if (m_recentAircraft.size() > MAX_RECENT_AIRCRAFT)
874 m_recentAircraft.pop_back();
876 globals->get_props()->setStringValue("/sim/aircraft", aircraftPropValue);
877 globals->get_props()->setStringValue("/sim/aircraft-dir", aircraftDir);
884 void QtLauncher::onQuit()
889 void QtLauncher::onToggleTerrasync(bool enabled)
893 QString downloadDir = settings.value("download-dir").toString();
894 if (downloadDir.isEmpty()) {
895 downloadDir = QString::fromStdString(flightgear::defaultDownloadDir());
898 QFileInfo info(downloadDir);
899 if (!info.exists()) {
901 msg.setWindowTitle(tr("Create download folder?"));
902 msg.setText(tr("The download folder '%1' does not exist, create it now? "
903 "Click 'change location' to choose another folder "
904 "to store downloaded files").arg(downloadDir));
905 msg.addButton(QMessageBox::Yes);
906 msg.addButton(QMessageBox::Cancel);
907 msg.addButton(tr("Change location"), QMessageBox::ActionRole);
908 int result = msg.exec();
910 if (result == QMessageBox::Cancel) {
911 m_ui->terrasyncCheck->setChecked(false);
915 if (result == QMessageBox::ActionRole) {
921 d.mkpath(downloadDir);
926 void QtLauncher::onAircraftInstalledCompleted(QModelIndex index)
928 maybeUpdateSelectedAircraft(index);
931 void QtLauncher::onRatingsFilterToggled()
933 QModelIndex aircraftIndex = m_aircraftModel->indexOfAircraftURI(m_selectedAircraft);
934 QModelIndex proxyIndex = m_aircraftProxy->mapFromSource(aircraftIndex);
935 if (proxyIndex.isValid()) {
936 m_ui->aircraftList->scrollTo(proxyIndex);
940 void QtLauncher::onAircraftInstallFailed(QModelIndex index, QString errorMessage)
942 qWarning() << Q_FUNC_INFO << index.data(AircraftURIRole) << errorMessage;
945 msg.setWindowTitle(tr("Aircraft installation failed"));
946 msg.setText(tr("An error occurred installing the aircraft %1: %2").
947 arg(index.data(Qt::DisplayRole).toString()).arg(errorMessage));
948 msg.addButton(QMessageBox::Ok);
951 maybeUpdateSelectedAircraft(index);
954 void QtLauncher::onAircraftSelected(const QModelIndex& index)
956 m_selectedAircraft = index.data(AircraftURIRole).toUrl();
957 updateSelectedAircraft();
960 void QtLauncher::onRequestPackageInstall(const QModelIndex& index)
962 // also select, otherwise UI is confusing
963 m_selectedAircraft = index.data(AircraftURIRole).toUrl();
964 updateSelectedAircraft();
966 QString pkg = index.data(AircraftPackageIdRole).toString();
967 simgear::pkg::PackageRef pref = globals->packageRoot()->getPackageById(pkg.toStdString());
968 if (pref->isInstalled()) {
969 InstallRef install = pref->existingInstall();
970 if (install && install->hasUpdate()) {
971 globals->packageRoot()->scheduleToUpdate(install);
978 void QtLauncher::onCancelDownload(const QModelIndex& index)
980 QString pkg = index.data(AircraftPackageIdRole).toString();
981 simgear::pkg::PackageRef pref = globals->packageRoot()->getPackageById(pkg.toStdString());
982 simgear::pkg::InstallRef i = pref->existingInstall();
986 void QtLauncher::maybeUpdateSelectedAircraft(QModelIndex index)
988 QUrl u = index.data(AircraftURIRole).toUrl();
989 if (u == m_selectedAircraft) {
990 // potentially enable the run button now!
991 updateSelectedAircraft();
995 void QtLauncher::updateSelectedAircraft()
997 QModelIndex index = m_aircraftModel->indexOfAircraftURI(m_selectedAircraft);
998 if (index.isValid()) {
999 QPixmap pm = index.data(Qt::DecorationRole).value<QPixmap>();
1000 m_ui->thumbnail->setPixmap(pm);
1001 m_ui->aircraftDescription->setText(index.data(Qt::DisplayRole).toString());
1003 int status = index.data(AircraftPackageStatusRole).toInt();
1004 bool canRun = (status == PackageInstalled);
1005 m_ui->runButton->setEnabled(canRun);
1007 LauncherAircraftType aircraftType = Airplane;
1008 if (index.data(AircraftIsHelicopterRole).toBool()) {
1009 aircraftType = Helicopter;
1010 } else if (index.data(AircraftIsSeaplaneRole).toBool()) {
1011 aircraftType = Seaplane;
1014 m_ui->location->setAircraftType(aircraftType);
1016 m_ui->thumbnail->setPixmap(QPixmap());
1017 m_ui->aircraftDescription->setText("");
1018 m_ui->runButton->setEnabled(false);
1022 QModelIndex QtLauncher::proxyIndexForAircraftURI(QUrl uri) const
1024 return m_aircraftProxy->mapFromSource(sourceIndexForAircraftURI(uri));
1027 QModelIndex QtLauncher::sourceIndexForAircraftURI(QUrl uri) const
1029 AircraftItemModel* sourceModel = qobject_cast<AircraftItemModel*>(m_aircraftProxy->sourceModel());
1030 Q_ASSERT(sourceModel);
1031 return sourceModel->indexOfAircraftURI(uri);
1034 void QtLauncher::onPopupAircraftHistory()
1036 if (m_recentAircraft.isEmpty()) {
1041 Q_FOREACH(QUrl uri, m_recentAircraft) {
1042 QModelIndex index = sourceIndexForAircraftURI(uri);
1043 if (!index.isValid()) {
1047 QAction* act = m.addAction(index.data(Qt::DisplayRole).toString());
1051 QPoint popupPos = m_ui->aircraftHistory->mapToGlobal(m_ui->aircraftHistory->rect().bottomLeft());
1052 QAction* triggered = m.exec(popupPos);
1054 m_selectedAircraft = triggered->data().toUrl();
1055 QModelIndex index = proxyIndexForAircraftURI(m_selectedAircraft);
1056 m_ui->aircraftList->selectionModel()->setCurrentIndex(index,
1057 QItemSelectionModel::ClearAndSelect);
1058 m_ui->aircraftFilter->clear();
1059 updateSelectedAircraft();
1063 void QtLauncher::onEditRatingsFilter()
1065 EditRatingsFilterDialog dialog(this);
1066 dialog.setRatings(m_ratingFilters);
1069 if (dialog.result() == QDialog::Accepted) {
1071 for (int i=0; i<4; ++i) {
1072 m_ratingFilters[i] = dialog.getRating(i);
1073 vl.append(m_ratingFilters[i]);
1075 m_aircraftProxy->setRatings(m_ratingFilters);
1078 settings.setValue("min-ratings", vl);
1082 void QtLauncher::updateSettingsSummary()
1084 QStringList summary;
1085 if (m_ui->timeOfDayCombo->currentIndex() > 0) {
1086 summary.append(QString(m_ui->timeOfDayCombo->currentText().toLower()));
1089 if (m_ui->seasonCombo->currentIndex() > 0) {
1090 summary.append(QString(m_ui->seasonCombo->currentText().toLower()));
1093 if (m_ui->rembrandtCheckbox->isChecked()) {
1094 summary.append("Rembrandt enabled");
1095 } else if (m_ui->msaaCheckbox->isChecked()) {
1096 summary.append("anti-aliasing");
1099 if (m_ui->fetchRealWxrCheckbox->isChecked()) {
1100 summary.append("live weather");
1103 if (m_ui->terrasyncCheck->isChecked()) {
1104 summary.append("automatic scenery downloads");
1107 if (m_ui->startPausedCheck->isChecked()) {
1108 summary.append("paused");
1111 QString s = summary.join(", ");
1112 s[0] = s[0].toUpper();
1113 m_ui->settingsDescription->setText(s);
1116 void QtLauncher::onRembrandtToggled(bool b)
1118 // Rembrandt and multi-sample are exclusive
1119 m_ui->msaaCheckbox->setEnabled(!b);
1122 void QtLauncher::onShowInstalledAircraftToggled(bool b)
1124 m_ui->ratingsFilterCheck->setEnabled(!b);
1125 maybeRestoreAircraftSelection();
1128 void QtLauncher::onSubsytemIdleTimeout()
1130 globals->get_subsystem_mgr()->update(0.0);
1133 void QtLauncher::onEditPaths()
1135 PathsDialog dlg(this, globals->packageRoot());
1137 if (dlg.result() == QDialog::Accepted) {
1138 // re-scan the aircraft list
1140 m_aircraftModel->setPaths(settings.value("aircraft-paths").toStringList());
1141 m_aircraftModel->scanDirs();
1143 // re-set scenery dirs
1148 void QtLauncher::onChangeRoot()
1150 QMessageBox mbox(this);
1151 mbox.setText(tr("Change the data files location used by FlightGear?"));
1152 mbox.setInformativeText(tr("FlightGear cannot work without its data files. "
1153 "(Also called the base package) "
1154 "To change which files are used, quit FlightGear and open it again, "
1155 "while holding down the 'shift' key, and you will be able to choose a "
1156 "different data files location, or restore the default setting."));
1157 QPushButton* quitButton = mbox.addButton(tr("Quit FlightGear now"), QMessageBox::YesRole);
1158 mbox.addButton(QMessageBox::Cancel);
1159 mbox.setDefaultButton(QMessageBox::Cancel);
1160 mbox.setIconPixmap(QPixmap(":/app-icon-large"));
1163 if (mbox.clickedButton() != quitButton) {
1167 // following code doesn't work reliably, so we take the simpler
1168 // option of asking the user to re-launch us while holding down
1169 // the hot-key (shift)
1173 // set the option to the magic marker value
1174 settings.setValue("fg-root", "!ask");
1175 } // scope the ensure settings are written nicel
1177 // Spawn a new instance of myApplication:
1179 #if defined(Q_OS_MAC)
1182 QDir dir(qApp->applicationDirPath()); // returns the 'MacOS' dir
1183 dir.cdUp(); // up to 'contents' dir
1184 dir.cdUp(); // up to .app dir
1185 args << dir.absolutePath();
1186 proc.startDetached("open", args);
1188 proc.startDetached(qApp->applicationFilePath());
1192 qDebug() << "doing app exit";
1196 simgear::pkg::PackageRef QtLauncher::packageForAircraftURI(QUrl uri) const
1198 if (uri.scheme() != "package") {
1199 qWarning() << "invalid URL scheme:" << uri;
1200 return simgear::pkg::PackageRef();
1203 QString ident = uri.path();
1204 return globals->packageRoot()->getPackageById(ident.toStdString());
1208 #include "QtLauncher.moc"