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 <Airports/airport.hxx>
67 #include <Airports/dynamics.hxx> // for parking
68 #include <Navaids/navrecord.hxx>
70 #include <Main/options.hxx>
71 #include <Main/fg_init.hxx>
72 #include <Viewer/WindowBuilder.hxx>
73 #include <Network/HTTPClient.hxx>
75 using namespace flightgear;
76 using namespace simgear::pkg;
78 const int MAX_RECENT_AIRPORTS = 32;
79 const int MAX_RECENT_AIRCRAFT = 20;
81 namespace { // anonymous namespace
85 QString baseLabel = QT_TR_NOOP("Initialising navigation data, this may take several minutes");
86 NavDataCache* cache = NavDataCache::createInstance();
87 if (cache->isRebuildRequired()) {
88 QProgressDialog rebuildProgress(baseLabel,
89 QString() /* cancel text */,
91 rebuildProgress.setWindowModality(Qt::WindowModal);
92 rebuildProgress.show();
94 NavDataCache::RebuildPhase phase = cache->rebuild();
96 while (phase != NavDataCache::REBUILD_DONE) {
97 // sleep to give the rebuild thread more time
98 SGTimeStamp::sleepForMSec(50);
99 phase = cache->rebuild();
102 case NavDataCache::REBUILD_AIRPORTS:
103 rebuildProgress.setLabelText(QT_TR_NOOP("Loading airport data"));
106 case NavDataCache::REBUILD_FIXES:
107 rebuildProgress.setLabelText(QT_TR_NOOP("Loading waypoint data"));
110 case NavDataCache::REBUILD_NAVAIDS:
111 rebuildProgress.setLabelText(QT_TR_NOOP("Loading navigation data"));
115 case NavDataCache::REBUILD_POIS:
116 rebuildProgress.setLabelText(QT_TR_NOOP("Loading point-of-interest data"));
120 rebuildProgress.setLabelText(baseLabel);
123 if (phase == NavDataCache::REBUILD_UNKNOWN) {
124 rebuildProgress.setValue(0);
125 rebuildProgress.setMaximum(0);
127 rebuildProgress.setValue(cache->rebuildPhaseCompletionPercentage());
128 rebuildProgress.setMaximum(100);
131 QCoreApplication::processEvents();
136 class ArgumentsTokenizer
142 explicit Arg(QString k, QString v = QString()) : arg(k), value(v) {}
148 QList<Arg> tokenize(QString in) const
151 const int len = in.count();
157 for (; index < len; ++index) {
159 nc = index < (len - 1) ? in.at(index + 1) : QChar();
163 if (c == QChar('-')) {
164 if (nc == QChar('-')) {
169 // should we pemit single hyphen arguments?
170 // choosing to fail for now
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('"')) {
215 } // of character loop
217 // ensure last argument isn't lost
219 result.append(Arg(key));
220 } else if (state == Value) {
221 result.append(Arg(key, value));
236 } // of anonymous namespace
238 class AirportSearchModel : public QAbstractListModel
242 AirportSearchModel() :
243 m_searchActive(false)
247 void setSearch(QString t)
254 std::string term(t.toUpper().toStdString());
255 // try ICAO lookup first
256 FGAirportRef ref = FGAirport::findByIdent(term);
259 m_ids.push_back(ref->guid());
260 m_airports.push_back(ref);
265 m_search.reset(new NavDataCache::ThreadedGUISearch(term));
266 QTimer::singleShot(100, this, SLOT(onSearchResultsPoll()));
267 m_searchActive = true;
270 bool isSearchActive() const
272 return m_searchActive;
275 virtual int rowCount(const QModelIndex&) const
277 // if empty, return 1 for special 'no matches'?
281 virtual QVariant data(const QModelIndex& index, int role) const
283 if (!index.isValid())
286 FGAirportRef apt = m_airports[index.row()];
288 apt = FGPositioned::loadById<FGAirport>(m_ids[index.row()]);
289 m_airports[index.row()] = apt;
292 if (role == Qt::DisplayRole) {
293 QString name = QString::fromStdString(apt->name());
294 return QString("%1: %2").arg(QString::fromStdString(apt->ident())).arg(name);
297 if (role == Qt::EditRole) {
298 return QString::fromStdString(apt->ident());
301 if (role == Qt::UserRole) {
302 return static_cast<qlonglong>(m_ids[index.row()]);
308 QString firstIdent() const
313 if (!m_airports.front().valid()) {
314 m_airports[0] = FGPositioned::loadById<FGAirport>(m_ids.front());
317 return QString::fromStdString(m_airports.front()->ident());
321 void searchComplete();
324 void onSearchResultsPoll()
326 PositionedIDVec newIds = m_search->results();
328 beginInsertRows(QModelIndex(), m_ids.size(), newIds.size() - 1);
329 for (unsigned int i=m_ids.size(); i < newIds.size(); ++i) {
330 m_ids.push_back(newIds[i]);
331 m_airports.push_back(FGAirportRef()); // null ref
335 if (m_search->isComplete()) {
336 m_searchActive = false;
338 emit searchComplete();
340 QTimer::singleShot(100, this, SLOT(onSearchResultsPoll()));
345 PositionedIDVec m_ids;
346 mutable std::vector<FGAirportRef> m_airports;
348 QScopedPointer<NavDataCache::ThreadedGUISearch> m_search;
351 class AircraftProxyModel : public QSortFilterProxyModel
355 AircraftProxyModel(QObject* pr) :
356 QSortFilterProxyModel(pr),
357 m_ratingsFilter(true)
359 for (int i=0; i<4; ++i) {
364 void setRatings(int* ratings)
366 ::memcpy(m_ratings, ratings, sizeof(int) * 4);
371 void setRatingFilterEnabled(bool e)
373 if (e == m_ratingsFilter) {
382 bool filterAcceptsRow(int sourceRow, const QModelIndex &sourceParent) const
384 if (!QSortFilterProxyModel::filterAcceptsRow(sourceRow, sourceParent)) {
388 if (m_ratingsFilter) {
389 QModelIndex index = sourceModel()->index(sourceRow, 0, sourceParent);
390 for (int i=0; i<4; ++i) {
391 if (m_ratings[i] > index.data(AircraftRatingRole + i).toInt()) {
401 bool m_ratingsFilter;
405 static void initQtResources()
407 Q_INIT_RESOURCE(resources);
413 void initApp(int& argc, char** argv)
415 static bool qtInitDone = false;
419 QApplication* app = new QApplication(argc, argv);
420 app->setOrganizationName("FlightGear");
421 app->setApplicationName("FlightGear");
422 app->setOrganizationDomain("flightgear.org");
424 // avoid double Apple menu and other weirdness if both Qt and OSG
425 // try to initialise various Cocoa structures.
426 flightgear::WindowBuilder::setPoseAsStandaloneApp(false);
428 Qt::KeyboardModifiers mods = app->queryKeyboardModifiers();
429 if (mods & Qt::AltModifier) {
430 qWarning() << "Alt pressed during launch";
432 // wipe out our settings
437 Options::sharedInstance()->addOption("restore-defaults", "");
442 bool runLauncherDialog()
444 sglog().setLogLevels( SG_ALL, SG_INFO );
447 initQtResources(); // can't be called inside a namespaceb
449 // startup the nav-cache now. This pre-empts normal startup of
450 // the cache, but no harm done. (Providing scenery paths are consistent)
457 // startup the HTTP system now since packages needs it
458 FGHTTPClient* http = new FGHTTPClient;
459 globals->add_subsystem("http", http);
460 // we guard against re-init in the global phase; bind and postinit
461 // will happen as normal
465 // setup scenery paths now, especially TerraSync path for airport
466 // parking locations (after they're downloaded)
470 if (dlg.result() != QDialog::Accepted) {
477 bool runInAppLauncherDialog()
482 if (dlg.result() != QDialog::Accepted) {
489 } // of namespace flightgear
491 QtLauncher::QtLauncher() :
494 m_subsystemIdleTimer(NULL),
497 m_ui.reset(new Ui::Launcher);
500 #if QT_VERSION >= 0x050300
501 // don't require Qt 5.3
502 m_ui->commandLineArgs->setPlaceholderText("--option=value --prop:/sim/name=value");
505 #if QT_VERSION >= 0x050200
506 m_ui->aircraftFilter->setClearButtonEnabled(true);
509 for (int i=0; i<4; ++i) {
510 m_ratingFilters[i] = 3;
513 m_subsystemIdleTimer = new QTimer(this);
514 m_subsystemIdleTimer->setInterval(0);
515 connect(m_subsystemIdleTimer, &QTimer::timeout,
516 this, &QtLauncher::onSubsytemIdleTimeout);
517 m_subsystemIdleTimer->start();
519 m_airportsModel = new AirportSearchModel;
520 m_ui->searchList->setModel(m_airportsModel);
521 connect(m_ui->searchList, &QListView::clicked,
522 this, &QtLauncher::onAirportChoiceSelected);
523 connect(m_airportsModel, &AirportSearchModel::searchComplete,
524 this, &QtLauncher::onAirportSearchComplete);
526 // create and configure the proxy model
527 m_aircraftProxy = new AircraftProxyModel(this);
528 connect(m_ui->ratingsFilterCheck, &QAbstractButton::toggled,
529 m_aircraftProxy, &AircraftProxyModel::setRatingFilterEnabled);
530 connect(m_ui->aircraftFilter, &QLineEdit::textChanged,
531 m_aircraftProxy, &QSortFilterProxyModel::setFilterFixedString);
533 connect(m_ui->runwayCombo, SIGNAL(currentIndexChanged(int)),
534 this, SLOT(updateAirportDescription()));
535 connect(m_ui->parkingCombo, SIGNAL(currentIndexChanged(int)),
536 this, SLOT(updateAirportDescription()));
537 connect(m_ui->runwayRadio, SIGNAL(toggled(bool)),
538 this, SLOT(updateAirportDescription()));
539 connect(m_ui->parkingRadio, SIGNAL(toggled(bool)),
540 this, SLOT(updateAirportDescription()));
541 connect(m_ui->onFinalCheckbox, SIGNAL(toggled(bool)),
542 this, SLOT(updateAirportDescription()));
545 connect(m_ui->airportDiagram, &AirportDiagram::clickedRunway,
546 this, &QtLauncher::onAirportDiagramClicked);
548 connect(m_ui->runButton, SIGNAL(clicked()), this, SLOT(onRun()));
549 connect(m_ui->quitButton, SIGNAL(clicked()), this, SLOT(onQuit()));
550 connect(m_ui->airportEdit, SIGNAL(returnPressed()),
551 this, SLOT(onSearchAirports()));
553 connect(m_ui->airportHistory, &QPushButton::clicked,
554 this, &QtLauncher::onPopupAirportHistory);
555 connect(m_ui->aircraftHistory, &QPushButton::clicked,
556 this, &QtLauncher::onPopupAircraftHistory);
558 QAction* qa = new QAction(this);
559 qa->setShortcut(QKeySequence("Ctrl+Q"));
560 connect(qa, &QAction::triggered, this, &QtLauncher::onQuit);
563 connect(m_ui->editRatingFilter, &QPushButton::clicked,
564 this, &QtLauncher::onEditRatingsFilter);
566 QIcon historyIcon(":/history-icon");
567 m_ui->aircraftHistory->setIcon(historyIcon);
568 m_ui->airportHistory->setIcon(historyIcon);
570 m_ui->searchIcon->setPixmap(QPixmap(":/search-icon"));
572 connect(m_ui->timeOfDayCombo, SIGNAL(currentIndexChanged(int)),
573 this, SLOT(updateSettingsSummary()));
574 connect(m_ui->seasonCombo, SIGNAL(currentIndexChanged(int)),
575 this, SLOT(updateSettingsSummary()));
576 connect(m_ui->fetchRealWxrCheckbox, SIGNAL(toggled(bool)),
577 this, SLOT(updateSettingsSummary()));
578 connect(m_ui->rembrandtCheckbox, SIGNAL(toggled(bool)),
579 this, SLOT(updateSettingsSummary()));
580 connect(m_ui->terrasyncCheck, SIGNAL(toggled(bool)),
581 this, SLOT(updateSettingsSummary()));
582 connect(m_ui->startPausedCheck, SIGNAL(toggled(bool)),
583 this, SLOT(updateSettingsSummary()));
584 connect(m_ui->msaaCheckbox, SIGNAL(toggled(bool)),
585 this, SLOT(updateSettingsSummary()));
587 connect(m_ui->rembrandtCheckbox, SIGNAL(toggled(bool)),
588 this, SLOT(onRembrandtToggled(bool)));
589 connect(m_ui->terrasyncCheck, &QCheckBox::toggled,
590 this, &QtLauncher::onToggleTerrasync);
591 updateSettingsSummary();
593 m_aircraftModel = new AircraftItemModel(this, RootRef(globals->packageRoot()));
594 m_aircraftProxy->setSourceModel(m_aircraftModel);
596 m_aircraftProxy->setFilterCaseSensitivity(Qt::CaseInsensitive);
597 m_aircraftProxy->setSortCaseSensitivity(Qt::CaseInsensitive);
598 m_aircraftProxy->setSortRole(Qt::DisplayRole);
599 m_aircraftProxy->setDynamicSortFilter(true);
601 m_ui->aircraftList->setModel(m_aircraftProxy);
602 m_ui->aircraftList->setHorizontalScrollBarPolicy(Qt::ScrollBarAlwaysOff);
603 AircraftItemDelegate* delegate = new AircraftItemDelegate(m_ui->aircraftList);
604 m_ui->aircraftList->setItemDelegate(delegate);
605 m_ui->aircraftList->setSelectionMode(QAbstractItemView::SingleSelection);
606 connect(m_ui->aircraftList, &QListView::clicked,
607 this, &QtLauncher::onAircraftSelected);
608 connect(delegate, &AircraftItemDelegate::variantChanged,
609 this, &QtLauncher::onAircraftSelected);
610 connect(delegate, &AircraftItemDelegate::requestInstall,
611 this, &QtLauncher::onRequestPackageInstall);
612 connect(delegate, &AircraftItemDelegate::cancelDownload,
613 this, &QtLauncher::onCancelDownload);
615 connect(m_aircraftModel, &AircraftItemModel::aircraftInstallCompleted,
616 this, &QtLauncher::onAircraftInstalledCompleted);
617 connect(m_aircraftModel, &AircraftItemModel::aircraftInstallFailed,
618 this, &QtLauncher::onAircraftInstallFailed);
620 connect(m_ui->pathsButton, &QPushButton::clicked,
621 this, &QtLauncher::onEditPaths);
624 connect(m_ui->trueBearing, &QCheckBox::toggled, this, &QtLauncher::onOffsetBearingTrueChanged);
625 connect(m_ui->offsetRadioButton, &QRadioButton::toggled,
626 this, &QtLauncher::onOffsetRadioToggled);
627 connect(m_ui->trueBearing, &QCheckBox::toggled, this, &QtLauncher::onOffsetDataChanged);
628 connect(m_ui->offsetBearingSpinbox, SIGNAL(valueChanged(int)), this, SLOT(onOffsetDataChanged()));
629 connect(m_ui->offsetNmSpinbox, SIGNAL(valueChanged(double)),
630 this, SLOT(onOffsetDataChanged()));
635 m_aircraftModel->setPaths(settings.value("aircraft-paths").toStringList());
636 m_aircraftModel->scanDirs();
639 QtLauncher::~QtLauncher()
644 void QtLauncher::setInAppMode()
647 m_ui->tabWidget->removeTab(2);
648 m_ui->runButton->setText(tr("Apply"));
649 m_ui->quitButton->setText(tr("Cancel"));
651 disconnect(m_ui->runButton, SIGNAL(clicked()), this, SLOT(onRun()));
652 connect(m_ui->runButton, SIGNAL(clicked()), this, SLOT(onApply()));
655 bool QtLauncher::runLauncherDialog()
657 sglog().setLogLevels( SG_ALL, SG_INFO );
658 Q_INIT_RESOURCE(resources);
660 static bool qtInitDone = false;
664 s_argc = argc; // QApplication only stores a reference to argc,
665 // and may crash if it is freed
666 // http://doc.qt.io/qt-5/qguiapplication.html#QGuiApplication
668 QApplication* app = new QApplication(s_argc, argv);
669 app->setOrganizationName("FlightGear");
670 app->setApplicationName("FlightGear");
671 app->setOrganizationDomain("flightgear.org");
673 // avoid double Apple menu and other weirdness if both Qt and OSG
674 // try to initialise various Cocoa structures.
675 flightgear::WindowBuilder::setPoseAsStandaloneApp(false);
677 Qt::KeyboardModifiers mods = app->queryKeyboardModifiers();
678 if (mods & Qt::AltModifier) {
679 qWarning() << "Alt pressed during launch";
681 // wipe out our settings
685 Options::sharedInstance()->addOption("restore-defaults", "");
689 // startup the nav-cache now. This preempts normal startup of
690 // the cache, but no harm done. (Providing scenery paths are consistent)
694 // setup scenery paths now, especially TerraSync path for airport
695 // parking locations (after they're downloaded)
699 if (dlg.result() != QDialog::Accepted) {
704 void QtLauncher::restoreSettings()
707 m_ui->rembrandtCheckbox->setChecked(settings.value("enable-rembrandt", false).toBool());
708 m_ui->terrasyncCheck->setChecked(settings.value("enable-terrasync", true).toBool());
709 m_ui->fullScreenCheckbox->setChecked(settings.value("start-fullscreen", false).toBool());
710 m_ui->msaaCheckbox->setChecked(settings.value("enable-msaa", false).toBool());
711 m_ui->fetchRealWxrCheckbox->setChecked(settings.value("enable-realwx", true).toBool());
712 m_ui->startPausedCheck->setChecked(settings.value("start-paused", false).toBool());
713 m_ui->timeOfDayCombo->setCurrentIndex(settings.value("timeofday", 0).toInt());
714 m_ui->seasonCombo->setCurrentIndex(settings.value("season", 0).toInt());
716 // full paths to -set.xml files
717 m_recentAircraft = QUrl::fromStringList(settings.value("recent-aircraft").toStringList());
719 if (!m_recentAircraft.empty()) {
720 m_selectedAircraft = m_recentAircraft.front();
722 // select the default C172p
725 updateSelectedAircraft();
728 m_recentAirports = settings.value("recent-airports").toStringList();
729 if (!m_recentAirports.empty()) {
730 setAirport(FGAirport::findByIdent(m_recentAirports.front().toStdString()));
732 updateAirportDescription();
735 m_ui->ratingsFilterCheck->setChecked(settings.value("ratings-filter", true).toBool());
737 Q_FOREACH(QVariant v, settings.value("min-ratings").toList()) {
738 m_ratingFilters[index++] = v.toInt();
741 m_aircraftProxy->setRatingFilterEnabled(m_ui->ratingsFilterCheck->isChecked());
742 m_aircraftProxy->setRatings(m_ratingFilters);
744 m_ui->commandLineArgs->setPlainText(settings.value("additional-args").toString());
747 void QtLauncher::saveSettings()
750 settings.setValue("enable-rembrandt", m_ui->rembrandtCheckbox->isChecked());
751 settings.setValue("enable-terrasync", m_ui->terrasyncCheck->isChecked());
752 settings.setValue("enable-msaa", m_ui->msaaCheckbox->isChecked());
753 settings.setValue("start-fullscreen", m_ui->fullScreenCheckbox->isChecked());
754 settings.setValue("enable-realwx", m_ui->fetchRealWxrCheckbox->isChecked());
755 settings.setValue("start-paused", m_ui->startPausedCheck->isChecked());
756 settings.setValue("ratings-filter", m_ui->ratingsFilterCheck->isChecked());
757 settings.setValue("recent-aircraft", QUrl::toStringList(m_recentAircraft));
758 settings.setValue("recent-airports", m_recentAirports);
759 settings.setValue("timeofday", m_ui->timeOfDayCombo->currentIndex());
760 settings.setValue("season", m_ui->seasonCombo->currentIndex());
761 settings.setValue("additional-args", m_ui->commandLineArgs->toPlainText());
764 void QtLauncher::setEnableDisableOptionFromCheckbox(QCheckBox* cbox, QString name) const
766 flightgear::Options* opt = flightgear::Options::sharedInstance();
767 std::string stdName(name.toStdString());
768 if (cbox->isChecked()) {
769 opt->addOption("enable-" + stdName, "");
771 opt->addOption("disable-" + stdName, "");
775 void QtLauncher::onRun()
779 flightgear::Options* opt = flightgear::Options::sharedInstance();
780 setEnableDisableOptionFromCheckbox(m_ui->terrasyncCheck, "terrasync");
781 setEnableDisableOptionFromCheckbox(m_ui->fetchRealWxrCheckbox, "real-weather-fetch");
782 setEnableDisableOptionFromCheckbox(m_ui->rembrandtCheckbox, "rembrandt");
783 setEnableDisableOptionFromCheckbox(m_ui->fullScreenCheckbox, "fullscreen");
784 setEnableDisableOptionFromCheckbox(m_ui->startPausedCheck, "freeze");
786 // MSAA is more complex
787 if (!m_ui->rembrandtCheckbox->isChecked()) {
788 if (m_ui->msaaCheckbox->isChecked()) {
789 globals->get_props()->setIntValue("/sim/rendering/multi-sample-buffers", 1);
790 globals->get_props()->setIntValue("/sim/rendering/multi-samples", 4);
792 globals->get_props()->setIntValue("/sim/rendering/multi-sample-buffers", 0);
797 if (!m_selectedAircraft.isEmpty()) {
798 if (m_selectedAircraft.isLocalFile()) {
799 QFileInfo setFileInfo(m_selectedAircraft.toLocalFile());
800 opt->addOption("aircraft-dir", setFileInfo.dir().absolutePath().toStdString());
801 QString setFile = setFileInfo.fileName();
802 Q_ASSERT(setFile.endsWith("-set.xml"));
803 setFile.truncate(setFile.count() - 8); // drop the '-set.xml' portion
804 opt->addOption("aircraft", setFile.toStdString());
805 } else if (m_selectedAircraft.scheme() == "package") {
806 PackageRef pkg = packageForAircraftURI(m_selectedAircraft);
807 // no need to set aircraft-dir, handled by the corresponding code
809 opt->addOption("aircraft", pkg->qualifiedId());
811 qWarning() << "unsupported aircraft launch URL" << m_selectedAircraft;
814 // manage aircraft history
815 if (m_recentAircraft.contains(m_selectedAircraft))
816 m_recentAircraft.removeOne(m_selectedAircraft);
817 m_recentAircraft.prepend(m_selectedAircraft);
818 if (m_recentAircraft.size() > MAX_RECENT_AIRCRAFT)
819 m_recentAircraft.pop_back();
822 // airport / location
823 if (m_selectedAirport) {
824 opt->addOption("airport", m_selectedAirport->ident());
827 if (m_ui->runwayRadio->isChecked()) {
828 int index = m_ui->runwayCombo->itemData(m_ui->runwayCombo->currentIndex()).toInt();
829 if ((index >= 0) && m_selectedAirport) {
830 // explicit runway choice
831 opt->addOption("runway", m_selectedAirport->getRunwayByIndex(index)->ident());
834 if (m_ui->onFinalCheckbox->isChecked()) {
835 opt->addOption("glideslope", "3.0");
836 opt->addOption("offset-distance", "10.0"); // in nautical miles
838 } else if (m_ui->parkingRadio->isChecked()) {
840 opt->addOption("parkpos", m_ui->parkingCombo->currentText().toStdString());
844 if (m_ui->timeOfDayCombo->currentIndex() != 0) {
845 QString dayval = m_ui->timeOfDayCombo->currentText().toLower();
846 opt->addOption("timeofday", dayval.toStdString());
849 if (m_ui->seasonCombo->currentIndex() != 0) {
850 QString dayval = m_ui->timeOfDayCombo->currentText().toLower();
851 opt->addOption("season", dayval.toStdString());
855 QString downloadDir = settings.value("download-dir").toString();
856 if (!downloadDir.isEmpty()) {
859 int result = QMessageBox::question(this, tr("Create download folder?"),
860 tr("The selected location for downloads does not exist. Create it?"),
861 QMessageBox::Yes | QMessageBox::No | QMessageBox::Cancel);
862 if (result == QMessageBox::Cancel) {
866 if (result == QMessageBox::Yes) {
867 d.mkpath(downloadDir);
871 qDebug() << "Download dir is:" << downloadDir;
872 opt->addOption("download-dir", downloadDir.toStdString());
876 Q_FOREACH(QString path, settings.value("scenery-paths").toStringList()) {
877 opt->addOption("fg-scenery", path.toStdString());
881 Q_FOREACH(QString path, settings.value("aircraft-paths").toStringList()) {
882 // can't use fg-aircraft for this, as it is processed before the launcher is run
883 globals->append_aircraft_path(path.toStdString());
886 // additional arguments
887 ArgumentsTokenizer tk;
888 Q_FOREACH(ArgumentsTokenizer::Arg a, tk.tokenize(m_ui->commandLineArgs->toPlainText())) {
889 if (a.arg.startsWith("prop:")) {
890 QString v = a.arg.mid(5) + "=" + a.value;
891 opt->addOption("prop", v.toStdString());
893 opt->addOption(a.arg.toStdString(), a.value.toStdString());
900 void QtLauncher::onApply()
905 if (!m_selectedAircraft.isEmpty()) {
906 std::string aircraftPropValue,
909 if (m_selectedAircraft.isLocalFile()) {
910 QFileInfo setFileInfo(m_selectedAircraft.toLocalFile());
911 QString setFile = setFileInfo.fileName();
912 Q_ASSERT(setFile.endsWith("-set.xml"));
913 setFile.truncate(setFile.count() - 8); // drop the '-set.xml' portion
914 aircraftDir = setFileInfo.dir().absolutePath().toStdString();
915 aircraftPropValue = setFile.toStdString();
916 } else if (m_selectedAircraft.scheme() == "package") {
917 PackageRef pkg = packageForAircraftURI(m_selectedAircraft);
918 // no need to set aircraft-dir, handled by the corresponding code
920 aircraftPropValue = pkg->qualifiedId();
922 qWarning() << "unsupported aircraft launch URL" << m_selectedAircraft;
925 // manage aircraft history
926 if (m_recentAircraft.contains(m_selectedAircraft))
927 m_recentAircraft.removeOne(m_selectedAircraft);
928 m_recentAircraft.prepend(m_selectedAircraft);
929 if (m_recentAircraft.size() > MAX_RECENT_AIRCRAFT)
930 m_recentAircraft.pop_back();
932 globals->get_props()->setStringValue("/sim/aircraft", aircraftPropValue);
933 globals->get_props()->setStringValue("/sim/aircraft-dir", aircraftDir);
940 void QtLauncher::onQuit()
945 void QtLauncher::onSearchAirports()
947 QString search = m_ui->airportEdit->text();
948 m_airportsModel->setSearch(search);
950 if (m_airportsModel->isSearchActive()) {
951 m_ui->searchStatusText->setText(QString("Searching for '%1'").arg(search));
952 m_ui->locationStack->setCurrentIndex(2);
953 } else if (m_airportsModel->rowCount(QModelIndex()) == 1) {
954 QString ident = m_airportsModel->firstIdent();
955 setAirport(FGAirport::findByIdent(ident.toStdString()));
956 m_ui->locationStack->setCurrentIndex(0);
960 void QtLauncher::onAirportSearchComplete()
962 int numResults = m_airportsModel->rowCount(QModelIndex());
963 if (numResults == 0) {
964 m_ui->searchStatusText->setText(QString("No matching airports for '%1'").arg(m_ui->airportEdit->text()));
965 } else if (numResults == 1) {
966 QString ident = m_airportsModel->firstIdent();
967 setAirport(FGAirport::findByIdent(ident.toStdString()));
968 m_ui->locationStack->setCurrentIndex(0);
970 m_ui->locationStack->setCurrentIndex(1);
974 void QtLauncher::onAirportChanged()
976 m_ui->runwayCombo->setEnabled(m_selectedAirport);
977 m_ui->parkingCombo->setEnabled(m_selectedAirport);
978 m_ui->airportDiagram->setAirport(m_selectedAirport);
980 m_ui->runwayRadio->setChecked(true); // default back to runway mode
981 // unelss multiplayer is enabled ?
983 if (!m_selectedAirport) {
984 m_ui->airportDescription->setText(QString());
985 m_ui->airportDiagram->setEnabled(false);
989 m_ui->airportDiagram->setEnabled(true);
991 m_ui->runwayCombo->clear();
992 m_ui->runwayCombo->addItem("Automatic", -1);
993 for (unsigned int r=0; r<m_selectedAirport->numRunways(); ++r) {
994 FGRunwayRef rwy = m_selectedAirport->getRunwayByIndex(r);
995 // add runway with index as data role
996 m_ui->runwayCombo->addItem(QString::fromStdString(rwy->ident()), r);
998 m_ui->airportDiagram->addRunway(rwy);
1001 m_ui->parkingCombo->clear();
1002 FGAirportDynamics* dynamics = m_selectedAirport->getDynamics();
1003 PositionedIDVec parkings = NavDataCache::instance()->airportItemsOfType(
1004 m_selectedAirport->guid(),
1005 FGPositioned::PARKING);
1006 if (parkings.empty()) {
1007 m_ui->parkingCombo->setEnabled(false);
1008 m_ui->parkingRadio->setEnabled(false);
1010 m_ui->parkingCombo->setEnabled(true);
1011 m_ui->parkingRadio->setEnabled(true);
1012 Q_FOREACH(PositionedID parking, parkings) {
1013 FGParking* park = dynamics->getParking(parking);
1014 m_ui->parkingCombo->addItem(QString::fromStdString(park->getName()),
1015 static_cast<qlonglong>(parking));
1017 m_ui->airportDiagram->addParking(park);
1022 void QtLauncher::onOffsetRadioToggled(bool on)
1024 m_ui->offsetNmSpinbox->setEnabled(on);
1025 m_ui->offsetBearingSpinbox->setEnabled(on);
1026 m_ui->trueBearing->setEnabled(on);
1027 m_ui->offsetBearingLabel->setEnabled(on);
1028 m_ui->offsetDistanceLabel->setEnabled(on);
1031 void QtLauncher::onAirportDiagramClicked(FGRunwayRef rwy)
1034 m_ui->runwayRadio->setChecked(true);
1035 int rwyIndex = m_ui->runwayCombo->findText(QString::fromStdString(rwy->ident()));
1036 m_ui->runwayCombo->setCurrentIndex(rwyIndex);
1039 updateAirportDescription();
1042 void QtLauncher::onToggleTerrasync(bool enabled)
1046 QString downloadDir = settings.value("download-dir").toString();
1047 if (downloadDir.isEmpty()) {
1048 downloadDir = QString::fromStdString(flightgear::defaultDownloadDir());
1051 QFileInfo info(downloadDir);
1052 if (!info.exists()) {
1054 msg.setWindowTitle(tr("Create download folder?"));
1055 msg.setText(tr("The download folder '%1' does not exist, create it now? "
1056 "Click 'change location' to choose another folder "
1057 "to store downloaded files").arg(downloadDir));
1058 msg.addButton(QMessageBox::Yes);
1059 msg.addButton(QMessageBox::Cancel);
1060 msg.addButton(tr("Change location"), QMessageBox::ActionRole);
1061 int result = msg.exec();
1063 if (result == QMessageBox::Cancel) {
1064 m_ui->terrasyncCheck->setChecked(false);
1068 if (result == QMessageBox::ActionRole) {
1073 QDir d(downloadDir);
1074 d.mkpath(downloadDir);
1079 void QtLauncher::onAircraftInstalledCompleted(QModelIndex index)
1081 maybeUpdateSelectedAircraft(index);
1084 void QtLauncher::onAircraftInstallFailed(QModelIndex index, QString errorMessage)
1086 qWarning() << Q_FUNC_INFO << index.data(AircraftURIRole) << errorMessage;
1089 msg.setWindowTitle(tr("Aircraft installation failed"));
1090 msg.setText(tr("An error occurred installing the aircraft %1: %2").
1091 arg(index.data(Qt::DisplayRole).toString()).arg(errorMessage));
1092 msg.addButton(QMessageBox::Ok);
1095 maybeUpdateSelectedAircraft(index);
1098 void QtLauncher::updateAirportDescription()
1100 if (!m_selectedAirport) {
1101 m_ui->airportDescription->setText(QString("No airport selected"));
1105 QString ident = QString::fromStdString(m_selectedAirport->ident()),
1106 name = QString::fromStdString(m_selectedAirport->name());
1107 QString locationOnAirport;
1108 if (m_ui->runwayRadio->isChecked()) {
1109 bool onFinal = m_ui->onFinalCheckbox->isChecked();
1110 int comboIndex = m_ui->runwayCombo->currentIndex();
1111 QString runwayName = (comboIndex == 0) ?
1113 QString("runway %1").arg(m_ui->runwayCombo->currentText());
1116 locationOnAirport = QString("on 10-mile final to %1").arg(runwayName);
1118 locationOnAirport = QString("on %1").arg(runwayName);
1121 int runwayIndex = m_ui->runwayCombo->itemData(comboIndex).toInt();
1122 FGRunwayRef rwy = (runwayIndex >= 0) ?
1123 m_selectedAirport->getRunwayByIndex(runwayIndex) : FGRunwayRef();
1124 m_ui->airportDiagram->setSelectedRunway(rwy);
1125 } else if (m_ui->parkingRadio->isChecked()) {
1126 locationOnAirport = QString("at parking position %1").arg(m_ui->parkingCombo->currentText());
1129 m_ui->airportDescription->setText(QString("%2 (%1): %3").arg(ident).arg(name).arg(locationOnAirport));
1132 void QtLauncher::onAirportChoiceSelected(const QModelIndex& index)
1134 m_ui->locationStack->setCurrentIndex(0);
1135 setAirport(FGPositioned::loadById<FGAirport>(index.data(Qt::UserRole).toULongLong()));
1138 void QtLauncher::onOffsetBearingTrueChanged(bool on)
1140 m_ui->offsetBearingLabel->setText(on ? tr("True bearing:") :
1141 tr("Magnetic bearing:"));
1144 void QtLauncher::onAircraftSelected(const QModelIndex& index)
1146 m_selectedAircraft = index.data(AircraftURIRole).toUrl();
1147 updateSelectedAircraft();
1150 void QtLauncher::onRequestPackageInstall(const QModelIndex& index)
1152 QString pkg = index.data(AircraftPackageIdRole).toString();
1153 simgear::pkg::PackageRef pref = globals->packageRoot()->getPackageById(pkg.toStdString());
1154 if (pref->isInstalled()) {
1155 InstallRef install = pref->existingInstall();
1156 if (install && install->hasUpdate()) {
1157 globals->packageRoot()->scheduleToUpdate(install);
1164 void QtLauncher::onCancelDownload(const QModelIndex& index)
1166 QString pkg = index.data(AircraftPackageIdRole).toString();
1167 simgear::pkg::PackageRef pref = globals->packageRoot()->getPackageById(pkg.toStdString());
1168 simgear::pkg::InstallRef i = pref->existingInstall();
1169 i->cancelDownload();
1172 void QtLauncher::maybeUpdateSelectedAircraft(QModelIndex index)
1174 QUrl u = index.data(AircraftURIRole).toUrl();
1175 if (u == m_selectedAircraft) {
1176 // potentially enable the run button now!
1177 updateSelectedAircraft();
1181 void QtLauncher::updateSelectedAircraft()
1183 QModelIndex index = m_aircraftModel->indexOfAircraftURI(m_selectedAircraft);
1184 if (index.isValid()) {
1185 QPixmap pm = index.data(Qt::DecorationRole).value<QPixmap>();
1186 m_ui->thumbnail->setPixmap(pm);
1187 m_ui->aircraftDescription->setText(index.data(Qt::DisplayRole).toString());
1189 int status = index.data(AircraftPackageStatusRole).toInt();
1190 bool canRun = (status == PackageInstalled);
1191 m_ui->runButton->setEnabled(canRun);
1193 m_ui->thumbnail->setPixmap(QPixmap());
1194 m_ui->aircraftDescription->setText("");
1195 m_ui->runButton->setEnabled(false);
1199 void QtLauncher::onPopupAirportHistory()
1201 if (m_recentAirports.isEmpty()) {
1206 Q_FOREACH(QString aptCode, m_recentAirports) {
1207 FGAirportRef apt = FGAirport::findByIdent(aptCode.toStdString());
1208 QString name = QString::fromStdString(apt->name());
1209 QAction* act = m.addAction(QString("%1 - %2").arg(aptCode).arg(name));
1210 act->setData(aptCode);
1213 QPoint popupPos = m_ui->airportHistory->mapToGlobal(m_ui->airportHistory->rect().bottomLeft());
1214 QAction* triggered = m.exec(popupPos);
1216 FGAirportRef apt = FGAirport::findByIdent(triggered->data().toString().toStdString());
1218 m_ui->airportEdit->clear();
1219 m_ui->locationStack->setCurrentIndex(0);
1223 QModelIndex QtLauncher::proxyIndexForAircraftURI(QUrl uri) const
1225 return m_aircraftProxy->mapFromSource(sourceIndexForAircraftURI(uri));
1228 QModelIndex QtLauncher::sourceIndexForAircraftURI(QUrl uri) const
1230 AircraftItemModel* sourceModel = qobject_cast<AircraftItemModel*>(m_aircraftProxy->sourceModel());
1231 Q_ASSERT(sourceModel);
1232 return sourceModel->indexOfAircraftURI(uri);
1235 void QtLauncher::onPopupAircraftHistory()
1237 if (m_recentAircraft.isEmpty()) {
1242 Q_FOREACH(QUrl uri, m_recentAircraft) {
1243 QModelIndex index = sourceIndexForAircraftURI(uri);
1244 if (!index.isValid()) {
1248 QAction* act = m.addAction(index.data(Qt::DisplayRole).toString());
1252 QPoint popupPos = m_ui->aircraftHistory->mapToGlobal(m_ui->aircraftHistory->rect().bottomLeft());
1253 QAction* triggered = m.exec(popupPos);
1255 m_selectedAircraft = triggered->data().toUrl();
1256 QModelIndex index = proxyIndexForAircraftURI(m_selectedAircraft);
1257 m_ui->aircraftList->selectionModel()->setCurrentIndex(index,
1258 QItemSelectionModel::ClearAndSelect);
1259 m_ui->aircraftFilter->clear();
1260 updateSelectedAircraft();
1264 void QtLauncher::setAirport(FGAirportRef ref)
1266 if (m_selectedAirport == ref)
1269 m_selectedAirport = ref;
1273 // maintain the recent airport list
1274 QString icao = QString::fromStdString(ref->ident());
1275 if (m_recentAirports.contains(icao)) {
1277 m_recentAirports.removeOne(icao);
1278 m_recentAirports.push_front(icao);
1280 // insert and trim list if necessary
1281 m_recentAirports.push_front(icao);
1282 if (m_recentAirports.size() > MAX_RECENT_AIRPORTS) {
1283 m_recentAirports.pop_back();
1288 updateAirportDescription();
1291 void QtLauncher::onEditRatingsFilter()
1293 EditRatingsFilterDialog dialog(this);
1294 dialog.setRatings(m_ratingFilters);
1297 if (dialog.result() == QDialog::Accepted) {
1299 for (int i=0; i<4; ++i) {
1300 m_ratingFilters[i] = dialog.getRating(i);
1301 vl.append(m_ratingFilters[i]);
1303 m_aircraftProxy->setRatings(m_ratingFilters);
1306 settings.setValue("min-ratings", vl);
1310 void QtLauncher::updateSettingsSummary()
1312 QStringList summary;
1313 if (m_ui->timeOfDayCombo->currentIndex() > 0) {
1314 summary.append(QString(m_ui->timeOfDayCombo->currentText().toLower()));
1317 if (m_ui->seasonCombo->currentIndex() > 0) {
1318 summary.append(QString(m_ui->seasonCombo->currentText().toLower()));
1321 if (m_ui->rembrandtCheckbox->isChecked()) {
1322 summary.append("Rembrandt enabled");
1323 } else if (m_ui->msaaCheckbox->isChecked()) {
1324 summary.append("anti-aliasing");
1327 if (m_ui->fetchRealWxrCheckbox->isChecked()) {
1328 summary.append("live weather");
1331 if (m_ui->terrasyncCheck->isChecked()) {
1332 summary.append("automatic scenery downloads");
1335 if (m_ui->startPausedCheck->isChecked()) {
1336 summary.append("paused");
1339 QString s = summary.join(", ");
1340 s[0] = s[0].toUpper();
1341 m_ui->settingsDescription->setText(s);
1344 void QtLauncher::onRembrandtToggled(bool b)
1346 // Rembrandt and multi-sample are exclusive
1347 m_ui->msaaCheckbox->setEnabled(!b);
1350 void QtLauncher::onSubsytemIdleTimeout()
1352 globals->get_subsystem_mgr()->update(0.0);
1355 void QtLauncher::onEditPaths()
1357 PathsDialog dlg(this, globals->packageRoot());
1359 if (dlg.result() == QDialog::Accepted) {
1360 // re-scan the aircraft list
1362 m_aircraftModel->setPaths(settings.value("aircraft-paths").toStringList());
1363 m_aircraftModel->scanDirs();
1367 simgear::pkg::PackageRef QtLauncher::packageForAircraftURI(QUrl uri) const
1369 if (uri.scheme() != "package") {
1370 qWarning() << "invalid URL scheme:" << uri;
1371 return simgear::pkg::PackageRef();
1374 QString ident = uri.path();
1375 return globals->packageRoot()->getPackageById(ident.toStdString());
1378 void QtLauncher::onOffsetDataChanged()
1380 qDebug() << "implement me";
1383 #include "QtLauncher.moc"