1 // QtLauncher.cxx - GUI launcher dialog using Qt5
3 // Written by James Turner, started December 2014.
5 // Copyright (C) 2014 James Turner <zakalawe@mac.com>
7 // This program is free software; you can redistribute it and/or
8 // modify it under the terms of the GNU General Public License as
9 // published by the Free Software Foundation; either version 2 of the
10 // License, or (at your option) any later version.
12 // This program is distributed in the hope that it will be useful, but
13 // WITHOUT ANY WARRANTY; without even the implied warranty of
14 // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
15 // General Public License for more details.
17 // You should have received a copy of the GNU General Public License
18 // along with this program; if not, write to the Free Software
19 // Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
21 #include "QtLauncher.hxx"
22 #include "QtLauncher_private.hxx"
27 #include <QProgressDialog>
28 #include <QCoreApplication>
29 #include <QAbstractListModel>
38 #include <QSortFilterProxyModel>
40 #include <QDesktopServices>
43 #include <QFileDialog>
44 #include <QMessageBox>
46 #include <QApplication>
48 #include <QDoubleSpinBox>
53 #include <simgear/timing/timestamp.hxx>
54 #include <simgear/props/props_io.hxx>
55 #include <simgear/structure/exception.hxx>
56 #include <simgear/structure/subsystem_mgr.hxx>
57 #include <simgear/misc/sg_path.hxx>
58 #include <simgear/package/Catalog.hxx>
59 #include <simgear/package/Package.hxx>
60 #include <simgear/package/Install.hxx>
62 #include "ui_Launcher.h"
63 #include "ui_NoOfficialHangar.h"
65 #include "EditRatingsFilterDialog.hxx"
66 #include "AircraftItemDelegate.hxx"
67 #include "AircraftModel.hxx"
68 #include "PathsDialog.hxx"
69 #include "EditCustomMPServerDialog.hxx"
71 #include <Main/globals.hxx>
72 #include <Main/fg_props.hxx>
73 #include <Navaids/NavDataCache.hxx>
74 #include <Navaids/navrecord.hxx>
75 #include <Navaids/SHPParser.hxx>
77 #include <Main/options.hxx>
78 #include <Main/fg_init.hxx>
79 #include <Viewer/WindowBuilder.hxx>
80 #include <Network/HTTPClient.hxx>
81 #include <Network/RemoteXMLRequest.hxx>
83 using namespace flightgear;
84 using namespace simgear::pkg;
86 const int MAX_RECENT_AIRCRAFT = 20;
88 namespace { // anonymous namespace
92 QString baseLabel = QT_TR_NOOP("Initialising navigation data, this may take several minutes");
93 NavDataCache* cache = NavDataCache::createInstance();
94 if (cache->isRebuildRequired()) {
95 QProgressDialog rebuildProgress(baseLabel,
96 QString() /* cancel text */,
99 | Qt::CustomizeWindowHint
100 | Qt::WindowTitleHint
101 | Qt::WindowSystemMenuHint
102 | Qt::MSWindowsFixedSizeDialogHint);
103 rebuildProgress.setWindowModality(Qt::WindowModal);
104 rebuildProgress.show();
106 NavDataCache::RebuildPhase phase = cache->rebuild();
108 while (phase != NavDataCache::REBUILD_DONE) {
109 // sleep to give the rebuild thread more time
110 SGTimeStamp::sleepForMSec(50);
111 phase = cache->rebuild();
114 case NavDataCache::REBUILD_AIRPORTS:
115 rebuildProgress.setLabelText(QT_TR_NOOP("Loading airport data"));
118 case NavDataCache::REBUILD_FIXES:
119 rebuildProgress.setLabelText(QT_TR_NOOP("Loading waypoint data"));
122 case NavDataCache::REBUILD_NAVAIDS:
123 rebuildProgress.setLabelText(QT_TR_NOOP("Loading navigation data"));
127 case NavDataCache::REBUILD_POIS:
128 rebuildProgress.setLabelText(QT_TR_NOOP("Loading point-of-interest data"));
132 rebuildProgress.setLabelText(baseLabel);
135 if (phase == NavDataCache::REBUILD_UNKNOWN) {
136 rebuildProgress.setValue(0);
137 rebuildProgress.setMaximum(0);
139 rebuildProgress.setValue(cache->rebuildPhaseCompletionPercentage());
140 rebuildProgress.setMaximum(100);
143 QCoreApplication::processEvents();
148 class ArgumentsTokenizer
154 explicit Arg(QString k, QString v = QString()) : arg(k), value(v) {}
160 QList<Arg> tokenize(QString in) const
163 const int len = in.count();
169 for (; index < len; ++index) {
171 nc = index < (len - 1) ? in.at(index + 1) : QChar();
175 if (c == QChar('-')) {
176 if (nc == QChar('-')) {
181 // should we pemit single hyphen arguments?
182 // choosing to fail for now
185 } else if (c == QChar('#')) {
188 } else if (c.isSpace()) {
194 if (c == QChar('=')) {
197 } else if (c.isSpace()) {
199 result.append(Arg(key));
201 // could check for illegal charatcers here
207 if (c == QChar('"')) {
209 } else if (c.isSpace()) {
211 result.append(Arg(key, value));
218 if (c == QChar('\\')) {
219 // check for escaped double-quote inside quoted value
220 if (nc == QChar('"')) {
223 } else if (c == QChar('"')) {
231 if ((c == QChar('\n')) || (c == QChar('\r'))) {
235 // nothing to do, eat comment chars
239 } // of character loop
241 // ensure last argument isn't lost
243 result.append(Arg(key));
244 } else if (state == Value) {
245 result.append(Arg(key, value));
261 class NaturalEarthDataLoaderThread : public QThread
266 NaturalEarthDataLoaderThread() :
269 connect(this, &QThread::finished, this, &NaturalEarthDataLoaderThread::onFinished);
273 virtual void run() Q_DECL_OVERRIDE
278 loadNaturalEarthFile("ne_10m_coastline.shp", flightgear::PolyLine::COASTLINE, false);
279 loadNaturalEarthFile("ne_10m_rivers_lake_centerlines.shp", flightgear::PolyLine::RIVER, false);
280 loadNaturalEarthFile("ne_10m_lakes.shp", flightgear::PolyLine::LAKE, true);
282 qDebug() << "load basic data took" << st.elapsedMSec();
285 loadNaturalEarthFile("ne_10m_urban_areas.shp", flightgear::PolyLine::URBAN, true);
287 qDebug() << "loading urban areas took:" << st.elapsedMSec();
293 flightgear::PolyLineList::const_iterator begin = m_parsedLines.begin() + m_lineInsertCount;
294 unsigned int numToAdd = std::min<unsigned long>(1000UL, m_parsedLines.size() - m_lineInsertCount);
295 flightgear::PolyLineList::const_iterator end = begin + numToAdd;
296 flightgear::PolyLine::bulkAddToSpatialIndex(begin, end);
298 if (end == m_parsedLines.end()) {
299 deleteLater(); // commit suicide
301 m_lineInsertCount += 1000;
302 QTimer::singleShot(50, this, SLOT(onFinished()));
306 void loadNaturalEarthFile(const std::string& aFileName,
307 flightgear::PolyLine::Type aType,
310 SGPath path(globals->get_fg_root());
311 path.append( "Geodata" );
312 path.append(aFileName);
314 return; // silently fail for now
316 flightgear::PolyLineList lines;
317 flightgear::SHPParser::parsePolyLines(path, aType, m_parsedLines, areClosed);
320 flightgear::PolyLineList m_parsedLines;
321 unsigned int m_lineInsertCount;
324 } // of anonymous namespace
326 class AircraftProxyModel : public QSortFilterProxyModel
330 AircraftProxyModel(QObject* pr) :
331 QSortFilterProxyModel(pr),
332 m_ratingsFilter(true),
333 m_onlyShowInstalled(false)
335 for (int i=0; i<4; ++i) {
340 void setRatings(int* ratings)
342 ::memcpy(m_ratings, ratings, sizeof(int) * 4);
347 void setRatingFilterEnabled(bool e)
349 if (e == m_ratingsFilter) {
357 void setInstalledFilterEnabled(bool e)
359 if (e == m_onlyShowInstalled) {
363 m_onlyShowInstalled = e;
368 bool filterAcceptsRow(int sourceRow, const QModelIndex &sourceParent) const
370 QModelIndex index = sourceModel()->index(sourceRow, 0, sourceParent);
371 QVariant v = index.data(AircraftPackageStatusRole);
372 AircraftItemStatus status = static_cast<AircraftItemStatus>(v.toInt());
373 if (status == NoOfficialCatalogMessage) {
377 if (!QSortFilterProxyModel::filterAcceptsRow(sourceRow, sourceParent)) {
381 if (m_onlyShowInstalled) {
382 QVariant v = index.data(AircraftPackageStatusRole);
383 AircraftItemStatus status = static_cast<AircraftItemStatus>(v.toInt());
384 if (status == PackageNotInstalled) {
389 if (!m_onlyShowInstalled && m_ratingsFilter) {
390 for (int i=0; i<4; ++i) {
391 if (m_ratings[i] > index.data(AircraftRatingRole + i).toInt()) {
401 bool m_ratingsFilter;
402 bool m_onlyShowInstalled;
406 class NoOfficialHangarMessage : public QWidget
410 NoOfficialHangarMessage() :
411 m_ui(new Ui::NoOfficialHangarMessage)
414 // proxy this signal upwards
415 connect(m_ui->label, &QLabel::linkActivated,
416 this, &NoOfficialHangarMessage::linkActivated);
420 void linkActivated(QUrl link);
423 Ui::NoOfficialHangarMessage* m_ui;
426 static void initQtResources()
428 Q_INIT_RESOURCE(resources);
434 void initApp(int& argc, char** argv)
436 static bool qtInitDone = false;
442 sglog().setLogLevels( SG_ALL, SG_INFO );
443 initQtResources(); // can't be called from a namespace
445 s_argc = argc; // QApplication only stores a reference to argc,
446 // and may crash if it is freed
447 // http://doc.qt.io/qt-5/qguiapplication.html#QGuiApplication
449 QApplication* app = new QApplication(s_argc, argv);
450 app->setOrganizationName("FlightGear");
451 app->setApplicationName("FlightGear");
452 app->setOrganizationDomain("flightgear.org");
454 QSettings::setDefaultFormat(QSettings::IniFormat);
455 QSettings::setPath(QSettings::IniFormat, QSettings::UserScope,
456 QString::fromStdString(globals->get_fg_home().utf8Str()));
458 // reset numeric / collation locales as described at:
459 // http://doc.qt.io/qt-5/qcoreapplication.html#details
460 ::setlocale(LC_NUMERIC, "C");
461 ::setlocale(LC_COLLATE, "C");
463 Qt::KeyboardModifiers mods = app->queryKeyboardModifiers();
464 if (mods & (Qt::AltModifier | Qt::ShiftModifier)) {
465 qWarning() << "Alt/shift pressed during launch";
467 settings.setValue("fg-root", "!ask");
472 bool runLauncherDialog()
474 // startup the nav-cache now. This pre-empts normal startup of
475 // the cache, but no harm done. (Providing scenery paths are consistent)
480 QString downloadDir = settings.value("download-dir").toString();
481 if (!downloadDir.isEmpty()) {
482 flightgear::Options::sharedInstance()->setOption("download-dir", downloadDir.toStdString());
487 // startup the HTTP system now since packages needs it
488 FGHTTPClient* http = globals->add_new_subsystem<FGHTTPClient>();
490 // we guard against re-init in the global phase; bind and postinit
491 // will happen as normal
494 NaturalEarthDataLoaderThread* naturalEarthLoader = new NaturalEarthDataLoaderThread;
495 naturalEarthLoader->start();
497 // avoid double Apple menu and other weirdness if both Qt and OSG
498 // try to initialise various Cocoa structures.
499 flightgear::WindowBuilder::setPoseAsStandaloneApp(false);
504 int appResult = qApp->exec();
506 return false; // quit
509 // don't set scenery paths twice
510 globals->clear_fg_scenery();
515 bool runInAppLauncherDialog()
520 if (dlg.result() != QDialog::Accepted) {
527 } // of namespace flightgear
529 QtLauncher::QtLauncher() :
532 m_subsystemIdleTimer(NULL),
534 m_doRestoreMPServer(false)
536 m_ui.reset(new Ui::Launcher);
539 #if QT_VERSION >= 0x050300
540 // don't require Qt 5.3
541 m_ui->commandLineArgs->setPlaceholderText("--option=value --prop:/sim/name=value");
544 #if QT_VERSION >= 0x050200
545 m_ui->aircraftFilter->setClearButtonEnabled(true);
548 for (int i=0; i<4; ++i) {
549 m_ratingFilters[i] = 3;
552 m_subsystemIdleTimer = new QTimer(this);
553 m_subsystemIdleTimer->setInterval(0);
554 connect(m_subsystemIdleTimer, &QTimer::timeout,
555 this, &QtLauncher::onSubsytemIdleTimeout);
556 m_subsystemIdleTimer->start();
558 // create and configure the proxy model
559 m_aircraftProxy = new AircraftProxyModel(this);
560 connect(m_ui->ratingsFilterCheck, &QAbstractButton::toggled,
561 m_aircraftProxy, &AircraftProxyModel::setRatingFilterEnabled);
562 connect(m_ui->ratingsFilterCheck, &QAbstractButton::toggled,
563 this, &QtLauncher::maybeRestoreAircraftSelection);
565 connect(m_ui->onlyShowInstalledCheck, &QAbstractButton::toggled,
566 m_aircraftProxy, &AircraftProxyModel::setInstalledFilterEnabled);
567 connect(m_ui->aircraftFilter, &QLineEdit::textChanged,
568 m_aircraftProxy, &QSortFilterProxyModel::setFilterFixedString);
570 connect(m_ui->runButton, SIGNAL(clicked()), this, SLOT(onRun()));
571 connect(m_ui->quitButton, SIGNAL(clicked()), this, SLOT(onQuit()));
573 connect(m_ui->aircraftHistory, &QPushButton::clicked,
574 this, &QtLauncher::onPopupAircraftHistory);
576 connect(m_ui->location, &LocationWidget::descriptionChanged,
577 m_ui->locationDescription, &QLabel::setText);
579 QAction* qa = new QAction(this);
580 qa->setShortcut(QKeySequence("Ctrl+Q"));
581 connect(qa, &QAction::triggered, this, &QtLauncher::onQuit);
584 connect(m_ui->editRatingFilter, &QPushButton::clicked,
585 this, &QtLauncher::onEditRatingsFilter);
586 connect(m_ui->onlyShowInstalledCheck, &QCheckBox::toggled,
587 this, &QtLauncher::onShowInstalledAircraftToggled);
589 QIcon historyIcon(":/history-icon");
590 m_ui->aircraftHistory->setIcon(historyIcon);
592 connect(m_ui->timeOfDayCombo, SIGNAL(currentIndexChanged(int)),
593 this, SLOT(updateSettingsSummary()));
594 connect(m_ui->seasonCombo, SIGNAL(currentIndexChanged(int)),
595 this, SLOT(updateSettingsSummary()));
596 connect(m_ui->fetchRealWxrCheckbox, SIGNAL(toggled(bool)),
597 this, SLOT(updateSettingsSummary()));
598 connect(m_ui->rembrandtCheckbox, SIGNAL(toggled(bool)),
599 this, SLOT(updateSettingsSummary()));
600 connect(m_ui->terrasyncCheck, SIGNAL(toggled(bool)),
601 this, SLOT(updateSettingsSummary()));
602 connect(m_ui->startPausedCheck, SIGNAL(toggled(bool)),
603 this, SLOT(updateSettingsSummary()));
604 connect(m_ui->msaaCheckbox, SIGNAL(toggled(bool)),
605 this, SLOT(updateSettingsSummary()));
607 connect(m_ui->rembrandtCheckbox, SIGNAL(toggled(bool)),
608 this, SLOT(onRembrandtToggled(bool)));
609 connect(m_ui->terrasyncCheck, &QCheckBox::toggled,
610 this, &QtLauncher::onToggleTerrasync);
611 updateSettingsSummary();
613 connect(m_ui->mpServerCombo, SIGNAL(activated(int)),
614 this, SLOT(onMPServerActivated(int)));
616 m_aircraftModel = new AircraftItemModel(this);
617 m_aircraftProxy->setSourceModel(m_aircraftModel);
619 m_aircraftProxy->setFilterCaseSensitivity(Qt::CaseInsensitive);
620 m_aircraftProxy->setSortCaseSensitivity(Qt::CaseInsensitive);
621 m_aircraftProxy->setSortRole(Qt::DisplayRole);
622 m_aircraftProxy->setDynamicSortFilter(true);
624 m_ui->aircraftList->setModel(m_aircraftProxy);
625 m_ui->aircraftList->setHorizontalScrollBarPolicy(Qt::ScrollBarAlwaysOff);
626 AircraftItemDelegate* delegate = new AircraftItemDelegate(m_ui->aircraftList);
627 m_ui->aircraftList->setItemDelegate(delegate);
628 m_ui->aircraftList->setSelectionMode(QAbstractItemView::SingleSelection);
629 connect(m_ui->aircraftList, &QListView::clicked,
630 this, &QtLauncher::onAircraftSelected);
631 connect(delegate, &AircraftItemDelegate::variantChanged,
632 this, &QtLauncher::onAircraftSelected);
633 connect(delegate, &AircraftItemDelegate::requestInstall,
634 this, &QtLauncher::onRequestPackageInstall);
635 connect(delegate, &AircraftItemDelegate::cancelDownload,
636 this, &QtLauncher::onCancelDownload);
638 connect(m_aircraftModel, &AircraftItemModel::aircraftInstallCompleted,
639 this, &QtLauncher::onAircraftInstalledCompleted);
640 connect(m_aircraftModel, &AircraftItemModel::aircraftInstallFailed,
641 this, &QtLauncher::onAircraftInstallFailed);
642 connect(m_aircraftModel, &AircraftItemModel::scanCompleted,
643 this, &QtLauncher::updateSelectedAircraft);
644 connect(m_ui->restoreDefaultsButton, &QPushButton::clicked,
645 this, &QtLauncher::onRestoreDefaults);
648 AddOnsPage* addOnsPage = new AddOnsPage(NULL, globals->packageRoot());
649 connect(addOnsPage, &AddOnsPage::downloadDirChanged,
650 this, &QtLauncher::onDownloadDirChanged);
651 connect(addOnsPage, &AddOnsPage::sceneryPathsChanged,
652 this, &QtLauncher::setSceneryPaths);
654 m_ui->tabWidget->addTab(addOnsPage, tr("Add-ons"));
655 // after any kind of reset, try to restore selection and scroll
656 // to match the m_selectedAircraft. This needs to be delayed
657 // fractionally otherwise the scrollTo seems to be ignored,
659 connect(m_aircraftProxy, &AircraftProxyModel::modelReset,
660 this, &QtLauncher::delayedAircraftModelReset);
663 m_aircraftModel->setPaths(settings.value("aircraft-paths").toStringList());
664 m_aircraftModel->setPackageRoot(globals->packageRoot());
665 m_aircraftModel->scanDirs();
667 checkOfficialCatalogMessage();
670 onRefreshMPServers();
673 QtLauncher::~QtLauncher()
678 void QtLauncher::setSceneryPaths()
680 globals->clear_fg_scenery();
682 // mimic what optionss.cxx does, so we can find airport data for parking
685 // append explicit scenery paths
686 Q_FOREACH(QString path, settings.value("scenery-paths").toStringList()) {
687 globals->append_fg_scenery(path.toStdString());
690 // append the TerraSync path
691 QString downloadDir = settings.value("download-dir").toString();
692 if (downloadDir.isEmpty()) {
693 downloadDir = QString::fromStdString(flightgear::defaultDownloadDir().utf8Str());
696 SGPath terraSyncDir(downloadDir.toStdString());
697 terraSyncDir.append("TerraSync");
698 if (terraSyncDir.exists()) {
699 globals->append_fg_scenery(terraSyncDir);
704 void QtLauncher::setInAppMode()
707 m_ui->tabWidget->removeTab(2);
708 m_ui->tabWidget->removeTab(2);
710 m_ui->runButton->setText(tr("Apply"));
711 m_ui->quitButton->setText(tr("Cancel"));
713 disconnect(m_ui->runButton, SIGNAL(clicked()), this, SLOT(onRun()));
714 connect(m_ui->runButton, SIGNAL(clicked()), this, SLOT(onApply()));
717 void QtLauncher::restoreSettings()
720 m_ui->rembrandtCheckbox->setChecked(settings.value("enable-rembrandt", false).toBool());
721 m_ui->terrasyncCheck->setChecked(settings.value("enable-terrasync", true).toBool());
722 m_ui->fullScreenCheckbox->setChecked(settings.value("start-fullscreen", false).toBool());
723 m_ui->msaaCheckbox->setChecked(settings.value("enable-msaa", false).toBool());
724 m_ui->fetchRealWxrCheckbox->setChecked(settings.value("enable-realwx", true).toBool());
725 m_ui->startPausedCheck->setChecked(settings.value("start-paused", false).toBool());
726 m_ui->timeOfDayCombo->setCurrentIndex(settings.value("timeofday", 0).toInt());
727 m_ui->seasonCombo->setCurrentIndex(settings.value("season", 0).toInt());
729 // full paths to -set.xml files
730 m_recentAircraft = QUrl::fromStringList(settings.value("recent-aircraft").toStringList());
732 if (!m_recentAircraft.empty()) {
733 m_selectedAircraft = m_recentAircraft.front();
735 // select the default C172p
742 m_ui->location->restoreSettings();
745 m_ui->onlyShowInstalledCheck->setChecked(settings.value("only-show-installed", false).toBool());
746 if (m_ui->onlyShowInstalledCheck->isChecked()) {
747 m_ui->ratingsFilterCheck->setEnabled(false);
750 m_ui->ratingsFilterCheck->setChecked(settings.value("ratings-filter", true).toBool());
752 Q_FOREACH(QVariant v, settings.value("min-ratings").toList()) {
753 m_ratingFilters[index++] = v.toInt();
756 m_aircraftProxy->setRatingFilterEnabled(m_ui->ratingsFilterCheck->isChecked());
757 m_aircraftProxy->setRatings(m_ratingFilters);
759 updateSelectedAircraft();
760 maybeRestoreAircraftSelection();
762 m_ui->commandLineArgs->setPlainText(settings.value("additional-args").toString());
764 m_ui->mpBox->setChecked(settings.value("mp-enabled").toBool());
765 m_ui->mpCallsign->setText(settings.value("mp-callsign").toString());
766 // don't restore MP server here, we do it after a refresh
767 m_doRestoreMPServer = true;
770 void QtLauncher::delayedAircraftModelReset()
772 QTimer::singleShot(1, this, SLOT(maybeRestoreAircraftSelection()));
775 void QtLauncher::maybeRestoreAircraftSelection()
777 QModelIndex aircraftIndex = m_aircraftModel->indexOfAircraftURI(m_selectedAircraft);
778 QModelIndex proxyIndex = m_aircraftProxy->mapFromSource(aircraftIndex);
779 if (proxyIndex.isValid()) {
780 m_ui->aircraftList->selectionModel()->setCurrentIndex(proxyIndex,
781 QItemSelectionModel::ClearAndSelect);
782 m_ui->aircraftList->selectionModel()->select(proxyIndex,
783 QItemSelectionModel::ClearAndSelect);
784 m_ui->aircraftList->scrollTo(proxyIndex);
788 void QtLauncher::saveSettings()
791 settings.setValue("enable-rembrandt", m_ui->rembrandtCheckbox->isChecked());
792 settings.setValue("enable-terrasync", m_ui->terrasyncCheck->isChecked());
793 settings.setValue("enable-msaa", m_ui->msaaCheckbox->isChecked());
794 settings.setValue("start-fullscreen", m_ui->fullScreenCheckbox->isChecked());
795 settings.setValue("enable-realwx", m_ui->fetchRealWxrCheckbox->isChecked());
796 settings.setValue("start-paused", m_ui->startPausedCheck->isChecked());
797 settings.setValue("ratings-filter", m_ui->ratingsFilterCheck->isChecked());
798 settings.setValue("only-show-installed", m_ui->onlyShowInstalledCheck->isChecked());
799 settings.setValue("recent-aircraft", QUrl::toStringList(m_recentAircraft));
801 settings.setValue("timeofday", m_ui->timeOfDayCombo->currentIndex());
802 settings.setValue("season", m_ui->seasonCombo->currentIndex());
803 settings.setValue("additional-args", m_ui->commandLineArgs->toPlainText());
805 m_ui->location->saveSettings();
807 settings.setValue("mp-callsign", m_ui->mpCallsign->text());
808 settings.setValue("mp-server", m_ui->mpServerCombo->currentData());
809 settings.setValue("mp-enabled", m_ui->mpBox->isChecked());
812 void QtLauncher::setEnableDisableOptionFromCheckbox(QCheckBox* cbox, QString name) const
814 flightgear::Options* opt = flightgear::Options::sharedInstance();
815 std::string stdName(name.toStdString());
816 if (cbox->isChecked()) {
817 opt->addOption("enable-" + stdName, "");
819 opt->addOption("disable-" + stdName, "");
823 void QtLauncher::closeEvent(QCloseEvent *event)
828 void QtLauncher::reject()
833 void QtLauncher::onRun()
835 flightgear::Options* opt = flightgear::Options::sharedInstance();
836 setEnableDisableOptionFromCheckbox(m_ui->terrasyncCheck, "terrasync");
837 setEnableDisableOptionFromCheckbox(m_ui->fetchRealWxrCheckbox, "real-weather-fetch");
838 setEnableDisableOptionFromCheckbox(m_ui->rembrandtCheckbox, "rembrandt");
839 setEnableDisableOptionFromCheckbox(m_ui->fullScreenCheckbox, "fullscreen");
840 // setEnableDisableOptionFromCheckbox(m_ui->startPausedCheck, "freeze");
842 bool startPaused = m_ui->startPausedCheck->isChecked() ||
843 m_ui->location->shouldStartPaused();
845 opt->addOption("enable-freeze", "");
848 // MSAA is more complex
849 if (!m_ui->rembrandtCheckbox->isChecked()) {
850 if (m_ui->msaaCheckbox->isChecked()) {
851 globals->get_props()->setIntValue("/sim/rendering/multi-sample-buffers", 1);
852 globals->get_props()->setIntValue("/sim/rendering/multi-samples", 4);
854 globals->get_props()->setIntValue("/sim/rendering/multi-sample-buffers", 0);
859 if (!m_selectedAircraft.isEmpty()) {
860 if (m_selectedAircraft.isLocalFile()) {
861 QFileInfo setFileInfo(m_selectedAircraft.toLocalFile());
862 opt->addOption("aircraft-dir", setFileInfo.dir().absolutePath().toStdString());
863 QString setFile = setFileInfo.fileName();
864 Q_ASSERT(setFile.endsWith("-set.xml"));
865 setFile.truncate(setFile.count() - 8); // drop the '-set.xml' portion
866 opt->addOption("aircraft", setFile.toStdString());
867 } else if (m_selectedAircraft.scheme() == "package") {
868 QString qualifiedId = m_selectedAircraft.path();
869 // no need to set aircraft-dir, handled by the corresponding code
871 opt->addOption("aircraft", qualifiedId.toStdString());
873 qWarning() << "unsupported aircraft launch URL" << m_selectedAircraft;
876 // manage aircraft history
877 if (m_recentAircraft.contains(m_selectedAircraft))
878 m_recentAircraft.removeOne(m_selectedAircraft);
879 m_recentAircraft.prepend(m_selectedAircraft);
880 if (m_recentAircraft.size() > MAX_RECENT_AIRCRAFT)
881 m_recentAircraft.pop_back();
884 if (m_ui->mpBox->isChecked()) {
885 opt->addOption("callsign", m_ui->mpCallsign->text().toStdString());
886 QString host = m_ui->mpServerCombo->currentData().toString();
888 if (host == "custom") {
890 host = settings.value("mp-custom-host").toString();
891 port = settings.value("mp-custom-port").toInt();
893 port = findMPServerPort(host.toStdString());
895 globals->get_props()->setStringValue("/sim/multiplay/txhost", host.toStdString());
896 globals->get_props()->setIntValue("/sim/multiplay/txport", port);
899 m_ui->location->setLocationOptions();
902 if (m_ui->timeOfDayCombo->currentIndex() != 0) {
903 QString dayval = m_ui->timeOfDayCombo->currentText().toLower();
904 opt->addOption("timeofday", dayval.toStdString());
907 if (m_ui->seasonCombo->currentIndex() != 0) {
908 QString seasonName = m_ui->seasonCombo->currentText().toLower();
909 opt->addOption("season", seasonName.toStdString());
913 QString downloadDir = settings.value("download-dir").toString();
914 if (!downloadDir.isEmpty()) {
917 int result = QMessageBox::question(this, tr("Create download folder?"),
918 tr("The selected location for downloads does not exist. Create it?"),
919 QMessageBox::Yes | QMessageBox::No | QMessageBox::Cancel);
920 if (result == QMessageBox::Cancel) {
924 if (result == QMessageBox::Yes) {
925 d.mkpath(downloadDir);
929 opt->addOption("download-dir", downloadDir.toStdString());
933 Q_FOREACH(QString path, settings.value("scenery-paths").toStringList()) {
934 opt->addOption("fg-scenery", path.toStdString());
938 Q_FOREACH(QString path, settings.value("aircraft-paths").toStringList()) {
939 // can't use fg-aircraft for this, as it is processed before the launcher is run
940 globals->append_aircraft_path(path.toStdString());
943 // additional arguments
944 ArgumentsTokenizer tk;
945 Q_FOREACH(ArgumentsTokenizer::Arg a, tk.tokenize(m_ui->commandLineArgs->toPlainText())) {
946 if (a.arg.startsWith("prop:")) {
947 QString v = a.arg.mid(5) + "=" + a.value;
948 opt->addOption("prop", v.toStdString());
950 opt->addOption(a.arg.toStdString(), a.value.toStdString());
954 if (settings.contains("restore-defaults-on-run")) {
955 settings.remove("restore-defaults-on-run");
956 opt->addOption("restore-defaults", "");
965 void QtLauncher::onApply()
970 if (!m_selectedAircraft.isEmpty()) {
971 std::string aircraftPropValue,
974 if (m_selectedAircraft.isLocalFile()) {
975 QFileInfo setFileInfo(m_selectedAircraft.toLocalFile());
976 QString setFile = setFileInfo.fileName();
977 Q_ASSERT(setFile.endsWith("-set.xml"));
978 setFile.truncate(setFile.count() - 8); // drop the '-set.xml' portion
979 aircraftDir = setFileInfo.dir().absolutePath().toStdString();
980 aircraftPropValue = setFile.toStdString();
981 } else if (m_selectedAircraft.scheme() == "package") {
982 // no need to set aircraft-dir, handled by the corresponding code
984 aircraftPropValue = m_selectedAircraft.path().toStdString();
986 qWarning() << "unsupported aircraft launch URL" << m_selectedAircraft;
989 // manage aircraft history
990 if (m_recentAircraft.contains(m_selectedAircraft))
991 m_recentAircraft.removeOne(m_selectedAircraft);
992 m_recentAircraft.prepend(m_selectedAircraft);
993 if (m_recentAircraft.size() > MAX_RECENT_AIRCRAFT)
994 m_recentAircraft.pop_back();
996 globals->get_props()->setStringValue("/sim/aircraft", aircraftPropValue);
997 globals->get_props()->setStringValue("/sim/aircraft-dir", aircraftDir);
1004 void QtLauncher::onQuit()
1009 void QtLauncher::onToggleTerrasync(bool enabled)
1013 QString downloadDir = settings.value("download-dir").toString();
1014 if (downloadDir.isEmpty()) {
1015 downloadDir = QString::fromStdString(flightgear::defaultDownloadDir().utf8Str());
1018 QFileInfo info(downloadDir);
1019 if (!info.exists()) {
1021 msg.setWindowTitle(tr("Create download folder?"));
1022 msg.setText(tr("The download folder '%1' does not exist, create it now?").arg(downloadDir));
1023 msg.addButton(QMessageBox::Yes);
1024 msg.addButton(QMessageBox::Cancel);
1025 int result = msg.exec();
1027 if (result == QMessageBox::Cancel) {
1028 m_ui->terrasyncCheck->setChecked(false);
1032 QDir d(downloadDir);
1033 d.mkpath(downloadDir);
1038 void QtLauncher::onAircraftInstalledCompleted(QModelIndex index)
1040 maybeUpdateSelectedAircraft(index);
1043 void QtLauncher::onRatingsFilterToggled()
1045 QModelIndex aircraftIndex = m_aircraftModel->indexOfAircraftURI(m_selectedAircraft);
1046 QModelIndex proxyIndex = m_aircraftProxy->mapFromSource(aircraftIndex);
1047 if (proxyIndex.isValid()) {
1048 m_ui->aircraftList->scrollTo(proxyIndex);
1052 void QtLauncher::onAircraftInstallFailed(QModelIndex index, QString errorMessage)
1054 qWarning() << Q_FUNC_INFO << index.data(AircraftURIRole) << errorMessage;
1057 msg.setWindowTitle(tr("Aircraft installation failed"));
1058 msg.setText(tr("An error occurred installing the aircraft %1: %2").
1059 arg(index.data(Qt::DisplayRole).toString()).arg(errorMessage));
1060 msg.addButton(QMessageBox::Ok);
1063 maybeUpdateSelectedAircraft(index);
1066 void QtLauncher::onAircraftSelected(const QModelIndex& index)
1068 m_selectedAircraft = index.data(AircraftURIRole).toUrl();
1069 updateSelectedAircraft();
1072 void QtLauncher::onRequestPackageInstall(const QModelIndex& index)
1074 // also select, otherwise UI is confusing
1075 m_selectedAircraft = index.data(AircraftURIRole).toUrl();
1076 updateSelectedAircraft();
1078 QString pkg = index.data(AircraftPackageIdRole).toString();
1079 simgear::pkg::PackageRef pref = globals->packageRoot()->getPackageById(pkg.toStdString());
1080 if (pref->isInstalled()) {
1081 InstallRef install = pref->existingInstall();
1082 if (install && install->hasUpdate()) {
1083 globals->packageRoot()->scheduleToUpdate(install);
1090 void QtLauncher::onCancelDownload(const QModelIndex& index)
1092 QString pkg = index.data(AircraftPackageIdRole).toString();
1093 simgear::pkg::PackageRef pref = globals->packageRoot()->getPackageById(pkg.toStdString());
1094 simgear::pkg::InstallRef i = pref->existingInstall();
1095 i->cancelDownload();
1098 void QtLauncher::onRestoreDefaults()
1100 QMessageBox mbox(this);
1101 mbox.setText(tr("Restore all settings to defaults?"));
1102 mbox.setInformativeText(tr("Restoring settings to their defaults may affect available add-ons such as scenery or aircraft."));
1103 QPushButton* quitButton = mbox.addButton(tr("Restore and restart now"), QMessageBox::YesRole);
1104 mbox.addButton(QMessageBox::Cancel);
1105 mbox.setDefaultButton(QMessageBox::Cancel);
1106 mbox.setIconPixmap(QPixmap(":/app-icon-large"));
1109 if (mbox.clickedButton() != quitButton) {
1116 settings.setValue("restore-defaults-on-run", true);
1119 restartTheApp(QStringList());
1122 void QtLauncher::maybeUpdateSelectedAircraft(QModelIndex index)
1124 QUrl u = index.data(AircraftURIRole).toUrl();
1125 if (u == m_selectedAircraft) {
1126 // potentially enable the run button now!
1127 updateSelectedAircraft();
1131 void QtLauncher::updateSelectedAircraft()
1133 QModelIndex index = m_aircraftModel->indexOfAircraftURI(m_selectedAircraft);
1134 if (index.isValid()) {
1135 QPixmap pm = index.data(Qt::DecorationRole).value<QPixmap>();
1136 m_ui->thumbnail->setPixmap(pm);
1137 m_ui->aircraftDescription->setText(index.data(Qt::DisplayRole).toString());
1139 int status = index.data(AircraftPackageStatusRole).toInt();
1140 bool canRun = (status == PackageInstalled);
1141 m_ui->runButton->setEnabled(canRun);
1143 LauncherAircraftType aircraftType = Airplane;
1144 if (index.data(AircraftIsHelicopterRole).toBool()) {
1145 aircraftType = Helicopter;
1146 } else if (index.data(AircraftIsSeaplaneRole).toBool()) {
1147 aircraftType = Seaplane;
1150 m_ui->location->setAircraftType(aircraftType);
1152 m_ui->thumbnail->setPixmap(QPixmap());
1153 m_ui->aircraftDescription->setText("");
1154 m_ui->runButton->setEnabled(false);
1158 QModelIndex QtLauncher::proxyIndexForAircraftURI(QUrl uri) const
1160 return m_aircraftProxy->mapFromSource(sourceIndexForAircraftURI(uri));
1163 QModelIndex QtLauncher::sourceIndexForAircraftURI(QUrl uri) const
1165 AircraftItemModel* sourceModel = qobject_cast<AircraftItemModel*>(m_aircraftProxy->sourceModel());
1166 Q_ASSERT(sourceModel);
1167 return sourceModel->indexOfAircraftURI(uri);
1170 void QtLauncher::onPopupAircraftHistory()
1172 if (m_recentAircraft.isEmpty()) {
1177 Q_FOREACH(QUrl uri, m_recentAircraft) {
1178 QModelIndex index = sourceIndexForAircraftURI(uri);
1179 if (!index.isValid()) {
1183 QAction* act = m.addAction(index.data(Qt::DisplayRole).toString());
1187 QPoint popupPos = m_ui->aircraftHistory->mapToGlobal(m_ui->aircraftHistory->rect().bottomLeft());
1188 QAction* triggered = m.exec(popupPos);
1190 m_selectedAircraft = triggered->data().toUrl();
1191 QModelIndex index = proxyIndexForAircraftURI(m_selectedAircraft);
1192 m_ui->aircraftList->selectionModel()->setCurrentIndex(index,
1193 QItemSelectionModel::ClearAndSelect);
1194 m_ui->aircraftFilter->clear();
1195 updateSelectedAircraft();
1199 void QtLauncher::onEditRatingsFilter()
1201 EditRatingsFilterDialog dialog(this);
1202 dialog.setRatings(m_ratingFilters);
1205 if (dialog.result() == QDialog::Accepted) {
1207 for (int i=0; i<4; ++i) {
1208 m_ratingFilters[i] = dialog.getRating(i);
1209 vl.append(m_ratingFilters[i]);
1211 m_aircraftProxy->setRatings(m_ratingFilters);
1214 settings.setValue("min-ratings", vl);
1218 void QtLauncher::updateSettingsSummary()
1220 QStringList summary;
1221 if (m_ui->timeOfDayCombo->currentIndex() > 0) {
1222 summary.append(QString(m_ui->timeOfDayCombo->currentText().toLower()));
1225 if (m_ui->seasonCombo->currentIndex() > 0) {
1226 summary.append(QString(m_ui->seasonCombo->currentText().toLower()));
1229 if (m_ui->rembrandtCheckbox->isChecked()) {
1230 summary.append("Rembrandt enabled");
1231 } else if (m_ui->msaaCheckbox->isChecked()) {
1232 summary.append("anti-aliasing");
1235 if (m_ui->fetchRealWxrCheckbox->isChecked()) {
1236 summary.append("live weather");
1239 if (m_ui->terrasyncCheck->isChecked()) {
1240 summary.append("automatic scenery downloads");
1243 if (m_ui->startPausedCheck->isChecked()) {
1244 summary.append("paused");
1247 QString s = summary.join(", ");
1248 s[0] = s[0].toUpper();
1249 m_ui->settingsDescription->setText(s);
1252 void QtLauncher::onRembrandtToggled(bool b)
1254 // Rembrandt and multi-sample are exclusive
1255 m_ui->msaaCheckbox->setEnabled(!b);
1258 void QtLauncher::onShowInstalledAircraftToggled(bool b)
1260 m_ui->ratingsFilterCheck->setEnabled(!b);
1261 maybeRestoreAircraftSelection();
1264 void QtLauncher::onSubsytemIdleTimeout()
1266 globals->get_subsystem_mgr()->update(0.0);
1269 void QtLauncher::onDownloadDirChanged()
1272 // replace existing package root
1273 globals->get_subsystem<FGHTTPClient>()->shutdown();
1274 globals->setPackageRoot(simgear::pkg::RootRef());
1276 // create new root with updated download-dir value
1277 fgInitPackageRoot();
1279 globals->get_subsystem<FGHTTPClient>()->init();
1282 // re-scan the aircraft list
1283 m_aircraftModel->setPackageRoot(globals->packageRoot());
1284 m_aircraftModel->setPaths(settings.value("aircraft-paths").toStringList());
1285 m_aircraftModel->scanDirs();
1287 checkOfficialCatalogMessage();
1289 // re-set scenery dirs
1293 void QtLauncher::checkOfficialCatalogMessage()
1296 bool showOfficialCatalogMesssage = !globals->get_subsystem<FGHTTPClient>()->isDefaultCatalogInstalled();
1297 if (settings.value("hide-official-catalog-message").toBool()) {
1298 showOfficialCatalogMesssage = false;
1301 m_aircraftModel->setOfficialHangarMessageVisible(showOfficialCatalogMesssage);
1302 if (showOfficialCatalogMesssage) {
1303 NoOfficialHangarMessage* messageWidget = new NoOfficialHangarMessage;
1304 connect(messageWidget, &NoOfficialHangarMessage::linkActivated,
1305 this, &QtLauncher::onOfficialCatalogMessageLink);
1307 QModelIndex index = m_aircraftProxy->mapFromSource(m_aircraftModel->officialHangarMessageIndex());
1308 m_ui->aircraftList->setIndexWidget(index, messageWidget);
1312 void QtLauncher::onOfficialCatalogMessageLink(QUrl link)
1314 QString s = link.toString();
1315 if (s == "action:hide") {
1317 settings.setValue("hide-official-catalog-message", true);
1318 } else if (s == "action:add-official") {
1319 AddOnsPage::addDefaultCatalog(this);
1322 checkOfficialCatalogMessage();
1325 void QtLauncher::onRefreshMPServers()
1327 if (m_mpServerRequest.get()) {
1328 return; // in-progress
1331 string url(fgGetString("/sim/multiplay/serverlist-url",
1332 "http://liveries.flightgear.org/mpstatus/mpservers.xml"));
1335 SG_LOG(SG_IO, SG_ALERT, "do_multiplayer.refreshserverlist: no URL given");
1339 SGPropertyNode *targetnode = fgGetNode("/sim/multiplay/server-list", true);
1340 m_mpServerRequest.reset(new RemoteXMLRequest(url, targetnode));
1341 m_mpServerRequest->done(this, &QtLauncher::onRefreshMPServersDone);
1342 m_mpServerRequest->fail(this, &QtLauncher::onRefreshMPServersFailed);
1343 globals->get_subsystem<FGHTTPClient>()->makeRequest(m_mpServerRequest);
1346 void QtLauncher::onRefreshMPServersDone(simgear::HTTP::Request*)
1348 // parse the properties
1349 SGPropertyNode *targetnode = fgGetNode("/sim/multiplay/server-list", true);
1350 m_ui->mpServerCombo->clear();
1352 for (int i=0; i<targetnode->nChildren(); ++i) {
1353 SGPropertyNode* c = targetnode->getChild(i);
1354 if (c->getName() != std::string("server")) {
1358 QString name = QString::fromStdString(c->getStringValue("name"));
1359 QString loc = QString::fromStdString(c->getStringValue("location"));
1360 QString host = QString::fromStdString(c->getStringValue("hostname"));
1361 m_ui->mpServerCombo->addItem(tr("%1 - %2").arg(name,loc), host);
1364 EditCustomMPServerDialog::addCustomItem(m_ui->mpServerCombo);
1365 restoreMPServerSelection();
1367 m_mpServerRequest.clear();
1370 void QtLauncher::onRefreshMPServersFailed(simgear::HTTP::Request*)
1372 qWarning() << "refreshing MP servers failed:" << QString::fromStdString(m_mpServerRequest->responseReason());
1373 m_mpServerRequest.clear();
1374 EditCustomMPServerDialog::addCustomItem(m_ui->mpServerCombo);
1375 restoreMPServerSelection();
1378 void QtLauncher::restoreMPServerSelection()
1380 if (m_doRestoreMPServer) {
1382 int index = m_ui->mpServerCombo->findData(settings.value("mp-server"));
1384 m_ui->mpServerCombo->setCurrentIndex(index);
1386 m_doRestoreMPServer = false;
1390 void QtLauncher::onMPServerActivated(int index)
1392 if (m_ui->mpServerCombo->itemData(index) == "custom") {
1393 EditCustomMPServerDialog dlg(this);
1395 if (dlg.result() == QDialog::Accepted) {
1396 m_ui->mpServerCombo->setItemText(index, tr("Custom - %1").arg(dlg.hostname()));
1401 int QtLauncher::findMPServerPort(const std::string& host)
1403 SGPropertyNode *targetnode = fgGetNode("/sim/multiplay/server-list", true);
1404 for (int i=0; i<targetnode->nChildren(); ++i) {
1405 SGPropertyNode* c = targetnode->getChild(i);
1406 if (c->getName() != std::string("server")) {
1410 if (c->getStringValue("hostname") == host) {
1411 return c->getIntValue("port");
1418 simgear::pkg::PackageRef QtLauncher::packageForAircraftURI(QUrl uri) const
1420 if (uri.scheme() != "package") {
1421 qWarning() << "invalid URL scheme:" << uri;
1422 return simgear::pkg::PackageRef();
1425 QString ident = uri.path();
1426 return globals->packageRoot()->getPackageById(ident.toStdString());
1429 void QtLauncher::restartTheApp(QStringList fgArgs)
1431 // Spawn a new instance of myApplication:
1435 #if defined(Q_OS_MAC)
1436 QDir dir(qApp->applicationDirPath()); // returns the 'MacOS' dir
1437 dir.cdUp(); // up to 'contents' dir
1438 dir.cdUp(); // up to .app dir
1439 // see 'man open' for details, but '-n' ensures we launch a new instance,
1440 // and we want to pass remaining arguments to us, not open.
1441 args << "-n" << dir.absolutePath() << "--args" << "--launcher" << fgArgs;
1442 qDebug() << "args" << args;
1443 proc.startDetached("open", args);
1445 args << "--launcher" << fgArgs;
1446 proc.startDetached(qApp->applicationFilePath(), args);
1451 #include "QtLauncher.moc"