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 qDebug() << "will start paused";
791 opt->addOption("enable-freeze", "");
794 // MSAA is more complex
795 if (!m_ui->rembrandtCheckbox->isChecked()) {
796 if (m_ui->msaaCheckbox->isChecked()) {
797 globals->get_props()->setIntValue("/sim/rendering/multi-sample-buffers", 1);
798 globals->get_props()->setIntValue("/sim/rendering/multi-samples", 4);
800 globals->get_props()->setIntValue("/sim/rendering/multi-sample-buffers", 0);
805 if (!m_selectedAircraft.isEmpty()) {
806 if (m_selectedAircraft.isLocalFile()) {
807 QFileInfo setFileInfo(m_selectedAircraft.toLocalFile());
808 opt->addOption("aircraft-dir", setFileInfo.dir().absolutePath().toStdString());
809 QString setFile = setFileInfo.fileName();
810 Q_ASSERT(setFile.endsWith("-set.xml"));
811 setFile.truncate(setFile.count() - 8); // drop the '-set.xml' portion
812 opt->addOption("aircraft", setFile.toStdString());
813 } else if (m_selectedAircraft.scheme() == "package") {
814 PackageRef pkg = packageForAircraftURI(m_selectedAircraft);
815 // no need to set aircraft-dir, handled by the corresponding code
817 opt->addOption("aircraft", pkg->qualifiedId());
819 qWarning() << "unsupported aircraft launch URL" << m_selectedAircraft;
822 // manage aircraft history
823 if (m_recentAircraft.contains(m_selectedAircraft))
824 m_recentAircraft.removeOne(m_selectedAircraft);
825 m_recentAircraft.prepend(m_selectedAircraft);
826 if (m_recentAircraft.size() > MAX_RECENT_AIRCRAFT)
827 m_recentAircraft.pop_back();
830 m_ui->location->setLocationOptions();
833 if (m_ui->timeOfDayCombo->currentIndex() != 0) {
834 QString dayval = m_ui->timeOfDayCombo->currentText().toLower();
835 opt->addOption("timeofday", dayval.toStdString());
838 if (m_ui->seasonCombo->currentIndex() != 0) {
839 QString dayval = m_ui->timeOfDayCombo->currentText().toLower();
840 opt->addOption("season", dayval.toStdString());
844 QString downloadDir = settings.value("download-dir").toString();
845 if (!downloadDir.isEmpty()) {
848 int result = QMessageBox::question(this, tr("Create download folder?"),
849 tr("The selected location for downloads does not exist. Create it?"),
850 QMessageBox::Yes | QMessageBox::No | QMessageBox::Cancel);
851 if (result == QMessageBox::Cancel) {
855 if (result == QMessageBox::Yes) {
856 d.mkpath(downloadDir);
860 qDebug() << "Download dir is:" << downloadDir;
861 opt->addOption("download-dir", downloadDir.toStdString());
865 Q_FOREACH(QString path, settings.value("scenery-paths").toStringList()) {
866 opt->addOption("fg-scenery", path.toStdString());
870 Q_FOREACH(QString path, settings.value("aircraft-paths").toStringList()) {
871 // can't use fg-aircraft for this, as it is processed before the launcher is run
872 globals->append_aircraft_path(path.toStdString());
875 // additional arguments
876 ArgumentsTokenizer tk;
877 Q_FOREACH(ArgumentsTokenizer::Arg a, tk.tokenize(m_ui->commandLineArgs->toPlainText())) {
878 if (a.arg.startsWith("prop:")) {
879 QString v = a.arg.mid(5) + "=" + a.value;
880 opt->addOption("prop", v.toStdString());
882 opt->addOption(a.arg.toStdString(), a.value.toStdString());
890 void QtLauncher::onApply()
895 if (!m_selectedAircraft.isEmpty()) {
896 std::string aircraftPropValue,
899 if (m_selectedAircraft.isLocalFile()) {
900 QFileInfo setFileInfo(m_selectedAircraft.toLocalFile());
901 QString setFile = setFileInfo.fileName();
902 Q_ASSERT(setFile.endsWith("-set.xml"));
903 setFile.truncate(setFile.count() - 8); // drop the '-set.xml' portion
904 aircraftDir = setFileInfo.dir().absolutePath().toStdString();
905 aircraftPropValue = setFile.toStdString();
906 } else if (m_selectedAircraft.scheme() == "package") {
907 PackageRef pkg = packageForAircraftURI(m_selectedAircraft);
908 // no need to set aircraft-dir, handled by the corresponding code
910 aircraftPropValue = pkg->qualifiedId();
912 qWarning() << "unsupported aircraft launch URL" << m_selectedAircraft;
915 // manage aircraft history
916 if (m_recentAircraft.contains(m_selectedAircraft))
917 m_recentAircraft.removeOne(m_selectedAircraft);
918 m_recentAircraft.prepend(m_selectedAircraft);
919 if (m_recentAircraft.size() > MAX_RECENT_AIRCRAFT)
920 m_recentAircraft.pop_back();
922 globals->get_props()->setStringValue("/sim/aircraft", aircraftPropValue);
923 globals->get_props()->setStringValue("/sim/aircraft-dir", aircraftDir);
930 void QtLauncher::onQuit()
935 <<<<<<< 56d7d049bc0b7361d1799298c38e61084f5d5e3f
936 void QtLauncher::onSearchAirports()
938 QString search = m_ui->airportEdit->text();
939 m_airportsModel->setSearch(search);
941 if (m_airportsModel->isSearchActive()) {
942 m_ui->searchStatusText->setText(QString("Searching for '%1'").arg(search));
943 m_ui->locationStack->setCurrentIndex(2);
944 } else if (m_airportsModel->rowCount(QModelIndex()) == 1) {
945 setBaseLocation(m_airportsModel->itemAtRow(0));
946 m_ui->locationStack->setCurrentIndex(0);
950 void QtLauncher::onAirportSearchComplete()
952 int numResults = m_airportsModel->rowCount(QModelIndex());
953 if (numResults == 0) {
954 m_ui->searchStatusText->setText(QString("No matching airports for '%1'").arg(m_ui->airportEdit->text()));
955 } else if (numResults == 1) {
956 setBaseLocation(m_airportsModel->itemAtRow(0));
957 m_ui->locationStack->setCurrentIndex(0);
959 m_ui->locationStack->setCurrentIndex(1);
963 void QtLauncher::onLocationChanged()
965 bool locIsAirport = FGAirport::isAirportType(m_location.ptr());
967 m_ui->runwayCombo->setEnabled(locIsAirport);
968 m_ui->parkingCombo->setEnabled(locIsAirport);
970 FGAirport* apt = static_cast<FGAirport*>(m_location.ptr());
971 m_ui->airportDiagram->setAirport(apt);
973 m_ui->runwayRadio->setChecked(true); // default back to runway mode
974 // unless multiplayer is enabled ?
975 m_ui->airportDiagram->setEnabled(true);
977 m_ui->runwayCombo->clear();
978 m_ui->runwayCombo->addItem("Automatic", -1);
979 for (unsigned int r=0; r<apt->numRunways(); ++r) {
980 FGRunwayRef rwy = apt->getRunwayByIndex(r);
981 // add runway with index as data role
982 m_ui->runwayCombo->addItem(QString::fromStdString(rwy->ident()), r);
984 m_ui->airportDiagram->addRunway(rwy);
987 m_ui->parkingCombo->clear();
988 FGAirportDynamics* dynamics = apt->getDynamics();
989 PositionedIDVec parkings = NavDataCache::instance()->airportItemsOfType(m_location->guid(),
990 FGPositioned::PARKING);
991 if (parkings.empty()) {
992 m_ui->parkingCombo->setEnabled(false);
993 m_ui->parkingRadio->setEnabled(false);
995 m_ui->parkingCombo->setEnabled(true);
996 m_ui->parkingRadio->setEnabled(true);
997 Q_FOREACH(PositionedID parking, parkings) {
998 FGParking* park = dynamics->getParking(parking);
999 m_ui->parkingCombo->addItem(QString::fromStdString(park->getName()),
1000 static_cast<qlonglong>(parking));
1002 m_ui->airportDiagram->addParking(park);
1007 } // of location is aiport
1014 void QtLauncher::onOffsetRadioToggled(bool on)
1016 m_ui->offsetNmSpinbox->setEnabled(on);
1017 m_ui->offsetBearingSpinbox->setEnabled(on);
1018 m_ui->trueBearing->setEnabled(on);
1019 m_ui->offsetBearingLabel->setEnabled(on);
1020 m_ui->offsetDistanceLabel->setEnabled(on);
1023 void QtLauncher::onAirportDiagramClicked(FGRunwayRef rwy)
1026 m_ui->runwayRadio->setChecked(true);
1027 int rwyIndex = m_ui->runwayCombo->findText(QString::fromStdString(rwy->ident()));
1028 m_ui->runwayCombo->setCurrentIndex(rwyIndex);
1031 updateLocationDescription();
1034 >>>>>>> Work on LocationWidget for Qt launcher
1036 void QtLauncher::onToggleTerrasync(bool enabled)
1040 QString downloadDir = settings.value("download-dir").toString();
1041 if (downloadDir.isEmpty()) {
1042 downloadDir = QString::fromStdString(flightgear::defaultDownloadDir());
1045 QFileInfo info(downloadDir);
1046 if (!info.exists()) {
1048 msg.setWindowTitle(tr("Create download folder?"));
1049 msg.setText(tr("The download folder '%1' does not exist, create it now? "
1050 "Click 'change location' to choose another folder "
1051 "to store downloaded files").arg(downloadDir));
1052 msg.addButton(QMessageBox::Yes);
1053 msg.addButton(QMessageBox::Cancel);
1054 msg.addButton(tr("Change location"), QMessageBox::ActionRole);
1055 int result = msg.exec();
1057 if (result == QMessageBox::Cancel) {
1058 m_ui->terrasyncCheck->setChecked(false);
1062 if (result == QMessageBox::ActionRole) {
1067 QDir d(downloadDir);
1068 d.mkpath(downloadDir);
1073 void QtLauncher::onAircraftInstalledCompleted(QModelIndex index)
1075 maybeUpdateSelectedAircraft(index);
1078 void QtLauncher::onAircraftInstallFailed(QModelIndex index, QString errorMessage)
1080 qWarning() << Q_FUNC_INFO << index.data(AircraftURIRole) << errorMessage;
1083 msg.setWindowTitle(tr("Aircraft installation failed"));
1084 msg.setText(tr("An error occurred installing the aircraft %1: %2").
1085 arg(index.data(Qt::DisplayRole).toString()).arg(errorMessage));
1086 msg.addButton(QMessageBox::Ok);
1089 maybeUpdateSelectedAircraft(index);
1092 void QtLauncher::onAircraftSelected(const QModelIndex& index)
1094 m_selectedAircraft = index.data(AircraftURIRole).toUrl();
1095 updateSelectedAircraft();
1098 void QtLauncher::onRequestPackageInstall(const QModelIndex& index)
1100 QString pkg = index.data(AircraftPackageIdRole).toString();
1101 simgear::pkg::PackageRef pref = globals->packageRoot()->getPackageById(pkg.toStdString());
1102 if (pref->isInstalled()) {
1103 InstallRef install = pref->existingInstall();
1104 if (install && install->hasUpdate()) {
1105 globals->packageRoot()->scheduleToUpdate(install);
1112 void QtLauncher::onCancelDownload(const QModelIndex& index)
1114 QString pkg = index.data(AircraftPackageIdRole).toString();
1115 simgear::pkg::PackageRef pref = globals->packageRoot()->getPackageById(pkg.toStdString());
1116 simgear::pkg::InstallRef i = pref->existingInstall();
1117 i->cancelDownload();
1120 void QtLauncher::maybeUpdateSelectedAircraft(QModelIndex index)
1122 QUrl u = index.data(AircraftURIRole).toUrl();
1123 if (u == m_selectedAircraft) {
1124 // potentially enable the run button now!
1125 updateSelectedAircraft();
1129 void QtLauncher::updateSelectedAircraft()
1131 QModelIndex index = m_aircraftModel->indexOfAircraftURI(m_selectedAircraft);
1132 if (index.isValid()) {
1133 QPixmap pm = index.data(Qt::DecorationRole).value<QPixmap>();
1134 m_ui->thumbnail->setPixmap(pm);
1135 m_ui->aircraftDescription->setText(index.data(Qt::DisplayRole).toString());
1137 int status = index.data(AircraftPackageStatusRole).toInt();
1138 bool canRun = (status == PackageInstalled);
1139 m_ui->runButton->setEnabled(canRun);
1141 m_ui->thumbnail->setPixmap(QPixmap());
1142 m_ui->aircraftDescription->setText("");
1143 m_ui->runButton->setEnabled(false);
1147 QModelIndex QtLauncher::proxyIndexForAircraftURI(QUrl uri) const
1149 return m_aircraftProxy->mapFromSource(sourceIndexForAircraftURI(uri));
1152 QModelIndex QtLauncher::sourceIndexForAircraftURI(QUrl uri) const
1154 AircraftItemModel* sourceModel = qobject_cast<AircraftItemModel*>(m_aircraftProxy->sourceModel());
1155 Q_ASSERT(sourceModel);
1156 return sourceModel->indexOfAircraftURI(uri);
1159 void QtLauncher::onPopupAircraftHistory()
1161 if (m_recentAircraft.isEmpty()) {
1166 Q_FOREACH(QUrl uri, m_recentAircraft) {
1167 QModelIndex index = sourceIndexForAircraftURI(uri);
1168 if (!index.isValid()) {
1172 QAction* act = m.addAction(index.data(Qt::DisplayRole).toString());
1176 QPoint popupPos = m_ui->aircraftHistory->mapToGlobal(m_ui->aircraftHistory->rect().bottomLeft());
1177 QAction* triggered = m.exec(popupPos);
1179 m_selectedAircraft = triggered->data().toUrl();
1180 QModelIndex index = proxyIndexForAircraftURI(m_selectedAircraft);
1181 m_ui->aircraftList->selectionModel()->setCurrentIndex(index,
1182 QItemSelectionModel::ClearAndSelect);
1183 m_ui->aircraftFilter->clear();
1184 updateSelectedAircraft();
1188 void QtLauncher::onEditRatingsFilter()
1190 EditRatingsFilterDialog dialog(this);
1191 dialog.setRatings(m_ratingFilters);
1194 if (dialog.result() == QDialog::Accepted) {
1196 for (int i=0; i<4; ++i) {
1197 m_ratingFilters[i] = dialog.getRating(i);
1198 vl.append(m_ratingFilters[i]);
1200 m_aircraftProxy->setRatings(m_ratingFilters);
1203 settings.setValue("min-ratings", vl);
1207 void QtLauncher::updateSettingsSummary()
1209 QStringList summary;
1210 if (m_ui->timeOfDayCombo->currentIndex() > 0) {
1211 summary.append(QString(m_ui->timeOfDayCombo->currentText().toLower()));
1214 if (m_ui->seasonCombo->currentIndex() > 0) {
1215 summary.append(QString(m_ui->seasonCombo->currentText().toLower()));
1218 if (m_ui->rembrandtCheckbox->isChecked()) {
1219 summary.append("Rembrandt enabled");
1220 } else if (m_ui->msaaCheckbox->isChecked()) {
1221 summary.append("anti-aliasing");
1224 if (m_ui->fetchRealWxrCheckbox->isChecked()) {
1225 summary.append("live weather");
1228 if (m_ui->terrasyncCheck->isChecked()) {
1229 summary.append("automatic scenery downloads");
1232 if (m_ui->startPausedCheck->isChecked()) {
1233 summary.append("paused");
1236 QString s = summary.join(", ");
1237 s[0] = s[0].toUpper();
1238 m_ui->settingsDescription->setText(s);
1241 void QtLauncher::onRembrandtToggled(bool b)
1243 // Rembrandt and multi-sample are exclusive
1244 m_ui->msaaCheckbox->setEnabled(!b);
1247 void QtLauncher::onSubsytemIdleTimeout()
1249 globals->get_subsystem_mgr()->update(0.0);
1252 void QtLauncher::onEditPaths()
1254 PathsDialog dlg(this, globals->packageRoot());
1256 if (dlg.result() == QDialog::Accepted) {
1257 // re-scan the aircraft list
1259 m_aircraftModel->setPaths(settings.value("aircraft-paths").toStringList());
1260 m_aircraftModel->scanDirs();
1264 simgear::pkg::PackageRef QtLauncher::packageForAircraftURI(QUrl uri) const
1266 if (uri.scheme() != "package") {
1267 qWarning() << "invalid URL scheme:" << uri;
1268 return simgear::pkg::PackageRef();
1271 QString ident = uri.path();
1272 return globals->packageRoot()->getPackageById(ident.toStdString());
1276 #include "QtLauncher.moc"