]> git.mxchange.org Git - flightgear.git/blob - src/GUI/QtLauncher.cxx
Remove some debug output.
[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->airportDiagram, &AirportDiagram::clickedRunway,
448             this, &QtLauncher::onAirportDiagramClicked);
449
450     connect(m_ui->runButton, SIGNAL(clicked()), this, SLOT(onRun()));
451     connect(m_ui->quitButton, SIGNAL(clicked()), this, SLOT(onQuit()));
452     connect(m_ui->airportEdit, SIGNAL(returnPressed()),
453             this, SLOT(onSearchAirports()));
454
455     connect(m_ui->airportHistory, &QPushButton::clicked,
456             this, &QtLauncher::onPopupAirportHistory);
457     connect(m_ui->aircraftHistory, &QPushButton::clicked,
458           this, &QtLauncher::onPopupAircraftHistory);
459
460     restoreSettings();
461
462     QAction* qa = new QAction(this);
463     qa->setShortcut(QKeySequence("Ctrl+Q"));
464     connect(qa, &QAction::triggered, this, &QtLauncher::onQuit);
465     addAction(qa);
466
467     connect(m_ui->editRatingFilter, &QPushButton::clicked,
468             this, &QtLauncher::onEditRatingsFilter);
469
470     QIcon historyIcon(":/history-icon");
471     m_ui->aircraftHistory->setIcon(historyIcon);
472     m_ui->airportHistory->setIcon(historyIcon);
473
474     m_ui->searchIcon->setPixmap(QPixmap(":/search-icon"));
475
476     connect(m_ui->timeOfDayCombo, SIGNAL(currentIndexChanged(int)),
477             this, SLOT(updateSettingsSummary()));
478     connect(m_ui->seasonCombo, SIGNAL(currentIndexChanged(int)),
479             this, SLOT(updateSettingsSummary()));
480     connect(m_ui->fetchRealWxrCheckbox, SIGNAL(toggled(bool)),
481             this, SLOT(updateSettingsSummary()));
482     connect(m_ui->rembrandtCheckbox, SIGNAL(toggled(bool)),
483             this, SLOT(updateSettingsSummary()));
484     connect(m_ui->terrasyncCheck, SIGNAL(toggled(bool)),
485             this, SLOT(updateSettingsSummary()));
486     connect(m_ui->startPausedCheck, SIGNAL(toggled(bool)),
487             this, SLOT(updateSettingsSummary()));
488     connect(m_ui->msaaCheckbox, SIGNAL(toggled(bool)),
489             this, SLOT(updateSettingsSummary()));
490
491     connect(m_ui->rembrandtCheckbox, SIGNAL(toggled(bool)),
492             this, SLOT(onRembrandtToggled(bool)));
493     connect(m_ui->terrasyncCheck, &QCheckBox::toggled,
494             this, &QtLauncher::onToggleTerrasync);
495     updateSettingsSummary();
496
497     fgInitPackageRoot();
498     simgear::pkg::RootRef r(globals->packageRoot());
499
500     FGHTTPClient* http = new FGHTTPClient;
501     globals->add_subsystem("http", http);
502
503     // we guard against re-init in the global phase; bind and postinit
504     // will happen as normal
505     http->init();
506
507     m_aircraftModel = new AircraftItemModel(this, r);
508     m_aircraftProxy->setSourceModel(m_aircraftModel);
509
510     m_aircraftProxy->setFilterCaseSensitivity(Qt::CaseInsensitive);
511     m_aircraftProxy->setSortCaseSensitivity(Qt::CaseInsensitive);
512     m_aircraftProxy->setSortRole(Qt::DisplayRole);
513     m_aircraftProxy->setDynamicSortFilter(true);
514
515     m_ui->aircraftList->setModel(m_aircraftProxy);
516     m_ui->aircraftList->setHorizontalScrollBarPolicy(Qt::ScrollBarAlwaysOff);
517     AircraftItemDelegate* delegate = new AircraftItemDelegate(m_ui->aircraftList);
518     m_ui->aircraftList->setItemDelegate(delegate);
519     m_ui->aircraftList->setSelectionMode(QAbstractItemView::SingleSelection);
520     connect(m_ui->aircraftList, &QListView::clicked,
521             this, &QtLauncher::onAircraftSelected);
522     connect(delegate, &AircraftItemDelegate::variantChanged,
523             this, &QtLauncher::onAircraftSelected);
524
525     connect(m_ui->pathsButton, &QPushButton::clicked,
526             this, &QtLauncher::onEditPaths);
527
528     QSettings settings;
529     m_aircraftModel->setPaths(settings.value("aircraft-paths").toStringList());
530     m_aircraftModel->scanDirs();
531 }
532
533 QtLauncher::~QtLauncher()
534 {
535     
536 }
537
538 void QtLauncher::initApp(int argc, char** argv)
539 {
540     static bool qtInitDone = false;
541     if (!qtInitDone) {
542         qtInitDone = true;
543
544         QApplication* app = new QApplication(argc, argv);
545         app->setOrganizationName("FlightGear");
546         app->setApplicationName("FlightGear");
547         app->setOrganizationDomain("flightgear.org");
548
549         // avoid double Apple menu and other weirdness if both Qt and OSG
550         // try to initialise various Cocoa structures.
551         flightgear::WindowBuilder::setPoseAsStandaloneApp(false);
552
553         Qt::KeyboardModifiers mods = app->queryKeyboardModifiers();
554         if (mods & Qt::AltModifier) {
555             qWarning() << "Alt pressed during launch";
556
557             // wipe out our settings
558             QSettings settings;
559             settings.clear();
560
561
562             Options::sharedInstance()->addOption("restore-defaults", "");
563         }
564     }
565 }
566
567 bool QtLauncher::runLauncherDialog()
568 {
569     Q_INIT_RESOURCE(resources);
570
571     // startup the nav-cache now. This pre-empts normal startup of
572     // the cache, but no harm done. (Providing scenery paths are consistent)
573
574     initNavCache();
575
576   // setup scenery paths now, especially TerraSync path for airport
577   // parking locations (after they're downloaded)
578
579     QtLauncher dlg;
580     dlg.exec();
581     if (dlg.result() != QDialog::Accepted) {
582         return false;
583     }
584
585     return true;
586 }
587
588 void QtLauncher::restoreSettings()
589 {
590     QSettings settings;
591     m_ui->rembrandtCheckbox->setChecked(settings.value("enable-rembrandt", false).toBool());
592     m_ui->terrasyncCheck->setChecked(settings.value("enable-terrasync", true).toBool());
593     m_ui->fullScreenCheckbox->setChecked(settings.value("start-fullscreen", false).toBool());
594     m_ui->msaaCheckbox->setChecked(settings.value("enable-msaa", false).toBool());
595     m_ui->fetchRealWxrCheckbox->setChecked(settings.value("enable-realwx", true).toBool());
596     m_ui->startPausedCheck->setChecked(settings.value("start-paused", false).toBool());
597     m_ui->timeOfDayCombo->setCurrentIndex(settings.value("timeofday", 0).toInt());
598     m_ui->seasonCombo->setCurrentIndex(settings.value("season", 0).toInt());
599
600     // full paths to -set.xml files
601     m_recentAircraft = settings.value("recent-aircraft").toStringList();
602
603     if (!m_recentAircraft.empty()) {
604         m_selectedAircraft = m_recentAircraft.front();
605     } else {
606         // select the default C172p
607     }
608
609     updateSelectedAircraft();
610
611     // ICAO identifiers
612     m_recentAirports = settings.value("recent-airports").toStringList();
613     if (!m_recentAirports.empty()) {
614         setAirport(FGAirport::findByIdent(m_recentAirports.front().toStdString()));
615     }
616     updateAirportDescription();
617
618     // rating filters
619     m_ui->ratingsFilterCheck->setChecked(settings.value("ratings-filter", true).toBool());
620     int index = 0;
621     Q_FOREACH(QVariant v, settings.value("min-ratings").toList()) {
622         m_ratingFilters[index++] = v.toInt();
623     }
624
625     m_aircraftProxy->setRatingFilterEnabled(m_ui->ratingsFilterCheck->isChecked());
626     m_aircraftProxy->setRatings(m_ratingFilters);
627
628     m_ui->commandLineArgs->setPlainText(settings.value("additional-args").toString());
629 }
630
631 void QtLauncher::saveSettings()
632 {
633     QSettings settings;
634     settings.setValue("enable-rembrandt", m_ui->rembrandtCheckbox->isChecked());
635     settings.setValue("enable-terrasync", m_ui->terrasyncCheck->isChecked());
636     settings.setValue("enable-msaa", m_ui->msaaCheckbox->isChecked());
637     settings.setValue("start-fullscreen", m_ui->fullScreenCheckbox->isChecked());
638     settings.setValue("enable-realwx", m_ui->fetchRealWxrCheckbox->isChecked());
639     settings.setValue("start-paused", m_ui->startPausedCheck->isChecked());
640     settings.setValue("ratings-filter", m_ui->ratingsFilterCheck->isChecked());
641     settings.setValue("recent-aircraft", m_recentAircraft);
642     settings.setValue("recent-airports", m_recentAirports);
643     settings.setValue("timeofday", m_ui->timeOfDayCombo->currentIndex());
644     settings.setValue("season", m_ui->seasonCombo->currentIndex());
645     settings.setValue("additional-args", m_ui->commandLineArgs->toPlainText());
646 }
647
648 void QtLauncher::setEnableDisableOptionFromCheckbox(QCheckBox* cbox, QString name) const
649 {
650     flightgear::Options* opt = flightgear::Options::sharedInstance();
651     std::string stdName(name.toStdString());
652     if (cbox->isChecked()) {
653         opt->addOption("enable-" + stdName, "");
654     } else {
655         opt->addOption("disable-" + stdName, "");
656     }
657 }
658
659 void QtLauncher::onRun()
660 {
661     accept();
662
663     flightgear::Options* opt = flightgear::Options::sharedInstance();
664     setEnableDisableOptionFromCheckbox(m_ui->terrasyncCheck, "terrasync");
665     setEnableDisableOptionFromCheckbox(m_ui->fetchRealWxrCheckbox, "real-weather-fetch");
666     setEnableDisableOptionFromCheckbox(m_ui->rembrandtCheckbox, "rembrandt");
667     setEnableDisableOptionFromCheckbox(m_ui->fullScreenCheckbox, "fullscreen");
668     setEnableDisableOptionFromCheckbox(m_ui->startPausedCheck, "freeze");
669
670     // MSAA is more complex
671     if (!m_ui->rembrandtCheckbox->isChecked()) {
672         if (m_ui->msaaCheckbox->isChecked()) {
673             globals->get_props()->setIntValue("/sim/rendering/multi-sample-buffers", 1);
674             globals->get_props()->setIntValue("/sim/rendering/multi-samples", 4);
675         } else {
676             globals->get_props()->setIntValue("/sim/rendering/multi-sample-buffers", 0);
677         }
678     }
679
680     // aircraft
681     if (!m_selectedAircraft.isEmpty()) {
682         QFileInfo setFileInfo(m_selectedAircraft);
683         opt->addOption("aircraft-dir", setFileInfo.dir().absolutePath().toStdString());
684         QString setFile = setFileInfo.fileName();
685         Q_ASSERT(setFile.endsWith("-set.xml"));
686         setFile.truncate(setFile.count() - 8); // drop the '-set.xml' portion
687         opt->addOption("aircraft", setFile.toStdString());
688
689       // manage aircraft history
690         if (m_recentAircraft.contains(m_selectedAircraft))
691           m_recentAircraft.removeOne(m_selectedAircraft);
692         m_recentAircraft.prepend(m_selectedAircraft);
693         if (m_recentAircraft.size() > MAX_RECENT_AIRCRAFT)
694           m_recentAircraft.pop_back();
695     }
696
697     // airport / location
698     if (m_selectedAirport) {
699         opt->addOption("airport", m_selectedAirport->ident());
700     }
701
702     if (m_ui->runwayRadio->isChecked()) {
703         int index = m_ui->runwayCombo->itemData(m_ui->runwayCombo->currentIndex()).toInt();
704         if ((index >= 0) && m_selectedAirport) {
705             // explicit runway choice
706             opt->addOption("runway", m_selectedAirport->getRunwayByIndex(index)->ident());
707         }
708
709         if (m_ui->onFinalCheckbox->isChecked()) {
710             opt->addOption("glideslope", "3.0");
711             opt->addOption("offset-distance", "10.0"); // in nautical miles
712         }
713     } else if (m_ui->parkingRadio->isChecked()) {
714         // parking selection
715         opt->addOption("parkpos", m_ui->parkingCombo->currentText().toStdString());
716     }
717
718     // time of day
719     if (m_ui->timeOfDayCombo->currentIndex() != 0) {
720         QString dayval = m_ui->timeOfDayCombo->currentText().toLower();
721         opt->addOption("timeofday", dayval.toStdString());
722     }
723
724     if (m_ui->seasonCombo->currentIndex() != 0) {
725         QString dayval = m_ui->timeOfDayCombo->currentText().toLower();
726         opt->addOption("season", dayval.toStdString());
727     }
728
729     QSettings settings;
730     QString downloadDir = settings.value("download-dir").toString();
731     if (!downloadDir.isEmpty()) {
732         QDir d(downloadDir);
733         if (!d.exists()) {
734             int result = QMessageBox::question(this, tr("Create download folder?"),
735                                   tr("The selected location for downloads does not exist. Create it?"),
736                                                QMessageBox::Yes | QMessageBox::No | QMessageBox::Cancel);
737             if (result == QMessageBox::Cancel) {
738                 return;
739             }
740
741             if (result == QMessageBox::Yes) {
742                 d.mkpath(downloadDir);
743             }
744         }
745
746         qDebug() << "Download dir is:" << downloadDir;
747         opt->addOption("download-dir", downloadDir.toStdString());
748     }
749
750     // scenery paths
751     Q_FOREACH(QString path, settings.value("scenery-paths").toStringList()) {
752         opt->addOption("fg-scenery", path.toStdString());
753     }
754
755     // aircraft paths
756     Q_FOREACH(QString path, settings.value("aircraft-paths").toStringList()) {
757         // can't use fg-aircraft for this, as it is processed before the launcher is run
758         globals->append_aircraft_path(path.toStdString());
759     }
760
761     // additional arguments
762     ArgumentsTokenizer tk;
763     Q_FOREACH(ArgumentsTokenizer::Arg a, tk.tokenize(m_ui->commandLineArgs->toPlainText())) {
764         if (a.arg.startsWith("prop:")) {
765             QString v = a.arg.mid(5) + "=" + a.value;
766             opt->addOption("prop", v.toStdString());
767         } else {
768             opt->addOption(a.arg.toStdString(), a.value.toStdString());
769         }
770     }
771
772     saveSettings();
773 }
774
775 void QtLauncher::onQuit()
776 {
777     reject();
778 }
779
780 void QtLauncher::onSearchAirports()
781 {
782     QString search = m_ui->airportEdit->text();
783     m_airportsModel->setSearch(search);
784
785     if (m_airportsModel->isSearchActive()) {
786         m_ui->searchStatusText->setText(QString("Searching for '%1'").arg(search));
787         m_ui->locationStack->setCurrentIndex(2);
788     } else if (m_airportsModel->rowCount(QModelIndex()) == 1) {
789         QString ident = m_airportsModel->firstIdent();
790         setAirport(FGAirport::findByIdent(ident.toStdString()));
791         m_ui->locationStack->setCurrentIndex(0);
792     }
793 }
794
795 void QtLauncher::onAirportSearchComplete()
796 {
797     int numResults = m_airportsModel->rowCount(QModelIndex());
798     if (numResults == 0) {
799         m_ui->searchStatusText->setText(QString("No matching airports for '%1'").arg(m_ui->airportEdit->text()));
800     } else if (numResults == 1) {
801         QString ident = m_airportsModel->firstIdent();
802         setAirport(FGAirport::findByIdent(ident.toStdString()));
803         m_ui->locationStack->setCurrentIndex(0);
804     } else {
805         m_ui->locationStack->setCurrentIndex(1);
806     }
807 }
808
809 void QtLauncher::onAirportChanged()
810 {
811     m_ui->runwayCombo->setEnabled(m_selectedAirport);
812     m_ui->parkingCombo->setEnabled(m_selectedAirport);
813     m_ui->airportDiagram->setAirport(m_selectedAirport);
814
815     m_ui->runwayRadio->setChecked(true); // default back to runway mode
816     // unelss multiplayer is enabled ?
817
818     if (!m_selectedAirport) {
819         m_ui->airportDescription->setText(QString());
820         m_ui->airportDiagram->setEnabled(false);
821         return;
822     }
823
824     m_ui->airportDiagram->setEnabled(true);
825
826     m_ui->runwayCombo->clear();
827     m_ui->runwayCombo->addItem("Automatic", -1);
828     for (unsigned int r=0; r<m_selectedAirport->numRunways(); ++r) {
829         FGRunwayRef rwy = m_selectedAirport->getRunwayByIndex(r);
830         // add runway with index as data role
831         m_ui->runwayCombo->addItem(QString::fromStdString(rwy->ident()), r);
832
833         m_ui->airportDiagram->addRunway(rwy);
834     }
835
836     m_ui->parkingCombo->clear();
837     FGAirportDynamics* dynamics = m_selectedAirport->getDynamics();
838     PositionedIDVec parkings = NavDataCache::instance()->airportItemsOfType(
839                                                                             m_selectedAirport->guid(),
840                                                                             FGPositioned::PARKING);
841     if (parkings.empty()) {
842         m_ui->parkingCombo->setEnabled(false);
843         m_ui->parkingRadio->setEnabled(false);
844     } else {
845         m_ui->parkingCombo->setEnabled(true);
846         m_ui->parkingRadio->setEnabled(true);
847         Q_FOREACH(PositionedID parking, parkings) {
848             FGParking* park = dynamics->getParking(parking);
849             m_ui->parkingCombo->addItem(QString::fromStdString(park->getName()),
850                                         static_cast<qlonglong>(parking));
851
852             m_ui->airportDiagram->addParking(park);
853         }
854     }
855 }
856
857 void QtLauncher::onAirportDiagramClicked(FGRunwayRef rwy)
858 {
859     if (rwy) {
860         m_ui->runwayRadio->setChecked(true);
861         int rwyIndex = m_ui->runwayCombo->findText(QString::fromStdString(rwy->ident()));
862         m_ui->runwayCombo->setCurrentIndex(rwyIndex);
863     }
864     
865     updateAirportDescription();
866 }
867
868 void QtLauncher::onToggleTerrasync(bool enabled)
869 {
870     if (enabled) {
871         QSettings settings;
872         QString downloadDir = settings.value("download-dir").toString();
873         if (downloadDir.isEmpty()) {
874             downloadDir = QString::fromStdString(flightgear::defaultDownloadDir());
875         }
876
877         QFileInfo info(downloadDir);
878         if (!info.exists()) {
879             QMessageBox msg;
880             msg.setWindowTitle(tr("Create download folder?"));
881             msg.setText(tr("The download folder '%1' does not exist, create it now? "
882                            "Click 'change location' to choose another folder "
883                            "to store downloaded files").arg(downloadDir));
884             msg.addButton(QMessageBox::Yes);
885             msg.addButton(QMessageBox::Cancel);
886             msg.addButton(tr("Change location"), QMessageBox::ActionRole);
887             int result = msg.exec();
888   
889             if (result == QMessageBox::Cancel) {
890                 m_ui->terrasyncCheck->setChecked(false);
891                 return;
892             }
893
894             if (result == QMessageBox::ActionRole) {
895                 onEditPaths();
896                 return;
897             }
898
899             QDir d(downloadDir);
900             d.mkpath(downloadDir);
901         }
902     } // of is enabled
903 }
904
905 void QtLauncher::updateAirportDescription()
906 {
907     if (!m_selectedAirport) {
908         m_ui->airportDescription->setText(QString("No airport selected"));
909         return;
910     }
911
912     QString ident = QString::fromStdString(m_selectedAirport->ident()),
913         name = QString::fromStdString(m_selectedAirport->name());
914     QString locationOnAirport;
915     if (m_ui->runwayRadio->isChecked()) {
916         bool onFinal = m_ui->onFinalCheckbox->isChecked();
917         int comboIndex = m_ui->runwayCombo->currentIndex();
918         QString runwayName = (comboIndex == 0) ?
919             "active runway" :
920             QString("runway %1").arg(m_ui->runwayCombo->currentText());
921
922         if (onFinal) {
923             locationOnAirport = QString("on 10-mile final to %1").arg(runwayName);
924         } else {
925             locationOnAirport = QString("on %1").arg(runwayName);
926         }
927         
928         int runwayIndex = m_ui->runwayCombo->itemData(comboIndex).toInt();
929         FGRunwayRef rwy = (runwayIndex >= 0) ?
930             m_selectedAirport->getRunwayByIndex(runwayIndex) : FGRunwayRef();
931         m_ui->airportDiagram->setSelectedRunway(rwy);
932     } else if (m_ui->parkingRadio->isChecked()) {
933         locationOnAirport =  QString("at parking position %1").arg(m_ui->parkingCombo->currentText());
934     }
935
936     m_ui->airportDescription->setText(QString("%2 (%1): %3").arg(ident).arg(name).arg(locationOnAirport));
937 }
938
939 void QtLauncher::onAirportChoiceSelected(const QModelIndex& index)
940 {
941     m_ui->locationStack->setCurrentIndex(0);
942     setAirport(FGPositioned::loadById<FGAirport>(index.data(Qt::UserRole).toULongLong()));
943 }
944
945 void QtLauncher::onAircraftSelected(const QModelIndex& index)
946 {
947     m_selectedAircraft = index.data(AircraftPathRole).toString();
948     updateSelectedAircraft();
949 }
950
951 void QtLauncher::updateSelectedAircraft()
952 {
953     try {
954         QFileInfo info(m_selectedAircraft);
955         AircraftItem item(info.dir(), m_selectedAircraft);
956         m_ui->thumbnail->setPixmap(item.thumbnail());
957         m_ui->aircraftDescription->setText(item.description);
958     } catch (sg_exception& e) {
959         m_ui->thumbnail->setPixmap(QPixmap());
960         m_ui->aircraftDescription->setText("");
961     }
962 }
963
964 void QtLauncher::onPopupAirportHistory()
965 {
966     if (m_recentAirports.isEmpty()) {
967         return;
968     }
969
970     QMenu m;
971     Q_FOREACH(QString aptCode, m_recentAirports) {
972         FGAirportRef apt = FGAirport::findByIdent(aptCode.toStdString());
973         QString name = QString::fromStdString(apt->name());
974         QAction* act = m.addAction(QString("%1 - %2").arg(aptCode).arg(name));
975         act->setData(aptCode);
976     }
977
978     QPoint popupPos = m_ui->airportHistory->mapToGlobal(m_ui->airportHistory->rect().bottomLeft());
979     QAction* triggered = m.exec(popupPos);
980     if (triggered) {
981         FGAirportRef apt = FGAirport::findByIdent(triggered->data().toString().toStdString());
982         setAirport(apt);
983         m_ui->airportEdit->clear();
984         m_ui->locationStack->setCurrentIndex(0);
985     }
986 }
987
988 QModelIndex QtLauncher::proxyIndexForAircraftPath(QString path) const
989 {
990   return m_aircraftProxy->mapFromSource(sourceIndexForAircraftPath(path));
991 }
992
993 QModelIndex QtLauncher::sourceIndexForAircraftPath(QString path) const
994 {
995     AircraftItemModel* sourceModel = qobject_cast<AircraftItemModel*>(m_aircraftProxy->sourceModel());
996     Q_ASSERT(sourceModel);
997     return sourceModel->indexOfAircraftPath(path);
998 }
999
1000 void QtLauncher::onPopupAircraftHistory()
1001 {
1002     if (m_recentAircraft.isEmpty()) {
1003         return;
1004     }
1005
1006     QMenu m;
1007     Q_FOREACH(QString path, m_recentAircraft) {
1008         QModelIndex index = sourceIndexForAircraftPath(path);
1009         if (!index.isValid()) {
1010             // not scanned yet
1011             continue;
1012         }
1013         QAction* act = m.addAction(index.data(Qt::DisplayRole).toString());
1014         act->setData(path);
1015     }
1016
1017     QPoint popupPos = m_ui->aircraftHistory->mapToGlobal(m_ui->aircraftHistory->rect().bottomLeft());
1018     QAction* triggered = m.exec(popupPos);
1019     if (triggered) {
1020         m_selectedAircraft = triggered->data().toString();
1021         QModelIndex index = proxyIndexForAircraftPath(m_selectedAircraft);
1022         m_ui->aircraftList->selectionModel()->setCurrentIndex(index,
1023                                                               QItemSelectionModel::ClearAndSelect);
1024         m_ui->aircraftFilter->clear();
1025         updateSelectedAircraft();
1026     }
1027 }
1028
1029 void QtLauncher::setAirport(FGAirportRef ref)
1030 {
1031     if (m_selectedAirport == ref)
1032         return;
1033
1034     m_selectedAirport = ref;
1035     onAirportChanged();
1036
1037     if (ref.valid()) {
1038         // maintain the recent airport list
1039         QString icao = QString::fromStdString(ref->ident());
1040         if (m_recentAirports.contains(icao)) {
1041             // move to front
1042             m_recentAirports.removeOne(icao);
1043             m_recentAirports.push_front(icao);
1044         } else {
1045             // insert and trim list if necessary
1046             m_recentAirports.push_front(icao);
1047             if (m_recentAirports.size() > MAX_RECENT_AIRPORTS) {
1048                 m_recentAirports.pop_back();
1049             }
1050         }
1051     }
1052
1053     updateAirportDescription();
1054 }
1055
1056 void QtLauncher::onEditRatingsFilter()
1057 {
1058     EditRatingsFilterDialog dialog(this);
1059     dialog.setRatings(m_ratingFilters);
1060
1061     dialog.exec();
1062     if (dialog.result() == QDialog::Accepted) {
1063         QVariantList vl;
1064         for (int i=0; i<4; ++i) {
1065             m_ratingFilters[i] = dialog.getRating(i);
1066             vl.append(m_ratingFilters[i]);
1067         }
1068         m_aircraftProxy->setRatings(m_ratingFilters);
1069
1070         QSettings settings;
1071         settings.setValue("min-ratings", vl);
1072     }
1073 }
1074
1075 void QtLauncher::updateSettingsSummary()
1076 {
1077     QStringList summary;
1078     if (m_ui->timeOfDayCombo->currentIndex() > 0) {
1079         summary.append(QString(m_ui->timeOfDayCombo->currentText().toLower()));
1080     }
1081
1082     if (m_ui->seasonCombo->currentIndex() > 0) {
1083         summary.append(QString(m_ui->seasonCombo->currentText().toLower()));
1084     }
1085
1086     if (m_ui->rembrandtCheckbox->isChecked()) {
1087         summary.append("Rembrandt enabled");
1088     } else if (m_ui->msaaCheckbox->isChecked()) {
1089         summary.append("anti-aliasing");
1090     }
1091
1092     if (m_ui->fetchRealWxrCheckbox->isChecked()) {
1093         summary.append("live weather");
1094     }
1095
1096     if (m_ui->terrasyncCheck->isChecked()) {
1097         summary.append("automatic scenery downloads");
1098     }
1099
1100     if (m_ui->startPausedCheck->isChecked()) {
1101         summary.append("paused");
1102     }
1103
1104     QString s = summary.join(", ");
1105     s[0] = s[0].toUpper();
1106     m_ui->settingsDescription->setText(s);
1107 }
1108
1109 void QtLauncher::onRembrandtToggled(bool b)
1110 {
1111     // Rembrandt and multi-sample are exclusive
1112     m_ui->msaaCheckbox->setEnabled(!b);
1113 }
1114
1115 void QtLauncher::onSubsytemIdleTimeout()
1116 {
1117     globals->get_subsystem_mgr()->update(0.0);
1118 }
1119
1120 void QtLauncher::onEditPaths()
1121 {
1122     PathsDialog dlg(this, globals->packageRoot());
1123     dlg.exec();
1124     if (dlg.result() == QDialog::Accepted) {
1125         // re-scan the aircraft list
1126         QSettings settings;
1127         m_aircraftModel->setPaths(settings.value("aircraft-paths").toStringList());
1128         m_aircraftModel->scanDirs();
1129     }
1130 }
1131
1132 #include "QtLauncher.moc"
1133