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