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 <<<<<<< 56d7d049bc0b7361d1799298c38e61084f5d5e3f
249 class IdentSearchFilter : public FGPositioned::TypeFilter
254 addType(FGPositioned::AIRPORT);
255 addType(FGPositioned::SEAPORT);
256 addType(FGPositioned::HELIPAD);
257 addType(FGPositioned::VOR);
258 addType(FGPositioned::FIX);
259 addType(FGPositioned::NDB);
263 class AircraftProxyModel : public QSortFilterProxyModel
267 AircraftProxyModel(QObject* pr) :
268 QSortFilterProxyModel(pr),
269 m_ratingsFilter(true)
271 for (int i=0; i<4; ++i) {
276 void setRatings(int* ratings)
278 ::memcpy(m_ratings, ratings, sizeof(int) * 4);
283 void setRatingFilterEnabled(bool e)
285 if (e == m_ratingsFilter) {
294 bool filterAcceptsRow(int sourceRow, const QModelIndex &sourceParent) const
296 if (!QSortFilterProxyModel::filterAcceptsRow(sourceRow, sourceParent)) {
300 if (m_ratingsFilter) {
301 QModelIndex index = sourceModel()->index(sourceRow, 0, sourceParent);
302 for (int i=0; i<4; ++i) {
303 if (m_ratings[i] > index.data(AircraftRatingRole + i).toInt()) {
313 bool m_ratingsFilter;
317 static void initQtResources()
319 Q_INIT_RESOURCE(resources);
325 void initApp(int& argc, char** argv)
327 static bool qtInitDone = false;
331 QApplication* app = new QApplication(argc, argv);
332 app->setOrganizationName("FlightGear");
333 app->setApplicationName("FlightGear");
334 app->setOrganizationDomain("flightgear.org");
336 // avoid double Apple menu and other weirdness if both Qt and OSG
337 // try to initialise various Cocoa structures.
338 flightgear::WindowBuilder::setPoseAsStandaloneApp(false);
340 Qt::KeyboardModifiers mods = app->queryKeyboardModifiers();
341 if (mods & Qt::AltModifier) {
342 qWarning() << "Alt pressed during launch";
344 // wipe out our settings
349 Options::sharedInstance()->addOption("restore-defaults", "");
354 bool runLauncherDialog()
356 sglog().setLogLevels( SG_ALL, SG_INFO );
358 initQtResources(); // can't be called inside a namespaceb
360 // startup the nav-cache now. This pre-empts normal startup of
361 // the cache, but no harm done. (Providing scenery paths are consistent)
367 // startup the HTTP system now since packages needs it
368 FGHTTPClient* http = new FGHTTPClient;
369 globals->add_subsystem("http", http);
370 // we guard against re-init in the global phase; bind and postinit
371 // will happen as normal
374 // setup scenery paths now, especially TerraSync path for airport
375 // parking locations (after they're downloaded)
379 if (dlg.result() != QDialog::Accepted) {
386 bool runInAppLauncherDialog()
391 if (dlg.result() != QDialog::Accepted) {
398 } // of namespace flightgear
400 QtLauncher::QtLauncher() :
403 m_subsystemIdleTimer(NULL),
406 m_ui.reset(new Ui::Launcher);
409 #if QT_VERSION >= 0x050300
410 // don't require Qt 5.3
411 m_ui->commandLineArgs->setPlaceholderText("--option=value --prop:/sim/name=value");
414 #if QT_VERSION >= 0x050200
415 m_ui->aircraftFilter->setClearButtonEnabled(true);
418 for (int i=0; i<4; ++i) {
419 m_ratingFilters[i] = 3;
422 m_subsystemIdleTimer = new QTimer(this);
423 m_subsystemIdleTimer->setInterval(0);
424 connect(m_subsystemIdleTimer, &QTimer::timeout,
425 this, &QtLauncher::onSubsytemIdleTimeout);
426 m_subsystemIdleTimer->start();
428 // create and configure the proxy model
429 m_aircraftProxy = new AircraftProxyModel(this);
430 connect(m_ui->ratingsFilterCheck, &QAbstractButton::toggled,
431 m_aircraftProxy, &AircraftProxyModel::setRatingFilterEnabled);
432 connect(m_ui->aircraftFilter, &QLineEdit::textChanged,
433 m_aircraftProxy, &QSortFilterProxyModel::setFilterFixedString);
435 connect(m_ui->runButton, SIGNAL(clicked()), this, SLOT(onRun()));
436 connect(m_ui->quitButton, SIGNAL(clicked()), this, SLOT(onQuit()));
438 connect(m_ui->aircraftHistory, &QPushButton::clicked,
439 this, &QtLauncher::onPopupAircraftHistory);
441 connect(m_ui->location, &LocationWidget::descriptionChanged,
442 m_ui->locationDescription, &QLabel::setText);
444 QAction* qa = new QAction(this);
445 qa->setShortcut(QKeySequence("Ctrl+Q"));
446 connect(qa, &QAction::triggered, this, &QtLauncher::onQuit);
449 connect(m_ui->editRatingFilter, &QPushButton::clicked,
450 this, &QtLauncher::onEditRatingsFilter);
452 QIcon historyIcon(":/history-icon");
453 m_ui->aircraftHistory->setIcon(historyIcon);
455 connect(m_ui->timeOfDayCombo, SIGNAL(currentIndexChanged(int)),
456 this, SLOT(updateSettingsSummary()));
457 connect(m_ui->seasonCombo, SIGNAL(currentIndexChanged(int)),
458 this, SLOT(updateSettingsSummary()));
459 connect(m_ui->fetchRealWxrCheckbox, SIGNAL(toggled(bool)),
460 this, SLOT(updateSettingsSummary()));
461 connect(m_ui->rembrandtCheckbox, SIGNAL(toggled(bool)),
462 this, SLOT(updateSettingsSummary()));
463 connect(m_ui->terrasyncCheck, SIGNAL(toggled(bool)),
464 this, SLOT(updateSettingsSummary()));
465 connect(m_ui->startPausedCheck, SIGNAL(toggled(bool)),
466 this, SLOT(updateSettingsSummary()));
467 connect(m_ui->msaaCheckbox, SIGNAL(toggled(bool)),
468 this, SLOT(updateSettingsSummary()));
470 connect(m_ui->rembrandtCheckbox, SIGNAL(toggled(bool)),
471 this, SLOT(onRembrandtToggled(bool)));
472 connect(m_ui->terrasyncCheck, &QCheckBox::toggled,
473 this, &QtLauncher::onToggleTerrasync);
474 updateSettingsSummary();
476 m_aircraftModel = new AircraftItemModel(this, RootRef(globals->packageRoot()));
477 m_aircraftProxy->setSourceModel(m_aircraftModel);
479 m_aircraftProxy->setFilterCaseSensitivity(Qt::CaseInsensitive);
480 m_aircraftProxy->setSortCaseSensitivity(Qt::CaseInsensitive);
481 m_aircraftProxy->setSortRole(Qt::DisplayRole);
482 m_aircraftProxy->setDynamicSortFilter(true);
484 m_ui->aircraftList->setModel(m_aircraftProxy);
485 m_ui->aircraftList->setHorizontalScrollBarPolicy(Qt::ScrollBarAlwaysOff);
486 AircraftItemDelegate* delegate = new AircraftItemDelegate(m_ui->aircraftList);
487 m_ui->aircraftList->setItemDelegate(delegate);
488 m_ui->aircraftList->setSelectionMode(QAbstractItemView::SingleSelection);
489 connect(m_ui->aircraftList, &QListView::clicked,
490 this, &QtLauncher::onAircraftSelected);
491 connect(delegate, &AircraftItemDelegate::variantChanged,
492 this, &QtLauncher::onAircraftSelected);
493 connect(delegate, &AircraftItemDelegate::requestInstall,
494 this, &QtLauncher::onRequestPackageInstall);
495 connect(delegate, &AircraftItemDelegate::cancelDownload,
496 this, &QtLauncher::onCancelDownload);
498 connect(m_aircraftModel, &AircraftItemModel::aircraftInstallCompleted,
499 this, &QtLauncher::onAircraftInstalledCompleted);
500 connect(m_aircraftModel, &AircraftItemModel::aircraftInstallFailed,
501 this, &QtLauncher::onAircraftInstallFailed);
502 connect(m_aircraftModel, &AircraftItemModel::scanCompleted,
503 this, &QtLauncher::updateSelectedAircraft);
504 connect(m_ui->pathsButton, &QPushButton::clicked,
505 this, &QtLauncher::onEditPaths);
510 m_aircraftModel->setPaths(settings.value("aircraft-paths").toStringList());
511 m_aircraftModel->scanDirs();
514 QtLauncher::~QtLauncher()
519 void QtLauncher::setInAppMode()
522 m_ui->tabWidget->removeTab(2);
523 m_ui->runButton->setText(tr("Apply"));
524 m_ui->quitButton->setText(tr("Cancel"));
526 disconnect(m_ui->runButton, SIGNAL(clicked()), this, SLOT(onRun()));
527 connect(m_ui->runButton, SIGNAL(clicked()), this, SLOT(onApply()));
530 bool QtLauncher::runLauncherDialog()
532 sglog().setLogLevels( SG_ALL, SG_INFO );
533 Q_INIT_RESOURCE(resources);
535 static bool qtInitDone = false;
539 s_argc = argc; // QApplication only stores a reference to argc,
540 // and may crash if it is freed
541 // http://doc.qt.io/qt-5/qguiapplication.html#QGuiApplication
543 QApplication* app = new QApplication(s_argc, argv);
544 app->setOrganizationName("FlightGear");
545 app->setApplicationName("FlightGear");
546 app->setOrganizationDomain("flightgear.org");
548 // avoid double Apple menu and other weirdness if both Qt and OSG
549 // try to initialise various Cocoa structures.
550 flightgear::WindowBuilder::setPoseAsStandaloneApp(false);
552 Qt::KeyboardModifiers mods = app->queryKeyboardModifiers();
553 if (mods & Qt::AltModifier) {
554 qWarning() << "Alt pressed during launch";
556 // wipe out our settings
560 Options::sharedInstance()->addOption("restore-defaults", "");
564 // startup the nav-cache now. This preempts normal startup of
565 // the cache, but no harm done. (Providing scenery paths are consistent)
569 // setup scenery paths now, especially TerraSync path for airport
570 // parking locations (after they're downloaded)
574 if (dlg.result() != QDialog::Accepted) {
579 void QtLauncher::restoreSettings()
582 m_ui->rembrandtCheckbox->setChecked(settings.value("enable-rembrandt", false).toBool());
583 m_ui->terrasyncCheck->setChecked(settings.value("enable-terrasync", true).toBool());
584 m_ui->fullScreenCheckbox->setChecked(settings.value("start-fullscreen", false).toBool());
585 m_ui->msaaCheckbox->setChecked(settings.value("enable-msaa", false).toBool());
586 m_ui->fetchRealWxrCheckbox->setChecked(settings.value("enable-realwx", true).toBool());
587 m_ui->startPausedCheck->setChecked(settings.value("start-paused", false).toBool());
588 m_ui->timeOfDayCombo->setCurrentIndex(settings.value("timeofday", 0).toInt());
589 m_ui->seasonCombo->setCurrentIndex(settings.value("season", 0).toInt());
591 // full paths to -set.xml files
592 m_recentAircraft = QUrl::fromStringList(settings.value("recent-aircraft").toStringList());
594 if (!m_recentAircraft.empty()) {
595 m_selectedAircraft = m_recentAircraft.front();
597 // select the default C172p
600 updateSelectedAircraft();
601 m_ui->location->restoreSettings();
604 m_ui->ratingsFilterCheck->setChecked(settings.value("ratings-filter", true).toBool());
606 Q_FOREACH(QVariant v, settings.value("min-ratings").toList()) {
607 m_ratingFilters[index++] = v.toInt();
610 m_aircraftProxy->setRatingFilterEnabled(m_ui->ratingsFilterCheck->isChecked());
611 m_aircraftProxy->setRatings(m_ratingFilters);
613 m_ui->commandLineArgs->setPlainText(settings.value("additional-args").toString());
616 void QtLauncher::saveSettings()
619 settings.setValue("enable-rembrandt", m_ui->rembrandtCheckbox->isChecked());
620 settings.setValue("enable-terrasync", m_ui->terrasyncCheck->isChecked());
621 settings.setValue("enable-msaa", m_ui->msaaCheckbox->isChecked());
622 settings.setValue("start-fullscreen", m_ui->fullScreenCheckbox->isChecked());
623 settings.setValue("enable-realwx", m_ui->fetchRealWxrCheckbox->isChecked());
624 settings.setValue("start-paused", m_ui->startPausedCheck->isChecked());
625 settings.setValue("ratings-filter", m_ui->ratingsFilterCheck->isChecked());
626 settings.setValue("recent-aircraft", QUrl::toStringList(m_recentAircraft));
628 settings.setValue("timeofday", m_ui->timeOfDayCombo->currentIndex());
629 settings.setValue("season", m_ui->seasonCombo->currentIndex());
630 settings.setValue("additional-args", m_ui->commandLineArgs->toPlainText());
632 m_ui->location->saveSettings();
633 qDebug() << "saving settings";
636 void QtLauncher::setEnableDisableOptionFromCheckbox(QCheckBox* cbox, QString name) const
638 flightgear::Options* opt = flightgear::Options::sharedInstance();
639 std::string stdName(name.toStdString());
640 if (cbox->isChecked()) {
641 opt->addOption("enable-" + stdName, "");
643 opt->addOption("disable-" + stdName, "");
647 void QtLauncher::onRun()
651 flightgear::Options* opt = flightgear::Options::sharedInstance();
652 setEnableDisableOptionFromCheckbox(m_ui->terrasyncCheck, "terrasync");
653 setEnableDisableOptionFromCheckbox(m_ui->fetchRealWxrCheckbox, "real-weather-fetch");
654 setEnableDisableOptionFromCheckbox(m_ui->rembrandtCheckbox, "rembrandt");
655 setEnableDisableOptionFromCheckbox(m_ui->fullScreenCheckbox, "fullscreen");
656 // setEnableDisableOptionFromCheckbox(m_ui->startPausedCheck, "freeze");
658 bool startPaused = m_ui->startPausedCheck->isChecked() ||
659 m_ui->location->shouldStartPaused();
661 qDebug() << "will start paused";
662 opt->addOption("enable-freeze", "");
665 // MSAA is more complex
666 if (!m_ui->rembrandtCheckbox->isChecked()) {
667 if (m_ui->msaaCheckbox->isChecked()) {
668 globals->get_props()->setIntValue("/sim/rendering/multi-sample-buffers", 1);
669 globals->get_props()->setIntValue("/sim/rendering/multi-samples", 4);
671 globals->get_props()->setIntValue("/sim/rendering/multi-sample-buffers", 0);
676 if (!m_selectedAircraft.isEmpty()) {
677 if (m_selectedAircraft.isLocalFile()) {
678 QFileInfo setFileInfo(m_selectedAircraft.toLocalFile());
679 opt->addOption("aircraft-dir", setFileInfo.dir().absolutePath().toStdString());
680 QString setFile = setFileInfo.fileName();
681 Q_ASSERT(setFile.endsWith("-set.xml"));
682 setFile.truncate(setFile.count() - 8); // drop the '-set.xml' portion
683 opt->addOption("aircraft", setFile.toStdString());
684 } else if (m_selectedAircraft.scheme() == "package") {
685 PackageRef pkg = packageForAircraftURI(m_selectedAircraft);
686 // no need to set aircraft-dir, handled by the corresponding code
688 opt->addOption("aircraft", pkg->qualifiedId());
690 qWarning() << "unsupported aircraft launch URL" << m_selectedAircraft;
693 // manage aircraft history
694 if (m_recentAircraft.contains(m_selectedAircraft))
695 m_recentAircraft.removeOne(m_selectedAircraft);
696 m_recentAircraft.prepend(m_selectedAircraft);
697 if (m_recentAircraft.size() > MAX_RECENT_AIRCRAFT)
698 m_recentAircraft.pop_back();
700 qDebug() << "recent aircraft is now" << m_recentAircraft;
703 m_ui->location->setLocationOptions();
706 if (m_ui->timeOfDayCombo->currentIndex() != 0) {
707 QString dayval = m_ui->timeOfDayCombo->currentText().toLower();
708 opt->addOption("timeofday", dayval.toStdString());
711 if (m_ui->seasonCombo->currentIndex() != 0) {
712 QString dayval = m_ui->timeOfDayCombo->currentText().toLower();
713 opt->addOption("season", dayval.toStdString());
717 QString downloadDir = settings.value("download-dir").toString();
718 if (!downloadDir.isEmpty()) {
721 int result = QMessageBox::question(this, tr("Create download folder?"),
722 tr("The selected location for downloads does not exist. Create it?"),
723 QMessageBox::Yes | QMessageBox::No | QMessageBox::Cancel);
724 if (result == QMessageBox::Cancel) {
728 if (result == QMessageBox::Yes) {
729 d.mkpath(downloadDir);
733 qDebug() << "Download dir is:" << downloadDir;
734 opt->addOption("download-dir", downloadDir.toStdString());
738 Q_FOREACH(QString path, settings.value("scenery-paths").toStringList()) {
739 opt->addOption("fg-scenery", path.toStdString());
743 Q_FOREACH(QString path, settings.value("aircraft-paths").toStringList()) {
744 // can't use fg-aircraft for this, as it is processed before the launcher is run
745 globals->append_aircraft_path(path.toStdString());
748 // additional arguments
749 ArgumentsTokenizer tk;
750 Q_FOREACH(ArgumentsTokenizer::Arg a, tk.tokenize(m_ui->commandLineArgs->toPlainText())) {
751 if (a.arg.startsWith("prop:")) {
752 QString v = a.arg.mid(5) + "=" + a.value;
753 opt->addOption("prop", v.toStdString());
755 opt->addOption(a.arg.toStdString(), a.value.toStdString());
763 void QtLauncher::onApply()
768 if (!m_selectedAircraft.isEmpty()) {
769 std::string aircraftPropValue,
772 if (m_selectedAircraft.isLocalFile()) {
773 QFileInfo setFileInfo(m_selectedAircraft.toLocalFile());
774 QString setFile = setFileInfo.fileName();
775 Q_ASSERT(setFile.endsWith("-set.xml"));
776 setFile.truncate(setFile.count() - 8); // drop the '-set.xml' portion
777 aircraftDir = setFileInfo.dir().absolutePath().toStdString();
778 aircraftPropValue = setFile.toStdString();
779 } else if (m_selectedAircraft.scheme() == "package") {
780 PackageRef pkg = packageForAircraftURI(m_selectedAircraft);
781 // no need to set aircraft-dir, handled by the corresponding code
783 aircraftPropValue = pkg->qualifiedId();
785 qWarning() << "unsupported aircraft launch URL" << m_selectedAircraft;
788 // manage aircraft history
789 if (m_recentAircraft.contains(m_selectedAircraft))
790 m_recentAircraft.removeOne(m_selectedAircraft);
791 m_recentAircraft.prepend(m_selectedAircraft);
792 if (m_recentAircraft.size() > MAX_RECENT_AIRCRAFT)
793 m_recentAircraft.pop_back();
795 globals->get_props()->setStringValue("/sim/aircraft", aircraftPropValue);
796 globals->get_props()->setStringValue("/sim/aircraft-dir", aircraftDir);
803 void QtLauncher::onQuit()
808 void QtLauncher::onToggleTerrasync(bool enabled)
812 QString downloadDir = settings.value("download-dir").toString();
813 if (downloadDir.isEmpty()) {
814 downloadDir = QString::fromStdString(flightgear::defaultDownloadDir());
817 QFileInfo info(downloadDir);
818 if (!info.exists()) {
820 msg.setWindowTitle(tr("Create download folder?"));
821 msg.setText(tr("The download folder '%1' does not exist, create it now? "
822 "Click 'change location' to choose another folder "
823 "to store downloaded files").arg(downloadDir));
824 msg.addButton(QMessageBox::Yes);
825 msg.addButton(QMessageBox::Cancel);
826 msg.addButton(tr("Change location"), QMessageBox::ActionRole);
827 int result = msg.exec();
829 if (result == QMessageBox::Cancel) {
830 m_ui->terrasyncCheck->setChecked(false);
834 if (result == QMessageBox::ActionRole) {
840 d.mkpath(downloadDir);
845 void QtLauncher::onAircraftInstalledCompleted(QModelIndex index)
847 maybeUpdateSelectedAircraft(index);
850 void QtLauncher::onAircraftInstallFailed(QModelIndex index, QString errorMessage)
852 qWarning() << Q_FUNC_INFO << index.data(AircraftURIRole) << errorMessage;
855 msg.setWindowTitle(tr("Aircraft installation failed"));
856 msg.setText(tr("An error occurred installing the aircraft %1: %2").
857 arg(index.data(Qt::DisplayRole).toString()).arg(errorMessage));
858 msg.addButton(QMessageBox::Ok);
861 maybeUpdateSelectedAircraft(index);
864 void QtLauncher::onAircraftSelected(const QModelIndex& index)
866 m_selectedAircraft = index.data(AircraftURIRole).toUrl();
867 qDebug() << "selected aircraft is now" << m_selectedAircraft;
868 updateSelectedAircraft();
871 void QtLauncher::onRequestPackageInstall(const QModelIndex& index)
873 QString pkg = index.data(AircraftPackageIdRole).toString();
874 simgear::pkg::PackageRef pref = globals->packageRoot()->getPackageById(pkg.toStdString());
875 if (pref->isInstalled()) {
876 InstallRef install = pref->existingInstall();
877 if (install && install->hasUpdate()) {
878 globals->packageRoot()->scheduleToUpdate(install);
885 void QtLauncher::onCancelDownload(const QModelIndex& index)
887 QString pkg = index.data(AircraftPackageIdRole).toString();
888 simgear::pkg::PackageRef pref = globals->packageRoot()->getPackageById(pkg.toStdString());
889 simgear::pkg::InstallRef i = pref->existingInstall();
893 void QtLauncher::maybeUpdateSelectedAircraft(QModelIndex index)
895 QUrl u = index.data(AircraftURIRole).toUrl();
896 if (u == m_selectedAircraft) {
897 // potentially enable the run button now!
898 updateSelectedAircraft();
902 void QtLauncher::updateSelectedAircraft()
904 QModelIndex index = m_aircraftModel->indexOfAircraftURI(m_selectedAircraft);
905 if (index.isValid()) {
906 QPixmap pm = index.data(Qt::DecorationRole).value<QPixmap>();
907 m_ui->thumbnail->setPixmap(pm);
908 m_ui->aircraftDescription->setText(index.data(Qt::DisplayRole).toString());
910 int status = index.data(AircraftPackageStatusRole).toInt();
911 bool canRun = (status == PackageInstalled);
912 m_ui->runButton->setEnabled(canRun);
914 m_ui->thumbnail->setPixmap(QPixmap());
915 m_ui->aircraftDescription->setText("");
916 m_ui->runButton->setEnabled(false);
920 QModelIndex QtLauncher::proxyIndexForAircraftURI(QUrl uri) const
922 return m_aircraftProxy->mapFromSource(sourceIndexForAircraftURI(uri));
925 QModelIndex QtLauncher::sourceIndexForAircraftURI(QUrl uri) const
927 AircraftItemModel* sourceModel = qobject_cast<AircraftItemModel*>(m_aircraftProxy->sourceModel());
928 Q_ASSERT(sourceModel);
929 return sourceModel->indexOfAircraftURI(uri);
932 void QtLauncher::onPopupAircraftHistory()
934 if (m_recentAircraft.isEmpty()) {
939 Q_FOREACH(QUrl uri, m_recentAircraft) {
940 QModelIndex index = sourceIndexForAircraftURI(uri);
941 if (!index.isValid()) {
945 QAction* act = m.addAction(index.data(Qt::DisplayRole).toString());
949 QPoint popupPos = m_ui->aircraftHistory->mapToGlobal(m_ui->aircraftHistory->rect().bottomLeft());
950 QAction* triggered = m.exec(popupPos);
952 m_selectedAircraft = triggered->data().toUrl();
953 QModelIndex index = proxyIndexForAircraftURI(m_selectedAircraft);
954 m_ui->aircraftList->selectionModel()->setCurrentIndex(index,
955 QItemSelectionModel::ClearAndSelect);
956 m_ui->aircraftFilter->clear();
957 updateSelectedAircraft();
961 void QtLauncher::onEditRatingsFilter()
963 EditRatingsFilterDialog dialog(this);
964 dialog.setRatings(m_ratingFilters);
967 if (dialog.result() == QDialog::Accepted) {
969 for (int i=0; i<4; ++i) {
970 m_ratingFilters[i] = dialog.getRating(i);
971 vl.append(m_ratingFilters[i]);
973 m_aircraftProxy->setRatings(m_ratingFilters);
976 settings.setValue("min-ratings", vl);
980 void QtLauncher::updateSettingsSummary()
983 if (m_ui->timeOfDayCombo->currentIndex() > 0) {
984 summary.append(QString(m_ui->timeOfDayCombo->currentText().toLower()));
987 if (m_ui->seasonCombo->currentIndex() > 0) {
988 summary.append(QString(m_ui->seasonCombo->currentText().toLower()));
991 if (m_ui->rembrandtCheckbox->isChecked()) {
992 summary.append("Rembrandt enabled");
993 } else if (m_ui->msaaCheckbox->isChecked()) {
994 summary.append("anti-aliasing");
997 if (m_ui->fetchRealWxrCheckbox->isChecked()) {
998 summary.append("live weather");
1001 if (m_ui->terrasyncCheck->isChecked()) {
1002 summary.append("automatic scenery downloads");
1005 if (m_ui->startPausedCheck->isChecked()) {
1006 summary.append("paused");
1009 QString s = summary.join(", ");
1010 s[0] = s[0].toUpper();
1011 m_ui->settingsDescription->setText(s);
1014 void QtLauncher::onRembrandtToggled(bool b)
1016 // Rembrandt and multi-sample are exclusive
1017 m_ui->msaaCheckbox->setEnabled(!b);
1020 void QtLauncher::onSubsytemIdleTimeout()
1022 globals->get_subsystem_mgr()->update(0.0);
1025 void QtLauncher::onEditPaths()
1027 PathsDialog dlg(this, globals->packageRoot());
1029 if (dlg.result() == QDialog::Accepted) {
1030 // re-scan the aircraft list
1032 m_aircraftModel->setPaths(settings.value("aircraft-paths").toStringList());
1033 m_aircraftModel->scanDirs();
1037 simgear::pkg::PackageRef QtLauncher::packageForAircraftURI(QUrl uri) const
1039 if (uri.scheme() != "package") {
1040 qWarning() << "invalid URL scheme:" << uri;
1041 return simgear::pkg::PackageRef();
1044 QString ident = uri.path();
1045 return globals->packageRoot()->getPackageById(ident.toStdString());
1049 #include "QtLauncher.moc"