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