1 // QtLauncher.cxx - GUI launcher dialog using Qt5
3 // Written by James Turner, started December 2014.
5 // Copyright (C) 2014 James Turner <zakalawe@mac.com>
7 // This program is free software; you can redistribute it and/or
8 // modify it under the terms of the GNU General Public License as
9 // published by the Free Software Foundation; either version 2 of the
10 // License, or (at your option) any later version.
12 // This program is distributed in the hope that it will be useful, but
13 // WITHOUT ANY WARRANTY; without even the implied warranty of
14 // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
15 // General Public License for more details.
17 // You should have received a copy of the GNU General Public License
18 // along with this program; if not, write to the Free Software
19 // Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
21 #include "QtLauncher.hxx"
22 #include "QtLauncher_private.hxx"
25 #include <QProgressDialog>
26 #include <QCoreApplication>
27 #include <QAbstractListModel>
36 #include <QSortFilterProxyModel>
38 #include <QDesktopServices>
41 #include <QFileDialog>
42 #include <QMessageBox>
44 #include <QApplication>
46 #include <QDoubleSpinBox>
49 #include <simgear/timing/timestamp.hxx>
50 #include <simgear/props/props_io.hxx>
51 #include <simgear/structure/exception.hxx>
52 #include <simgear/structure/subsystem_mgr.hxx>
53 #include <simgear/misc/sg_path.hxx>
54 #include <simgear/package/Catalog.hxx>
55 #include <simgear/package/Package.hxx>
56 #include <simgear/package/Install.hxx>
58 #include "ui_Launcher.h"
59 #include "EditRatingsFilterDialog.hxx"
60 #include "AircraftItemDelegate.hxx"
61 #include "AircraftModel.hxx"
62 #include "PathsDialog.hxx"
64 #include <Main/globals.hxx>
65 #include <Navaids/NavDataCache.hxx>
66 #include <Navaids/navrecord.hxx>
68 #include <Main/options.hxx>
69 #include <Main/fg_init.hxx>
70 #include <Viewer/WindowBuilder.hxx>
71 #include <Network/HTTPClient.hxx>
73 using namespace flightgear;
74 using namespace simgear::pkg;
76 const int MAX_RECENT_AIRCRAFT = 20;
78 namespace { // anonymous namespace
82 QString baseLabel = QT_TR_NOOP("Initialising navigation data, this may take several minutes");
83 NavDataCache* cache = NavDataCache::createInstance();
84 if (cache->isRebuildRequired()) {
85 QProgressDialog rebuildProgress(baseLabel,
86 QString() /* cancel text */,
88 rebuildProgress.setWindowModality(Qt::WindowModal);
89 rebuildProgress.show();
91 NavDataCache::RebuildPhase phase = cache->rebuild();
93 while (phase != NavDataCache::REBUILD_DONE) {
94 // sleep to give the rebuild thread more time
95 SGTimeStamp::sleepForMSec(50);
96 phase = cache->rebuild();
99 case NavDataCache::REBUILD_AIRPORTS:
100 rebuildProgress.setLabelText(QT_TR_NOOP("Loading airport data"));
103 case NavDataCache::REBUILD_FIXES:
104 rebuildProgress.setLabelText(QT_TR_NOOP("Loading waypoint data"));
107 case NavDataCache::REBUILD_NAVAIDS:
108 rebuildProgress.setLabelText(QT_TR_NOOP("Loading navigation data"));
112 case NavDataCache::REBUILD_POIS:
113 rebuildProgress.setLabelText(QT_TR_NOOP("Loading point-of-interest data"));
117 rebuildProgress.setLabelText(baseLabel);
120 if (phase == NavDataCache::REBUILD_UNKNOWN) {
121 rebuildProgress.setValue(0);
122 rebuildProgress.setMaximum(0);
124 rebuildProgress.setValue(cache->rebuildPhaseCompletionPercentage());
125 rebuildProgress.setMaximum(100);
128 QCoreApplication::processEvents();
133 class ArgumentsTokenizer
139 explicit Arg(QString k, QString v = QString()) : arg(k), value(v) {}
145 QList<Arg> tokenize(QString in) const
148 const int len = in.count();
154 for (; index < len; ++index) {
156 nc = index < (len - 1) ? in.at(index + 1) : QChar();
160 if (c == QChar('-')) {
161 if (nc == QChar('-')) {
166 // should we pemit single hyphen arguments?
167 // choosing to fail for now
170 } else if (c == QChar('#')) {
173 } else if (c.isSpace()) {
179 if (c == QChar('=')) {
182 } else if (c.isSpace()) {
184 result.append(Arg(key));
186 // could check for illegal charatcers here
192 if (c == QChar('"')) {
194 } else if (c.isSpace()) {
196 result.append(Arg(key, value));
203 if (c == QChar('\\')) {
204 // check for escaped double-quote inside quoted value
205 if (nc == QChar('"')) {
208 } else if (c == QChar('"')) {
216 if ((c == QChar('\n')) || (c == QChar('\r'))) {
220 // nothing to do, eat comment chars
224 } // of character loop
226 // ensure last argument isn't lost
228 result.append(Arg(key));
229 } else if (state == Value) {
230 result.append(Arg(key, value));
246 } // of anonymous namespace
248 <<<<<<< 56d7d049bc0b7361d1799298c38e61084f5d5e3f
249 class IdentSearchFilter : public FGPositioned::TypeFilter
254 addType(FGPositioned::AIRPORT);
255 addType(FGPositioned::SEAPORT);
256 addType(FGPositioned::HELIPAD);
257 addType(FGPositioned::VOR);
258 addType(FGPositioned::FIX);
259 addType(FGPositioned::NDB);
263 class AirportSearchModel : public QAbstractListModel
267 AirportSearchModel() :
268 m_searchActive(false)
272 void setSearch(QString t)
279 std::string term(t.toUpper().toStdString());
281 IdentSearchFilter filter;
282 FGPositionedList exactMatches = NavDataCache::instance()->findAllWithIdent(term, &filter, true);
284 for (unsigned int i=0; i<exactMatches.size(); ++i) {
285 m_ids.push_back(exactMatches[i]->guid());
286 m_items.push_back(exactMatches[i]);
291 m_search.reset(new NavDataCache::ThreadedGUISearch(term));
292 QTimer::singleShot(100, this, SLOT(onSearchResultsPoll()));
293 m_searchActive = true;
297 bool isSearchActive() const
299 return m_searchActive;
302 virtual int rowCount(const QModelIndex&) const
304 // if empty, return 1 for special 'no matches'?
308 virtual QVariant data(const QModelIndex& index, int role) const
310 if (!index.isValid())
313 FGPositionedRef pos = itemAtRow(index.row());
314 if (role == Qt::DisplayRole) {
315 QString name = QString::fromStdString(pos->name());
316 return QString("%1: %2").arg(QString::fromStdString(pos->ident())).arg(name);
319 if (role == Qt::EditRole) {
320 return QString::fromStdString(pos->ident());
323 if (role == Qt::UserRole) {
324 return static_cast<qlonglong>(m_ids[index.row()]);
330 FGPositionedRef itemAtRow(unsigned int row) const
332 FGPositionedRef pos = m_items[row];
334 pos = NavDataCache::instance()->loadById(m_ids[row]);
341 void searchComplete();
344 void onSearchResultsPoll()
346 PositionedIDVec newIds = m_search->results();
348 beginInsertRows(QModelIndex(), m_ids.size(), newIds.size() - 1);
349 for (unsigned int i=m_ids.size(); i < newIds.size(); ++i) {
350 m_ids.push_back(newIds[i]);
351 m_items.push_back(FGPositionedRef()); // null ref
355 if (m_search->isComplete()) {
356 m_searchActive = false;
358 emit searchComplete();
360 QTimer::singleShot(100, this, SLOT(onSearchResultsPoll()));
365 PositionedIDVec m_ids;
366 mutable FGPositionedList m_items;
368 QScopedPointer<NavDataCache::ThreadedGUISearch> m_search;
371 >>>>>>> Work on LocationWidget for Qt launcher
373 class AircraftProxyModel : public QSortFilterProxyModel
377 AircraftProxyModel(QObject* pr) :
378 QSortFilterProxyModel(pr),
379 m_ratingsFilter(true)
381 for (int i=0; i<4; ++i) {
386 void setRatings(int* ratings)
388 ::memcpy(m_ratings, ratings, sizeof(int) * 4);
393 void setRatingFilterEnabled(bool e)
395 if (e == m_ratingsFilter) {
404 bool filterAcceptsRow(int sourceRow, const QModelIndex &sourceParent) const
406 if (!QSortFilterProxyModel::filterAcceptsRow(sourceRow, sourceParent)) {
410 if (m_ratingsFilter) {
411 QModelIndex index = sourceModel()->index(sourceRow, 0, sourceParent);
412 for (int i=0; i<4; ++i) {
413 if (m_ratings[i] > index.data(AircraftRatingRole + i).toInt()) {
423 bool m_ratingsFilter;
427 static void initQtResources()
429 Q_INIT_RESOURCE(resources);
435 void initApp(int& argc, char** argv)
437 static bool qtInitDone = false;
441 QApplication* app = new QApplication(argc, argv);
442 app->setOrganizationName("FlightGear");
443 app->setApplicationName("FlightGear");
444 app->setOrganizationDomain("flightgear.org");
446 // avoid double Apple menu and other weirdness if both Qt and OSG
447 // try to initialise various Cocoa structures.
448 flightgear::WindowBuilder::setPoseAsStandaloneApp(false);
450 Qt::KeyboardModifiers mods = app->queryKeyboardModifiers();
451 if (mods & Qt::AltModifier) {
452 qWarning() << "Alt pressed during launch";
454 // wipe out our settings
459 Options::sharedInstance()->addOption("restore-defaults", "");
464 bool runLauncherDialog()
466 sglog().setLogLevels( SG_ALL, SG_INFO );
469 initQtResources(); // can't be called inside a namespaceb
471 // startup the nav-cache now. This pre-empts normal startup of
472 // the cache, but no harm done. (Providing scenery paths are consistent)
479 // startup the HTTP system now since packages needs it
480 FGHTTPClient* http = new FGHTTPClient;
481 globals->add_subsystem("http", http);
482 // we guard against re-init in the global phase; bind and postinit
483 // will happen as normal
487 // setup scenery paths now, especially TerraSync path for airport
488 // parking locations (after they're downloaded)
492 if (dlg.result() != QDialog::Accepted) {
499 bool runInAppLauncherDialog()
504 if (dlg.result() != QDialog::Accepted) {
511 } // of namespace flightgear
513 QtLauncher::QtLauncher() :
516 m_subsystemIdleTimer(NULL),
519 m_ui.reset(new Ui::Launcher);
522 #if QT_VERSION >= 0x050300
523 // don't require Qt 5.3
524 m_ui->commandLineArgs->setPlaceholderText("--option=value --prop:/sim/name=value");
527 #if QT_VERSION >= 0x050200
528 m_ui->aircraftFilter->setClearButtonEnabled(true);
531 for (int i=0; i<4; ++i) {
532 m_ratingFilters[i] = 3;
535 m_subsystemIdleTimer = new QTimer(this);
536 m_subsystemIdleTimer->setInterval(0);
537 connect(m_subsystemIdleTimer, &QTimer::timeout,
538 this, &QtLauncher::onSubsytemIdleTimeout);
539 m_subsystemIdleTimer->start();
541 // create and configure the proxy model
542 m_aircraftProxy = new AircraftProxyModel(this);
543 connect(m_ui->ratingsFilterCheck, &QAbstractButton::toggled,
544 m_aircraftProxy, &AircraftProxyModel::setRatingFilterEnabled);
545 connect(m_ui->aircraftFilter, &QLineEdit::textChanged,
546 m_aircraftProxy, &QSortFilterProxyModel::setFilterFixedString);
548 <<<<<<< 56d7d049bc0b7361d1799298c38e61084f5d5e3f
549 connect(m_ui->runwayCombo, SIGNAL(currentIndexChanged(int)),
550 this, SLOT(updateLocationDescription()));
551 connect(m_ui->parkingCombo, SIGNAL(currentIndexChanged(int)),
552 this, SLOT(updateLocationDescription()));
553 connect(m_ui->runwayRadio, SIGNAL(toggled(bool)),
554 this, SLOT(updateLocationDescription()));
555 connect(m_ui->parkingRadio, SIGNAL(toggled(bool)),
556 this, SLOT(updateLocationDescription()));
557 connect(m_ui->onFinalCheckbox, SIGNAL(toggled(bool)),
558 this, SLOT(updateLocationDescription()));
561 connect(m_ui->airportDiagram, &AirportDiagram::clickedRunway,
562 this, &QtLauncher::onAirportDiagramClicked);
564 >>>>>>> Work on LocationWidget for Qt launcher
566 connect(m_ui->runButton, SIGNAL(clicked()), this, SLOT(onRun()));
567 connect(m_ui->quitButton, SIGNAL(clicked()), this, SLOT(onQuit()));
569 connect(m_ui->aircraftHistory, &QPushButton::clicked,
570 this, &QtLauncher::onPopupAircraftHistory);
572 connect(m_ui->location, &LocationWidget::descriptionChanged,
573 m_ui->locationDescription, &QLabel::setText);
575 QAction* qa = new QAction(this);
576 qa->setShortcut(QKeySequence("Ctrl+Q"));
577 connect(qa, &QAction::triggered, this, &QtLauncher::onQuit);
580 connect(m_ui->editRatingFilter, &QPushButton::clicked,
581 this, &QtLauncher::onEditRatingsFilter);
583 QIcon historyIcon(":/history-icon");
584 m_ui->aircraftHistory->setIcon(historyIcon);
586 connect(m_ui->timeOfDayCombo, SIGNAL(currentIndexChanged(int)),
587 this, SLOT(updateSettingsSummary()));
588 connect(m_ui->seasonCombo, SIGNAL(currentIndexChanged(int)),
589 this, SLOT(updateSettingsSummary()));
590 connect(m_ui->fetchRealWxrCheckbox, SIGNAL(toggled(bool)),
591 this, SLOT(updateSettingsSummary()));
592 connect(m_ui->rembrandtCheckbox, SIGNAL(toggled(bool)),
593 this, SLOT(updateSettingsSummary()));
594 connect(m_ui->terrasyncCheck, SIGNAL(toggled(bool)),
595 this, SLOT(updateSettingsSummary()));
596 connect(m_ui->startPausedCheck, SIGNAL(toggled(bool)),
597 this, SLOT(updateSettingsSummary()));
598 connect(m_ui->msaaCheckbox, SIGNAL(toggled(bool)),
599 this, SLOT(updateSettingsSummary()));
601 connect(m_ui->rembrandtCheckbox, SIGNAL(toggled(bool)),
602 this, SLOT(onRembrandtToggled(bool)));
603 connect(m_ui->terrasyncCheck, &QCheckBox::toggled,
604 this, &QtLauncher::onToggleTerrasync);
605 updateSettingsSummary();
607 m_aircraftModel = new AircraftItemModel(this, RootRef(globals->packageRoot()));
608 m_aircraftProxy->setSourceModel(m_aircraftModel);
610 m_aircraftProxy->setFilterCaseSensitivity(Qt::CaseInsensitive);
611 m_aircraftProxy->setSortCaseSensitivity(Qt::CaseInsensitive);
612 m_aircraftProxy->setSortRole(Qt::DisplayRole);
613 m_aircraftProxy->setDynamicSortFilter(true);
615 m_ui->aircraftList->setModel(m_aircraftProxy);
616 m_ui->aircraftList->setHorizontalScrollBarPolicy(Qt::ScrollBarAlwaysOff);
617 AircraftItemDelegate* delegate = new AircraftItemDelegate(m_ui->aircraftList);
618 m_ui->aircraftList->setItemDelegate(delegate);
619 m_ui->aircraftList->setSelectionMode(QAbstractItemView::SingleSelection);
620 connect(m_ui->aircraftList, &QListView::clicked,
621 this, &QtLauncher::onAircraftSelected);
622 connect(delegate, &AircraftItemDelegate::variantChanged,
623 this, &QtLauncher::onAircraftSelected);
624 connect(delegate, &AircraftItemDelegate::requestInstall,
625 this, &QtLauncher::onRequestPackageInstall);
626 connect(delegate, &AircraftItemDelegate::cancelDownload,
627 this, &QtLauncher::onCancelDownload);
629 connect(m_aircraftModel, &AircraftItemModel::aircraftInstallCompleted,
630 this, &QtLauncher::onAircraftInstalledCompleted);
631 connect(m_aircraftModel, &AircraftItemModel::aircraftInstallFailed,
632 this, &QtLauncher::onAircraftInstallFailed);
634 connect(m_ui->pathsButton, &QPushButton::clicked,
635 this, &QtLauncher::onEditPaths);
640 m_aircraftModel->setPaths(settings.value("aircraft-paths").toStringList());
641 m_aircraftModel->scanDirs();
644 QtLauncher::~QtLauncher()
649 void QtLauncher::setInAppMode()
652 m_ui->tabWidget->removeTab(2);
653 m_ui->runButton->setText(tr("Apply"));
654 m_ui->quitButton->setText(tr("Cancel"));
656 disconnect(m_ui->runButton, SIGNAL(clicked()), this, SLOT(onRun()));
657 connect(m_ui->runButton, SIGNAL(clicked()), this, SLOT(onApply()));
660 bool QtLauncher::runLauncherDialog()
662 sglog().setLogLevels( SG_ALL, SG_INFO );
663 Q_INIT_RESOURCE(resources);
665 static bool qtInitDone = false;
669 s_argc = argc; // QApplication only stores a reference to argc,
670 // and may crash if it is freed
671 // http://doc.qt.io/qt-5/qguiapplication.html#QGuiApplication
673 QApplication* app = new QApplication(s_argc, argv);
674 app->setOrganizationName("FlightGear");
675 app->setApplicationName("FlightGear");
676 app->setOrganizationDomain("flightgear.org");
678 // avoid double Apple menu and other weirdness if both Qt and OSG
679 // try to initialise various Cocoa structures.
680 flightgear::WindowBuilder::setPoseAsStandaloneApp(false);
682 Qt::KeyboardModifiers mods = app->queryKeyboardModifiers();
683 if (mods & Qt::AltModifier) {
684 qWarning() << "Alt pressed during launch";
686 // wipe out our settings
690 Options::sharedInstance()->addOption("restore-defaults", "");
694 // startup the nav-cache now. This preempts normal startup of
695 // the cache, but no harm done. (Providing scenery paths are consistent)
699 // setup scenery paths now, especially TerraSync path for airport
700 // parking locations (after they're downloaded)
704 if (dlg.result() != QDialog::Accepted) {
709 void QtLauncher::restoreSettings()
712 m_ui->rembrandtCheckbox->setChecked(settings.value("enable-rembrandt", false).toBool());
713 m_ui->terrasyncCheck->setChecked(settings.value("enable-terrasync", true).toBool());
714 m_ui->fullScreenCheckbox->setChecked(settings.value("start-fullscreen", false).toBool());
715 m_ui->msaaCheckbox->setChecked(settings.value("enable-msaa", false).toBool());
716 m_ui->fetchRealWxrCheckbox->setChecked(settings.value("enable-realwx", true).toBool());
717 m_ui->startPausedCheck->setChecked(settings.value("start-paused", false).toBool());
718 m_ui->timeOfDayCombo->setCurrentIndex(settings.value("timeofday", 0).toInt());
719 m_ui->seasonCombo->setCurrentIndex(settings.value("season", 0).toInt());
721 // full paths to -set.xml files
722 m_recentAircraft = QUrl::fromStringList(settings.value("recent-aircraft").toStringList());
724 if (!m_recentAircraft.empty()) {
725 m_selectedAircraft = m_recentAircraft.front();
727 // select the default C172p
730 updateSelectedAircraft();
731 m_ui->location->restoreSettings();
734 m_ui->ratingsFilterCheck->setChecked(settings.value("ratings-filter", true).toBool());
736 Q_FOREACH(QVariant v, settings.value("min-ratings").toList()) {
737 m_ratingFilters[index++] = v.toInt();
740 m_aircraftProxy->setRatingFilterEnabled(m_ui->ratingsFilterCheck->isChecked());
741 m_aircraftProxy->setRatings(m_ratingFilters);
743 m_ui->commandLineArgs->setPlainText(settings.value("additional-args").toString());
746 void QtLauncher::saveSettings()
749 settings.setValue("enable-rembrandt", m_ui->rembrandtCheckbox->isChecked());
750 settings.setValue("enable-terrasync", m_ui->terrasyncCheck->isChecked());
751 settings.setValue("enable-msaa", m_ui->msaaCheckbox->isChecked());
752 settings.setValue("start-fullscreen", m_ui->fullScreenCheckbox->isChecked());
753 settings.setValue("enable-realwx", m_ui->fetchRealWxrCheckbox->isChecked());
754 settings.setValue("start-paused", m_ui->startPausedCheck->isChecked());
755 settings.setValue("ratings-filter", m_ui->ratingsFilterCheck->isChecked());
756 settings.setValue("recent-aircraft", QUrl::toStringList(m_recentAircraft));
758 settings.setValue("timeofday", m_ui->timeOfDayCombo->currentIndex());
759 settings.setValue("season", m_ui->seasonCombo->currentIndex());
760 settings.setValue("additional-args", m_ui->commandLineArgs->toPlainText());
762 m_ui->location->saveSettings();
765 void QtLauncher::setEnableDisableOptionFromCheckbox(QCheckBox* cbox, QString name) const
767 flightgear::Options* opt = flightgear::Options::sharedInstance();
768 std::string stdName(name.toStdString());
769 if (cbox->isChecked()) {
770 opt->addOption("enable-" + stdName, "");
772 opt->addOption("disable-" + stdName, "");
776 void QtLauncher::onRun()
780 flightgear::Options* opt = flightgear::Options::sharedInstance();
781 setEnableDisableOptionFromCheckbox(m_ui->terrasyncCheck, "terrasync");
782 setEnableDisableOptionFromCheckbox(m_ui->fetchRealWxrCheckbox, "real-weather-fetch");
783 setEnableDisableOptionFromCheckbox(m_ui->rembrandtCheckbox, "rembrandt");
784 setEnableDisableOptionFromCheckbox(m_ui->fullScreenCheckbox, "fullscreen");
785 // setEnableDisableOptionFromCheckbox(m_ui->startPausedCheck, "freeze");
787 bool startPaused = m_ui->startPausedCheck->isChecked() ||
788 m_ui->location->shouldStartPaused();
790 opt->addOption("enable-freeze", "");
793 // MSAA is more complex
794 if (!m_ui->rembrandtCheckbox->isChecked()) {
795 if (m_ui->msaaCheckbox->isChecked()) {
796 globals->get_props()->setIntValue("/sim/rendering/multi-sample-buffers", 1);
797 globals->get_props()->setIntValue("/sim/rendering/multi-samples", 4);
799 globals->get_props()->setIntValue("/sim/rendering/multi-sample-buffers", 0);
804 if (!m_selectedAircraft.isEmpty()) {
805 if (m_selectedAircraft.isLocalFile()) {
806 QFileInfo setFileInfo(m_selectedAircraft.toLocalFile());
807 opt->addOption("aircraft-dir", setFileInfo.dir().absolutePath().toStdString());
808 QString setFile = setFileInfo.fileName();
809 Q_ASSERT(setFile.endsWith("-set.xml"));
810 setFile.truncate(setFile.count() - 8); // drop the '-set.xml' portion
811 opt->addOption("aircraft", setFile.toStdString());
812 } else if (m_selectedAircraft.scheme() == "package") {
813 PackageRef pkg = packageForAircraftURI(m_selectedAircraft);
814 // no need to set aircraft-dir, handled by the corresponding code
816 opt->addOption("aircraft", pkg->qualifiedId());
818 qWarning() << "unsupported aircraft launch URL" << m_selectedAircraft;
821 // manage aircraft history
822 if (m_recentAircraft.contains(m_selectedAircraft))
823 m_recentAircraft.removeOne(m_selectedAircraft);
824 m_recentAircraft.prepend(m_selectedAircraft);
825 if (m_recentAircraft.size() > MAX_RECENT_AIRCRAFT)
826 m_recentAircraft.pop_back();
829 m_ui->location->setLocationOptions();
832 if (m_ui->timeOfDayCombo->currentIndex() != 0) {
833 QString dayval = m_ui->timeOfDayCombo->currentText().toLower();
834 opt->addOption("timeofday", dayval.toStdString());
837 if (m_ui->seasonCombo->currentIndex() != 0) {
838 QString dayval = m_ui->timeOfDayCombo->currentText().toLower();
839 opt->addOption("season", dayval.toStdString());
843 QString downloadDir = settings.value("download-dir").toString();
844 if (!downloadDir.isEmpty()) {
847 int result = QMessageBox::question(this, tr("Create download folder?"),
848 tr("The selected location for downloads does not exist. Create it?"),
849 QMessageBox::Yes | QMessageBox::No | QMessageBox::Cancel);
850 if (result == QMessageBox::Cancel) {
854 if (result == QMessageBox::Yes) {
855 d.mkpath(downloadDir);
859 qDebug() << "Download dir is:" << downloadDir;
860 opt->addOption("download-dir", downloadDir.toStdString());
864 Q_FOREACH(QString path, settings.value("scenery-paths").toStringList()) {
865 opt->addOption("fg-scenery", path.toStdString());
869 Q_FOREACH(QString path, settings.value("aircraft-paths").toStringList()) {
870 // can't use fg-aircraft for this, as it is processed before the launcher is run
871 globals->append_aircraft_path(path.toStdString());
874 // additional arguments
875 ArgumentsTokenizer tk;
876 Q_FOREACH(ArgumentsTokenizer::Arg a, tk.tokenize(m_ui->commandLineArgs->toPlainText())) {
877 if (a.arg.startsWith("prop:")) {
878 QString v = a.arg.mid(5) + "=" + a.value;
879 opt->addOption("prop", v.toStdString());
881 opt->addOption(a.arg.toStdString(), a.value.toStdString());
889 void QtLauncher::onApply()
894 if (!m_selectedAircraft.isEmpty()) {
895 std::string aircraftPropValue,
898 if (m_selectedAircraft.isLocalFile()) {
899 QFileInfo setFileInfo(m_selectedAircraft.toLocalFile());
900 QString setFile = setFileInfo.fileName();
901 Q_ASSERT(setFile.endsWith("-set.xml"));
902 setFile.truncate(setFile.count() - 8); // drop the '-set.xml' portion
903 aircraftDir = setFileInfo.dir().absolutePath().toStdString();
904 aircraftPropValue = setFile.toStdString();
905 } else if (m_selectedAircraft.scheme() == "package") {
906 PackageRef pkg = packageForAircraftURI(m_selectedAircraft);
907 // no need to set aircraft-dir, handled by the corresponding code
909 aircraftPropValue = pkg->qualifiedId();
911 qWarning() << "unsupported aircraft launch URL" << m_selectedAircraft;
914 // manage aircraft history
915 if (m_recentAircraft.contains(m_selectedAircraft))
916 m_recentAircraft.removeOne(m_selectedAircraft);
917 m_recentAircraft.prepend(m_selectedAircraft);
918 if (m_recentAircraft.size() > MAX_RECENT_AIRCRAFT)
919 m_recentAircraft.pop_back();
921 globals->get_props()->setStringValue("/sim/aircraft", aircraftPropValue);
922 globals->get_props()->setStringValue("/sim/aircraft-dir", aircraftDir);
929 void QtLauncher::onQuit()
934 <<<<<<< 56d7d049bc0b7361d1799298c38e61084f5d5e3f
935 void QtLauncher::onSearchAirports()
937 QString search = m_ui->airportEdit->text();
938 m_airportsModel->setSearch(search);
940 if (m_airportsModel->isSearchActive()) {
941 m_ui->searchStatusText->setText(QString("Searching for '%1'").arg(search));
942 m_ui->locationStack->setCurrentIndex(2);
943 } else if (m_airportsModel->rowCount(QModelIndex()) == 1) {
944 setBaseLocation(m_airportsModel->itemAtRow(0));
945 m_ui->locationStack->setCurrentIndex(0);
949 void QtLauncher::onAirportSearchComplete()
951 int numResults = m_airportsModel->rowCount(QModelIndex());
952 if (numResults == 0) {
953 m_ui->searchStatusText->setText(QString("No matching airports for '%1'").arg(m_ui->airportEdit->text()));
954 } else if (numResults == 1) {
955 setBaseLocation(m_airportsModel->itemAtRow(0));
956 m_ui->locationStack->setCurrentIndex(0);
958 m_ui->locationStack->setCurrentIndex(1);
962 void QtLauncher::onLocationChanged()
964 bool locIsAirport = FGAirport::isAirportType(m_location.ptr());
966 m_ui->runwayCombo->setEnabled(locIsAirport);
967 m_ui->parkingCombo->setEnabled(locIsAirport);
969 FGAirport* apt = static_cast<FGAirport*>(m_location.ptr());
970 m_ui->airportDiagram->setAirport(apt);
972 m_ui->runwayRadio->setChecked(true); // default back to runway mode
973 // unless multiplayer is enabled ?
974 m_ui->airportDiagram->setEnabled(true);
976 m_ui->runwayCombo->clear();
977 m_ui->runwayCombo->addItem("Automatic", -1);
978 for (unsigned int r=0; r<apt->numRunways(); ++r) {
979 FGRunwayRef rwy = apt->getRunwayByIndex(r);
980 // add runway with index as data role
981 m_ui->runwayCombo->addItem(QString::fromStdString(rwy->ident()), r);
983 m_ui->airportDiagram->addRunway(rwy);
986 m_ui->parkingCombo->clear();
987 FGAirportDynamics* dynamics = apt->getDynamics();
988 PositionedIDVec parkings = NavDataCache::instance()->airportItemsOfType(m_location->guid(),
989 FGPositioned::PARKING);
990 if (parkings.empty()) {
991 m_ui->parkingCombo->setEnabled(false);
992 m_ui->parkingRadio->setEnabled(false);
994 m_ui->parkingCombo->setEnabled(true);
995 m_ui->parkingRadio->setEnabled(true);
996 Q_FOREACH(PositionedID parking, parkings) {
997 FGParking* park = dynamics->getParking(parking);
998 m_ui->parkingCombo->addItem(QString::fromStdString(park->getName()),
999 static_cast<qlonglong>(parking));
1001 m_ui->airportDiagram->addParking(park);
1006 } // of location is aiport
1013 void QtLauncher::onOffsetRadioToggled(bool on)
1015 m_ui->offsetNmSpinbox->setEnabled(on);
1016 m_ui->offsetBearingSpinbox->setEnabled(on);
1017 m_ui->trueBearing->setEnabled(on);
1018 m_ui->offsetBearingLabel->setEnabled(on);
1019 m_ui->offsetDistanceLabel->setEnabled(on);
1022 void QtLauncher::onAirportDiagramClicked(FGRunwayRef rwy)
1025 m_ui->runwayRadio->setChecked(true);
1026 int rwyIndex = m_ui->runwayCombo->findText(QString::fromStdString(rwy->ident()));
1027 m_ui->runwayCombo->setCurrentIndex(rwyIndex);
1030 updateLocationDescription();
1033 >>>>>>> Work on LocationWidget for Qt launcher
1035 void QtLauncher::onToggleTerrasync(bool enabled)
1039 QString downloadDir = settings.value("download-dir").toString();
1040 if (downloadDir.isEmpty()) {
1041 downloadDir = QString::fromStdString(flightgear::defaultDownloadDir());
1044 QFileInfo info(downloadDir);
1045 if (!info.exists()) {
1047 msg.setWindowTitle(tr("Create download folder?"));
1048 msg.setText(tr("The download folder '%1' does not exist, create it now? "
1049 "Click 'change location' to choose another folder "
1050 "to store downloaded files").arg(downloadDir));
1051 msg.addButton(QMessageBox::Yes);
1052 msg.addButton(QMessageBox::Cancel);
1053 msg.addButton(tr("Change location"), QMessageBox::ActionRole);
1054 int result = msg.exec();
1056 if (result == QMessageBox::Cancel) {
1057 m_ui->terrasyncCheck->setChecked(false);
1061 if (result == QMessageBox::ActionRole) {
1066 QDir d(downloadDir);
1067 d.mkpath(downloadDir);
1072 void QtLauncher::onAircraftInstalledCompleted(QModelIndex index)
1074 maybeUpdateSelectedAircraft(index);
1077 void QtLauncher::onAircraftInstallFailed(QModelIndex index, QString errorMessage)
1079 qWarning() << Q_FUNC_INFO << index.data(AircraftURIRole) << errorMessage;
1082 msg.setWindowTitle(tr("Aircraft installation failed"));
1083 msg.setText(tr("An error occurred installing the aircraft %1: %2").
1084 arg(index.data(Qt::DisplayRole).toString()).arg(errorMessage));
1085 msg.addButton(QMessageBox::Ok);
1088 maybeUpdateSelectedAircraft(index);
1091 void QtLauncher::onAircraftSelected(const QModelIndex& index)
1093 m_selectedAircraft = index.data(AircraftURIRole).toUrl();
1094 updateSelectedAircraft();
1097 void QtLauncher::onRequestPackageInstall(const QModelIndex& index)
1099 QString pkg = index.data(AircraftPackageIdRole).toString();
1100 simgear::pkg::PackageRef pref = globals->packageRoot()->getPackageById(pkg.toStdString());
1101 if (pref->isInstalled()) {
1102 InstallRef install = pref->existingInstall();
1103 if (install && install->hasUpdate()) {
1104 globals->packageRoot()->scheduleToUpdate(install);
1111 void QtLauncher::onCancelDownload(const QModelIndex& index)
1113 QString pkg = index.data(AircraftPackageIdRole).toString();
1114 simgear::pkg::PackageRef pref = globals->packageRoot()->getPackageById(pkg.toStdString());
1115 simgear::pkg::InstallRef i = pref->existingInstall();
1116 i->cancelDownload();
1119 void QtLauncher::maybeUpdateSelectedAircraft(QModelIndex index)
1121 QUrl u = index.data(AircraftURIRole).toUrl();
1122 if (u == m_selectedAircraft) {
1123 // potentially enable the run button now!
1124 updateSelectedAircraft();
1128 void QtLauncher::updateSelectedAircraft()
1130 QModelIndex index = m_aircraftModel->indexOfAircraftURI(m_selectedAircraft);
1131 if (index.isValid()) {
1132 QPixmap pm = index.data(Qt::DecorationRole).value<QPixmap>();
1133 m_ui->thumbnail->setPixmap(pm);
1134 m_ui->aircraftDescription->setText(index.data(Qt::DisplayRole).toString());
1136 int status = index.data(AircraftPackageStatusRole).toInt();
1137 bool canRun = (status == PackageInstalled);
1138 m_ui->runButton->setEnabled(canRun);
1140 m_ui->thumbnail->setPixmap(QPixmap());
1141 m_ui->aircraftDescription->setText("");
1142 m_ui->runButton->setEnabled(false);
1146 QModelIndex QtLauncher::proxyIndexForAircraftURI(QUrl uri) const
1148 return m_aircraftProxy->mapFromSource(sourceIndexForAircraftURI(uri));
1151 QModelIndex QtLauncher::sourceIndexForAircraftURI(QUrl uri) const
1153 AircraftItemModel* sourceModel = qobject_cast<AircraftItemModel*>(m_aircraftProxy->sourceModel());
1154 Q_ASSERT(sourceModel);
1155 return sourceModel->indexOfAircraftURI(uri);
1158 void QtLauncher::onPopupAircraftHistory()
1160 if (m_recentAircraft.isEmpty()) {
1165 Q_FOREACH(QUrl uri, m_recentAircraft) {
1166 QModelIndex index = sourceIndexForAircraftURI(uri);
1167 if (!index.isValid()) {
1171 QAction* act = m.addAction(index.data(Qt::DisplayRole).toString());
1175 QPoint popupPos = m_ui->aircraftHistory->mapToGlobal(m_ui->aircraftHistory->rect().bottomLeft());
1176 QAction* triggered = m.exec(popupPos);
1178 m_selectedAircraft = triggered->data().toUrl();
1179 QModelIndex index = proxyIndexForAircraftURI(m_selectedAircraft);
1180 m_ui->aircraftList->selectionModel()->setCurrentIndex(index,
1181 QItemSelectionModel::ClearAndSelect);
1182 m_ui->aircraftFilter->clear();
1183 updateSelectedAircraft();
1187 void QtLauncher::onEditRatingsFilter()
1189 EditRatingsFilterDialog dialog(this);
1190 dialog.setRatings(m_ratingFilters);
1193 if (dialog.result() == QDialog::Accepted) {
1195 for (int i=0; i<4; ++i) {
1196 m_ratingFilters[i] = dialog.getRating(i);
1197 vl.append(m_ratingFilters[i]);
1199 m_aircraftProxy->setRatings(m_ratingFilters);
1202 settings.setValue("min-ratings", vl);
1206 void QtLauncher::updateSettingsSummary()
1208 QStringList summary;
1209 if (m_ui->timeOfDayCombo->currentIndex() > 0) {
1210 summary.append(QString(m_ui->timeOfDayCombo->currentText().toLower()));
1213 if (m_ui->seasonCombo->currentIndex() > 0) {
1214 summary.append(QString(m_ui->seasonCombo->currentText().toLower()));
1217 if (m_ui->rembrandtCheckbox->isChecked()) {
1218 summary.append("Rembrandt enabled");
1219 } else if (m_ui->msaaCheckbox->isChecked()) {
1220 summary.append("anti-aliasing");
1223 if (m_ui->fetchRealWxrCheckbox->isChecked()) {
1224 summary.append("live weather");
1227 if (m_ui->terrasyncCheck->isChecked()) {
1228 summary.append("automatic scenery downloads");
1231 if (m_ui->startPausedCheck->isChecked()) {
1232 summary.append("paused");
1235 QString s = summary.join(", ");
1236 s[0] = s[0].toUpper();
1237 m_ui->settingsDescription->setText(s);
1240 void QtLauncher::onRembrandtToggled(bool b)
1242 // Rembrandt and multi-sample are exclusive
1243 m_ui->msaaCheckbox->setEnabled(!b);
1246 void QtLauncher::onSubsytemIdleTimeout()
1248 globals->get_subsystem_mgr()->update(0.0);
1251 void QtLauncher::onEditPaths()
1253 PathsDialog dlg(this, globals->packageRoot());
1255 if (dlg.result() == QDialog::Accepted) {
1256 // re-scan the aircraft list
1258 m_aircraftModel->setPaths(settings.value("aircraft-paths").toStringList());
1259 m_aircraftModel->scanDirs();
1263 simgear::pkg::PackageRef QtLauncher::packageForAircraftURI(QUrl uri) const
1265 if (uri.scheme() != "package") {
1266 qWarning() << "invalid URL scheme:" << uri;
1267 return simgear::pkg::PackageRef();
1270 QString ident = uri.path();
1271 return globals->packageRoot()->getPackageById(ident.toStdString());
1275 #include "QtLauncher.moc"