]> git.mxchange.org Git - flightgear.git/blob - src/GUI/QtLauncher.cxx
Percentage feedback during nav-cache build.
[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         opt->addOption("fg-aircraft", path.toStdString());
773     }
774
775     // additional arguments
776     ArgumentsTokenizer tk;
777     Q_FOREACH(ArgumentsTokenizer::Arg a, tk.tokenize(m_ui->commandLineArgs->toPlainText())) {
778         if (a.arg.startsWith("prop:")) {
779             QString v = a.arg.mid(5) + "=" + a.value;
780             opt->addOption("prop", v.toStdString());
781         } else {
782             opt->addOption(a.arg.toStdString(), a.value.toStdString());
783         }
784     }
785
786     saveSettings();
787 }
788
789 void QtLauncher::onQuit()
790 {
791     reject();
792 }
793
794 void QtLauncher::onSearchAirports()
795 {
796     QString search = m_ui->airportEdit->text();
797     m_airportsModel->setSearch(search);
798
799     if (m_airportsModel->isSearchActive()) {
800         m_ui->searchStatusText->setText(QString("Searching for '%1'").arg(search));
801         m_ui->locationStack->setCurrentIndex(2);
802     } else if (m_airportsModel->rowCount(QModelIndex()) == 1) {
803         QString ident = m_airportsModel->firstIdent();
804         setAirport(FGAirport::findByIdent(ident.toStdString()));
805         m_ui->locationStack->setCurrentIndex(0);
806     }
807 }
808
809 void QtLauncher::onAirportSearchComplete()
810 {
811     int numResults = m_airportsModel->rowCount(QModelIndex());
812     if (numResults == 0) {
813         m_ui->searchStatusText->setText(QString("No matching airports for '%1'").arg(m_ui->airportEdit->text()));
814     } else if (numResults == 1) {
815         QString ident = m_airportsModel->firstIdent();
816         setAirport(FGAirport::findByIdent(ident.toStdString()));
817         m_ui->locationStack->setCurrentIndex(0);
818     } else {
819         m_ui->locationStack->setCurrentIndex(1);
820     }
821 }
822
823 void QtLauncher::onAirportChanged()
824 {
825     m_ui->runwayCombo->setEnabled(m_selectedAirport);
826     m_ui->parkingCombo->setEnabled(m_selectedAirport);
827     m_ui->airportDiagram->setAirport(m_selectedAirport);
828
829     m_ui->runwayRadio->setChecked(true); // default back to runway mode
830     // unelss multiplayer is enabled ?
831
832     if (!m_selectedAirport) {
833         m_ui->airportDescription->setText(QString());
834         m_ui->airportDiagram->setEnabled(false);
835         return;
836     }
837
838     m_ui->airportDiagram->setEnabled(true);
839
840     m_ui->runwayCombo->clear();
841     m_ui->runwayCombo->addItem("Automatic", -1);
842     for (unsigned int r=0; r<m_selectedAirport->numRunways(); ++r) {
843         FGRunwayRef rwy = m_selectedAirport->getRunwayByIndex(r);
844         // add runway with index as data role
845         m_ui->runwayCombo->addItem(QString::fromStdString(rwy->ident()), r);
846
847         m_ui->airportDiagram->addRunway(rwy);
848     }
849
850     m_ui->parkingCombo->clear();
851     FGAirportDynamics* dynamics = m_selectedAirport->getDynamics();
852     PositionedIDVec parkings = NavDataCache::instance()->airportItemsOfType(
853                                                                             m_selectedAirport->guid(),
854                                                                             FGPositioned::PARKING);
855     if (parkings.empty()) {
856         m_ui->parkingCombo->setEnabled(false);
857         m_ui->parkingRadio->setEnabled(false);
858     } else {
859         m_ui->parkingCombo->setEnabled(true);
860         m_ui->parkingRadio->setEnabled(true);
861         Q_FOREACH(PositionedID parking, parkings) {
862             FGParking* park = dynamics->getParking(parking);
863             m_ui->parkingCombo->addItem(QString::fromStdString(park->getName()),
864                                         static_cast<qlonglong>(parking));
865
866             m_ui->airportDiagram->addParking(park);
867         }
868     }
869 }
870
871 void QtLauncher::updateAirportDescription()
872 {
873     if (!m_selectedAirport) {
874         m_ui->airportDescription->setText(QString("No airport selected"));
875         return;
876     }
877
878     QString ident = QString::fromStdString(m_selectedAirport->ident()),
879         name = QString::fromStdString(m_selectedAirport->name());
880     QString locationOnAirport;
881     if (m_ui->runwayRadio->isChecked()) {
882         bool onFinal = m_ui->onFinalCheckbox->isChecked();
883         QString runwayName = (m_ui->runwayCombo->currentIndex() == 0) ?
884             "active runway" :
885             QString("runway %1").arg(m_ui->runwayCombo->currentText());
886
887         if (onFinal) {
888             locationOnAirport = QString("on 10-mile final to %1").arg(runwayName);
889         } else {
890             locationOnAirport = QString("on %1").arg(runwayName);
891         }
892     } else if (m_ui->parkingRadio->isChecked()) {
893         locationOnAirport =  QString("at parking position %1").arg(m_ui->parkingCombo->currentText());
894     }
895
896     m_ui->airportDescription->setText(QString("%2 (%1): %3").arg(ident).arg(name).arg(locationOnAirport));
897 }
898
899 void QtLauncher::onAirportChoiceSelected(const QModelIndex& index)
900 {
901     m_ui->locationStack->setCurrentIndex(0);
902     setAirport(FGPositioned::loadById<FGAirport>(index.data(Qt::UserRole).toULongLong()));
903 }
904
905 void QtLauncher::onAircraftSelected(const QModelIndex& index)
906 {
907     m_selectedAircraft = index.data(AircraftPathRole).toString();
908     updateSelectedAircraft();
909 }
910
911 void QtLauncher::updateSelectedAircraft()
912 {
913     try {
914         QFileInfo info(m_selectedAircraft);
915         AircraftItem item(info.dir(), m_selectedAircraft);
916         m_ui->thumbnail->setPixmap(item.thumbnail());
917         m_ui->aircraftDescription->setText(item.description);
918     } catch (sg_exception& e) {
919         m_ui->thumbnail->setPixmap(QPixmap());
920         m_ui->aircraftDescription->setText("");
921     }
922 }
923
924 void QtLauncher::onPopupAirportHistory()
925 {
926     if (m_recentAirports.isEmpty()) {
927         return;
928     }
929
930     QMenu m;
931     Q_FOREACH(QString aptCode, m_recentAirports) {
932         FGAirportRef apt = FGAirport::findByIdent(aptCode.toStdString());
933         QString name = QString::fromStdString(apt->name());
934         QAction* act = m.addAction(QString("%1 - %2").arg(aptCode).arg(name));
935         act->setData(aptCode);
936     }
937
938     QPoint popupPos = m_ui->airportHistory->mapToGlobal(m_ui->airportHistory->rect().bottomLeft());
939     QAction* triggered = m.exec(popupPos);
940     if (triggered) {
941         FGAirportRef apt = FGAirport::findByIdent(triggered->data().toString().toStdString());
942         setAirport(apt);
943         m_ui->airportEdit->clear();
944         m_ui->locationStack->setCurrentIndex(0);
945     }
946 }
947
948 QModelIndex QtLauncher::proxyIndexForAircraftPath(QString path) const
949 {
950   return m_aircraftProxy->mapFromSource(sourceIndexForAircraftPath(path));
951 }
952
953 QModelIndex QtLauncher::sourceIndexForAircraftPath(QString path) const
954 {
955     AircraftItemModel* sourceModel = qobject_cast<AircraftItemModel*>(m_aircraftProxy->sourceModel());
956     Q_ASSERT(sourceModel);
957     return sourceModel->indexOfAircraftPath(path);
958 }
959
960 void QtLauncher::onPopupAircraftHistory()
961 {
962     if (m_recentAircraft.isEmpty()) {
963         return;
964     }
965
966     QMenu m;
967     Q_FOREACH(QString path, m_recentAircraft) {
968         QModelIndex index = sourceIndexForAircraftPath(path);
969         if (!index.isValid()) {
970             // not scanned yet
971             continue;
972         }
973         QAction* act = m.addAction(index.data(Qt::DisplayRole).toString());
974         act->setData(path);
975     }
976
977     QPoint popupPos = m_ui->aircraftHistory->mapToGlobal(m_ui->aircraftHistory->rect().bottomLeft());
978     QAction* triggered = m.exec(popupPos);
979     if (triggered) {
980         m_selectedAircraft = triggered->data().toString();
981         QModelIndex index = proxyIndexForAircraftPath(m_selectedAircraft);
982         m_ui->aircraftList->selectionModel()->setCurrentIndex(index,
983                                                               QItemSelectionModel::ClearAndSelect);
984         m_ui->aircraftFilter->clear();
985         updateSelectedAircraft();
986     }
987 }
988
989 void QtLauncher::setAirport(FGAirportRef ref)
990 {
991     if (m_selectedAirport == ref)
992         return;
993
994     m_selectedAirport = ref;
995     onAirportChanged();
996
997     if (ref.valid()) {
998         // maintain the recent airport list
999         QString icao = QString::fromStdString(ref->ident());
1000         if (m_recentAirports.contains(icao)) {
1001             // move to front
1002             m_recentAirports.removeOne(icao);
1003             m_recentAirports.push_front(icao);
1004         } else {
1005             // insert and trim list if necessary
1006             m_recentAirports.push_front(icao);
1007             if (m_recentAirports.size() > MAX_RECENT_AIRPORTS) {
1008                 m_recentAirports.pop_back();
1009             }
1010         }
1011     }
1012
1013     updateAirportDescription();
1014 }
1015
1016 void QtLauncher::onOpenCustomAircraftDir()
1017 {
1018     QFileInfo info(m_customAircraftDir);
1019     if (!info.exists()) {
1020         int result = QMessageBox::question(this, "Create folder?",
1021                                            "The custom aircraft folder does not exist, create it now?",
1022                                            QMessageBox::Yes | QMessageBox::No,
1023                                            QMessageBox::Yes);
1024         if (result == QMessageBox::No) {
1025             return;
1026         }
1027
1028         QDir d(m_customAircraftDir);
1029         d.mkpath(m_customAircraftDir);
1030     }
1031
1032   QUrl u = QUrl::fromLocalFile(m_customAircraftDir);
1033   QDesktopServices::openUrl(u);
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::onAddSceneryPath()
1090 {
1091     QString path = QFileDialog::getExistingDirectory(this, tr("Choose scenery folder"));
1092     if (!path.isEmpty()) {
1093         m_ui->sceneryPathsList->addItem(path);
1094         saveSettings();
1095     }
1096 }
1097
1098 void QtLauncher::onRemoveSceneryPath()
1099 {
1100     if (m_ui->sceneryPathsList->currentItem()) {
1101         delete m_ui->sceneryPathsList->currentItem();
1102         saveSettings();
1103     }
1104 }
1105
1106 void QtLauncher::onAddAircraftPath()
1107 {
1108     QString path = QFileDialog::getExistingDirectory(this, tr("Choose aircraft folder"));
1109     if (!path.isEmpty()) {
1110         m_ui->aircraftPathsList->addItem(path);
1111         saveSettings();
1112
1113         // re-scan the aircraft list
1114         QSettings settings;
1115         m_aircraftModel->setPaths(settings.value("aircraft-paths").toStringList());
1116         m_aircraftModel->scanDirs();
1117     }
1118 }
1119
1120 void QtLauncher::onRemoveAircraftPath()
1121 {
1122     if (m_ui->aircraftPathsList->currentItem()) {
1123         delete m_ui->aircraftPathsList->currentItem();
1124         saveSettings();
1125     }
1126 }
1127
1128 void QtLauncher::onRembrandtToggled(bool b)
1129 {
1130     // Rembrandt and multi-sample are exclusive
1131     m_ui->msaaCheckbox->setEnabled(!b);
1132 }
1133
1134 void QtLauncher::onSubsytemIdleTimeout()
1135 {
1136     globals->get_subsystem_mgr()->update(0.0);
1137 }
1138
1139 #include "QtLauncher.moc"
1140