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();
291 Q_SLOT void onFinished()
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);
702 // add the installation path since it contains default airport data,
703 // if terrasync is disabled or on first-launch
704 globals->append_fg_scenery(globals->get_fg_root() / "Scenery");
708 void QtLauncher::setInAppMode()
711 m_ui->tabWidget->removeTab(3);
712 m_ui->tabWidget->removeTab(3);
714 m_ui->runButton->setText(tr("Apply"));
715 m_ui->quitButton->setText(tr("Cancel"));
717 disconnect(m_ui->runButton, SIGNAL(clicked()), this, SLOT(onRun()));
718 connect(m_ui->runButton, SIGNAL(clicked()), this, SLOT(onApply()));
721 void QtLauncher::restoreSettings()
724 m_ui->rembrandtCheckbox->setChecked(settings.value("enable-rembrandt", false).toBool());
725 m_ui->terrasyncCheck->setChecked(settings.value("enable-terrasync", true).toBool());
726 m_ui->fullScreenCheckbox->setChecked(settings.value("start-fullscreen", false).toBool());
727 m_ui->msaaCheckbox->setChecked(settings.value("enable-msaa", false).toBool());
728 m_ui->fetchRealWxrCheckbox->setChecked(settings.value("enable-realwx", true).toBool());
729 m_ui->startPausedCheck->setChecked(settings.value("start-paused", false).toBool());
730 m_ui->timeOfDayCombo->setCurrentIndex(settings.value("timeofday", 0).toInt());
731 m_ui->seasonCombo->setCurrentIndex(settings.value("season", 0).toInt());
733 // full paths to -set.xml files
734 m_recentAircraft = QUrl::fromStringList(settings.value("recent-aircraft").toStringList());
736 if (!m_recentAircraft.empty()) {
737 m_selectedAircraft = m_recentAircraft.front();
739 // select the default C172p
746 m_ui->location->restoreSettings();
749 m_ui->onlyShowInstalledCheck->setChecked(settings.value("only-show-installed", false).toBool());
750 if (m_ui->onlyShowInstalledCheck->isChecked()) {
751 m_ui->ratingsFilterCheck->setEnabled(false);
754 m_ui->ratingsFilterCheck->setChecked(settings.value("ratings-filter", true).toBool());
756 Q_FOREACH(QVariant v, settings.value("min-ratings").toList()) {
757 m_ratingFilters[index++] = v.toInt();
760 m_aircraftProxy->setRatingFilterEnabled(m_ui->ratingsFilterCheck->isChecked());
761 m_aircraftProxy->setRatings(m_ratingFilters);
763 updateSelectedAircraft();
764 maybeRestoreAircraftSelection();
766 m_ui->commandLineArgs->setPlainText(settings.value("additional-args").toString());
768 m_ui->mpBox->setChecked(settings.value("mp-enabled").toBool());
769 m_ui->mpCallsign->setText(settings.value("mp-callsign").toString());
770 // don't restore MP server here, we do it after a refresh
771 m_doRestoreMPServer = true;
774 void QtLauncher::delayedAircraftModelReset()
776 QTimer::singleShot(1, this, SLOT(maybeRestoreAircraftSelection()));
779 void QtLauncher::maybeRestoreAircraftSelection()
781 QModelIndex aircraftIndex = m_aircraftModel->indexOfAircraftURI(m_selectedAircraft);
782 QModelIndex proxyIndex = m_aircraftProxy->mapFromSource(aircraftIndex);
783 if (proxyIndex.isValid()) {
784 m_ui->aircraftList->selectionModel()->setCurrentIndex(proxyIndex,
785 QItemSelectionModel::ClearAndSelect);
786 m_ui->aircraftList->selectionModel()->select(proxyIndex,
787 QItemSelectionModel::ClearAndSelect);
788 m_ui->aircraftList->scrollTo(proxyIndex);
792 void QtLauncher::saveSettings()
795 settings.setValue("enable-rembrandt", m_ui->rembrandtCheckbox->isChecked());
796 settings.setValue("enable-terrasync", m_ui->terrasyncCheck->isChecked());
797 settings.setValue("enable-msaa", m_ui->msaaCheckbox->isChecked());
798 settings.setValue("start-fullscreen", m_ui->fullScreenCheckbox->isChecked());
799 settings.setValue("enable-realwx", m_ui->fetchRealWxrCheckbox->isChecked());
800 settings.setValue("start-paused", m_ui->startPausedCheck->isChecked());
801 settings.setValue("ratings-filter", m_ui->ratingsFilterCheck->isChecked());
802 settings.setValue("only-show-installed", m_ui->onlyShowInstalledCheck->isChecked());
803 settings.setValue("recent-aircraft", QUrl::toStringList(m_recentAircraft));
805 settings.setValue("timeofday", m_ui->timeOfDayCombo->currentIndex());
806 settings.setValue("season", m_ui->seasonCombo->currentIndex());
807 settings.setValue("additional-args", m_ui->commandLineArgs->toPlainText());
809 m_ui->location->saveSettings();
811 settings.setValue("mp-callsign", m_ui->mpCallsign->text());
812 settings.setValue("mp-server", m_ui->mpServerCombo->currentData());
813 settings.setValue("mp-enabled", m_ui->mpBox->isChecked());
816 void QtLauncher::setEnableDisableOptionFromCheckbox(QCheckBox* cbox, QString name) const
818 flightgear::Options* opt = flightgear::Options::sharedInstance();
819 std::string stdName(name.toStdString());
820 if (cbox->isChecked()) {
821 opt->addOption("enable-" + stdName, "");
823 opt->addOption("disable-" + stdName, "");
827 void QtLauncher::closeEvent(QCloseEvent *event)
832 void QtLauncher::reject()
837 void QtLauncher::onRun()
839 flightgear::Options* opt = flightgear::Options::sharedInstance();
840 setEnableDisableOptionFromCheckbox(m_ui->terrasyncCheck, "terrasync");
841 setEnableDisableOptionFromCheckbox(m_ui->fetchRealWxrCheckbox, "real-weather-fetch");
842 setEnableDisableOptionFromCheckbox(m_ui->rembrandtCheckbox, "rembrandt");
843 setEnableDisableOptionFromCheckbox(m_ui->fullScreenCheckbox, "fullscreen");
844 // setEnableDisableOptionFromCheckbox(m_ui->startPausedCheck, "freeze");
846 bool startPaused = m_ui->startPausedCheck->isChecked() ||
847 m_ui->location->shouldStartPaused();
849 opt->addOption("enable-freeze", "");
852 // MSAA is more complex
853 if (!m_ui->rembrandtCheckbox->isChecked()) {
854 if (m_ui->msaaCheckbox->isChecked()) {
855 globals->get_props()->setIntValue("/sim/rendering/multi-sample-buffers", 1);
856 globals->get_props()->setIntValue("/sim/rendering/multi-samples", 4);
858 globals->get_props()->setIntValue("/sim/rendering/multi-sample-buffers", 0);
863 if (!m_selectedAircraft.isEmpty()) {
864 if (m_selectedAircraft.isLocalFile()) {
865 QFileInfo setFileInfo(m_selectedAircraft.toLocalFile());
866 opt->addOption("aircraft-dir", setFileInfo.dir().absolutePath().toStdString());
867 QString setFile = setFileInfo.fileName();
868 Q_ASSERT(setFile.endsWith("-set.xml"));
869 setFile.truncate(setFile.count() - 8); // drop the '-set.xml' portion
870 opt->addOption("aircraft", setFile.toStdString());
871 } else if (m_selectedAircraft.scheme() == "package") {
872 QString qualifiedId = m_selectedAircraft.path();
873 // no need to set aircraft-dir, handled by the corresponding code
875 opt->addOption("aircraft", qualifiedId.toStdString());
877 qWarning() << "unsupported aircraft launch URL" << m_selectedAircraft;
880 // manage aircraft history
881 if (m_recentAircraft.contains(m_selectedAircraft))
882 m_recentAircraft.removeOne(m_selectedAircraft);
883 m_recentAircraft.prepend(m_selectedAircraft);
884 if (m_recentAircraft.size() > MAX_RECENT_AIRCRAFT)
885 m_recentAircraft.pop_back();
888 if (m_ui->mpBox->isChecked()) {
889 opt->addOption("callsign", m_ui->mpCallsign->text().toStdString());
890 QString host = m_ui->mpServerCombo->currentData().toString();
892 if (host == "custom") {
894 host = settings.value("mp-custom-host").toString();
895 port = settings.value("mp-custom-port").toInt();
897 port = findMPServerPort(host.toStdString());
899 globals->get_props()->setStringValue("/sim/multiplay/txhost", host.toStdString());
900 globals->get_props()->setIntValue("/sim/multiplay/txport", port);
903 m_ui->location->setLocationProperties();
906 if (m_ui->timeOfDayCombo->currentIndex() != 0) {
907 QString dayval = m_ui->timeOfDayCombo->currentText().toLower();
908 opt->addOption("timeofday", dayval.toStdString());
911 if (m_ui->seasonCombo->currentIndex() != 0) {
912 QString seasonName = m_ui->seasonCombo->currentText().toLower();
913 opt->addOption("season", seasonName.toStdString());
917 QString downloadDir = settings.value("download-dir").toString();
918 if (!downloadDir.isEmpty()) {
921 int result = QMessageBox::question(this, tr("Create download folder?"),
922 tr("The selected location for downloads does not exist. Create it?"),
923 QMessageBox::Yes | QMessageBox::No | QMessageBox::Cancel);
924 if (result == QMessageBox::Cancel) {
928 if (result == QMessageBox::Yes) {
929 d.mkpath(downloadDir);
933 opt->addOption("download-dir", downloadDir.toStdString());
937 Q_FOREACH(QString path, settings.value("scenery-paths").toStringList()) {
938 opt->addOption("fg-scenery", path.toStdString());
942 Q_FOREACH(QString path, settings.value("aircraft-paths").toStringList()) {
943 // can't use fg-aircraft for this, as it is processed before the launcher is run
944 globals->append_aircraft_path(path.toStdString());
947 // additional arguments
948 ArgumentsTokenizer tk;
949 Q_FOREACH(ArgumentsTokenizer::Arg a, tk.tokenize(m_ui->commandLineArgs->toPlainText())) {
950 if (a.arg.startsWith("prop:")) {
951 QString v = a.arg.mid(5) + "=" + a.value;
952 opt->addOption("prop", v.toStdString());
954 opt->addOption(a.arg.toStdString(), a.value.toStdString());
958 if (settings.contains("restore-defaults-on-run")) {
959 settings.remove("restore-defaults-on-run");
960 opt->addOption("restore-defaults", "");
969 void QtLauncher::onApply()
974 if (!m_selectedAircraft.isEmpty()) {
975 std::string aircraftPropValue,
978 if (m_selectedAircraft.isLocalFile()) {
979 QFileInfo setFileInfo(m_selectedAircraft.toLocalFile());
980 QString setFile = setFileInfo.fileName();
981 Q_ASSERT(setFile.endsWith("-set.xml"));
982 setFile.truncate(setFile.count() - 8); // drop the '-set.xml' portion
983 aircraftDir = setFileInfo.dir().absolutePath().toStdString();
984 aircraftPropValue = setFile.toStdString();
985 } else if (m_selectedAircraft.scheme() == "package") {
986 // no need to set aircraft-dir, handled by the corresponding code
988 aircraftPropValue = m_selectedAircraft.path().toStdString();
990 qWarning() << "unsupported aircraft launch URL" << m_selectedAircraft;
993 // manage aircraft history
994 if (m_recentAircraft.contains(m_selectedAircraft))
995 m_recentAircraft.removeOne(m_selectedAircraft);
996 m_recentAircraft.prepend(m_selectedAircraft);
997 if (m_recentAircraft.size() > MAX_RECENT_AIRCRAFT)
998 m_recentAircraft.pop_back();
1000 globals->get_props()->setStringValue("/sim/aircraft", aircraftPropValue);
1001 globals->get_props()->setStringValue("/sim/aircraft-dir", aircraftDir);
1005 m_ui->location->setLocationProperties();
1010 void QtLauncher::onQuit()
1015 void QtLauncher::onToggleTerrasync(bool enabled)
1019 QString downloadDir = settings.value("download-dir").toString();
1020 if (downloadDir.isEmpty()) {
1021 downloadDir = QString::fromStdString(flightgear::defaultDownloadDir().utf8Str());
1024 QFileInfo info(downloadDir);
1025 if (!info.exists()) {
1027 msg.setWindowTitle(tr("Create download folder?"));
1028 msg.setText(tr("The download folder '%1' does not exist, create it now?").arg(downloadDir));
1029 msg.addButton(QMessageBox::Yes);
1030 msg.addButton(QMessageBox::Cancel);
1031 int result = msg.exec();
1033 if (result == QMessageBox::Cancel) {
1034 m_ui->terrasyncCheck->setChecked(false);
1038 QDir d(downloadDir);
1039 d.mkpath(downloadDir);
1044 void QtLauncher::onAircraftInstalledCompleted(QModelIndex index)
1046 maybeUpdateSelectedAircraft(index);
1049 void QtLauncher::onRatingsFilterToggled()
1051 QModelIndex aircraftIndex = m_aircraftModel->indexOfAircraftURI(m_selectedAircraft);
1052 QModelIndex proxyIndex = m_aircraftProxy->mapFromSource(aircraftIndex);
1053 if (proxyIndex.isValid()) {
1054 m_ui->aircraftList->scrollTo(proxyIndex);
1058 void QtLauncher::onAircraftInstallFailed(QModelIndex index, QString errorMessage)
1060 qWarning() << Q_FUNC_INFO << index.data(AircraftURIRole) << errorMessage;
1063 msg.setWindowTitle(tr("Aircraft installation failed"));
1064 msg.setText(tr("An error occurred installing the aircraft %1: %2").
1065 arg(index.data(Qt::DisplayRole).toString()).arg(errorMessage));
1066 msg.addButton(QMessageBox::Ok);
1069 maybeUpdateSelectedAircraft(index);
1072 void QtLauncher::onAircraftSelected(const QModelIndex& index)
1074 m_selectedAircraft = index.data(AircraftURIRole).toUrl();
1075 updateSelectedAircraft();
1078 void QtLauncher::onRequestPackageInstall(const QModelIndex& index)
1080 // also select, otherwise UI is confusing
1081 m_selectedAircraft = index.data(AircraftURIRole).toUrl();
1082 updateSelectedAircraft();
1084 QString pkg = index.data(AircraftPackageIdRole).toString();
1085 simgear::pkg::PackageRef pref = globals->packageRoot()->getPackageById(pkg.toStdString());
1086 if (pref->isInstalled()) {
1087 InstallRef install = pref->existingInstall();
1088 if (install && install->hasUpdate()) {
1089 globals->packageRoot()->scheduleToUpdate(install);
1096 void QtLauncher::onCancelDownload(const QModelIndex& index)
1098 QString pkg = index.data(AircraftPackageIdRole).toString();
1099 simgear::pkg::PackageRef pref = globals->packageRoot()->getPackageById(pkg.toStdString());
1100 simgear::pkg::InstallRef i = pref->existingInstall();
1101 i->cancelDownload();
1104 void QtLauncher::onRestoreDefaults()
1106 QMessageBox mbox(this);
1107 mbox.setText(tr("Restore all settings to defaults?"));
1108 mbox.setInformativeText(tr("Restoring settings to their defaults may affect available add-ons such as scenery or aircraft."));
1109 QPushButton* quitButton = mbox.addButton(tr("Restore and restart now"), QMessageBox::YesRole);
1110 mbox.addButton(QMessageBox::Cancel);
1111 mbox.setDefaultButton(QMessageBox::Cancel);
1112 mbox.setIconPixmap(QPixmap(":/app-icon-large"));
1115 if (mbox.clickedButton() != quitButton) {
1122 settings.setValue("restore-defaults-on-run", true);
1125 restartTheApp(QStringList());
1128 void QtLauncher::maybeUpdateSelectedAircraft(QModelIndex index)
1130 QUrl u = index.data(AircraftURIRole).toUrl();
1131 if (u == m_selectedAircraft) {
1132 // potentially enable the run button now!
1133 updateSelectedAircraft();
1137 void QtLauncher::updateSelectedAircraft()
1139 QModelIndex index = m_aircraftModel->indexOfAircraftURI(m_selectedAircraft);
1140 if (index.isValid()) {
1141 QPixmap pm = index.data(Qt::DecorationRole).value<QPixmap>();
1142 m_ui->thumbnail->setPixmap(pm);
1143 m_ui->aircraftDescription->setText(index.data(Qt::DisplayRole).toString());
1145 int status = index.data(AircraftPackageStatusRole).toInt();
1146 bool canRun = (status == PackageInstalled);
1147 m_ui->runButton->setEnabled(canRun);
1149 LauncherAircraftType aircraftType = Airplane;
1150 if (index.data(AircraftIsHelicopterRole).toBool()) {
1151 aircraftType = Helicopter;
1152 } else if (index.data(AircraftIsSeaplaneRole).toBool()) {
1153 aircraftType = Seaplane;
1156 m_ui->location->setAircraftType(aircraftType);
1158 m_ui->thumbnail->setPixmap(QPixmap());
1159 m_ui->aircraftDescription->setText("");
1160 m_ui->runButton->setEnabled(false);
1164 QModelIndex QtLauncher::proxyIndexForAircraftURI(QUrl uri) const
1166 return m_aircraftProxy->mapFromSource(sourceIndexForAircraftURI(uri));
1169 QModelIndex QtLauncher::sourceIndexForAircraftURI(QUrl uri) const
1171 AircraftItemModel* sourceModel = qobject_cast<AircraftItemModel*>(m_aircraftProxy->sourceModel());
1172 Q_ASSERT(sourceModel);
1173 return sourceModel->indexOfAircraftURI(uri);
1176 void QtLauncher::onPopupAircraftHistory()
1178 if (m_recentAircraft.isEmpty()) {
1183 Q_FOREACH(QUrl uri, m_recentAircraft) {
1184 QModelIndex index = sourceIndexForAircraftURI(uri);
1185 if (!index.isValid()) {
1189 QAction* act = m.addAction(index.data(Qt::DisplayRole).toString());
1193 QPoint popupPos = m_ui->aircraftHistory->mapToGlobal(m_ui->aircraftHistory->rect().bottomLeft());
1194 QAction* triggered = m.exec(popupPos);
1196 m_selectedAircraft = triggered->data().toUrl();
1197 QModelIndex index = proxyIndexForAircraftURI(m_selectedAircraft);
1198 m_ui->aircraftList->selectionModel()->setCurrentIndex(index,
1199 QItemSelectionModel::ClearAndSelect);
1200 m_ui->aircraftFilter->clear();
1201 updateSelectedAircraft();
1205 void QtLauncher::onEditRatingsFilter()
1207 EditRatingsFilterDialog dialog(this);
1208 dialog.setRatings(m_ratingFilters);
1211 if (dialog.result() == QDialog::Accepted) {
1213 for (int i=0; i<4; ++i) {
1214 m_ratingFilters[i] = dialog.getRating(i);
1215 vl.append(m_ratingFilters[i]);
1217 m_aircraftProxy->setRatings(m_ratingFilters);
1220 settings.setValue("min-ratings", vl);
1224 void QtLauncher::updateSettingsSummary()
1226 QStringList summary;
1227 if (m_ui->timeOfDayCombo->currentIndex() > 0) {
1228 summary.append(QString(m_ui->timeOfDayCombo->currentText().toLower()));
1231 if (m_ui->seasonCombo->currentIndex() > 0) {
1232 summary.append(QString(m_ui->seasonCombo->currentText().toLower()));
1235 if (m_ui->rembrandtCheckbox->isChecked()) {
1236 summary.append("Rembrandt enabled");
1237 } else if (m_ui->msaaCheckbox->isChecked()) {
1238 summary.append("anti-aliasing");
1241 if (m_ui->fetchRealWxrCheckbox->isChecked()) {
1242 summary.append("live weather");
1245 if (m_ui->terrasyncCheck->isChecked()) {
1246 summary.append("automatic scenery downloads");
1249 if (m_ui->startPausedCheck->isChecked()) {
1250 summary.append("paused");
1253 QString s = summary.join(", ");
1254 s[0] = s[0].toUpper();
1255 m_ui->settingsDescription->setText(s);
1258 void QtLauncher::onRembrandtToggled(bool b)
1260 // Rembrandt and multi-sample are exclusive
1261 m_ui->msaaCheckbox->setEnabled(!b);
1264 void QtLauncher::onShowInstalledAircraftToggled(bool b)
1266 m_ui->ratingsFilterCheck->setEnabled(!b);
1267 maybeRestoreAircraftSelection();
1270 void QtLauncher::onSubsytemIdleTimeout()
1272 globals->get_subsystem_mgr()->update(0.0);
1275 void QtLauncher::onDownloadDirChanged()
1278 // replace existing package root
1279 globals->get_subsystem<FGHTTPClient>()->shutdown();
1280 globals->setPackageRoot(simgear::pkg::RootRef());
1282 // create new root with updated download-dir value
1283 fgInitPackageRoot();
1285 globals->get_subsystem<FGHTTPClient>()->init();
1288 // re-scan the aircraft list
1289 m_aircraftModel->setPackageRoot(globals->packageRoot());
1290 m_aircraftModel->setPaths(settings.value("aircraft-paths").toStringList());
1291 m_aircraftModel->scanDirs();
1293 checkOfficialCatalogMessage();
1295 // re-set scenery dirs
1299 void QtLauncher::checkOfficialCatalogMessage()
1302 bool showOfficialCatalogMesssage = !globals->get_subsystem<FGHTTPClient>()->isDefaultCatalogInstalled();
1303 if (settings.value("hide-official-catalog-message").toBool()) {
1304 showOfficialCatalogMesssage = false;
1307 m_aircraftModel->setOfficialHangarMessageVisible(showOfficialCatalogMesssage);
1308 if (showOfficialCatalogMesssage) {
1309 NoOfficialHangarMessage* messageWidget = new NoOfficialHangarMessage;
1310 connect(messageWidget, &NoOfficialHangarMessage::linkActivated,
1311 this, &QtLauncher::onOfficialCatalogMessageLink);
1313 QModelIndex index = m_aircraftProxy->mapFromSource(m_aircraftModel->officialHangarMessageIndex());
1314 m_ui->aircraftList->setIndexWidget(index, messageWidget);
1318 void QtLauncher::onOfficialCatalogMessageLink(QUrl link)
1320 QString s = link.toString();
1321 if (s == "action:hide") {
1323 settings.setValue("hide-official-catalog-message", true);
1324 } else if (s == "action:add-official") {
1325 AddOnsPage::addDefaultCatalog(this);
1328 checkOfficialCatalogMessage();
1331 void QtLauncher::onRefreshMPServers()
1333 if (m_mpServerRequest.get()) {
1334 return; // in-progress
1337 string url(fgGetString("/sim/multiplay/serverlist-url",
1338 "http://liveries.flightgear.org/mpstatus/mpservers.xml"));
1341 SG_LOG(SG_IO, SG_ALERT, "do_multiplayer.refreshserverlist: no URL given");
1345 SGPropertyNode *targetnode = fgGetNode("/sim/multiplay/server-list", true);
1346 m_mpServerRequest.reset(new RemoteXMLRequest(url, targetnode));
1347 m_mpServerRequest->done(this, &QtLauncher::onRefreshMPServersDone);
1348 m_mpServerRequest->fail(this, &QtLauncher::onRefreshMPServersFailed);
1349 globals->get_subsystem<FGHTTPClient>()->makeRequest(m_mpServerRequest);
1352 void QtLauncher::onRefreshMPServersDone(simgear::HTTP::Request*)
1354 // parse the properties
1355 SGPropertyNode *targetnode = fgGetNode("/sim/multiplay/server-list", true);
1356 m_ui->mpServerCombo->clear();
1358 for (int i=0; i<targetnode->nChildren(); ++i) {
1359 SGPropertyNode* c = targetnode->getChild(i);
1360 if (c->getName() != std::string("server")) {
1364 QString name = QString::fromStdString(c->getStringValue("name"));
1365 QString loc = QString::fromStdString(c->getStringValue("location"));
1366 QString host = QString::fromStdString(c->getStringValue("hostname"));
1367 m_ui->mpServerCombo->addItem(tr("%1 - %2").arg(name,loc), host);
1370 EditCustomMPServerDialog::addCustomItem(m_ui->mpServerCombo);
1371 restoreMPServerSelection();
1373 m_mpServerRequest.clear();
1376 void QtLauncher::onRefreshMPServersFailed(simgear::HTTP::Request*)
1378 qWarning() << "refreshing MP servers failed:" << QString::fromStdString(m_mpServerRequest->responseReason());
1379 m_mpServerRequest.clear();
1380 EditCustomMPServerDialog::addCustomItem(m_ui->mpServerCombo);
1381 restoreMPServerSelection();
1384 void QtLauncher::restoreMPServerSelection()
1386 if (m_doRestoreMPServer) {
1388 int index = m_ui->mpServerCombo->findData(settings.value("mp-server"));
1390 m_ui->mpServerCombo->setCurrentIndex(index);
1392 m_doRestoreMPServer = false;
1396 void QtLauncher::onMPServerActivated(int index)
1398 if (m_ui->mpServerCombo->itemData(index) == "custom") {
1399 EditCustomMPServerDialog dlg(this);
1401 if (dlg.result() == QDialog::Accepted) {
1402 m_ui->mpServerCombo->setItemText(index, tr("Custom - %1").arg(dlg.hostname()));
1407 int QtLauncher::findMPServerPort(const std::string& host)
1409 SGPropertyNode *targetnode = fgGetNode("/sim/multiplay/server-list", true);
1410 for (int i=0; i<targetnode->nChildren(); ++i) {
1411 SGPropertyNode* c = targetnode->getChild(i);
1412 if (c->getName() != std::string("server")) {
1416 if (c->getStringValue("hostname") == host) {
1417 return c->getIntValue("port");
1424 simgear::pkg::PackageRef QtLauncher::packageForAircraftURI(QUrl uri) const
1426 if (uri.scheme() != "package") {
1427 qWarning() << "invalid URL scheme:" << uri;
1428 return simgear::pkg::PackageRef();
1431 QString ident = uri.path();
1432 return globals->packageRoot()->getPackageById(ident.toStdString());
1435 void QtLauncher::restartTheApp(QStringList fgArgs)
1437 // Spawn a new instance of myApplication:
1441 #if defined(Q_OS_MAC)
1442 QDir dir(qApp->applicationDirPath()); // returns the 'MacOS' dir
1443 dir.cdUp(); // up to 'contents' dir
1444 dir.cdUp(); // up to .app dir
1445 // see 'man open' for details, but '-n' ensures we launch a new instance,
1446 // and we want to pass remaining arguments to us, not open.
1447 args << "-n" << dir.absolutePath() << "--args" << "--launcher" << fgArgs;
1448 qDebug() << "args" << args;
1449 proc.startDetached("open", args);
1451 args << "--launcher" << fgArgs;
1452 proc.startDetached(qApp->applicationFilePath(), args);
1457 #include "QtLauncher.moc"