]> git.mxchange.org Git - flightgear.git/blob - src/GUI/QtLauncher.cxx
Explicit NSPathUtilities include.
[flightgear.git] / src / GUI / QtLauncher.cxx
1 // QtLauncher.cxx - GUI launcher dialog using Qt5
2 //
3 // Written by James Turner, started December 2014.
4 //
5 // Copyright (C) 2014 James Turner <zakalawe@mac.com>
6 //
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.
11 //
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.
16 //
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.
20
21 #include "QtLauncher.hxx"
22
23 // Qt
24 #include <QProgressDialog>
25 #include <QCoreApplication>
26 #include <QAbstractListModel>
27 #include <QDir>
28 #include <QFileInfo>
29 #include <QPixmap>
30 #include <QTimer>
31 #include <QDebug>
32 #include <QCompleter>
33 #include <QListView>
34 #include <QSettings>
35 #include <QSortFilterProxyModel>
36 #include <QMenu>
37 #include <QDesktopServices>
38 #include <QUrl>
39 #include <QAction>
40 #include <QFileDialog>
41 #include <QMessageBox>
42 #include <QDateTime>
43 #include <QApplication>
44
45 // Simgear
46 #include <simgear/timing/timestamp.hxx>
47 #include <simgear/props/props_io.hxx>
48 #include <simgear/structure/exception.hxx>
49 #include <simgear/structure/subsystem_mgr.hxx>
50 #include <simgear/misc/sg_path.hxx>
51
52 #include "ui_Launcher.h"
53 #include "EditRatingsFilterDialog.hxx"
54 #include "AircraftItemDelegate.hxx"
55 #include "AircraftModel.hxx"
56 #include "PathsDialog.hxx"
57
58 #include <Main/globals.hxx>
59 #include <Navaids/NavDataCache.hxx>
60 #include <Airports/airport.hxx>
61 #include <Airports/dynamics.hxx> // for parking
62 #include <Main/options.hxx>
63 #include <Main/fg_init.hxx>
64 #include <Viewer/WindowBuilder.hxx>
65 #include <Network/HTTPClient.hxx>
66
67 using namespace flightgear;
68
69 const int MAX_RECENT_AIRPORTS = 32;
70 const int MAX_RECENT_AIRCRAFT = 20;
71
72 namespace { // anonymous namespace
73
74 void initNavCache()
75 {
76     QString baseLabel = QT_TR_NOOP("Initialising navigation data, this may take several minutes");
77     NavDataCache* cache = NavDataCache::createInstance();
78     if (cache->isRebuildRequired()) {
79         QProgressDialog rebuildProgress(baseLabel,
80                                        QString() /* cancel text */,
81                                        0, 100);
82         rebuildProgress.setWindowModality(Qt::WindowModal);
83         rebuildProgress.show();
84
85         NavDataCache::RebuildPhase phase = cache->rebuild();
86
87         while (phase != NavDataCache::REBUILD_DONE) {
88             // sleep to give the rebuild thread more time
89             SGTimeStamp::sleepForMSec(50);
90             phase = cache->rebuild();
91             
92             switch (phase) {
93             case NavDataCache::REBUILD_AIRPORTS:
94                 rebuildProgress.setLabelText(QT_TR_NOOP("Loading airport data"));
95                 break;
96
97             case NavDataCache::REBUILD_FIXES:
98                 rebuildProgress.setLabelText(QT_TR_NOOP("Loading waypoint data"));
99                 break;
100
101             case NavDataCache::REBUILD_NAVAIDS:
102                 rebuildProgress.setLabelText(QT_TR_NOOP("Loading navigation data"));
103                 break;
104
105
106             case NavDataCache::REBUILD_POIS:
107                 rebuildProgress.setLabelText(QT_TR_NOOP("Loading point-of-interest data"));
108                 break;
109
110             default:
111                 rebuildProgress.setLabelText(baseLabel);
112             }
113
114             if (phase == NavDataCache::REBUILD_UNKNOWN) {
115                 rebuildProgress.setValue(0);
116                 rebuildProgress.setMaximum(0);
117             } else {
118                 rebuildProgress.setValue(cache->rebuildPhaseCompletionPercentage());
119                 rebuildProgress.setMaximum(100);
120             }
121
122             QCoreApplication::processEvents();
123         }
124     }
125 }
126
127 class ArgumentsTokenizer
128 {
129 public:
130     class Arg
131     {
132     public:
133         explicit Arg(QString k, QString v = QString()) : arg(k), value(v) {}
134
135         QString arg;
136         QString value;
137     };
138
139     QList<Arg> tokenize(QString in) const
140     {
141         int index = 0;
142         const int len = in.count();
143         QChar c, nc;
144         State state = Start;
145         QString key, value;
146         QList<Arg> result;
147
148         for (; index < len; ++index) {
149             c = in.at(index);
150             nc = index < (len - 1) ? in.at(index + 1) : QChar();
151
152             switch (state) {
153             case Start:
154                 if (c == QChar('-')) {
155                     if (nc == QChar('-')) {
156                         state = Key;
157                         key.clear();
158                         ++index;
159                     } else {
160                         // should we pemit single hyphen arguments?
161                         // choosing to fail for now
162                         return QList<Arg>();
163                     }
164                 } else if (c.isSpace()) {
165                     break;
166                 }
167                 break;
168
169             case Key:
170                 if (c == QChar('=')) {
171                     state = Value;
172                     value.clear();
173                 } else if (c.isSpace()) {
174                     state = Start;
175                     result.append(Arg(key));
176                 } else {
177                     // could check for illegal charatcers here
178                     key.append(c);
179                 }
180                 break;
181
182             case Value:
183                 if (c == QChar('"')) {
184                     state = Quoted;
185                 } else if (c.isSpace()) {
186                     state = Start;
187                     result.append(Arg(key, value));
188                 } else {
189                     value.append(c);
190                 }
191                 break;
192
193             case Quoted:
194                 if (c == QChar('\\')) {
195                     // check for escaped double-quote inside quoted value
196                     if (nc == QChar('"')) {
197                         ++index;
198                     }
199                 } else if (c == QChar('"')) {
200                     state = Value;
201                 } else {
202                     value.append(c);
203                 }
204                 break;
205             } // of state switch
206         } // of character loop
207
208         // ensure last argument isn't lost
209         if (state == Key) {
210             result.append(Arg(key));
211         } else if (state == Value) {
212             result.append(Arg(key, value));
213         }
214
215         return result;
216     }
217
218 private:
219     enum State {
220         Start = 0,
221         Key,
222         Value,
223         Quoted
224     };
225 };
226
227 } // of anonymous namespace
228
229 class AirportSearchModel : public QAbstractListModel
230 {
231     Q_OBJECT
232 public:
233     AirportSearchModel() :
234         m_searchActive(false)
235     {
236     }
237
238     void setSearch(QString t)
239     {
240         beginResetModel();
241
242         m_airports.clear();
243         m_ids.clear();
244
245         std::string term(t.toUpper().toStdString());
246         // try ICAO lookup first
247         FGAirportRef ref = FGAirport::findByIdent(term);
248         if (ref) {
249             m_ids.push_back(ref->guid());
250             m_airports.push_back(ref);
251         } else {
252             m_search.reset(new NavDataCache::ThreadedAirportSearch(term));
253             QTimer::singleShot(100, this, SLOT(onSearchResultsPoll()));
254             m_searchActive = true;
255         }
256
257         endResetModel();
258     }
259
260     bool isSearchActive() const
261     {
262         return m_searchActive;
263     }
264
265     virtual int rowCount(const QModelIndex&) const
266     {
267         // if empty, return 1 for special 'no matches'?
268         return m_ids.size();
269     }
270
271     virtual QVariant data(const QModelIndex& index, int role) const
272     {
273         if (!index.isValid())
274             return QVariant();
275         
276         FGAirportRef apt = m_airports[index.row()];
277         if (!apt.valid()) {
278             apt = FGPositioned::loadById<FGAirport>(m_ids[index.row()]);
279             m_airports[index.row()] = apt;
280         }
281
282         if (role == Qt::DisplayRole) {
283             QString name = QString::fromStdString(apt->name());
284             return QString("%1: %2").arg(QString::fromStdString(apt->ident())).arg(name);
285         }
286
287         if (role == Qt::EditRole) {
288             return QString::fromStdString(apt->ident());
289         }
290
291         if (role == Qt::UserRole) {
292             return static_cast<qlonglong>(m_ids[index.row()]);
293         }
294
295         return QVariant();
296     }
297
298     QString firstIdent() const
299     {
300         if (m_ids.empty())
301             return QString();
302
303         if (!m_airports.front().valid()) {
304             m_airports[0] = FGPositioned::loadById<FGAirport>(m_ids.front());
305         }
306
307         return QString::fromStdString(m_airports.front()->ident());
308     }
309
310 Q_SIGNALS:
311     void searchComplete();
312
313 private slots:
314     void onSearchResultsPoll()
315     {
316         PositionedIDVec newIds = m_search->results();
317         
318         beginInsertRows(QModelIndex(), m_ids.size(), newIds.size() - 1);
319         for (unsigned int i=m_ids.size(); i < newIds.size(); ++i) {
320             m_ids.push_back(newIds[i]);
321             m_airports.push_back(FGAirportRef()); // null ref
322         }
323         endInsertRows();
324
325         if (m_search->isComplete()) {
326             m_searchActive = false;
327             m_search.reset();
328             emit searchComplete();
329         } else {
330             QTimer::singleShot(100, this, SLOT(onSearchResultsPoll()));
331         }
332     }
333
334 private:
335     PositionedIDVec m_ids;
336     mutable std::vector<FGAirportRef> m_airports;
337     bool m_searchActive;
338     QScopedPointer<NavDataCache::ThreadedAirportSearch> m_search;
339 };
340
341 class AircraftProxyModel : public QSortFilterProxyModel
342 {
343     Q_OBJECT
344 public:
345     AircraftProxyModel(QObject* pr) :
346         QSortFilterProxyModel(pr),
347         m_ratingsFilter(true)
348     {
349         for (int i=0; i<4; ++i) {
350             m_ratings[i] = 3;
351         }
352     }
353
354     void setRatings(int* ratings)
355     {
356         ::memcpy(m_ratings, ratings, sizeof(int) * 4);
357         invalidate();
358     }
359
360 public slots:
361     void setRatingFilterEnabled(bool e)
362     {
363         if (e == m_ratingsFilter) {
364             return;
365         }
366
367         m_ratingsFilter = e;
368         invalidate();
369     }
370
371 protected:
372     bool filterAcceptsRow(int sourceRow, const QModelIndex &sourceParent) const
373     {
374         if (!QSortFilterProxyModel::filterAcceptsRow(sourceRow, sourceParent)) {
375             return false;
376         }
377
378         if (m_ratingsFilter) {
379             QModelIndex index = sourceModel()->index(sourceRow, 0, sourceParent);
380             for (int i=0; i<4; ++i) {
381                 if (m_ratings[i] > index.data(AircraftRatingRole + i).toInt()) {
382                     return false;
383                 }
384             }
385         }
386
387         return true;
388     }
389
390 private:
391     bool m_ratingsFilter;
392     int m_ratings[4];
393 };
394
395 QtLauncher::QtLauncher() :
396     QDialog(),
397     m_ui(NULL)
398 {
399     m_ui.reset(new Ui::Launcher);
400     m_ui->setupUi(this);
401
402 #if QT_VERSION >= 0x050300
403     // don't require Qt 5.3
404     m_ui->commandLineArgs->setPlaceholderText("--option=value --prop:/sim/name=value");
405 #endif
406
407 #if QT_VERSION >= 0x050200
408     m_ui->aircraftFilter->setClearButtonEnabled(true);
409 #endif
410
411     for (int i=0; i<4; ++i) {
412         m_ratingFilters[i] = 3;
413     }
414
415     m_subsystemIdleTimer = new QTimer(this);
416     m_subsystemIdleTimer->setInterval(0);
417     connect(m_subsystemIdleTimer, &QTimer::timeout,
418             this, &QtLauncher::onSubsytemIdleTimeout);
419     m_subsystemIdleTimer->start();
420
421     m_airportsModel = new AirportSearchModel;
422     m_ui->searchList->setModel(m_airportsModel);
423     connect(m_ui->searchList, &QListView::clicked,
424             this, &QtLauncher::onAirportChoiceSelected);
425     connect(m_airportsModel, &AirportSearchModel::searchComplete,
426             this, &QtLauncher::onAirportSearchComplete);
427
428     // create and configure the proxy model
429     m_aircraftProxy = new AircraftProxyModel(this);
430     connect(m_ui->ratingsFilterCheck, &QAbstractButton::toggled,
431             m_aircraftProxy, &AircraftProxyModel::setRatingFilterEnabled);
432     connect(m_ui->aircraftFilter, &QLineEdit::textChanged,
433             m_aircraftProxy, &QSortFilterProxyModel::setFilterFixedString);
434
435     connect(m_ui->runwayCombo, SIGNAL(currentIndexChanged(int)),
436             this, SLOT(updateAirportDescription()));
437     connect(m_ui->parkingCombo, SIGNAL(currentIndexChanged(int)),
438             this, SLOT(updateAirportDescription()));
439     connect(m_ui->runwayRadio, SIGNAL(toggled(bool)),
440             this, SLOT(updateAirportDescription()));
441     connect(m_ui->parkingRadio, SIGNAL(toggled(bool)),
442             this, SLOT(updateAirportDescription()));
443     connect(m_ui->onFinalCheckbox, SIGNAL(toggled(bool)),
444             this, SLOT(updateAirportDescription()));
445
446
447     connect(m_ui->runButton, SIGNAL(clicked()), this, SLOT(onRun()));
448     connect(m_ui->quitButton, SIGNAL(clicked()), this, SLOT(onQuit()));
449     connect(m_ui->airportEdit, SIGNAL(returnPressed()),
450             this, SLOT(onSearchAirports()));
451
452     connect(m_ui->airportHistory, &QPushButton::clicked,
453             this, &QtLauncher::onPopupAirportHistory);
454     connect(m_ui->aircraftHistory, &QPushButton::clicked,
455           this, &QtLauncher::onPopupAircraftHistory);
456
457     restoreSettings();
458
459     QAction* qa = new QAction(this);
460     qa->setShortcut(QKeySequence("Ctrl+Q"));
461     connect(qa, &QAction::triggered, this, &QtLauncher::onQuit);
462     addAction(qa);
463
464     connect(m_ui->editRatingFilter, &QPushButton::clicked,
465             this, &QtLauncher::onEditRatingsFilter);
466
467     QIcon historyIcon(":/history-icon");
468     m_ui->aircraftHistory->setIcon(historyIcon);
469     m_ui->airportHistory->setIcon(historyIcon);
470
471     m_ui->searchIcon->setPixmap(QPixmap(":/search-icon"));
472
473     connect(m_ui->timeOfDayCombo, SIGNAL(currentIndexChanged(int)),
474             this, SLOT(updateSettingsSummary()));
475     connect(m_ui->seasonCombo, SIGNAL(currentIndexChanged(int)),
476             this, SLOT(updateSettingsSummary()));
477     connect(m_ui->fetchRealWxrCheckbox, SIGNAL(toggled(bool)),
478             this, SLOT(updateSettingsSummary()));
479     connect(m_ui->rembrandtCheckbox, SIGNAL(toggled(bool)),
480             this, SLOT(updateSettingsSummary()));
481     connect(m_ui->terrasyncCheck, SIGNAL(toggled(bool)),
482             this, SLOT(updateSettingsSummary()));
483     connect(m_ui->startPausedCheck, SIGNAL(toggled(bool)),
484             this, SLOT(updateSettingsSummary()));
485     connect(m_ui->msaaCheckbox, SIGNAL(toggled(bool)),
486             this, SLOT(updateSettingsSummary()));
487
488     connect(m_ui->rembrandtCheckbox, SIGNAL(toggled(bool)),
489             this, SLOT(onRembrandtToggled(bool)));
490     connect(m_ui->terrasyncCheck, &QCheckBox::toggled,
491             this, &QtLauncher::onToggleTerrasync);
492     updateSettingsSummary();
493
494     fgInitPackageRoot();
495     simgear::pkg::RootRef r(globals->packageRoot());
496
497     FGHTTPClient* http = new FGHTTPClient;
498     globals->add_subsystem("http", http);
499
500     // we guard against re-init in the global phase; bind and postinit
501     // will happen as normal
502     http->init();
503
504     m_aircraftModel = new AircraftItemModel(this, r);
505     m_aircraftProxy->setSourceModel(m_aircraftModel);
506
507     m_aircraftProxy->setFilterCaseSensitivity(Qt::CaseInsensitive);
508     m_aircraftProxy->setSortCaseSensitivity(Qt::CaseInsensitive);
509     m_aircraftProxy->setSortRole(Qt::DisplayRole);
510     m_aircraftProxy->setDynamicSortFilter(true);
511
512     m_ui->aircraftList->setModel(m_aircraftProxy);
513     m_ui->aircraftList->setHorizontalScrollBarPolicy(Qt::ScrollBarAlwaysOff);
514     AircraftItemDelegate* delegate = new AircraftItemDelegate(m_ui->aircraftList);
515     m_ui->aircraftList->setItemDelegate(delegate);
516     m_ui->aircraftList->setSelectionMode(QAbstractItemView::SingleSelection);
517     connect(m_ui->aircraftList, &QListView::clicked,
518             this, &QtLauncher::onAircraftSelected);
519     connect(delegate, &AircraftItemDelegate::variantChanged,
520             this, &QtLauncher::onAircraftSelected);
521
522     connect(m_ui->pathsButton, &QPushButton::clicked,
523             this, &QtLauncher::onEditPaths);
524
525     QSettings settings;
526     m_aircraftModel->setPaths(settings.value("aircraft-paths").toStringList());
527     m_aircraftModel->scanDirs();
528 }
529
530 QtLauncher::~QtLauncher()
531 {
532     
533 }
534
535 void QtLauncher::initApp(int argc, char** argv)
536 {
537     static bool qtInitDone = false;
538     if (!qtInitDone) {
539         qtInitDone = true;
540
541         QApplication* app = new QApplication(argc, argv);
542         app->setOrganizationName("FlightGear");
543         app->setApplicationName("FlightGear");
544         app->setOrganizationDomain("flightgear.org");
545
546         // avoid double Apple menu and other weirdness if both Qt and OSG
547         // try to initialise various Cocoa structures.
548         flightgear::WindowBuilder::setPoseAsStandaloneApp(false);
549
550         Qt::KeyboardModifiers mods = app->queryKeyboardModifiers();
551         if (mods & Qt::AltModifier) {
552             qWarning() << "Alt pressed during launch";
553
554             // wipe out our settings
555             QSettings settings;
556             settings.clear();
557
558
559             Options::sharedInstance()->addOption("restore-defaults", "");
560         }
561     }
562 }
563
564 bool QtLauncher::runLauncherDialog()
565 {
566     Q_INIT_RESOURCE(resources);
567
568     // startup the nav-cache now. This pre-empts normal startup of
569     // the cache, but no harm done. (Providing scenery paths are consistent)
570
571     initNavCache();
572
573   // setup scenery paths now, especially TerraSync path for airport
574   // parking locations (after they're downloaded)
575
576     QtLauncher dlg;
577     dlg.exec();
578     if (dlg.result() != QDialog::Accepted) {
579         return false;
580     }
581
582     return true;
583 }
584
585 void QtLauncher::restoreSettings()
586 {
587     QSettings settings;
588     m_ui->rembrandtCheckbox->setChecked(settings.value("enable-rembrandt", false).toBool());
589     m_ui->terrasyncCheck->setChecked(settings.value("enable-terrasync", true).toBool());
590     m_ui->fullScreenCheckbox->setChecked(settings.value("start-fullscreen", false).toBool());
591     m_ui->msaaCheckbox->setChecked(settings.value("enable-msaa", false).toBool());
592     m_ui->fetchRealWxrCheckbox->setChecked(settings.value("enable-realwx", true).toBool());
593     m_ui->startPausedCheck->setChecked(settings.value("start-paused", false).toBool());
594     m_ui->timeOfDayCombo->setCurrentIndex(settings.value("timeofday", 0).toInt());
595     m_ui->seasonCombo->setCurrentIndex(settings.value("season", 0).toInt());
596
597     // full paths to -set.xml files
598     m_recentAircraft = settings.value("recent-aircraft").toStringList();
599
600     if (!m_recentAircraft.empty()) {
601         m_selectedAircraft = m_recentAircraft.front();
602     } else {
603         // select the default C172p
604     }
605
606     updateSelectedAircraft();
607
608     // ICAO identifiers
609     m_recentAirports = settings.value("recent-airports").toStringList();
610     if (!m_recentAirports.empty()) {
611         setAirport(FGAirport::findByIdent(m_recentAirports.front().toStdString()));
612     }
613     updateAirportDescription();
614
615     // rating filters
616     m_ui->ratingsFilterCheck->setChecked(settings.value("ratings-filter", true).toBool());
617     int index = 0;
618     Q_FOREACH(QVariant v, settings.value("min-ratings").toList()) {
619         m_ratingFilters[index++] = v.toInt();
620     }
621
622     m_aircraftProxy->setRatingFilterEnabled(m_ui->ratingsFilterCheck->isChecked());
623     m_aircraftProxy->setRatings(m_ratingFilters);
624
625     m_ui->commandLineArgs->setPlainText(settings.value("additional-args").toString());
626 }
627
628 void QtLauncher::saveSettings()
629 {
630     QSettings settings;
631     settings.setValue("enable-rembrandt", m_ui->rembrandtCheckbox->isChecked());
632     settings.setValue("enable-terrasync", m_ui->terrasyncCheck->isChecked());
633     settings.setValue("enable-msaa", m_ui->msaaCheckbox->isChecked());
634     settings.setValue("start-fullscreen", m_ui->fullScreenCheckbox->isChecked());
635     settings.setValue("enable-realwx", m_ui->fetchRealWxrCheckbox->isChecked());
636     settings.setValue("start-paused", m_ui->startPausedCheck->isChecked());
637     settings.setValue("ratings-filter", m_ui->ratingsFilterCheck->isChecked());
638     settings.setValue("recent-aircraft", m_recentAircraft);
639     settings.setValue("recent-airports", m_recentAirports);
640     settings.setValue("timeofday", m_ui->timeOfDayCombo->currentIndex());
641     settings.setValue("season", m_ui->seasonCombo->currentIndex());
642     settings.setValue("additional-args", m_ui->commandLineArgs->toPlainText());
643 }
644
645 void QtLauncher::setEnableDisableOptionFromCheckbox(QCheckBox* cbox, QString name) const
646 {
647     flightgear::Options* opt = flightgear::Options::sharedInstance();
648     std::string stdName(name.toStdString());
649     if (cbox->isChecked()) {
650         opt->addOption("enable-" + stdName, "");
651     } else {
652         opt->addOption("disable-" + stdName, "");
653     }
654 }
655
656 void QtLauncher::onRun()
657 {
658     accept();
659
660     flightgear::Options* opt = flightgear::Options::sharedInstance();
661     setEnableDisableOptionFromCheckbox(m_ui->terrasyncCheck, "terrasync");
662     setEnableDisableOptionFromCheckbox(m_ui->fetchRealWxrCheckbox, "real-weather-fetch");
663     setEnableDisableOptionFromCheckbox(m_ui->rembrandtCheckbox, "rembrandt");
664     setEnableDisableOptionFromCheckbox(m_ui->fullScreenCheckbox, "fullscreen");
665     setEnableDisableOptionFromCheckbox(m_ui->startPausedCheck, "freeze");
666
667     // MSAA is more complex
668     if (!m_ui->rembrandtCheckbox->isChecked()) {
669         if (m_ui->msaaCheckbox->isChecked()) {
670             globals->get_props()->setIntValue("/sim/rendering/multi-sample-buffers", 1);
671             globals->get_props()->setIntValue("/sim/rendering/multi-samples", 4);
672         } else {
673             globals->get_props()->setIntValue("/sim/rendering/multi-sample-buffers", 0);
674         }
675     }
676
677     // aircraft
678     if (!m_selectedAircraft.isEmpty()) {
679         QFileInfo setFileInfo(m_selectedAircraft);
680         opt->addOption("aircraft-dir", setFileInfo.dir().absolutePath().toStdString());
681         QString setFile = setFileInfo.fileName();
682         Q_ASSERT(setFile.endsWith("-set.xml"));
683         setFile.truncate(setFile.count() - 8); // drop the '-set.xml' portion
684         opt->addOption("aircraft", setFile.toStdString());
685
686       // manage aircraft history
687         if (m_recentAircraft.contains(m_selectedAircraft))
688           m_recentAircraft.removeOne(m_selectedAircraft);
689         m_recentAircraft.prepend(m_selectedAircraft);
690         if (m_recentAircraft.size() > MAX_RECENT_AIRCRAFT)
691           m_recentAircraft.pop_back();
692     }
693
694     // airport / location
695     if (m_selectedAirport) {
696         opt->addOption("airport", m_selectedAirport->ident());
697     }
698
699     if (m_ui->runwayRadio->isChecked()) {
700         int index = m_ui->runwayCombo->itemData(m_ui->runwayCombo->currentIndex()).toInt();
701         if ((index >= 0) && m_selectedAirport) {
702             // explicit runway choice
703             opt->addOption("runway", m_selectedAirport->getRunwayByIndex(index)->ident());
704         }
705
706         if (m_ui->onFinalCheckbox->isChecked()) {
707             opt->addOption("glideslope", "3.0");
708             opt->addOption("offset-distance", "10.0"); // in nautical miles
709         }
710     } else if (m_ui->parkingRadio->isChecked()) {
711         // parking selection
712         opt->addOption("parkpos", m_ui->parkingCombo->currentText().toStdString());
713     }
714
715     // time of day
716     if (m_ui->timeOfDayCombo->currentIndex() != 0) {
717         QString dayval = m_ui->timeOfDayCombo->currentText().toLower();
718         opt->addOption("timeofday", dayval.toStdString());
719     }
720
721     if (m_ui->seasonCombo->currentIndex() != 0) {
722         QString dayval = m_ui->timeOfDayCombo->currentText().toLower();
723         opt->addOption("season", dayval.toStdString());
724     }
725
726     QSettings settings;
727     QString downloadDir = settings.value("download-dir").toString();
728     if (!downloadDir.isEmpty()) {
729         QDir d(downloadDir);
730         if (!d.exists()) {
731             int result = QMessageBox::question(this, tr("Create download folder?"),
732                                   tr("The selected location for downloads does not exist. Create it?"),
733                                                QMessageBox::Yes | QMessageBox::No | QMessageBox::Cancel);
734             if (result == QMessageBox::Cancel) {
735                 return;
736             }
737
738             if (result == QMessageBox::Yes) {
739                 d.mkpath(downloadDir);
740             }
741         }
742
743         qDebug() << "Download dir is:" << downloadDir;
744         opt->addOption("download-dir", downloadDir.toStdString());
745     }
746
747     // scenery paths
748     Q_FOREACH(QString path, settings.value("scenery-paths").toStringList()) {
749         opt->addOption("fg-scenery", path.toStdString());
750     }
751
752     // aircraft paths
753     Q_FOREACH(QString path, settings.value("aircraft-paths").toStringList()) {
754         // can't use fg-aircraft for this, as it is processed before the launcher is run
755         globals->append_aircraft_path(path.toStdString());
756     }
757
758     // additional arguments
759     ArgumentsTokenizer tk;
760     Q_FOREACH(ArgumentsTokenizer::Arg a, tk.tokenize(m_ui->commandLineArgs->toPlainText())) {
761         if (a.arg.startsWith("prop:")) {
762             QString v = a.arg.mid(5) + "=" + a.value;
763             opt->addOption("prop", v.toStdString());
764         } else {
765             opt->addOption(a.arg.toStdString(), a.value.toStdString());
766         }
767     }
768
769     saveSettings();
770 }
771
772 void QtLauncher::onQuit()
773 {
774     reject();
775 }
776
777 void QtLauncher::onSearchAirports()
778 {
779     QString search = m_ui->airportEdit->text();
780     m_airportsModel->setSearch(search);
781
782     if (m_airportsModel->isSearchActive()) {
783         m_ui->searchStatusText->setText(QString("Searching for '%1'").arg(search));
784         m_ui->locationStack->setCurrentIndex(2);
785     } else if (m_airportsModel->rowCount(QModelIndex()) == 1) {
786         QString ident = m_airportsModel->firstIdent();
787         setAirport(FGAirport::findByIdent(ident.toStdString()));
788         m_ui->locationStack->setCurrentIndex(0);
789     }
790 }
791
792 void QtLauncher::onAirportSearchComplete()
793 {
794     int numResults = m_airportsModel->rowCount(QModelIndex());
795     if (numResults == 0) {
796         m_ui->searchStatusText->setText(QString("No matching airports for '%1'").arg(m_ui->airportEdit->text()));
797     } else if (numResults == 1) {
798         QString ident = m_airportsModel->firstIdent();
799         setAirport(FGAirport::findByIdent(ident.toStdString()));
800         m_ui->locationStack->setCurrentIndex(0);
801     } else {
802         m_ui->locationStack->setCurrentIndex(1);
803     }
804 }
805
806 void QtLauncher::onAirportChanged()
807 {
808     m_ui->runwayCombo->setEnabled(m_selectedAirport);
809     m_ui->parkingCombo->setEnabled(m_selectedAirport);
810     m_ui->airportDiagram->setAirport(m_selectedAirport);
811
812     m_ui->runwayRadio->setChecked(true); // default back to runway mode
813     // unelss multiplayer is enabled ?
814
815     if (!m_selectedAirport) {
816         m_ui->airportDescription->setText(QString());
817         m_ui->airportDiagram->setEnabled(false);
818         return;
819     }
820
821     m_ui->airportDiagram->setEnabled(true);
822
823     m_ui->runwayCombo->clear();
824     m_ui->runwayCombo->addItem("Automatic", -1);
825     for (unsigned int r=0; r<m_selectedAirport->numRunways(); ++r) {
826         FGRunwayRef rwy = m_selectedAirport->getRunwayByIndex(r);
827         // add runway with index as data role
828         m_ui->runwayCombo->addItem(QString::fromStdString(rwy->ident()), r);
829
830         m_ui->airportDiagram->addRunway(rwy);
831     }
832
833     m_ui->parkingCombo->clear();
834     FGAirportDynamics* dynamics = m_selectedAirport->getDynamics();
835     PositionedIDVec parkings = NavDataCache::instance()->airportItemsOfType(
836                                                                             m_selectedAirport->guid(),
837                                                                             FGPositioned::PARKING);
838     if (parkings.empty()) {
839         m_ui->parkingCombo->setEnabled(false);
840         m_ui->parkingRadio->setEnabled(false);
841     } else {
842         m_ui->parkingCombo->setEnabled(true);
843         m_ui->parkingRadio->setEnabled(true);
844         Q_FOREACH(PositionedID parking, parkings) {
845             FGParking* park = dynamics->getParking(parking);
846             m_ui->parkingCombo->addItem(QString::fromStdString(park->getName()),
847                                         static_cast<qlonglong>(parking));
848
849             m_ui->airportDiagram->addParking(park);
850         }
851     }
852 }
853
854 void QtLauncher::onToggleTerrasync(bool enabled)
855 {
856     if (enabled) {
857         QSettings settings;
858         QString downloadDir = settings.value("download-dir").toString();
859         if (downloadDir.isEmpty()) {
860             downloadDir = QString::fromStdString(flightgear::defaultDownloadDir());
861         }
862
863         QFileInfo info(downloadDir);
864         if (!info.exists()) {
865             QMessageBox msg;
866             msg.setWindowTitle(tr("Create download folder?"));
867             msg.setText(tr("The download folder '%1' does not exist, create it now? "
868                            "Click 'change location' to choose another folder "
869                            "to store downloaded files").arg(downloadDir));
870             msg.addButton(QMessageBox::Yes);
871             msg.addButton(QMessageBox::Cancel);
872             msg.addButton(tr("Change location"), QMessageBox::ActionRole);
873             int result = msg.exec();
874   
875             if (result == QMessageBox::Cancel) {
876                 m_ui->terrasyncCheck->setChecked(false);
877                 return;
878             }
879
880             if (result == QMessageBox::ActionRole) {
881                 onEditPaths();
882                 return;
883             }
884
885             QDir d(downloadDir);
886             d.mkpath(downloadDir);
887         }
888     } // of is enabled
889 }
890
891 void QtLauncher::updateAirportDescription()
892 {
893     if (!m_selectedAirport) {
894         m_ui->airportDescription->setText(QString("No airport selected"));
895         return;
896     }
897
898     QString ident = QString::fromStdString(m_selectedAirport->ident()),
899         name = QString::fromStdString(m_selectedAirport->name());
900     QString locationOnAirport;
901     if (m_ui->runwayRadio->isChecked()) {
902         bool onFinal = m_ui->onFinalCheckbox->isChecked();
903         QString runwayName = (m_ui->runwayCombo->currentIndex() == 0) ?
904             "active runway" :
905             QString("runway %1").arg(m_ui->runwayCombo->currentText());
906
907         if (onFinal) {
908             locationOnAirport = QString("on 10-mile final to %1").arg(runwayName);
909         } else {
910             locationOnAirport = QString("on %1").arg(runwayName);
911         }
912     } else if (m_ui->parkingRadio->isChecked()) {
913         locationOnAirport =  QString("at parking position %1").arg(m_ui->parkingCombo->currentText());
914     }
915
916     m_ui->airportDescription->setText(QString("%2 (%1): %3").arg(ident).arg(name).arg(locationOnAirport));
917 }
918
919 void QtLauncher::onAirportChoiceSelected(const QModelIndex& index)
920 {
921     m_ui->locationStack->setCurrentIndex(0);
922     setAirport(FGPositioned::loadById<FGAirport>(index.data(Qt::UserRole).toULongLong()));
923 }
924
925 void QtLauncher::onAircraftSelected(const QModelIndex& index)
926 {
927     m_selectedAircraft = index.data(AircraftPathRole).toString();
928     updateSelectedAircraft();
929 }
930
931 void QtLauncher::updateSelectedAircraft()
932 {
933     try {
934         QFileInfo info(m_selectedAircraft);
935         AircraftItem item(info.dir(), m_selectedAircraft);
936         m_ui->thumbnail->setPixmap(item.thumbnail());
937         m_ui->aircraftDescription->setText(item.description);
938     } catch (sg_exception& e) {
939         m_ui->thumbnail->setPixmap(QPixmap());
940         m_ui->aircraftDescription->setText("");
941     }
942 }
943
944 void QtLauncher::onPopupAirportHistory()
945 {
946     if (m_recentAirports.isEmpty()) {
947         return;
948     }
949
950     QMenu m;
951     Q_FOREACH(QString aptCode, m_recentAirports) {
952         FGAirportRef apt = FGAirport::findByIdent(aptCode.toStdString());
953         QString name = QString::fromStdString(apt->name());
954         QAction* act = m.addAction(QString("%1 - %2").arg(aptCode).arg(name));
955         act->setData(aptCode);
956     }
957
958     QPoint popupPos = m_ui->airportHistory->mapToGlobal(m_ui->airportHistory->rect().bottomLeft());
959     QAction* triggered = m.exec(popupPos);
960     if (triggered) {
961         FGAirportRef apt = FGAirport::findByIdent(triggered->data().toString().toStdString());
962         setAirport(apt);
963         m_ui->airportEdit->clear();
964         m_ui->locationStack->setCurrentIndex(0);
965     }
966 }
967
968 QModelIndex QtLauncher::proxyIndexForAircraftPath(QString path) const
969 {
970   return m_aircraftProxy->mapFromSource(sourceIndexForAircraftPath(path));
971 }
972
973 QModelIndex QtLauncher::sourceIndexForAircraftPath(QString path) const
974 {
975     AircraftItemModel* sourceModel = qobject_cast<AircraftItemModel*>(m_aircraftProxy->sourceModel());
976     Q_ASSERT(sourceModel);
977     return sourceModel->indexOfAircraftPath(path);
978 }
979
980 void QtLauncher::onPopupAircraftHistory()
981 {
982     if (m_recentAircraft.isEmpty()) {
983         return;
984     }
985
986     QMenu m;
987     Q_FOREACH(QString path, m_recentAircraft) {
988         QModelIndex index = sourceIndexForAircraftPath(path);
989         if (!index.isValid()) {
990             // not scanned yet
991             continue;
992         }
993         QAction* act = m.addAction(index.data(Qt::DisplayRole).toString());
994         act->setData(path);
995     }
996
997     QPoint popupPos = m_ui->aircraftHistory->mapToGlobal(m_ui->aircraftHistory->rect().bottomLeft());
998     QAction* triggered = m.exec(popupPos);
999     if (triggered) {
1000         m_selectedAircraft = triggered->data().toString();
1001         QModelIndex index = proxyIndexForAircraftPath(m_selectedAircraft);
1002         m_ui->aircraftList->selectionModel()->setCurrentIndex(index,
1003                                                               QItemSelectionModel::ClearAndSelect);
1004         m_ui->aircraftFilter->clear();
1005         updateSelectedAircraft();
1006     }
1007 }
1008
1009 void QtLauncher::setAirport(FGAirportRef ref)
1010 {
1011     if (m_selectedAirport == ref)
1012         return;
1013
1014     m_selectedAirport = ref;
1015     onAirportChanged();
1016
1017     if (ref.valid()) {
1018         // maintain the recent airport list
1019         QString icao = QString::fromStdString(ref->ident());
1020         if (m_recentAirports.contains(icao)) {
1021             // move to front
1022             m_recentAirports.removeOne(icao);
1023             m_recentAirports.push_front(icao);
1024         } else {
1025             // insert and trim list if necessary
1026             m_recentAirports.push_front(icao);
1027             if (m_recentAirports.size() > MAX_RECENT_AIRPORTS) {
1028                 m_recentAirports.pop_back();
1029             }
1030         }
1031     }
1032
1033     updateAirportDescription();
1034 }
1035
1036 void QtLauncher::onEditRatingsFilter()
1037 {
1038     EditRatingsFilterDialog dialog(this);
1039     dialog.setRatings(m_ratingFilters);
1040
1041     dialog.exec();
1042     if (dialog.result() == QDialog::Accepted) {
1043         QVariantList vl;
1044         for (int i=0; i<4; ++i) {
1045             m_ratingFilters[i] = dialog.getRating(i);
1046             vl.append(m_ratingFilters[i]);
1047         }
1048         m_aircraftProxy->setRatings(m_ratingFilters);
1049
1050         QSettings settings;
1051         settings.setValue("min-ratings", vl);
1052     }
1053 }
1054
1055 void QtLauncher::updateSettingsSummary()
1056 {
1057     QStringList summary;
1058     if (m_ui->timeOfDayCombo->currentIndex() > 0) {
1059         summary.append(QString(m_ui->timeOfDayCombo->currentText().toLower()));
1060     }
1061
1062     if (m_ui->seasonCombo->currentIndex() > 0) {
1063         summary.append(QString(m_ui->seasonCombo->currentText().toLower()));
1064     }
1065
1066     if (m_ui->rembrandtCheckbox->isChecked()) {
1067         summary.append("Rembrandt enabled");
1068     } else if (m_ui->msaaCheckbox->isChecked()) {
1069         summary.append("anti-aliasing");
1070     }
1071
1072     if (m_ui->fetchRealWxrCheckbox->isChecked()) {
1073         summary.append("live weather");
1074     }
1075
1076     if (m_ui->terrasyncCheck->isChecked()) {
1077         summary.append("automatic scenery downloads");
1078     }
1079
1080     if (m_ui->startPausedCheck->isChecked()) {
1081         summary.append("paused");
1082     }
1083
1084     QString s = summary.join(", ");
1085     s[0] = s[0].toUpper();
1086     m_ui->settingsDescription->setText(s);
1087 }
1088
1089 void QtLauncher::onRembrandtToggled(bool b)
1090 {
1091     // Rembrandt and multi-sample are exclusive
1092     m_ui->msaaCheckbox->setEnabled(!b);
1093 }
1094
1095 void QtLauncher::onSubsytemIdleTimeout()
1096 {
1097     globals->get_subsystem_mgr()->update(0.0);
1098 }
1099
1100 void QtLauncher::onEditPaths()
1101 {
1102     PathsDialog dlg(this, globals->packageRoot());
1103     dlg.exec();
1104     if (dlg.result() == QDialog::Accepted) {
1105         // re-scan the aircraft list
1106         QSettings settings;
1107         m_aircraftModel->setPaths(settings.value("aircraft-paths").toStringList());
1108         m_aircraftModel->scanDirs();
1109     }
1110 }
1111
1112 #include "QtLauncher.moc"
1113