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"
24 #include <QProgressDialog>
25 #include <QCoreApplication>
26 #include <QAbstractListModel>
35 #include <QSortFilterProxyModel>
37 #include <QDesktopServices>
40 #include <QFileDialog>
41 #include <QMessageBox>
43 #include <QApplication>
46 #include <simgear/timing/timestamp.hxx>
47 #include <simgear/props/props_io.hxx>
48 #include <simgear/structure/exception.hxx>
49 #include <simgear/structure/subsystem_mgr.hxx>
50 #include <simgear/misc/sg_path.hxx>
51 #include <simgear/package/Catalog.hxx>
52 #include <simgear/package/Package.hxx>
53 #include <simgear/package/Install.hxx>
55 #include "ui_Launcher.h"
56 #include "EditRatingsFilterDialog.hxx"
57 #include "AircraftItemDelegate.hxx"
58 #include "AircraftModel.hxx"
59 #include "PathsDialog.hxx"
61 #include <Main/globals.hxx>
62 #include <Navaids/NavDataCache.hxx>
63 #include <Airports/airport.hxx>
64 #include <Airports/dynamics.hxx> // for parking
65 #include <Main/options.hxx>
66 #include <Main/fg_init.hxx>
67 #include <Viewer/WindowBuilder.hxx>
68 #include <Network/HTTPClient.hxx>
70 using namespace flightgear;
71 using namespace simgear::pkg;
73 const int MAX_RECENT_AIRPORTS = 32;
74 const int MAX_RECENT_AIRCRAFT = 20;
76 namespace { // anonymous namespace
80 QString baseLabel = QT_TR_NOOP("Initialising navigation data, this may take several minutes");
81 NavDataCache* cache = NavDataCache::createInstance();
82 if (cache->isRebuildRequired()) {
83 QProgressDialog rebuildProgress(baseLabel,
84 QString() /* cancel text */,
86 rebuildProgress.setWindowModality(Qt::WindowModal);
87 rebuildProgress.show();
89 NavDataCache::RebuildPhase phase = cache->rebuild();
91 while (phase != NavDataCache::REBUILD_DONE) {
92 // sleep to give the rebuild thread more time
93 SGTimeStamp::sleepForMSec(50);
94 phase = cache->rebuild();
97 case NavDataCache::REBUILD_AIRPORTS:
98 rebuildProgress.setLabelText(QT_TR_NOOP("Loading airport data"));
101 case NavDataCache::REBUILD_FIXES:
102 rebuildProgress.setLabelText(QT_TR_NOOP("Loading waypoint data"));
105 case NavDataCache::REBUILD_NAVAIDS:
106 rebuildProgress.setLabelText(QT_TR_NOOP("Loading navigation data"));
110 case NavDataCache::REBUILD_POIS:
111 rebuildProgress.setLabelText(QT_TR_NOOP("Loading point-of-interest data"));
115 rebuildProgress.setLabelText(baseLabel);
118 if (phase == NavDataCache::REBUILD_UNKNOWN) {
119 rebuildProgress.setValue(0);
120 rebuildProgress.setMaximum(0);
122 rebuildProgress.setValue(cache->rebuildPhaseCompletionPercentage());
123 rebuildProgress.setMaximum(100);
126 QCoreApplication::processEvents();
131 class ArgumentsTokenizer
137 explicit Arg(QString k, QString v = QString()) : arg(k), value(v) {}
143 QList<Arg> tokenize(QString in) const
146 const int len = in.count();
152 for (; index < len; ++index) {
154 nc = index < (len - 1) ? in.at(index + 1) : QChar();
158 if (c == QChar('-')) {
159 if (nc == QChar('-')) {
164 // should we pemit single hyphen arguments?
165 // choosing to fail for now
168 } else if (c.isSpace()) {
174 if (c == QChar('=')) {
177 } else if (c.isSpace()) {
179 result.append(Arg(key));
181 // could check for illegal charatcers here
187 if (c == QChar('"')) {
189 } else if (c.isSpace()) {
191 result.append(Arg(key, value));
198 if (c == QChar('\\')) {
199 // check for escaped double-quote inside quoted value
200 if (nc == QChar('"')) {
203 } else if (c == QChar('"')) {
210 } // of character loop
212 // ensure last argument isn't lost
214 result.append(Arg(key));
215 } else if (state == Value) {
216 result.append(Arg(key, value));
231 } // of anonymous namespace
233 class AirportSearchModel : public QAbstractListModel
237 AirportSearchModel() :
238 m_searchActive(false)
242 void setSearch(QString t)
249 std::string term(t.toUpper().toStdString());
250 // try ICAO lookup first
251 FGAirportRef ref = FGAirport::findByIdent(term);
253 m_ids.push_back(ref->guid());
254 m_airports.push_back(ref);
256 m_search.reset(new NavDataCache::ThreadedAirportSearch(term));
257 QTimer::singleShot(100, this, SLOT(onSearchResultsPoll()));
258 m_searchActive = true;
264 bool isSearchActive() const
266 return m_searchActive;
269 virtual int rowCount(const QModelIndex&) const
271 // if empty, return 1 for special 'no matches'?
275 virtual QVariant data(const QModelIndex& index, int role) const
277 if (!index.isValid())
280 FGAirportRef apt = m_airports[index.row()];
282 apt = FGPositioned::loadById<FGAirport>(m_ids[index.row()]);
283 m_airports[index.row()] = apt;
286 if (role == Qt::DisplayRole) {
287 QString name = QString::fromStdString(apt->name());
288 return QString("%1: %2").arg(QString::fromStdString(apt->ident())).arg(name);
291 if (role == Qt::EditRole) {
292 return QString::fromStdString(apt->ident());
295 if (role == Qt::UserRole) {
296 return static_cast<qlonglong>(m_ids[index.row()]);
302 QString firstIdent() const
307 if (!m_airports.front().valid()) {
308 m_airports[0] = FGPositioned::loadById<FGAirport>(m_ids.front());
311 return QString::fromStdString(m_airports.front()->ident());
315 void searchComplete();
318 void onSearchResultsPoll()
320 PositionedIDVec newIds = m_search->results();
322 beginInsertRows(QModelIndex(), m_ids.size(), newIds.size() - 1);
323 for (unsigned int i=m_ids.size(); i < newIds.size(); ++i) {
324 m_ids.push_back(newIds[i]);
325 m_airports.push_back(FGAirportRef()); // null ref
329 if (m_search->isComplete()) {
330 m_searchActive = false;
332 emit searchComplete();
334 QTimer::singleShot(100, this, SLOT(onSearchResultsPoll()));
339 PositionedIDVec m_ids;
340 mutable std::vector<FGAirportRef> m_airports;
342 QScopedPointer<NavDataCache::ThreadedAirportSearch> m_search;
345 class AircraftProxyModel : public QSortFilterProxyModel
349 AircraftProxyModel(QObject* pr) :
350 QSortFilterProxyModel(pr),
351 m_ratingsFilter(true)
353 for (int i=0; i<4; ++i) {
358 void setRatings(int* ratings)
360 ::memcpy(m_ratings, ratings, sizeof(int) * 4);
365 void setRatingFilterEnabled(bool e)
367 if (e == m_ratingsFilter) {
376 bool filterAcceptsRow(int sourceRow, const QModelIndex &sourceParent) const
378 if (!QSortFilterProxyModel::filterAcceptsRow(sourceRow, sourceParent)) {
382 if (m_ratingsFilter) {
383 QModelIndex index = sourceModel()->index(sourceRow, 0, sourceParent);
384 for (int i=0; i<4; ++i) {
385 if (m_ratings[i] > index.data(AircraftRatingRole + i).toInt()) {
395 bool m_ratingsFilter;
399 QtLauncher::QtLauncher() :
403 m_ui.reset(new Ui::Launcher);
406 #if QT_VERSION >= 0x050300
407 // don't require Qt 5.3
408 m_ui->commandLineArgs->setPlaceholderText("--option=value --prop:/sim/name=value");
411 #if QT_VERSION >= 0x050200
412 m_ui->aircraftFilter->setClearButtonEnabled(true);
415 for (int i=0; i<4; ++i) {
416 m_ratingFilters[i] = 3;
419 m_subsystemIdleTimer = new QTimer(this);
420 m_subsystemIdleTimer->setInterval(0);
421 connect(m_subsystemIdleTimer, &QTimer::timeout,
422 this, &QtLauncher::onSubsytemIdleTimeout);
423 m_subsystemIdleTimer->start();
425 m_airportsModel = new AirportSearchModel;
426 m_ui->searchList->setModel(m_airportsModel);
427 connect(m_ui->searchList, &QListView::clicked,
428 this, &QtLauncher::onAirportChoiceSelected);
429 connect(m_airportsModel, &AirportSearchModel::searchComplete,
430 this, &QtLauncher::onAirportSearchComplete);
432 // create and configure the proxy model
433 m_aircraftProxy = new AircraftProxyModel(this);
434 connect(m_ui->ratingsFilterCheck, &QAbstractButton::toggled,
435 m_aircraftProxy, &AircraftProxyModel::setRatingFilterEnabled);
436 connect(m_ui->aircraftFilter, &QLineEdit::textChanged,
437 m_aircraftProxy, &QSortFilterProxyModel::setFilterFixedString);
439 connect(m_ui->runwayCombo, SIGNAL(currentIndexChanged(int)),
440 this, SLOT(updateAirportDescription()));
441 connect(m_ui->parkingCombo, SIGNAL(currentIndexChanged(int)),
442 this, SLOT(updateAirportDescription()));
443 connect(m_ui->runwayRadio, SIGNAL(toggled(bool)),
444 this, SLOT(updateAirportDescription()));
445 connect(m_ui->parkingRadio, SIGNAL(toggled(bool)),
446 this, SLOT(updateAirportDescription()));
447 connect(m_ui->onFinalCheckbox, SIGNAL(toggled(bool)),
448 this, SLOT(updateAirportDescription()));
451 connect(m_ui->airportDiagram, &AirportDiagram::clickedRunway,
452 this, &QtLauncher::onAirportDiagramClicked);
454 connect(m_ui->runButton, SIGNAL(clicked()), this, SLOT(onRun()));
455 connect(m_ui->quitButton, SIGNAL(clicked()), this, SLOT(onQuit()));
456 connect(m_ui->airportEdit, SIGNAL(returnPressed()),
457 this, SLOT(onSearchAirports()));
459 connect(m_ui->airportHistory, &QPushButton::clicked,
460 this, &QtLauncher::onPopupAirportHistory);
461 connect(m_ui->aircraftHistory, &QPushButton::clicked,
462 this, &QtLauncher::onPopupAircraftHistory);
464 QAction* qa = new QAction(this);
465 qa->setShortcut(QKeySequence("Ctrl+Q"));
466 connect(qa, &QAction::triggered, this, &QtLauncher::onQuit);
469 connect(m_ui->editRatingFilter, &QPushButton::clicked,
470 this, &QtLauncher::onEditRatingsFilter);
472 QIcon historyIcon(":/history-icon");
473 m_ui->aircraftHistory->setIcon(historyIcon);
474 m_ui->airportHistory->setIcon(historyIcon);
476 m_ui->searchIcon->setPixmap(QPixmap(":/search-icon"));
478 connect(m_ui->timeOfDayCombo, SIGNAL(currentIndexChanged(int)),
479 this, SLOT(updateSettingsSummary()));
480 connect(m_ui->seasonCombo, SIGNAL(currentIndexChanged(int)),
481 this, SLOT(updateSettingsSummary()));
482 connect(m_ui->fetchRealWxrCheckbox, SIGNAL(toggled(bool)),
483 this, SLOT(updateSettingsSummary()));
484 connect(m_ui->rembrandtCheckbox, SIGNAL(toggled(bool)),
485 this, SLOT(updateSettingsSummary()));
486 connect(m_ui->terrasyncCheck, SIGNAL(toggled(bool)),
487 this, SLOT(updateSettingsSummary()));
488 connect(m_ui->startPausedCheck, SIGNAL(toggled(bool)),
489 this, SLOT(updateSettingsSummary()));
490 connect(m_ui->msaaCheckbox, SIGNAL(toggled(bool)),
491 this, SLOT(updateSettingsSummary()));
493 connect(m_ui->rembrandtCheckbox, SIGNAL(toggled(bool)),
494 this, SLOT(onRembrandtToggled(bool)));
495 connect(m_ui->terrasyncCheck, &QCheckBox::toggled,
496 this, &QtLauncher::onToggleTerrasync);
497 updateSettingsSummary();
500 RootRef r(globals->packageRoot());
502 FGHTTPClient* http = new FGHTTPClient;
503 globals->add_subsystem("http", http);
505 // we guard against re-init in the global phase; bind and postinit
506 // will happen as normal
509 m_aircraftModel = new AircraftItemModel(this, r);
510 m_aircraftProxy->setSourceModel(m_aircraftModel);
512 m_aircraftProxy->setFilterCaseSensitivity(Qt::CaseInsensitive);
513 m_aircraftProxy->setSortCaseSensitivity(Qt::CaseInsensitive);
514 m_aircraftProxy->setSortRole(Qt::DisplayRole);
515 m_aircraftProxy->setDynamicSortFilter(true);
517 m_ui->aircraftList->setModel(m_aircraftProxy);
518 m_ui->aircraftList->setHorizontalScrollBarPolicy(Qt::ScrollBarAlwaysOff);
519 AircraftItemDelegate* delegate = new AircraftItemDelegate(m_ui->aircraftList);
520 m_ui->aircraftList->setItemDelegate(delegate);
521 m_ui->aircraftList->setSelectionMode(QAbstractItemView::SingleSelection);
522 connect(m_ui->aircraftList, &QListView::clicked,
523 this, &QtLauncher::onAircraftSelected);
524 connect(delegate, &AircraftItemDelegate::variantChanged,
525 this, &QtLauncher::onAircraftSelected);
526 connect(delegate, &AircraftItemDelegate::requestInstall,
527 this, &QtLauncher::onRequestPackageInstall);
528 connect(delegate, &AircraftItemDelegate::cancelDownload,
529 this, &QtLauncher::onCancelDownload);
531 connect(m_aircraftModel, &AircraftItemModel::aircraftInstallCompleted,
532 this, &QtLauncher::onAircraftInstalledCompleted);
533 connect(m_aircraftModel, &AircraftItemModel::aircraftInstallFailed,
534 this, &QtLauncher::onAircraftInstallFailed);
536 connect(m_ui->pathsButton, &QPushButton::clicked,
537 this, &QtLauncher::onEditPaths);
542 m_aircraftModel->setPaths(settings.value("aircraft-paths").toStringList());
543 m_aircraftModel->scanDirs();
546 QtLauncher::~QtLauncher()
551 void QtLauncher::initApp(int& argc, char** argv)
553 static bool qtInitDone = false;
557 QApplication* app = new QApplication(argc, argv);
558 app->setOrganizationName("FlightGear");
559 app->setApplicationName("FlightGear");
560 app->setOrganizationDomain("flightgear.org");
562 // avoid double Apple menu and other weirdness if both Qt and OSG
563 // try to initialise various Cocoa structures.
564 flightgear::WindowBuilder::setPoseAsStandaloneApp(false);
566 Qt::KeyboardModifiers mods = app->queryKeyboardModifiers();
567 if (mods & Qt::AltModifier) {
568 qWarning() << "Alt pressed during launch";
570 // wipe out our settings
575 Options::sharedInstance()->addOption("restore-defaults", "");
580 bool QtLauncher::runLauncherDialog()
582 sglog().setLogLevels( SG_ALL, SG_INFO );
583 Q_INIT_RESOURCE(resources);
585 // startup the nav-cache now. This pre-empts normal startup of
586 // the cache, but no harm done. (Providing scenery paths are consistent)
590 // setup scenery paths now, especially TerraSync path for airport
591 // parking locations (after they're downloaded)
595 if (dlg.result() != QDialog::Accepted) {
602 void QtLauncher::restoreSettings()
605 m_ui->rembrandtCheckbox->setChecked(settings.value("enable-rembrandt", false).toBool());
606 m_ui->terrasyncCheck->setChecked(settings.value("enable-terrasync", true).toBool());
607 m_ui->fullScreenCheckbox->setChecked(settings.value("start-fullscreen", false).toBool());
608 m_ui->msaaCheckbox->setChecked(settings.value("enable-msaa", false).toBool());
609 m_ui->fetchRealWxrCheckbox->setChecked(settings.value("enable-realwx", true).toBool());
610 m_ui->startPausedCheck->setChecked(settings.value("start-paused", false).toBool());
611 m_ui->timeOfDayCombo->setCurrentIndex(settings.value("timeofday", 0).toInt());
612 m_ui->seasonCombo->setCurrentIndex(settings.value("season", 0).toInt());
614 // full paths to -set.xml files
615 m_recentAircraft = QUrl::fromStringList(settings.value("recent-aircraft").toStringList());
617 if (!m_recentAircraft.empty()) {
618 m_selectedAircraft = m_recentAircraft.front();
620 // select the default C172p
623 updateSelectedAircraft();
626 m_recentAirports = settings.value("recent-airports").toStringList();
627 if (!m_recentAirports.empty()) {
628 setAirport(FGAirport::findByIdent(m_recentAirports.front().toStdString()));
630 updateAirportDescription();
633 m_ui->ratingsFilterCheck->setChecked(settings.value("ratings-filter", true).toBool());
635 Q_FOREACH(QVariant v, settings.value("min-ratings").toList()) {
636 m_ratingFilters[index++] = v.toInt();
639 m_aircraftProxy->setRatingFilterEnabled(m_ui->ratingsFilterCheck->isChecked());
640 m_aircraftProxy->setRatings(m_ratingFilters);
642 m_ui->commandLineArgs->setPlainText(settings.value("additional-args").toString());
645 void QtLauncher::saveSettings()
648 settings.setValue("enable-rembrandt", m_ui->rembrandtCheckbox->isChecked());
649 settings.setValue("enable-terrasync", m_ui->terrasyncCheck->isChecked());
650 settings.setValue("enable-msaa", m_ui->msaaCheckbox->isChecked());
651 settings.setValue("start-fullscreen", m_ui->fullScreenCheckbox->isChecked());
652 settings.setValue("enable-realwx", m_ui->fetchRealWxrCheckbox->isChecked());
653 settings.setValue("start-paused", m_ui->startPausedCheck->isChecked());
654 settings.setValue("ratings-filter", m_ui->ratingsFilterCheck->isChecked());
655 settings.setValue("recent-aircraft", QUrl::toStringList(m_recentAircraft));
656 settings.setValue("recent-airports", m_recentAirports);
657 settings.setValue("timeofday", m_ui->timeOfDayCombo->currentIndex());
658 settings.setValue("season", m_ui->seasonCombo->currentIndex());
659 settings.setValue("additional-args", m_ui->commandLineArgs->toPlainText());
662 void QtLauncher::setEnableDisableOptionFromCheckbox(QCheckBox* cbox, QString name) const
664 flightgear::Options* opt = flightgear::Options::sharedInstance();
665 std::string stdName(name.toStdString());
666 if (cbox->isChecked()) {
667 opt->addOption("enable-" + stdName, "");
669 opt->addOption("disable-" + stdName, "");
673 void QtLauncher::onRun()
677 flightgear::Options* opt = flightgear::Options::sharedInstance();
678 setEnableDisableOptionFromCheckbox(m_ui->terrasyncCheck, "terrasync");
679 setEnableDisableOptionFromCheckbox(m_ui->fetchRealWxrCheckbox, "real-weather-fetch");
680 setEnableDisableOptionFromCheckbox(m_ui->rembrandtCheckbox, "rembrandt");
681 setEnableDisableOptionFromCheckbox(m_ui->fullScreenCheckbox, "fullscreen");
682 setEnableDisableOptionFromCheckbox(m_ui->startPausedCheck, "freeze");
684 // MSAA is more complex
685 if (!m_ui->rembrandtCheckbox->isChecked()) {
686 if (m_ui->msaaCheckbox->isChecked()) {
687 globals->get_props()->setIntValue("/sim/rendering/multi-sample-buffers", 1);
688 globals->get_props()->setIntValue("/sim/rendering/multi-samples", 4);
690 globals->get_props()->setIntValue("/sim/rendering/multi-sample-buffers", 0);
695 if (!m_selectedAircraft.isEmpty()) {
696 if (m_selectedAircraft.isLocalFile()) {
697 QFileInfo setFileInfo(m_selectedAircraft.toLocalFile());
698 opt->addOption("aircraft-dir", setFileInfo.dir().absolutePath().toStdString());
699 QString setFile = setFileInfo.fileName();
700 Q_ASSERT(setFile.endsWith("-set.xml"));
701 setFile.truncate(setFile.count() - 8); // drop the '-set.xml' portion
702 opt->addOption("aircraft", setFile.toStdString());
703 } else if (m_selectedAircraft.scheme() == "package") {
704 PackageRef pkg = packageForAircraftURI(m_selectedAircraft);
705 // no need to set aircraft-dir, handled by the corresponding code
707 opt->addOption("aircraft", pkg->qualifiedId());
709 qWarning() << "unsupported aircraft launch URL" << m_selectedAircraft;
712 // manage aircraft history
713 if (m_recentAircraft.contains(m_selectedAircraft))
714 m_recentAircraft.removeOne(m_selectedAircraft);
715 m_recentAircraft.prepend(m_selectedAircraft);
716 if (m_recentAircraft.size() > MAX_RECENT_AIRCRAFT)
717 m_recentAircraft.pop_back();
720 // airport / location
721 if (m_selectedAirport) {
722 opt->addOption("airport", m_selectedAirport->ident());
725 if (m_ui->runwayRadio->isChecked()) {
726 int index = m_ui->runwayCombo->itemData(m_ui->runwayCombo->currentIndex()).toInt();
727 if ((index >= 0) && m_selectedAirport) {
728 // explicit runway choice
729 opt->addOption("runway", m_selectedAirport->getRunwayByIndex(index)->ident());
732 if (m_ui->onFinalCheckbox->isChecked()) {
733 opt->addOption("glideslope", "3.0");
734 opt->addOption("offset-distance", "10.0"); // in nautical miles
736 } else if (m_ui->parkingRadio->isChecked()) {
738 opt->addOption("parkpos", m_ui->parkingCombo->currentText().toStdString());
742 if (m_ui->timeOfDayCombo->currentIndex() != 0) {
743 QString dayval = m_ui->timeOfDayCombo->currentText().toLower();
744 opt->addOption("timeofday", dayval.toStdString());
747 if (m_ui->seasonCombo->currentIndex() != 0) {
748 QString dayval = m_ui->timeOfDayCombo->currentText().toLower();
749 opt->addOption("season", dayval.toStdString());
753 QString downloadDir = settings.value("download-dir").toString();
754 if (!downloadDir.isEmpty()) {
757 int result = QMessageBox::question(this, tr("Create download folder?"),
758 tr("The selected location for downloads does not exist. Create it?"),
759 QMessageBox::Yes | QMessageBox::No | QMessageBox::Cancel);
760 if (result == QMessageBox::Cancel) {
764 if (result == QMessageBox::Yes) {
765 d.mkpath(downloadDir);
769 qDebug() << "Download dir is:" << downloadDir;
770 opt->addOption("download-dir", downloadDir.toStdString());
774 Q_FOREACH(QString path, settings.value("scenery-paths").toStringList()) {
775 opt->addOption("fg-scenery", path.toStdString());
779 Q_FOREACH(QString path, settings.value("aircraft-paths").toStringList()) {
780 // can't use fg-aircraft for this, as it is processed before the launcher is run
781 globals->append_aircraft_path(path.toStdString());
784 // additional arguments
785 ArgumentsTokenizer tk;
786 Q_FOREACH(ArgumentsTokenizer::Arg a, tk.tokenize(m_ui->commandLineArgs->toPlainText())) {
787 if (a.arg.startsWith("prop:")) {
788 QString v = a.arg.mid(5) + "=" + a.value;
789 opt->addOption("prop", v.toStdString());
791 opt->addOption(a.arg.toStdString(), a.value.toStdString());
798 void QtLauncher::onQuit()
803 void QtLauncher::onSearchAirports()
805 QString search = m_ui->airportEdit->text();
806 m_airportsModel->setSearch(search);
808 if (m_airportsModel->isSearchActive()) {
809 m_ui->searchStatusText->setText(QString("Searching for '%1'").arg(search));
810 m_ui->locationStack->setCurrentIndex(2);
811 } else if (m_airportsModel->rowCount(QModelIndex()) == 1) {
812 QString ident = m_airportsModel->firstIdent();
813 setAirport(FGAirport::findByIdent(ident.toStdString()));
814 m_ui->locationStack->setCurrentIndex(0);
818 void QtLauncher::onAirportSearchComplete()
820 int numResults = m_airportsModel->rowCount(QModelIndex());
821 if (numResults == 0) {
822 m_ui->searchStatusText->setText(QString("No matching airports for '%1'").arg(m_ui->airportEdit->text()));
823 } else if (numResults == 1) {
824 QString ident = m_airportsModel->firstIdent();
825 setAirport(FGAirport::findByIdent(ident.toStdString()));
826 m_ui->locationStack->setCurrentIndex(0);
828 m_ui->locationStack->setCurrentIndex(1);
832 void QtLauncher::onAirportChanged()
834 m_ui->runwayCombo->setEnabled(m_selectedAirport);
835 m_ui->parkingCombo->setEnabled(m_selectedAirport);
836 m_ui->airportDiagram->setAirport(m_selectedAirport);
838 m_ui->runwayRadio->setChecked(true); // default back to runway mode
839 // unelss multiplayer is enabled ?
841 if (!m_selectedAirport) {
842 m_ui->airportDescription->setText(QString());
843 m_ui->airportDiagram->setEnabled(false);
847 m_ui->airportDiagram->setEnabled(true);
849 m_ui->runwayCombo->clear();
850 m_ui->runwayCombo->addItem("Automatic", -1);
851 for (unsigned int r=0; r<m_selectedAirport->numRunways(); ++r) {
852 FGRunwayRef rwy = m_selectedAirport->getRunwayByIndex(r);
853 // add runway with index as data role
854 m_ui->runwayCombo->addItem(QString::fromStdString(rwy->ident()), r);
856 m_ui->airportDiagram->addRunway(rwy);
859 m_ui->parkingCombo->clear();
860 FGAirportDynamics* dynamics = m_selectedAirport->getDynamics();
861 PositionedIDVec parkings = NavDataCache::instance()->airportItemsOfType(
862 m_selectedAirport->guid(),
863 FGPositioned::PARKING);
864 if (parkings.empty()) {
865 m_ui->parkingCombo->setEnabled(false);
866 m_ui->parkingRadio->setEnabled(false);
868 m_ui->parkingCombo->setEnabled(true);
869 m_ui->parkingRadio->setEnabled(true);
870 Q_FOREACH(PositionedID parking, parkings) {
871 FGParking* park = dynamics->getParking(parking);
872 m_ui->parkingCombo->addItem(QString::fromStdString(park->getName()),
873 static_cast<qlonglong>(parking));
875 m_ui->airportDiagram->addParking(park);
880 void QtLauncher::onAirportDiagramClicked(FGRunwayRef rwy)
883 m_ui->runwayRadio->setChecked(true);
884 int rwyIndex = m_ui->runwayCombo->findText(QString::fromStdString(rwy->ident()));
885 m_ui->runwayCombo->setCurrentIndex(rwyIndex);
888 updateAirportDescription();
891 void QtLauncher::onToggleTerrasync(bool enabled)
895 QString downloadDir = settings.value("download-dir").toString();
896 if (downloadDir.isEmpty()) {
897 downloadDir = QString::fromStdString(flightgear::defaultDownloadDir());
900 QFileInfo info(downloadDir);
901 if (!info.exists()) {
903 msg.setWindowTitle(tr("Create download folder?"));
904 msg.setText(tr("The download folder '%1' does not exist, create it now? "
905 "Click 'change location' to choose another folder "
906 "to store downloaded files").arg(downloadDir));
907 msg.addButton(QMessageBox::Yes);
908 msg.addButton(QMessageBox::Cancel);
909 msg.addButton(tr("Change location"), QMessageBox::ActionRole);
910 int result = msg.exec();
912 if (result == QMessageBox::Cancel) {
913 m_ui->terrasyncCheck->setChecked(false);
917 if (result == QMessageBox::ActionRole) {
923 d.mkpath(downloadDir);
928 void QtLauncher::onAircraftInstalledCompleted(QModelIndex index)
930 maybeUpdateSelectedAircraft(index);
933 void QtLauncher::onAircraftInstallFailed(QModelIndex index, QString errorMessage)
935 qWarning() << Q_FUNC_INFO << index.data(AircraftURIRole) << errorMessage;
938 msg.setWindowTitle(tr("Aircraft installation failed"));
939 msg.setText(tr("An error occurred installing the aircraft %1: %2").
940 arg(index.data(Qt::DisplayRole).toString()).arg(errorMessage));
941 msg.addButton(QMessageBox::Ok);
944 maybeUpdateSelectedAircraft(index);
947 void QtLauncher::updateAirportDescription()
949 if (!m_selectedAirport) {
950 m_ui->airportDescription->setText(QString("No airport selected"));
954 QString ident = QString::fromStdString(m_selectedAirport->ident()),
955 name = QString::fromStdString(m_selectedAirport->name());
956 QString locationOnAirport;
957 if (m_ui->runwayRadio->isChecked()) {
958 bool onFinal = m_ui->onFinalCheckbox->isChecked();
959 int comboIndex = m_ui->runwayCombo->currentIndex();
960 QString runwayName = (comboIndex == 0) ?
962 QString("runway %1").arg(m_ui->runwayCombo->currentText());
965 locationOnAirport = QString("on 10-mile final to %1").arg(runwayName);
967 locationOnAirport = QString("on %1").arg(runwayName);
970 int runwayIndex = m_ui->runwayCombo->itemData(comboIndex).toInt();
971 FGRunwayRef rwy = (runwayIndex >= 0) ?
972 m_selectedAirport->getRunwayByIndex(runwayIndex) : FGRunwayRef();
973 m_ui->airportDiagram->setSelectedRunway(rwy);
974 } else if (m_ui->parkingRadio->isChecked()) {
975 locationOnAirport = QString("at parking position %1").arg(m_ui->parkingCombo->currentText());
978 m_ui->airportDescription->setText(QString("%2 (%1): %3").arg(ident).arg(name).arg(locationOnAirport));
981 void QtLauncher::onAirportChoiceSelected(const QModelIndex& index)
983 m_ui->locationStack->setCurrentIndex(0);
984 setAirport(FGPositioned::loadById<FGAirport>(index.data(Qt::UserRole).toULongLong()));
987 void QtLauncher::onAircraftSelected(const QModelIndex& index)
989 m_selectedAircraft = index.data(AircraftURIRole).toUrl();
990 updateSelectedAircraft();
993 void QtLauncher::onRequestPackageInstall(const QModelIndex& index)
995 QString pkg = index.data(AircraftPackageIdRole).toString();
996 simgear::pkg::PackageRef pref = globals->packageRoot()->getPackageById(pkg.toStdString());
997 if (pref->isInstalled()) {
998 InstallRef install = pref->existingInstall();
999 if (install && install->hasUpdate()) {
1000 globals->packageRoot()->scheduleToUpdate(install);
1007 void QtLauncher::onCancelDownload(const QModelIndex& index)
1009 QString pkg = index.data(AircraftPackageIdRole).toString();
1010 qDebug() << "cancel download of" << pkg;
1011 simgear::pkg::PackageRef pref = globals->packageRoot()->getPackageById(pkg.toStdString());
1012 simgear::pkg::InstallRef i = pref->existingInstall();
1013 i->cancelDownload();
1016 void QtLauncher::maybeUpdateSelectedAircraft(QModelIndex index)
1018 QUrl u = index.data(AircraftURIRole).toUrl();
1019 if (u == m_selectedAircraft) {
1020 // potentially enable the run button now!
1021 updateSelectedAircraft();
1025 void QtLauncher::updateSelectedAircraft()
1027 QModelIndex index = m_aircraftModel->indexOfAircraftURI(m_selectedAircraft);
1028 if (index.isValid()) {
1029 QPixmap pm = index.data(Qt::DecorationRole).value<QPixmap>();
1030 m_ui->thumbnail->setPixmap(pm);
1031 m_ui->aircraftDescription->setText(index.data(Qt::DisplayRole).toString());
1033 int status = index.data(AircraftPackageStatusRole).toInt();
1034 bool canRun = (status == PackageInstalled);
1035 m_ui->runButton->setEnabled(canRun);
1037 m_ui->thumbnail->setPixmap(QPixmap());
1038 m_ui->aircraftDescription->setText("");
1039 m_ui->runButton->setEnabled(false);
1043 void QtLauncher::onPopupAirportHistory()
1045 if (m_recentAirports.isEmpty()) {
1050 Q_FOREACH(QString aptCode, m_recentAirports) {
1051 FGAirportRef apt = FGAirport::findByIdent(aptCode.toStdString());
1052 QString name = QString::fromStdString(apt->name());
1053 QAction* act = m.addAction(QString("%1 - %2").arg(aptCode).arg(name));
1054 act->setData(aptCode);
1057 QPoint popupPos = m_ui->airportHistory->mapToGlobal(m_ui->airportHistory->rect().bottomLeft());
1058 QAction* triggered = m.exec(popupPos);
1060 FGAirportRef apt = FGAirport::findByIdent(triggered->data().toString().toStdString());
1062 m_ui->airportEdit->clear();
1063 m_ui->locationStack->setCurrentIndex(0);
1067 QModelIndex QtLauncher::proxyIndexForAircraftURI(QUrl uri) const
1069 return m_aircraftProxy->mapFromSource(sourceIndexForAircraftURI(uri));
1072 QModelIndex QtLauncher::sourceIndexForAircraftURI(QUrl uri) const
1074 AircraftItemModel* sourceModel = qobject_cast<AircraftItemModel*>(m_aircraftProxy->sourceModel());
1075 Q_ASSERT(sourceModel);
1076 return sourceModel->indexOfAircraftURI(uri);
1079 void QtLauncher::onPopupAircraftHistory()
1081 if (m_recentAircraft.isEmpty()) {
1086 Q_FOREACH(QUrl uri, m_recentAircraft) {
1087 QModelIndex index = sourceIndexForAircraftURI(uri);
1088 if (!index.isValid()) {
1092 QAction* act = m.addAction(index.data(Qt::DisplayRole).toString());
1096 QPoint popupPos = m_ui->aircraftHistory->mapToGlobal(m_ui->aircraftHistory->rect().bottomLeft());
1097 QAction* triggered = m.exec(popupPos);
1099 m_selectedAircraft = triggered->data().toUrl();
1100 QModelIndex index = proxyIndexForAircraftURI(m_selectedAircraft);
1101 m_ui->aircraftList->selectionModel()->setCurrentIndex(index,
1102 QItemSelectionModel::ClearAndSelect);
1103 m_ui->aircraftFilter->clear();
1104 updateSelectedAircraft();
1108 void QtLauncher::setAirport(FGAirportRef ref)
1110 if (m_selectedAirport == ref)
1113 m_selectedAirport = ref;
1117 // maintain the recent airport list
1118 QString icao = QString::fromStdString(ref->ident());
1119 if (m_recentAirports.contains(icao)) {
1121 m_recentAirports.removeOne(icao);
1122 m_recentAirports.push_front(icao);
1124 // insert and trim list if necessary
1125 m_recentAirports.push_front(icao);
1126 if (m_recentAirports.size() > MAX_RECENT_AIRPORTS) {
1127 m_recentAirports.pop_back();
1132 updateAirportDescription();
1135 void QtLauncher::onEditRatingsFilter()
1137 EditRatingsFilterDialog dialog(this);
1138 dialog.setRatings(m_ratingFilters);
1141 if (dialog.result() == QDialog::Accepted) {
1143 for (int i=0; i<4; ++i) {
1144 m_ratingFilters[i] = dialog.getRating(i);
1145 vl.append(m_ratingFilters[i]);
1147 m_aircraftProxy->setRatings(m_ratingFilters);
1150 settings.setValue("min-ratings", vl);
1154 void QtLauncher::updateSettingsSummary()
1156 QStringList summary;
1157 if (m_ui->timeOfDayCombo->currentIndex() > 0) {
1158 summary.append(QString(m_ui->timeOfDayCombo->currentText().toLower()));
1161 if (m_ui->seasonCombo->currentIndex() > 0) {
1162 summary.append(QString(m_ui->seasonCombo->currentText().toLower()));
1165 if (m_ui->rembrandtCheckbox->isChecked()) {
1166 summary.append("Rembrandt enabled");
1167 } else if (m_ui->msaaCheckbox->isChecked()) {
1168 summary.append("anti-aliasing");
1171 if (m_ui->fetchRealWxrCheckbox->isChecked()) {
1172 summary.append("live weather");
1175 if (m_ui->terrasyncCheck->isChecked()) {
1176 summary.append("automatic scenery downloads");
1179 if (m_ui->startPausedCheck->isChecked()) {
1180 summary.append("paused");
1183 QString s = summary.join(", ");
1184 s[0] = s[0].toUpper();
1185 m_ui->settingsDescription->setText(s);
1188 void QtLauncher::onRembrandtToggled(bool b)
1190 // Rembrandt and multi-sample are exclusive
1191 m_ui->msaaCheckbox->setEnabled(!b);
1194 void QtLauncher::onSubsytemIdleTimeout()
1196 globals->get_subsystem_mgr()->update(0.0);
1199 void QtLauncher::onEditPaths()
1201 PathsDialog dlg(this, globals->packageRoot());
1203 if (dlg.result() == QDialog::Accepted) {
1204 // re-scan the aircraft list
1206 m_aircraftModel->setPaths(settings.value("aircraft-paths").toStringList());
1207 m_aircraftModel->scanDirs();
1211 simgear::pkg::PackageRef QtLauncher::packageForAircraftURI(QUrl uri) const
1213 if (uri.scheme() != "package") {
1214 qWarning() << "invalid URL scheme:" << uri;
1215 return simgear::pkg::PackageRef();
1218 QString ident = uri.path();
1219 qDebug() << Q_FUNC_INFO << uri << ident;
1220 return globals->packageRoot()->getPackageById(ident.toStdString());
1223 #include "QtLauncher.moc"