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