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>
68 #include <Main/options.hxx>
69 #include <Main/fg_init.hxx>
70 #include <Viewer/WindowBuilder.hxx>
71 #include <Network/HTTPClient.hxx>
73 using namespace flightgear;
74 using namespace simgear::pkg;
76 const int MAX_RECENT_AIRCRAFT = 20;
78 namespace { // anonymous namespace
82 QString baseLabel = QT_TR_NOOP("Initialising navigation data, this may take several minutes");
83 NavDataCache* cache = NavDataCache::createInstance();
84 if (cache->isRebuildRequired()) {
85 QProgressDialog rebuildProgress(baseLabel,
86 QString() /* cancel text */,
88 rebuildProgress.setWindowModality(Qt::WindowModal);
89 rebuildProgress.show();
91 NavDataCache::RebuildPhase phase = cache->rebuild();
93 while (phase != NavDataCache::REBUILD_DONE) {
94 // sleep to give the rebuild thread more time
95 SGTimeStamp::sleepForMSec(50);
96 phase = cache->rebuild();
99 case NavDataCache::REBUILD_AIRPORTS:
100 rebuildProgress.setLabelText(QT_TR_NOOP("Loading airport data"));
103 case NavDataCache::REBUILD_FIXES:
104 rebuildProgress.setLabelText(QT_TR_NOOP("Loading waypoint data"));
107 case NavDataCache::REBUILD_NAVAIDS:
108 rebuildProgress.setLabelText(QT_TR_NOOP("Loading navigation data"));
112 case NavDataCache::REBUILD_POIS:
113 rebuildProgress.setLabelText(QT_TR_NOOP("Loading point-of-interest data"));
117 rebuildProgress.setLabelText(baseLabel);
120 if (phase == NavDataCache::REBUILD_UNKNOWN) {
121 rebuildProgress.setValue(0);
122 rebuildProgress.setMaximum(0);
124 rebuildProgress.setValue(cache->rebuildPhaseCompletionPercentage());
125 rebuildProgress.setMaximum(100);
128 QCoreApplication::processEvents();
133 class ArgumentsTokenizer
139 explicit Arg(QString k, QString v = QString()) : arg(k), value(v) {}
145 QList<Arg> tokenize(QString in) const
148 const int len = in.count();
154 for (; index < len; ++index) {
156 nc = index < (len - 1) ? in.at(index + 1) : QChar();
160 if (c == QChar('-')) {
161 if (nc == QChar('-')) {
166 // should we pemit single hyphen arguments?
167 // choosing to fail for now
170 } else if (c == QChar('#')) {
173 } else if (c.isSpace()) {
179 if (c == QChar('=')) {
182 } else if (c.isSpace()) {
184 result.append(Arg(key));
186 // could check for illegal charatcers here
192 if (c == QChar('"')) {
194 } else if (c.isSpace()) {
196 result.append(Arg(key, value));
203 if (c == QChar('\\')) {
204 // check for escaped double-quote inside quoted value
205 if (nc == QChar('"')) {
208 } else if (c == QChar('"')) {
216 if ((c == QChar('\n')) || (c == QChar('\r'))) {
220 // nothing to do, eat comment chars
224 } // of character loop
226 // ensure last argument isn't lost
228 result.append(Arg(key));
229 } else if (state == Value) {
230 result.append(Arg(key, value));
246 } // of anonymous namespace
248 class AircraftProxyModel : public QSortFilterProxyModel
252 AircraftProxyModel(QObject* pr) :
253 QSortFilterProxyModel(pr),
254 m_ratingsFilter(true)
256 for (int i=0; i<4; ++i) {
261 void setRatings(int* ratings)
263 ::memcpy(m_ratings, ratings, sizeof(int) * 4);
268 void setRatingFilterEnabled(bool e)
270 if (e == m_ratingsFilter) {
279 bool filterAcceptsRow(int sourceRow, const QModelIndex &sourceParent) const
281 if (!QSortFilterProxyModel::filterAcceptsRow(sourceRow, sourceParent)) {
285 if (m_ratingsFilter) {
286 QModelIndex index = sourceModel()->index(sourceRow, 0, sourceParent);
287 for (int i=0; i<4; ++i) {
288 if (m_ratings[i] > index.data(AircraftRatingRole + i).toInt()) {
298 bool m_ratingsFilter;
302 static void initQtResources()
304 Q_INIT_RESOURCE(resources);
310 void initApp(int& argc, char** argv)
312 static bool qtInitDone = false;
316 QApplication* app = new QApplication(argc, argv);
317 app->setOrganizationName("FlightGear");
318 app->setApplicationName("FlightGear");
319 app->setOrganizationDomain("flightgear.org");
321 // avoid double Apple menu and other weirdness if both Qt and OSG
322 // try to initialise various Cocoa structures.
323 flightgear::WindowBuilder::setPoseAsStandaloneApp(false);
325 Qt::KeyboardModifiers mods = app->queryKeyboardModifiers();
326 if (mods & Qt::AltModifier) {
327 qWarning() << "Alt pressed during launch";
329 // wipe out our settings
334 Options::sharedInstance()->addOption("restore-defaults", "");
339 bool runLauncherDialog()
341 sglog().setLogLevels( SG_ALL, SG_INFO );
343 initQtResources(); // can't be called inside a namespaceb
345 // startup the nav-cache now. This pre-empts normal startup of
346 // the cache, but no harm done. (Providing scenery paths are consistent)
352 // startup the HTTP system now since packages needs it
353 FGHTTPClient* http = new FGHTTPClient;
354 globals->add_subsystem("http", http);
355 // we guard against re-init in the global phase; bind and postinit
356 // will happen as normal
359 // setup scenery paths now, especially TerraSync path for airport
360 // parking locations (after they're downloaded)
364 if (dlg.result() != QDialog::Accepted) {
371 bool runInAppLauncherDialog()
376 if (dlg.result() != QDialog::Accepted) {
383 } // of namespace flightgear
385 QtLauncher::QtLauncher() :
388 m_subsystemIdleTimer(NULL),
391 m_ui.reset(new Ui::Launcher);
394 #if QT_VERSION >= 0x050300
395 // don't require Qt 5.3
396 m_ui->commandLineArgs->setPlaceholderText("--option=value --prop:/sim/name=value");
399 #if QT_VERSION >= 0x050200
400 m_ui->aircraftFilter->setClearButtonEnabled(true);
403 for (int i=0; i<4; ++i) {
404 m_ratingFilters[i] = 3;
407 m_subsystemIdleTimer = new QTimer(this);
408 m_subsystemIdleTimer->setInterval(0);
409 connect(m_subsystemIdleTimer, &QTimer::timeout,
410 this, &QtLauncher::onSubsytemIdleTimeout);
411 m_subsystemIdleTimer->start();
413 // create and configure the proxy model
414 m_aircraftProxy = new AircraftProxyModel(this);
415 connect(m_ui->ratingsFilterCheck, &QAbstractButton::toggled,
416 m_aircraftProxy, &AircraftProxyModel::setRatingFilterEnabled);
417 connect(m_ui->aircraftFilter, &QLineEdit::textChanged,
418 m_aircraftProxy, &QSortFilterProxyModel::setFilterFixedString);
420 connect(m_ui->runButton, SIGNAL(clicked()), this, SLOT(onRun()));
421 connect(m_ui->quitButton, SIGNAL(clicked()), this, SLOT(onQuit()));
423 connect(m_ui->aircraftHistory, &QPushButton::clicked,
424 this, &QtLauncher::onPopupAircraftHistory);
426 connect(m_ui->location, &LocationWidget::descriptionChanged,
427 m_ui->locationDescription, &QLabel::setText);
429 QAction* qa = new QAction(this);
430 qa->setShortcut(QKeySequence("Ctrl+Q"));
431 connect(qa, &QAction::triggered, this, &QtLauncher::onQuit);
434 connect(m_ui->editRatingFilter, &QPushButton::clicked,
435 this, &QtLauncher::onEditRatingsFilter);
437 QIcon historyIcon(":/history-icon");
438 m_ui->aircraftHistory->setIcon(historyIcon);
440 connect(m_ui->timeOfDayCombo, SIGNAL(currentIndexChanged(int)),
441 this, SLOT(updateSettingsSummary()));
442 connect(m_ui->seasonCombo, SIGNAL(currentIndexChanged(int)),
443 this, SLOT(updateSettingsSummary()));
444 connect(m_ui->fetchRealWxrCheckbox, SIGNAL(toggled(bool)),
445 this, SLOT(updateSettingsSummary()));
446 connect(m_ui->rembrandtCheckbox, SIGNAL(toggled(bool)),
447 this, SLOT(updateSettingsSummary()));
448 connect(m_ui->terrasyncCheck, SIGNAL(toggled(bool)),
449 this, SLOT(updateSettingsSummary()));
450 connect(m_ui->startPausedCheck, SIGNAL(toggled(bool)),
451 this, SLOT(updateSettingsSummary()));
452 connect(m_ui->msaaCheckbox, SIGNAL(toggled(bool)),
453 this, SLOT(updateSettingsSummary()));
455 connect(m_ui->rembrandtCheckbox, SIGNAL(toggled(bool)),
456 this, SLOT(onRembrandtToggled(bool)));
457 connect(m_ui->terrasyncCheck, &QCheckBox::toggled,
458 this, &QtLauncher::onToggleTerrasync);
459 updateSettingsSummary();
461 m_aircraftModel = new AircraftItemModel(this, RootRef(globals->packageRoot()));
462 m_aircraftProxy->setSourceModel(m_aircraftModel);
464 m_aircraftProxy->setFilterCaseSensitivity(Qt::CaseInsensitive);
465 m_aircraftProxy->setSortCaseSensitivity(Qt::CaseInsensitive);
466 m_aircraftProxy->setSortRole(Qt::DisplayRole);
467 m_aircraftProxy->setDynamicSortFilter(true);
469 m_ui->aircraftList->setModel(m_aircraftProxy);
470 m_ui->aircraftList->setHorizontalScrollBarPolicy(Qt::ScrollBarAlwaysOff);
471 AircraftItemDelegate* delegate = new AircraftItemDelegate(m_ui->aircraftList);
472 m_ui->aircraftList->setItemDelegate(delegate);
473 m_ui->aircraftList->setSelectionMode(QAbstractItemView::SingleSelection);
474 connect(m_ui->aircraftList, &QListView::clicked,
475 this, &QtLauncher::onAircraftSelected);
476 connect(delegate, &AircraftItemDelegate::variantChanged,
477 this, &QtLauncher::onAircraftSelected);
478 connect(delegate, &AircraftItemDelegate::requestInstall,
479 this, &QtLauncher::onRequestPackageInstall);
480 connect(delegate, &AircraftItemDelegate::cancelDownload,
481 this, &QtLauncher::onCancelDownload);
483 connect(m_aircraftModel, &AircraftItemModel::aircraftInstallCompleted,
484 this, &QtLauncher::onAircraftInstalledCompleted);
485 connect(m_aircraftModel, &AircraftItemModel::aircraftInstallFailed,
486 this, &QtLauncher::onAircraftInstallFailed);
487 connect(m_aircraftModel, &AircraftItemModel::scanCompleted,
488 this, &QtLauncher::updateSelectedAircraft);
489 connect(m_ui->pathsButton, &QPushButton::clicked,
490 this, &QtLauncher::onEditPaths);
495 m_aircraftModel->setPaths(settings.value("aircraft-paths").toStringList());
496 m_aircraftModel->scanDirs();
499 QtLauncher::~QtLauncher()
504 void QtLauncher::setInAppMode()
507 m_ui->tabWidget->removeTab(2);
508 m_ui->runButton->setText(tr("Apply"));
509 m_ui->quitButton->setText(tr("Cancel"));
511 disconnect(m_ui->runButton, SIGNAL(clicked()), this, SLOT(onRun()));
512 connect(m_ui->runButton, SIGNAL(clicked()), this, SLOT(onApply()));
515 void initApp(int& argc, char** argv)
517 sglog().setLogLevels( SG_ALL, SG_INFO );
518 Q_INIT_RESOURCE(resources);
520 static bool qtInitDone = false;
524 s_argc = argc; // QApplication only stores a reference to argc,
525 // and may crash if it is freed
526 // http://doc.qt.io/qt-5/qguiapplication.html#QGuiApplication
528 QApplication* app = new QApplication(s_argc, argv);
529 app->setOrganizationName("FlightGear");
530 app->setApplicationName("FlightGear");
531 app->setOrganizationDomain("flightgear.org");
533 // avoid double Apple menu and other weirdness if both Qt and OSG
534 // try to initialise various Cocoa structures.
535 flightgear::WindowBuilder::setPoseAsStandaloneApp(false);
537 Qt::KeyboardModifiers mods = app->queryKeyboardModifiers();
538 if (mods & Qt::AltModifier) {
539 qWarning() << "Alt pressed during launch";
541 // wipe out our settings
545 Options::sharedInstance()->addOption("restore-defaults", "");
550 bool runLauncherDialog()
552 // startup the nav-cache now. This preempts normal startup of
553 // the cache, but no harm done. (Providing scenery paths are consistent)
557 // setup scenery paths now, especially TerraSync path for airport
558 // parking locations (after they're downloaded)
562 if (dlg.result() != QDialog::Accepted) {
569 void QtLauncher::restoreSettings()
572 m_ui->rembrandtCheckbox->setChecked(settings.value("enable-rembrandt", false).toBool());
573 m_ui->terrasyncCheck->setChecked(settings.value("enable-terrasync", true).toBool());
574 m_ui->fullScreenCheckbox->setChecked(settings.value("start-fullscreen", false).toBool());
575 m_ui->msaaCheckbox->setChecked(settings.value("enable-msaa", false).toBool());
576 m_ui->fetchRealWxrCheckbox->setChecked(settings.value("enable-realwx", true).toBool());
577 m_ui->startPausedCheck->setChecked(settings.value("start-paused", false).toBool());
578 m_ui->timeOfDayCombo->setCurrentIndex(settings.value("timeofday", 0).toInt());
579 m_ui->seasonCombo->setCurrentIndex(settings.value("season", 0).toInt());
581 // full paths to -set.xml files
582 m_recentAircraft = QUrl::fromStringList(settings.value("recent-aircraft").toStringList());
584 if (!m_recentAircraft.empty()) {
585 m_selectedAircraft = m_recentAircraft.front();
587 // select the default C172p
590 updateSelectedAircraft();
591 m_ui->location->restoreSettings();
594 m_ui->ratingsFilterCheck->setChecked(settings.value("ratings-filter", true).toBool());
596 Q_FOREACH(QVariant v, settings.value("min-ratings").toList()) {
597 m_ratingFilters[index++] = v.toInt();
600 m_aircraftProxy->setRatingFilterEnabled(m_ui->ratingsFilterCheck->isChecked());
601 m_aircraftProxy->setRatings(m_ratingFilters);
603 m_ui->commandLineArgs->setPlainText(settings.value("additional-args").toString());
606 void QtLauncher::saveSettings()
609 settings.setValue("enable-rembrandt", m_ui->rembrandtCheckbox->isChecked());
610 settings.setValue("enable-terrasync", m_ui->terrasyncCheck->isChecked());
611 settings.setValue("enable-msaa", m_ui->msaaCheckbox->isChecked());
612 settings.setValue("start-fullscreen", m_ui->fullScreenCheckbox->isChecked());
613 settings.setValue("enable-realwx", m_ui->fetchRealWxrCheckbox->isChecked());
614 settings.setValue("start-paused", m_ui->startPausedCheck->isChecked());
615 settings.setValue("ratings-filter", m_ui->ratingsFilterCheck->isChecked());
616 settings.setValue("recent-aircraft", QUrl::toStringList(m_recentAircraft));
618 settings.setValue("timeofday", m_ui->timeOfDayCombo->currentIndex());
619 settings.setValue("season", m_ui->seasonCombo->currentIndex());
620 settings.setValue("additional-args", m_ui->commandLineArgs->toPlainText());
622 m_ui->location->saveSettings();
623 qDebug() << "saving settings";
626 void QtLauncher::setEnableDisableOptionFromCheckbox(QCheckBox* cbox, QString name) const
628 flightgear::Options* opt = flightgear::Options::sharedInstance();
629 std::string stdName(name.toStdString());
630 if (cbox->isChecked()) {
631 opt->addOption("enable-" + stdName, "");
633 opt->addOption("disable-" + stdName, "");
637 void QtLauncher::onRun()
641 flightgear::Options* opt = flightgear::Options::sharedInstance();
642 setEnableDisableOptionFromCheckbox(m_ui->terrasyncCheck, "terrasync");
643 setEnableDisableOptionFromCheckbox(m_ui->fetchRealWxrCheckbox, "real-weather-fetch");
644 setEnableDisableOptionFromCheckbox(m_ui->rembrandtCheckbox, "rembrandt");
645 setEnableDisableOptionFromCheckbox(m_ui->fullScreenCheckbox, "fullscreen");
646 // setEnableDisableOptionFromCheckbox(m_ui->startPausedCheck, "freeze");
648 bool startPaused = m_ui->startPausedCheck->isChecked() ||
649 m_ui->location->shouldStartPaused();
651 qDebug() << "will start paused";
652 opt->addOption("enable-freeze", "");
655 // MSAA is more complex
656 if (!m_ui->rembrandtCheckbox->isChecked()) {
657 if (m_ui->msaaCheckbox->isChecked()) {
658 globals->get_props()->setIntValue("/sim/rendering/multi-sample-buffers", 1);
659 globals->get_props()->setIntValue("/sim/rendering/multi-samples", 4);
661 globals->get_props()->setIntValue("/sim/rendering/multi-sample-buffers", 0);
666 if (!m_selectedAircraft.isEmpty()) {
667 if (m_selectedAircraft.isLocalFile()) {
668 QFileInfo setFileInfo(m_selectedAircraft.toLocalFile());
669 opt->addOption("aircraft-dir", setFileInfo.dir().absolutePath().toStdString());
670 QString setFile = setFileInfo.fileName();
671 Q_ASSERT(setFile.endsWith("-set.xml"));
672 setFile.truncate(setFile.count() - 8); // drop the '-set.xml' portion
673 opt->addOption("aircraft", setFile.toStdString());
674 } else if (m_selectedAircraft.scheme() == "package") {
675 PackageRef pkg = packageForAircraftURI(m_selectedAircraft);
676 // no need to set aircraft-dir, handled by the corresponding code
678 opt->addOption("aircraft", pkg->qualifiedId());
680 qWarning() << "unsupported aircraft launch URL" << m_selectedAircraft;
683 // manage aircraft history
684 if (m_recentAircraft.contains(m_selectedAircraft))
685 m_recentAircraft.removeOne(m_selectedAircraft);
686 m_recentAircraft.prepend(m_selectedAircraft);
687 if (m_recentAircraft.size() > MAX_RECENT_AIRCRAFT)
688 m_recentAircraft.pop_back();
690 qDebug() << "recent aircraft is now" << m_recentAircraft;
693 m_ui->location->setLocationOptions();
696 if (m_ui->timeOfDayCombo->currentIndex() != 0) {
697 QString dayval = m_ui->timeOfDayCombo->currentText().toLower();
698 opt->addOption("timeofday", dayval.toStdString());
701 if (m_ui->seasonCombo->currentIndex() != 0) {
702 QString dayval = m_ui->timeOfDayCombo->currentText().toLower();
703 opt->addOption("season", dayval.toStdString());
707 QString downloadDir = settings.value("download-dir").toString();
708 if (!downloadDir.isEmpty()) {
711 int result = QMessageBox::question(this, tr("Create download folder?"),
712 tr("The selected location for downloads does not exist. Create it?"),
713 QMessageBox::Yes | QMessageBox::No | QMessageBox::Cancel);
714 if (result == QMessageBox::Cancel) {
718 if (result == QMessageBox::Yes) {
719 d.mkpath(downloadDir);
723 qDebug() << "Download dir is:" << downloadDir;
724 opt->addOption("download-dir", downloadDir.toStdString());
728 Q_FOREACH(QString path, settings.value("scenery-paths").toStringList()) {
729 opt->addOption("fg-scenery", path.toStdString());
733 Q_FOREACH(QString path, settings.value("aircraft-paths").toStringList()) {
734 // can't use fg-aircraft for this, as it is processed before the launcher is run
735 globals->append_aircraft_path(path.toStdString());
738 // additional arguments
739 ArgumentsTokenizer tk;
740 Q_FOREACH(ArgumentsTokenizer::Arg a, tk.tokenize(m_ui->commandLineArgs->toPlainText())) {
741 if (a.arg.startsWith("prop:")) {
742 QString v = a.arg.mid(5) + "=" + a.value;
743 opt->addOption("prop", v.toStdString());
745 opt->addOption(a.arg.toStdString(), a.value.toStdString());
753 void QtLauncher::onApply()
758 if (!m_selectedAircraft.isEmpty()) {
759 std::string aircraftPropValue,
762 if (m_selectedAircraft.isLocalFile()) {
763 QFileInfo setFileInfo(m_selectedAircraft.toLocalFile());
764 QString setFile = setFileInfo.fileName();
765 Q_ASSERT(setFile.endsWith("-set.xml"));
766 setFile.truncate(setFile.count() - 8); // drop the '-set.xml' portion
767 aircraftDir = setFileInfo.dir().absolutePath().toStdString();
768 aircraftPropValue = setFile.toStdString();
769 } else if (m_selectedAircraft.scheme() == "package") {
770 PackageRef pkg = packageForAircraftURI(m_selectedAircraft);
771 // no need to set aircraft-dir, handled by the corresponding code
773 aircraftPropValue = pkg->qualifiedId();
775 qWarning() << "unsupported aircraft launch URL" << m_selectedAircraft;
778 // manage aircraft history
779 if (m_recentAircraft.contains(m_selectedAircraft))
780 m_recentAircraft.removeOne(m_selectedAircraft);
781 m_recentAircraft.prepend(m_selectedAircraft);
782 if (m_recentAircraft.size() > MAX_RECENT_AIRCRAFT)
783 m_recentAircraft.pop_back();
785 globals->get_props()->setStringValue("/sim/aircraft", aircraftPropValue);
786 globals->get_props()->setStringValue("/sim/aircraft-dir", aircraftDir);
793 void QtLauncher::onQuit()
798 void QtLauncher::onToggleTerrasync(bool enabled)
802 QString downloadDir = settings.value("download-dir").toString();
803 if (downloadDir.isEmpty()) {
804 downloadDir = QString::fromStdString(flightgear::defaultDownloadDir());
807 QFileInfo info(downloadDir);
808 if (!info.exists()) {
810 msg.setWindowTitle(tr("Create download folder?"));
811 msg.setText(tr("The download folder '%1' does not exist, create it now? "
812 "Click 'change location' to choose another folder "
813 "to store downloaded files").arg(downloadDir));
814 msg.addButton(QMessageBox::Yes);
815 msg.addButton(QMessageBox::Cancel);
816 msg.addButton(tr("Change location"), QMessageBox::ActionRole);
817 int result = msg.exec();
819 if (result == QMessageBox::Cancel) {
820 m_ui->terrasyncCheck->setChecked(false);
824 if (result == QMessageBox::ActionRole) {
830 d.mkpath(downloadDir);
835 void QtLauncher::onAircraftInstalledCompleted(QModelIndex index)
837 maybeUpdateSelectedAircraft(index);
840 void QtLauncher::onAircraftInstallFailed(QModelIndex index, QString errorMessage)
842 qWarning() << Q_FUNC_INFO << index.data(AircraftURIRole) << errorMessage;
845 msg.setWindowTitle(tr("Aircraft installation failed"));
846 msg.setText(tr("An error occurred installing the aircraft %1: %2").
847 arg(index.data(Qt::DisplayRole).toString()).arg(errorMessage));
848 msg.addButton(QMessageBox::Ok);
851 maybeUpdateSelectedAircraft(index);
854 void QtLauncher::onAircraftSelected(const QModelIndex& index)
856 m_selectedAircraft = index.data(AircraftURIRole).toUrl();
857 updateSelectedAircraft();
860 void QtLauncher::onRequestPackageInstall(const QModelIndex& index)
862 QString pkg = index.data(AircraftPackageIdRole).toString();
863 simgear::pkg::PackageRef pref = globals->packageRoot()->getPackageById(pkg.toStdString());
864 if (pref->isInstalled()) {
865 InstallRef install = pref->existingInstall();
866 if (install && install->hasUpdate()) {
867 globals->packageRoot()->scheduleToUpdate(install);
874 void QtLauncher::onCancelDownload(const QModelIndex& index)
876 QString pkg = index.data(AircraftPackageIdRole).toString();
877 simgear::pkg::PackageRef pref = globals->packageRoot()->getPackageById(pkg.toStdString());
878 simgear::pkg::InstallRef i = pref->existingInstall();
882 void QtLauncher::maybeUpdateSelectedAircraft(QModelIndex index)
884 QUrl u = index.data(AircraftURIRole).toUrl();
885 if (u == m_selectedAircraft) {
886 // potentially enable the run button now!
887 updateSelectedAircraft();
891 void QtLauncher::updateSelectedAircraft()
893 QModelIndex index = m_aircraftModel->indexOfAircraftURI(m_selectedAircraft);
894 if (index.isValid()) {
895 QPixmap pm = index.data(Qt::DecorationRole).value<QPixmap>();
896 m_ui->thumbnail->setPixmap(pm);
897 m_ui->aircraftDescription->setText(index.data(Qt::DisplayRole).toString());
899 int status = index.data(AircraftPackageStatusRole).toInt();
900 bool canRun = (status == PackageInstalled);
901 m_ui->runButton->setEnabled(canRun);
903 LauncherAircraftType aircraftType = Airplane;
904 if (index.data(AircraftIsHelicopterRole).toBool()) {
905 aircraftType = Helicopter;
906 } else if (index.data(AircraftIsSeaplaneRole).toBool()) {
907 aircraftType = Seaplane;
910 m_ui->location->setAircraftType(aircraftType);
912 m_ui->thumbnail->setPixmap(QPixmap());
913 m_ui->aircraftDescription->setText("");
914 m_ui->runButton->setEnabled(false);
918 QModelIndex QtLauncher::proxyIndexForAircraftURI(QUrl uri) const
920 return m_aircraftProxy->mapFromSource(sourceIndexForAircraftURI(uri));
923 QModelIndex QtLauncher::sourceIndexForAircraftURI(QUrl uri) const
925 AircraftItemModel* sourceModel = qobject_cast<AircraftItemModel*>(m_aircraftProxy->sourceModel());
926 Q_ASSERT(sourceModel);
927 return sourceModel->indexOfAircraftURI(uri);
930 void QtLauncher::onPopupAircraftHistory()
932 if (m_recentAircraft.isEmpty()) {
937 Q_FOREACH(QUrl uri, m_recentAircraft) {
938 QModelIndex index = sourceIndexForAircraftURI(uri);
939 if (!index.isValid()) {
943 QAction* act = m.addAction(index.data(Qt::DisplayRole).toString());
947 QPoint popupPos = m_ui->aircraftHistory->mapToGlobal(m_ui->aircraftHistory->rect().bottomLeft());
948 QAction* triggered = m.exec(popupPos);
950 m_selectedAircraft = triggered->data().toUrl();
951 QModelIndex index = proxyIndexForAircraftURI(m_selectedAircraft);
952 m_ui->aircraftList->selectionModel()->setCurrentIndex(index,
953 QItemSelectionModel::ClearAndSelect);
954 m_ui->aircraftFilter->clear();
955 updateSelectedAircraft();
959 void QtLauncher::onEditRatingsFilter()
961 EditRatingsFilterDialog dialog(this);
962 dialog.setRatings(m_ratingFilters);
965 if (dialog.result() == QDialog::Accepted) {
967 for (int i=0; i<4; ++i) {
968 m_ratingFilters[i] = dialog.getRating(i);
969 vl.append(m_ratingFilters[i]);
971 m_aircraftProxy->setRatings(m_ratingFilters);
974 settings.setValue("min-ratings", vl);
978 void QtLauncher::updateSettingsSummary()
981 if (m_ui->timeOfDayCombo->currentIndex() > 0) {
982 summary.append(QString(m_ui->timeOfDayCombo->currentText().toLower()));
985 if (m_ui->seasonCombo->currentIndex() > 0) {
986 summary.append(QString(m_ui->seasonCombo->currentText().toLower()));
989 if (m_ui->rembrandtCheckbox->isChecked()) {
990 summary.append("Rembrandt enabled");
991 } else if (m_ui->msaaCheckbox->isChecked()) {
992 summary.append("anti-aliasing");
995 if (m_ui->fetchRealWxrCheckbox->isChecked()) {
996 summary.append("live weather");
999 if (m_ui->terrasyncCheck->isChecked()) {
1000 summary.append("automatic scenery downloads");
1003 if (m_ui->startPausedCheck->isChecked()) {
1004 summary.append("paused");
1007 QString s = summary.join(", ");
1008 s[0] = s[0].toUpper();
1009 m_ui->settingsDescription->setText(s);
1012 void QtLauncher::onRembrandtToggled(bool b)
1014 // Rembrandt and multi-sample are exclusive
1015 m_ui->msaaCheckbox->setEnabled(!b);
1018 void QtLauncher::onSubsytemIdleTimeout()
1020 globals->get_subsystem_mgr()->update(0.0);
1023 void QtLauncher::onEditPaths()
1025 PathsDialog dlg(this, globals->packageRoot());
1027 if (dlg.result() == QDialog::Accepted) {
1028 // re-scan the aircraft list
1030 m_aircraftModel->setPaths(settings.value("aircraft-paths").toStringList());
1031 m_aircraftModel->scanDirs();
1035 simgear::pkg::PackageRef QtLauncher::packageForAircraftURI(QUrl uri) const
1037 if (uri.scheme() != "package") {
1038 qWarning() << "invalid URL scheme:" << uri;
1039 return simgear::pkg::PackageRef();
1042 QString ident = uri.path();
1043 return globals->packageRoot()->getPackageById(ident.toStdString());
1047 #include "QtLauncher.moc"