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