]> git.mxchange.org Git - flightgear.git/blob - src/GUI/QtLauncher.cxx
Work with new SGPath API.
[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 #include "QtLauncher_private.hxx"
23
24 #include <locale.h>
25
26 // Qt
27 #include <QProgressDialog>
28 #include <QCoreApplication>
29 #include <QAbstractListModel>
30 #include <QDir>
31 #include <QFileInfo>
32 #include <QPixmap>
33 #include <QTimer>
34 #include <QDebug>
35 #include <QCompleter>
36 #include <QListView>
37 #include <QSettings>
38 #include <QSortFilterProxyModel>
39 #include <QMenu>
40 #include <QDesktopServices>
41 #include <QUrl>
42 #include <QAction>
43 #include <QFileDialog>
44 #include <QMessageBox>
45 #include <QDateTime>
46 #include <QApplication>
47 #include <QSpinBox>
48 #include <QDoubleSpinBox>
49 #include <QProcess>
50
51 // Simgear
52 #include <simgear/timing/timestamp.hxx>
53 #include <simgear/props/props_io.hxx>
54 #include <simgear/structure/exception.hxx>
55 #include <simgear/structure/subsystem_mgr.hxx>
56 #include <simgear/misc/sg_path.hxx>
57 #include <simgear/package/Catalog.hxx>
58 #include <simgear/package/Package.hxx>
59 #include <simgear/package/Install.hxx>
60
61 #include "ui_Launcher.h"
62 #include "ui_NoOfficialHangar.h"
63
64 #include "EditRatingsFilterDialog.hxx"
65 #include "AircraftItemDelegate.hxx"
66 #include "AircraftModel.hxx"
67 #include "PathsDialog.hxx"
68
69 #include <Main/globals.hxx>
70 #include <Navaids/NavDataCache.hxx>
71 #include <Navaids/navrecord.hxx>
72 #include <Navaids/SHPParser.hxx>
73
74 #include <Main/options.hxx>
75 #include <Main/fg_init.hxx>
76 #include <Viewer/WindowBuilder.hxx>
77 #include <Network/HTTPClient.hxx>
78
79 using namespace flightgear;
80 using namespace simgear::pkg;
81
82 const int MAX_RECENT_AIRCRAFT = 20;
83
84 namespace { // anonymous namespace
85
86 void initNavCache()
87 {
88     QString baseLabel = QT_TR_NOOP("Initialising navigation data, this may take several minutes");
89     NavDataCache* cache = NavDataCache::createInstance();
90     if (cache->isRebuildRequired()) {
91         QProgressDialog rebuildProgress(baseLabel,
92                                        QString() /* cancel text */,
93                                        0, 100, Q_NULLPTR,
94                                        Qt::Dialog
95                                            | Qt::CustomizeWindowHint
96                                            | Qt::WindowTitleHint
97                                            | Qt::WindowSystemMenuHint
98                                            | Qt::MSWindowsFixedSizeDialogHint);
99         rebuildProgress.setWindowModality(Qt::WindowModal);
100         rebuildProgress.show();
101
102         NavDataCache::RebuildPhase phase = cache->rebuild();
103
104         while (phase != NavDataCache::REBUILD_DONE) {
105             // sleep to give the rebuild thread more time
106             SGTimeStamp::sleepForMSec(50);
107             phase = cache->rebuild();
108
109             switch (phase) {
110             case NavDataCache::REBUILD_AIRPORTS:
111                 rebuildProgress.setLabelText(QT_TR_NOOP("Loading airport data"));
112                 break;
113
114             case NavDataCache::REBUILD_FIXES:
115                 rebuildProgress.setLabelText(QT_TR_NOOP("Loading waypoint data"));
116                 break;
117
118             case NavDataCache::REBUILD_NAVAIDS:
119                 rebuildProgress.setLabelText(QT_TR_NOOP("Loading navigation data"));
120                 break;
121
122
123             case NavDataCache::REBUILD_POIS:
124                 rebuildProgress.setLabelText(QT_TR_NOOP("Loading point-of-interest data"));
125                 break;
126
127             default:
128                 rebuildProgress.setLabelText(baseLabel);
129             }
130
131             if (phase == NavDataCache::REBUILD_UNKNOWN) {
132                 rebuildProgress.setValue(0);
133                 rebuildProgress.setMaximum(0);
134             } else {
135                 rebuildProgress.setValue(cache->rebuildPhaseCompletionPercentage());
136                 rebuildProgress.setMaximum(100);
137             }
138
139             QCoreApplication::processEvents();
140         }
141     }
142 }
143
144 class ArgumentsTokenizer
145 {
146 public:
147     class Arg
148     {
149     public:
150         explicit Arg(QString k, QString v = QString()) : arg(k), value(v) {}
151
152         QString arg;
153         QString value;
154     };
155
156     QList<Arg> tokenize(QString in) const
157     {
158         int index = 0;
159         const int len = in.count();
160         QChar c, nc;
161         State state = Start;
162         QString key, value;
163         QList<Arg> result;
164
165         for (; index < len; ++index) {
166             c = in.at(index);
167             nc = index < (len - 1) ? in.at(index + 1) : QChar();
168
169             switch (state) {
170             case Start:
171                 if (c == QChar('-')) {
172                     if (nc == QChar('-')) {
173                         state = Key;
174                         key.clear();
175                         ++index;
176                     } else {
177                         // should we pemit single hyphen arguments?
178                         // choosing to fail for now
179                         return QList<Arg>();
180                     }
181                 } else if (c == QChar('#')) {
182                     state = Comment;
183                     break;
184                 } else if (c.isSpace()) {
185                     break;
186                 }
187                 break;
188
189             case Key:
190                 if (c == QChar('=')) {
191                     state = Value;
192                     value.clear();
193                 } else if (c.isSpace()) {
194                     state = Start;
195                     result.append(Arg(key));
196                 } else {
197                     // could check for illegal charatcers here
198                     key.append(c);
199                 }
200                 break;
201
202             case Value:
203                 if (c == QChar('"')) {
204                     state = Quoted;
205                 } else if (c.isSpace()) {
206                     state = Start;
207                     result.append(Arg(key, value));
208                 } else {
209                     value.append(c);
210                 }
211                 break;
212
213             case Quoted:
214                 if (c == QChar('\\')) {
215                     // check for escaped double-quote inside quoted value
216                     if (nc == QChar('"')) {
217                         ++index;
218                     }
219                 } else if (c == QChar('"')) {
220                     state = Value;
221                 } else {
222                     value.append(c);
223                 }
224                 break;
225
226             case Comment:
227                 if ((c == QChar('\n')) || (c == QChar('\r'))) {
228                     state = Start;
229                     break;
230                 } else {
231                     // nothing to do, eat comment chars
232                 }
233                 break;
234             } // of state switch
235         } // of character loop
236
237         // ensure last argument isn't lost
238         if (state == Key) {
239             result.append(Arg(key));
240         } else if (state == Value) {
241             result.append(Arg(key, value));
242         }
243
244         return result;
245     }
246
247 private:
248     enum State {
249         Start = 0,
250         Key,
251         Value,
252         Quoted,
253         Comment
254     };
255 };
256
257 } // of anonymous namespace
258
259 class AircraftProxyModel : public QSortFilterProxyModel
260 {
261     Q_OBJECT
262 public:
263     AircraftProxyModel(QObject* pr) :
264         QSortFilterProxyModel(pr),
265         m_ratingsFilter(true),
266         m_onlyShowInstalled(false)
267     {
268         for (int i=0; i<4; ++i) {
269             m_ratings[i] = 3;
270         }
271     }
272
273     void setRatings(int* ratings)
274     {
275         ::memcpy(m_ratings, ratings, sizeof(int) * 4);
276         invalidate();
277     }
278
279 public slots:
280     void setRatingFilterEnabled(bool e)
281     {
282         if (e == m_ratingsFilter) {
283             return;
284         }
285
286         m_ratingsFilter = e;
287         invalidate();
288     }
289
290     void setInstalledFilterEnabled(bool e)
291     {
292         if (e == m_onlyShowInstalled) {
293             return;
294         }
295
296         m_onlyShowInstalled = e;
297         invalidate();
298     }
299
300 protected:
301     bool filterAcceptsRow(int sourceRow, const QModelIndex &sourceParent) const
302     {
303         QModelIndex index = sourceModel()->index(sourceRow, 0, sourceParent);
304         QVariant v = index.data(AircraftPackageStatusRole);
305         AircraftItemStatus status = static_cast<AircraftItemStatus>(v.toInt());
306         if (status == NoOfficialCatalogMessage) {
307             return true;
308         }
309         
310         if (!QSortFilterProxyModel::filterAcceptsRow(sourceRow, sourceParent)) {
311             return false;
312         }
313
314         if (m_onlyShowInstalled) {
315             QVariant v = index.data(AircraftPackageStatusRole);
316             AircraftItemStatus status = static_cast<AircraftItemStatus>(v.toInt());
317             if (status == PackageNotInstalled) {
318                 return false;
319             }
320         }
321
322         if (!m_onlyShowInstalled && m_ratingsFilter) {
323             for (int i=0; i<4; ++i) {
324                 if (m_ratings[i] > index.data(AircraftRatingRole + i).toInt()) {
325                     return false;
326                 }
327             }
328         }
329
330         return true;
331     }
332
333 private:
334     bool m_ratingsFilter;
335     bool m_onlyShowInstalled;
336     int m_ratings[4];
337 };
338
339 class NoOfficialHangarMessage : public QWidget
340 {
341     Q_OBJECT
342 public:
343     NoOfficialHangarMessage() :
344         m_ui(new Ui::NoOfficialHangarMessage)
345     {
346         m_ui->setupUi(this);
347         // proxy this signal upwards
348         connect(m_ui->label, &QLabel::linkActivated,
349                 this, &NoOfficialHangarMessage::linkActivated);
350     }
351
352 Q_SIGNALS:
353     void linkActivated(QUrl link);
354
355 private:
356     Ui::NoOfficialHangarMessage* m_ui;
357 };
358
359 static void initQtResources()
360 {
361     Q_INIT_RESOURCE(resources);
362 }
363
364 namespace flightgear
365 {
366
367 void initApp(int& argc, char** argv)
368 {
369     static bool qtInitDone = false;
370     static int s_argc;
371
372     if (!qtInitDone) {
373         qtInitDone = true;
374
375         sglog().setLogLevels( SG_ALL, SG_INFO );
376         initQtResources(); // can't be called from a namespace
377
378         s_argc = argc; // QApplication only stores a reference to argc,
379         // and may crash if it is freed
380         // http://doc.qt.io/qt-5/qguiapplication.html#QGuiApplication
381
382         QApplication* app = new QApplication(s_argc, argv);
383         app->setOrganizationName("FlightGear");
384         app->setApplicationName("FlightGear");
385         app->setOrganizationDomain("flightgear.org");
386
387         QSettings::setDefaultFormat(QSettings::IniFormat);
388         QSettings::setPath(QSettings::IniFormat, QSettings::UserScope,
389                            QString::fromStdString(globals->get_fg_home()));
390
391         // reset numeric / collation locales as described at:
392         // http://doc.qt.io/qt-5/qcoreapplication.html#details
393         ::setlocale(LC_NUMERIC, "C");
394         ::setlocale(LC_COLLATE, "C");
395
396         Qt::KeyboardModifiers mods = app->queryKeyboardModifiers();
397         if (mods & (Qt::AltModifier | Qt::ShiftModifier)) {
398             qWarning() << "Alt/shift pressed during launch";
399             QSettings settings;
400             settings.setValue("fg-root", "!ask");
401         }
402     }
403 }
404
405 void loadNaturalEarthFile(const std::string& aFileName,
406                           flightgear::PolyLine::Type aType,
407                           bool areClosed)
408 {
409     SGPath path(globals->get_fg_root());
410     path.append( "Geodata" );
411     path.append(aFileName);
412     if (!path.exists())
413         return; // silently fail for now
414
415     flightgear::PolyLineList lines;
416     flightgear::SHPParser::parsePolyLines(path, aType, lines, areClosed);
417     flightgear::PolyLine::bulkAddToSpatialIndex(lines);
418 }
419
420 void loadNaturalEarthData()
421 {
422     SGTimeStamp st;
423     st.stamp();
424
425     loadNaturalEarthFile("ne_10m_coastline.shp", flightgear::PolyLine::COASTLINE, false);
426     loadNaturalEarthFile("ne_10m_rivers_lake_centerlines.shp", flightgear::PolyLine::RIVER, false);
427     loadNaturalEarthFile("ne_10m_lakes.shp", flightgear::PolyLine::LAKE, true);
428
429     qDebug() << "load basic data took" << st.elapsedMSec();
430
431
432     st.stamp();
433     loadNaturalEarthFile("ne_10m_urban_areas.shp", flightgear::PolyLine::URBAN, true);
434
435     qDebug() << "loading urban areas took:" << st.elapsedMSec();
436 }
437
438 bool runLauncherDialog()
439 {
440     // startup the nav-cache now. This pre-empts normal startup of
441     // the cache, but no harm done. (Providing scenery paths are consistent)
442
443     initNavCache();
444
445     QSettings settings;
446     QString downloadDir = settings.value("download-dir").toString();
447     if (!downloadDir.isEmpty()) {
448         flightgear::Options::sharedInstance()->setOption("download-dir", downloadDir.toStdString());
449     }
450
451     fgInitPackageRoot();
452
453     // startup the HTTP system now since packages needs it
454     FGHTTPClient* http = globals->add_new_subsystem<FGHTTPClient>();
455     
456     // we guard against re-init in the global phase; bind and postinit
457     // will happen as normal
458     http->init();
459
460     loadNaturalEarthData();
461
462     // avoid double Apple menu and other weirdness if both Qt and OSG
463     // try to initialise various Cocoa structures.
464     flightgear::WindowBuilder::setPoseAsStandaloneApp(false);
465
466     QtLauncher dlg;
467     dlg.show();
468
469     int appResult = qApp->exec();
470     if (appResult < 0) {
471         return false; // quit
472     }
473
474     // don't set scenery paths twice
475     globals->clear_fg_scenery();
476
477     return true;
478 }
479
480 bool runInAppLauncherDialog()
481 {
482     QtLauncher dlg;
483     dlg.setInAppMode();
484     dlg.exec();
485     if (dlg.result() != QDialog::Accepted) {
486         return false;
487     }
488
489     return true;
490 }
491
492 } // of namespace flightgear
493
494 QtLauncher::QtLauncher() :
495     QDialog(),
496     m_ui(NULL),
497     m_subsystemIdleTimer(NULL),
498     m_inAppMode(false)
499 {
500     m_ui.reset(new Ui::Launcher);
501     m_ui->setupUi(this);
502
503 #if QT_VERSION >= 0x050300
504     // don't require Qt 5.3
505     m_ui->commandLineArgs->setPlaceholderText("--option=value --prop:/sim/name=value");
506 #endif
507
508 #if QT_VERSION >= 0x050200
509     m_ui->aircraftFilter->setClearButtonEnabled(true);
510 #endif
511
512     for (int i=0; i<4; ++i) {
513         m_ratingFilters[i] = 3;
514     }
515
516     m_subsystemIdleTimer = new QTimer(this);
517     m_subsystemIdleTimer->setInterval(0);
518     connect(m_subsystemIdleTimer, &QTimer::timeout,
519             this, &QtLauncher::onSubsytemIdleTimeout);
520     m_subsystemIdleTimer->start();
521
522     // create and configure the proxy model
523     m_aircraftProxy = new AircraftProxyModel(this);
524     connect(m_ui->ratingsFilterCheck, &QAbstractButton::toggled,
525             m_aircraftProxy, &AircraftProxyModel::setRatingFilterEnabled);
526     connect(m_ui->ratingsFilterCheck, &QAbstractButton::toggled,
527             this, &QtLauncher::maybeRestoreAircraftSelection);
528
529     connect(m_ui->onlyShowInstalledCheck, &QAbstractButton::toggled,
530             m_aircraftProxy, &AircraftProxyModel::setInstalledFilterEnabled);
531     connect(m_ui->aircraftFilter, &QLineEdit::textChanged,
532             m_aircraftProxy, &QSortFilterProxyModel::setFilterFixedString);
533
534     connect(m_ui->runButton, SIGNAL(clicked()), this, SLOT(onRun()));
535     connect(m_ui->quitButton, SIGNAL(clicked()), this, SLOT(onQuit()));
536
537     connect(m_ui->aircraftHistory, &QPushButton::clicked,
538           this, &QtLauncher::onPopupAircraftHistory);
539
540     connect(m_ui->location, &LocationWidget::descriptionChanged,
541             m_ui->locationDescription, &QLabel::setText);
542
543     QAction* qa = new QAction(this);
544     qa->setShortcut(QKeySequence("Ctrl+Q"));
545     connect(qa, &QAction::triggered, this, &QtLauncher::onQuit);
546     addAction(qa);
547
548     connect(m_ui->editRatingFilter, &QPushButton::clicked,
549             this, &QtLauncher::onEditRatingsFilter);
550     connect(m_ui->onlyShowInstalledCheck, &QCheckBox::toggled,
551             this, &QtLauncher::onShowInstalledAircraftToggled);
552
553     QIcon historyIcon(":/history-icon");
554     m_ui->aircraftHistory->setIcon(historyIcon);
555
556     connect(m_ui->timeOfDayCombo, SIGNAL(currentIndexChanged(int)),
557             this, SLOT(updateSettingsSummary()));
558     connect(m_ui->seasonCombo, SIGNAL(currentIndexChanged(int)),
559             this, SLOT(updateSettingsSummary()));
560     connect(m_ui->fetchRealWxrCheckbox, SIGNAL(toggled(bool)),
561             this, SLOT(updateSettingsSummary()));
562     connect(m_ui->rembrandtCheckbox, SIGNAL(toggled(bool)),
563             this, SLOT(updateSettingsSummary()));
564     connect(m_ui->terrasyncCheck, SIGNAL(toggled(bool)),
565             this, SLOT(updateSettingsSummary()));
566     connect(m_ui->startPausedCheck, SIGNAL(toggled(bool)),
567             this, SLOT(updateSettingsSummary()));
568     connect(m_ui->msaaCheckbox, SIGNAL(toggled(bool)),
569             this, SLOT(updateSettingsSummary()));
570
571     connect(m_ui->rembrandtCheckbox, SIGNAL(toggled(bool)),
572             this, SLOT(onRembrandtToggled(bool)));
573     connect(m_ui->terrasyncCheck, &QCheckBox::toggled,
574             this, &QtLauncher::onToggleTerrasync);
575     updateSettingsSummary();
576
577     m_aircraftModel = new AircraftItemModel(this);
578     m_aircraftProxy->setSourceModel(m_aircraftModel);
579
580     m_aircraftProxy->setFilterCaseSensitivity(Qt::CaseInsensitive);
581     m_aircraftProxy->setSortCaseSensitivity(Qt::CaseInsensitive);
582     m_aircraftProxy->setSortRole(Qt::DisplayRole);
583     m_aircraftProxy->setDynamicSortFilter(true);
584
585     m_ui->aircraftList->setModel(m_aircraftProxy);
586     m_ui->aircraftList->setHorizontalScrollBarPolicy(Qt::ScrollBarAlwaysOff);
587     AircraftItemDelegate* delegate = new AircraftItemDelegate(m_ui->aircraftList);
588     m_ui->aircraftList->setItemDelegate(delegate);
589     m_ui->aircraftList->setSelectionMode(QAbstractItemView::SingleSelection);
590     connect(m_ui->aircraftList, &QListView::clicked,
591             this, &QtLauncher::onAircraftSelected);
592     connect(delegate, &AircraftItemDelegate::variantChanged,
593             this, &QtLauncher::onAircraftSelected);
594     connect(delegate, &AircraftItemDelegate::requestInstall,
595             this, &QtLauncher::onRequestPackageInstall);
596     connect(delegate, &AircraftItemDelegate::cancelDownload,
597             this, &QtLauncher::onCancelDownload);
598
599     connect(m_aircraftModel, &AircraftItemModel::aircraftInstallCompleted,
600             this, &QtLauncher::onAircraftInstalledCompleted);
601     connect(m_aircraftModel, &AircraftItemModel::aircraftInstallFailed,
602             this, &QtLauncher::onAircraftInstallFailed);
603     connect(m_aircraftModel, &AircraftItemModel::scanCompleted,
604             this, &QtLauncher::updateSelectedAircraft);
605     connect(m_ui->restoreDefaultsButton, &QPushButton::clicked,
606             this, &QtLauncher::onRestoreDefaults);
607
608
609     AddOnsPage* addOnsPage = new AddOnsPage(NULL, globals->packageRoot());
610     connect(addOnsPage, &AddOnsPage::downloadDirChanged,
611             this, &QtLauncher::onDownloadDirChanged);
612     connect(addOnsPage, &AddOnsPage::sceneryPathsChanged,
613             this, &QtLauncher::setSceneryPaths);
614
615     m_ui->tabWidget->addTab(addOnsPage, tr("Add-ons"));
616     // after any kind of reset, try to restore selection and scroll
617     // to match the m_selectedAircraft. This needs to be delayed
618     // fractionally otherwise the scrollTo seems to be ignored,
619     // unfortunately.
620     connect(m_aircraftProxy, &AircraftProxyModel::modelReset,
621             this, &QtLauncher::delayedAircraftModelReset);
622
623     QSettings settings;
624     m_aircraftModel->setPaths(settings.value("aircraft-paths").toStringList());
625     m_aircraftModel->setPackageRoot(globals->packageRoot());
626     m_aircraftModel->scanDirs();
627
628     checkOfficialCatalogMessage();
629     restoreSettings();
630 }
631
632 QtLauncher::~QtLauncher()
633 {
634
635 }
636
637 void QtLauncher::setSceneryPaths()
638 {
639     globals->clear_fg_scenery();
640
641 // mimic what optionss.cxx does, so we can find airport data for parking
642 // positions
643     QSettings settings;
644     // append explicit scenery paths
645     Q_FOREACH(QString path, settings.value("scenery-paths").toStringList()) {
646         globals->append_fg_scenery(path.toStdString());
647     }
648
649     // append the TerraSync path
650     QString downloadDir = settings.value("download-dir").toString();
651     if (downloadDir.isEmpty()) {
652         downloadDir = QString::fromStdString(flightgear::defaultDownloadDir());
653     }
654
655     SGPath terraSyncDir(downloadDir.toStdString());
656     terraSyncDir.append("TerraSync");
657     if (terraSyncDir.exists()) {
658         globals->append_fg_scenery(terraSyncDir.utf8Str());
659     }
660
661 }
662
663 void QtLauncher::setInAppMode()
664 {
665   m_inAppMode = true;
666   m_ui->tabWidget->removeTab(2);
667   m_ui->tabWidget->removeTab(2);
668
669   m_ui->runButton->setText(tr("Apply"));
670   m_ui->quitButton->setText(tr("Cancel"));
671
672   disconnect(m_ui->runButton, SIGNAL(clicked()), this, SLOT(onRun()));
673   connect(m_ui->runButton, SIGNAL(clicked()), this, SLOT(onApply()));
674 }
675
676 void QtLauncher::restoreSettings()
677 {
678     QSettings settings;
679     m_ui->rembrandtCheckbox->setChecked(settings.value("enable-rembrandt", false).toBool());
680     m_ui->terrasyncCheck->setChecked(settings.value("enable-terrasync", true).toBool());
681     m_ui->fullScreenCheckbox->setChecked(settings.value("start-fullscreen", false).toBool());
682     m_ui->msaaCheckbox->setChecked(settings.value("enable-msaa", false).toBool());
683     m_ui->fetchRealWxrCheckbox->setChecked(settings.value("enable-realwx", true).toBool());
684     m_ui->startPausedCheck->setChecked(settings.value("start-paused", false).toBool());
685     m_ui->timeOfDayCombo->setCurrentIndex(settings.value("timeofday", 0).toInt());
686     m_ui->seasonCombo->setCurrentIndex(settings.value("season", 0).toInt());
687
688     // full paths to -set.xml files
689     m_recentAircraft = QUrl::fromStringList(settings.value("recent-aircraft").toStringList());
690
691     if (!m_recentAircraft.empty()) {
692         m_selectedAircraft = m_recentAircraft.front();
693     } else {
694         // select the default C172p
695     }
696
697     if (!m_inAppMode) {
698         setSceneryPaths();
699     }
700
701     m_ui->location->restoreSettings();
702
703     // rating filters
704     m_ui->onlyShowInstalledCheck->setChecked(settings.value("only-show-installed", false).toBool());
705     if (m_ui->onlyShowInstalledCheck->isChecked()) {
706         m_ui->ratingsFilterCheck->setEnabled(false);
707     }
708
709     m_ui->ratingsFilterCheck->setChecked(settings.value("ratings-filter", true).toBool());
710     int index = 0;
711     Q_FOREACH(QVariant v, settings.value("min-ratings").toList()) {
712         m_ratingFilters[index++] = v.toInt();
713     }
714
715     m_aircraftProxy->setRatingFilterEnabled(m_ui->ratingsFilterCheck->isChecked());
716     m_aircraftProxy->setRatings(m_ratingFilters);
717
718     updateSelectedAircraft();
719     maybeRestoreAircraftSelection();
720
721     m_ui->commandLineArgs->setPlainText(settings.value("additional-args").toString());
722 }
723
724 void QtLauncher::delayedAircraftModelReset()
725 {
726     QTimer::singleShot(1, this, SLOT(maybeRestoreAircraftSelection()));
727 }
728
729 void QtLauncher::maybeRestoreAircraftSelection()
730 {
731     QModelIndex aircraftIndex = m_aircraftModel->indexOfAircraftURI(m_selectedAircraft);
732     QModelIndex proxyIndex = m_aircraftProxy->mapFromSource(aircraftIndex);
733     if (proxyIndex.isValid()) {
734         m_ui->aircraftList->selectionModel()->setCurrentIndex(proxyIndex,
735                                                               QItemSelectionModel::ClearAndSelect);
736         m_ui->aircraftList->selectionModel()->select(proxyIndex,
737                                                      QItemSelectionModel::ClearAndSelect);
738         m_ui->aircraftList->scrollTo(proxyIndex);
739     }
740 }
741
742 void QtLauncher::saveSettings()
743 {
744     QSettings settings;
745     settings.setValue("enable-rembrandt", m_ui->rembrandtCheckbox->isChecked());
746     settings.setValue("enable-terrasync", m_ui->terrasyncCheck->isChecked());
747     settings.setValue("enable-msaa", m_ui->msaaCheckbox->isChecked());
748     settings.setValue("start-fullscreen", m_ui->fullScreenCheckbox->isChecked());
749     settings.setValue("enable-realwx", m_ui->fetchRealWxrCheckbox->isChecked());
750     settings.setValue("start-paused", m_ui->startPausedCheck->isChecked());
751     settings.setValue("ratings-filter", m_ui->ratingsFilterCheck->isChecked());
752     settings.setValue("only-show-installed", m_ui->onlyShowInstalledCheck->isChecked());
753     settings.setValue("recent-aircraft", QUrl::toStringList(m_recentAircraft));
754
755     settings.setValue("timeofday", m_ui->timeOfDayCombo->currentIndex());
756     settings.setValue("season", m_ui->seasonCombo->currentIndex());
757     settings.setValue("additional-args", m_ui->commandLineArgs->toPlainText());
758
759     m_ui->location->saveSettings();
760 }
761
762 void QtLauncher::setEnableDisableOptionFromCheckbox(QCheckBox* cbox, QString name) const
763 {
764     flightgear::Options* opt = flightgear::Options::sharedInstance();
765     std::string stdName(name.toStdString());
766     if (cbox->isChecked()) {
767         opt->addOption("enable-" + stdName, "");
768     } else {
769         opt->addOption("disable-" + stdName, "");
770     }
771 }
772
773 void QtLauncher::closeEvent(QCloseEvent *event)
774 {
775     qApp->exit(-1);
776 }
777
778 void QtLauncher::reject()
779 {
780     qApp->exit(-1);
781 }
782
783 void QtLauncher::onRun()
784 {
785     flightgear::Options* opt = flightgear::Options::sharedInstance();
786     setEnableDisableOptionFromCheckbox(m_ui->terrasyncCheck, "terrasync");
787     setEnableDisableOptionFromCheckbox(m_ui->fetchRealWxrCheckbox, "real-weather-fetch");
788     setEnableDisableOptionFromCheckbox(m_ui->rembrandtCheckbox, "rembrandt");
789     setEnableDisableOptionFromCheckbox(m_ui->fullScreenCheckbox, "fullscreen");
790 //    setEnableDisableOptionFromCheckbox(m_ui->startPausedCheck, "freeze");
791
792     bool startPaused = m_ui->startPausedCheck->isChecked() ||
793             m_ui->location->shouldStartPaused();
794     if (startPaused) {
795         opt->addOption("enable-freeze", "");
796     }
797
798     // MSAA is more complex
799     if (!m_ui->rembrandtCheckbox->isChecked()) {
800         if (m_ui->msaaCheckbox->isChecked()) {
801             globals->get_props()->setIntValue("/sim/rendering/multi-sample-buffers", 1);
802             globals->get_props()->setIntValue("/sim/rendering/multi-samples", 4);
803         } else {
804             globals->get_props()->setIntValue("/sim/rendering/multi-sample-buffers", 0);
805         }
806     }
807
808     // aircraft
809     if (!m_selectedAircraft.isEmpty()) {
810         if (m_selectedAircraft.isLocalFile()) {
811             QFileInfo setFileInfo(m_selectedAircraft.toLocalFile());
812             opt->addOption("aircraft-dir", setFileInfo.dir().absolutePath().toStdString());
813             QString setFile = setFileInfo.fileName();
814             Q_ASSERT(setFile.endsWith("-set.xml"));
815             setFile.truncate(setFile.count() - 8); // drop the '-set.xml' portion
816             opt->addOption("aircraft", setFile.toStdString());
817         } else if (m_selectedAircraft.scheme() == "package") {
818             QString qualifiedId = m_selectedAircraft.path();
819             // no need to set aircraft-dir, handled by the corresponding code
820             // in fgInitAircraft
821             opt->addOption("aircraft", qualifiedId.toStdString());
822         } else {
823             qWarning() << "unsupported aircraft launch URL" << m_selectedAircraft;
824         }
825
826       // manage aircraft history
827         if (m_recentAircraft.contains(m_selectedAircraft))
828           m_recentAircraft.removeOne(m_selectedAircraft);
829         m_recentAircraft.prepend(m_selectedAircraft);
830         if (m_recentAircraft.size() > MAX_RECENT_AIRCRAFT)
831           m_recentAircraft.pop_back();
832     }
833
834     m_ui->location->setLocationOptions();
835
836     // time of day
837     if (m_ui->timeOfDayCombo->currentIndex() != 0) {
838         QString dayval = m_ui->timeOfDayCombo->currentText().toLower();
839         opt->addOption("timeofday", dayval.toStdString());
840     }
841
842     if (m_ui->seasonCombo->currentIndex() != 0) {
843         QString seasonName = m_ui->seasonCombo->currentText().toLower();
844         opt->addOption("season", seasonName.toStdString());
845     }
846
847     QSettings settings;
848     QString downloadDir = settings.value("download-dir").toString();
849     if (!downloadDir.isEmpty()) {
850         QDir d(downloadDir);
851         if (!d.exists()) {
852             int result = QMessageBox::question(this, tr("Create download folder?"),
853                                   tr("The selected location for downloads does not exist. Create it?"),
854                                                QMessageBox::Yes | QMessageBox::No | QMessageBox::Cancel);
855             if (result == QMessageBox::Cancel) {
856                 return;
857             }
858
859             if (result == QMessageBox::Yes) {
860                 d.mkpath(downloadDir);
861             }
862         }
863
864         opt->addOption("download-dir", downloadDir.toStdString());
865     }
866
867     // scenery paths
868     Q_FOREACH(QString path, settings.value("scenery-paths").toStringList()) {
869         opt->addOption("fg-scenery", path.toStdString());
870     }
871
872     // aircraft paths
873     Q_FOREACH(QString path, settings.value("aircraft-paths").toStringList()) {
874         // can't use fg-aircraft for this, as it is processed before the launcher is run
875         globals->append_aircraft_path(path.toStdString());
876     }
877
878     // additional arguments
879     ArgumentsTokenizer tk;
880     Q_FOREACH(ArgumentsTokenizer::Arg a, tk.tokenize(m_ui->commandLineArgs->toPlainText())) {
881         if (a.arg.startsWith("prop:")) {
882             QString v = a.arg.mid(5) + "=" + a.value;
883             opt->addOption("prop", v.toStdString());
884         } else {
885             opt->addOption(a.arg.toStdString(), a.value.toStdString());
886         }
887     }
888
889     if (settings.contains("restore-defaults-on-run")) {
890         settings.remove("restore-defaults-on-run");
891         opt->addOption("restore-defaults", "");
892     }
893
894     saveSettings();
895
896     qApp->exit(0);
897 }
898
899
900 void QtLauncher::onApply()
901 {
902     accept();
903
904     // aircraft
905     if (!m_selectedAircraft.isEmpty()) {
906         std::string aircraftPropValue,
907             aircraftDir;
908
909         if (m_selectedAircraft.isLocalFile()) {
910             QFileInfo setFileInfo(m_selectedAircraft.toLocalFile());
911             QString setFile = setFileInfo.fileName();
912             Q_ASSERT(setFile.endsWith("-set.xml"));
913             setFile.truncate(setFile.count() - 8); // drop the '-set.xml' portion
914             aircraftDir = setFileInfo.dir().absolutePath().toStdString();
915             aircraftPropValue = setFile.toStdString();
916         } else if (m_selectedAircraft.scheme() == "package") {
917             // no need to set aircraft-dir, handled by the corresponding code
918             // in fgInitAircraft
919             aircraftPropValue = m_selectedAircraft.path().toStdString();
920         } else {
921             qWarning() << "unsupported aircraft launch URL" << m_selectedAircraft;
922         }
923
924         // manage aircraft history
925         if (m_recentAircraft.contains(m_selectedAircraft))
926             m_recentAircraft.removeOne(m_selectedAircraft);
927         m_recentAircraft.prepend(m_selectedAircraft);
928         if (m_recentAircraft.size() > MAX_RECENT_AIRCRAFT)
929             m_recentAircraft.pop_back();
930
931         globals->get_props()->setStringValue("/sim/aircraft", aircraftPropValue);
932         globals->get_props()->setStringValue("/sim/aircraft-dir", aircraftDir);
933     }
934
935
936     saveSettings();
937 }
938
939 void QtLauncher::onQuit()
940 {
941     qApp->exit(-1);
942 }
943
944 void QtLauncher::onToggleTerrasync(bool enabled)
945 {
946     if (enabled) {
947         QSettings settings;
948         QString downloadDir = settings.value("download-dir").toString();
949         if (downloadDir.isEmpty()) {
950             downloadDir = QString::fromStdString(flightgear::defaultDownloadDir());
951         }
952
953         QFileInfo info(downloadDir);
954         if (!info.exists()) {
955             QMessageBox msg;
956             msg.setWindowTitle(tr("Create download folder?"));
957             msg.setText(tr("The download folder '%1' does not exist, create it now?").arg(downloadDir));
958             msg.addButton(QMessageBox::Yes);
959             msg.addButton(QMessageBox::Cancel);
960             int result = msg.exec();
961
962             if (result == QMessageBox::Cancel) {
963                 m_ui->terrasyncCheck->setChecked(false);
964                 return;
965             }
966
967             QDir d(downloadDir);
968             d.mkpath(downloadDir);
969         }
970     } // of is enabled
971 }
972
973 void QtLauncher::onAircraftInstalledCompleted(QModelIndex index)
974 {
975     maybeUpdateSelectedAircraft(index);
976 }
977
978 void QtLauncher::onRatingsFilterToggled()
979 {
980     QModelIndex aircraftIndex = m_aircraftModel->indexOfAircraftURI(m_selectedAircraft);
981     QModelIndex proxyIndex = m_aircraftProxy->mapFromSource(aircraftIndex);
982     if (proxyIndex.isValid()) {
983         m_ui->aircraftList->scrollTo(proxyIndex);
984     }
985 }
986
987 void QtLauncher::onAircraftInstallFailed(QModelIndex index, QString errorMessage)
988 {
989     qWarning() << Q_FUNC_INFO << index.data(AircraftURIRole) << errorMessage;
990
991     QMessageBox msg;
992     msg.setWindowTitle(tr("Aircraft installation failed"));
993     msg.setText(tr("An error occurred installing the aircraft %1: %2").
994                 arg(index.data(Qt::DisplayRole).toString()).arg(errorMessage));
995     msg.addButton(QMessageBox::Ok);
996     msg.exec();
997
998     maybeUpdateSelectedAircraft(index);
999 }
1000
1001 void QtLauncher::onAircraftSelected(const QModelIndex& index)
1002 {
1003     m_selectedAircraft = index.data(AircraftURIRole).toUrl();
1004     updateSelectedAircraft();
1005 }
1006
1007 void QtLauncher::onRequestPackageInstall(const QModelIndex& index)
1008 {
1009     // also select, otherwise UI is confusing
1010     m_selectedAircraft = index.data(AircraftURIRole).toUrl();
1011     updateSelectedAircraft();
1012
1013     QString pkg = index.data(AircraftPackageIdRole).toString();
1014     simgear::pkg::PackageRef pref = globals->packageRoot()->getPackageById(pkg.toStdString());
1015     if (pref->isInstalled()) {
1016         InstallRef install = pref->existingInstall();
1017         if (install && install->hasUpdate()) {
1018             globals->packageRoot()->scheduleToUpdate(install);
1019         }
1020     } else {
1021         pref->install();
1022     }
1023 }
1024
1025 void QtLauncher::onCancelDownload(const QModelIndex& index)
1026 {
1027     QString pkg = index.data(AircraftPackageIdRole).toString();
1028     simgear::pkg::PackageRef pref = globals->packageRoot()->getPackageById(pkg.toStdString());
1029     simgear::pkg::InstallRef i = pref->existingInstall();
1030     i->cancelDownload();
1031 }
1032
1033 void QtLauncher::onRestoreDefaults()
1034 {
1035     QMessageBox mbox(this);
1036     mbox.setText(tr("Restore all settings to defaults?"));
1037     mbox.setInformativeText(tr("Restoring settings to their defaults may affect available add-ons such as scenery or aircraft."));
1038     QPushButton* quitButton = mbox.addButton(tr("Restore and restart now"), QMessageBox::YesRole);
1039     mbox.addButton(QMessageBox::Cancel);
1040     mbox.setDefaultButton(QMessageBox::Cancel);
1041     mbox.setIconPixmap(QPixmap(":/app-icon-large"));
1042
1043     mbox.exec();
1044     if (mbox.clickedButton() != quitButton) {
1045         return;
1046     }
1047
1048     {
1049         QSettings settings;
1050         settings.clear();
1051         settings.setValue("restore-defaults-on-run", true);
1052     }
1053
1054     restartTheApp(QStringList());
1055 }
1056
1057 void QtLauncher::maybeUpdateSelectedAircraft(QModelIndex index)
1058 {
1059     QUrl u = index.data(AircraftURIRole).toUrl();
1060     if (u == m_selectedAircraft) {
1061         // potentially enable the run button now!
1062         updateSelectedAircraft();
1063     }
1064 }
1065
1066 void QtLauncher::updateSelectedAircraft()
1067 {
1068     QModelIndex index = m_aircraftModel->indexOfAircraftURI(m_selectedAircraft);
1069     if (index.isValid()) {
1070         QPixmap pm = index.data(Qt::DecorationRole).value<QPixmap>();
1071         m_ui->thumbnail->setPixmap(pm);
1072         m_ui->aircraftDescription->setText(index.data(Qt::DisplayRole).toString());
1073
1074         int status = index.data(AircraftPackageStatusRole).toInt();
1075         bool canRun = (status == PackageInstalled);
1076         m_ui->runButton->setEnabled(canRun);
1077
1078         LauncherAircraftType aircraftType = Airplane;
1079         if (index.data(AircraftIsHelicopterRole).toBool()) {
1080             aircraftType = Helicopter;
1081         } else if (index.data(AircraftIsSeaplaneRole).toBool()) {
1082             aircraftType = Seaplane;
1083         }
1084
1085         m_ui->location->setAircraftType(aircraftType);
1086     } else {
1087         m_ui->thumbnail->setPixmap(QPixmap());
1088         m_ui->aircraftDescription->setText("");
1089         m_ui->runButton->setEnabled(false);
1090     }
1091 }
1092
1093 QModelIndex QtLauncher::proxyIndexForAircraftURI(QUrl uri) const
1094 {
1095   return m_aircraftProxy->mapFromSource(sourceIndexForAircraftURI(uri));
1096 }
1097
1098 QModelIndex QtLauncher::sourceIndexForAircraftURI(QUrl uri) const
1099 {
1100     AircraftItemModel* sourceModel = qobject_cast<AircraftItemModel*>(m_aircraftProxy->sourceModel());
1101     Q_ASSERT(sourceModel);
1102     return sourceModel->indexOfAircraftURI(uri);
1103 }
1104
1105 void QtLauncher::onPopupAircraftHistory()
1106 {
1107     if (m_recentAircraft.isEmpty()) {
1108         return;
1109     }
1110
1111     QMenu m;
1112     Q_FOREACH(QUrl uri, m_recentAircraft) {
1113         QModelIndex index = sourceIndexForAircraftURI(uri);
1114         if (!index.isValid()) {
1115             // not scanned yet
1116             continue;
1117         }
1118         QAction* act = m.addAction(index.data(Qt::DisplayRole).toString());
1119         act->setData(uri);
1120     }
1121
1122     QPoint popupPos = m_ui->aircraftHistory->mapToGlobal(m_ui->aircraftHistory->rect().bottomLeft());
1123     QAction* triggered = m.exec(popupPos);
1124     if (triggered) {
1125         m_selectedAircraft = triggered->data().toUrl();
1126         QModelIndex index = proxyIndexForAircraftURI(m_selectedAircraft);
1127         m_ui->aircraftList->selectionModel()->setCurrentIndex(index,
1128                                                               QItemSelectionModel::ClearAndSelect);
1129         m_ui->aircraftFilter->clear();
1130         updateSelectedAircraft();
1131     }
1132 }
1133
1134 void QtLauncher::onEditRatingsFilter()
1135 {
1136     EditRatingsFilterDialog dialog(this);
1137     dialog.setRatings(m_ratingFilters);
1138
1139     dialog.exec();
1140     if (dialog.result() == QDialog::Accepted) {
1141         QVariantList vl;
1142         for (int i=0; i<4; ++i) {
1143             m_ratingFilters[i] = dialog.getRating(i);
1144             vl.append(m_ratingFilters[i]);
1145         }
1146         m_aircraftProxy->setRatings(m_ratingFilters);
1147
1148         QSettings settings;
1149         settings.setValue("min-ratings", vl);
1150     }
1151 }
1152
1153 void QtLauncher::updateSettingsSummary()
1154 {
1155     QStringList summary;
1156     if (m_ui->timeOfDayCombo->currentIndex() > 0) {
1157         summary.append(QString(m_ui->timeOfDayCombo->currentText().toLower()));
1158     }
1159
1160     if (m_ui->seasonCombo->currentIndex() > 0) {
1161         summary.append(QString(m_ui->seasonCombo->currentText().toLower()));
1162     }
1163
1164     if (m_ui->rembrandtCheckbox->isChecked()) {
1165         summary.append("Rembrandt enabled");
1166     } else if (m_ui->msaaCheckbox->isChecked()) {
1167         summary.append("anti-aliasing");
1168     }
1169
1170     if (m_ui->fetchRealWxrCheckbox->isChecked()) {
1171         summary.append("live weather");
1172     }
1173
1174     if (m_ui->terrasyncCheck->isChecked()) {
1175         summary.append("automatic scenery downloads");
1176     }
1177
1178     if (m_ui->startPausedCheck->isChecked()) {
1179         summary.append("paused");
1180     }
1181
1182     QString s = summary.join(", ");
1183     s[0] = s[0].toUpper();
1184     m_ui->settingsDescription->setText(s);
1185 }
1186
1187 void QtLauncher::onRembrandtToggled(bool b)
1188 {
1189     // Rembrandt and multi-sample are exclusive
1190     m_ui->msaaCheckbox->setEnabled(!b);
1191 }
1192
1193 void QtLauncher::onShowInstalledAircraftToggled(bool b)
1194 {
1195     m_ui->ratingsFilterCheck->setEnabled(!b);
1196     maybeRestoreAircraftSelection();
1197 }
1198
1199 void QtLauncher::onSubsytemIdleTimeout()
1200 {
1201     globals->get_subsystem_mgr()->update(0.0);
1202 }
1203
1204 void QtLauncher::onDownloadDirChanged()
1205 {
1206
1207     // replace existing package root
1208     globals->get_subsystem<FGHTTPClient>()->shutdown();
1209     globals->setPackageRoot(simgear::pkg::RootRef());
1210
1211     // create new root with updated download-dir value
1212     fgInitPackageRoot();
1213
1214     globals->get_subsystem<FGHTTPClient>()->init();
1215
1216     QSettings settings;
1217     // re-scan the aircraft list
1218     m_aircraftModel->setPackageRoot(globals->packageRoot());
1219     m_aircraftModel->setPaths(settings.value("aircraft-paths").toStringList());
1220     m_aircraftModel->scanDirs();
1221
1222     checkOfficialCatalogMessage();
1223     
1224     // re-set scenery dirs
1225     setSceneryPaths();
1226 }
1227
1228 void QtLauncher::checkOfficialCatalogMessage()
1229 {
1230     QSettings settings;
1231     bool showOfficialCatalogMesssage = !globals->get_subsystem<FGHTTPClient>()->isDefaultCatalogInstalled();
1232     if (settings.value("hide-official-catalog-message").toBool()) {
1233         showOfficialCatalogMesssage = false;
1234     }
1235
1236     m_aircraftModel->setOfficialHangarMessageVisible(showOfficialCatalogMesssage);
1237     if (showOfficialCatalogMesssage) {
1238         NoOfficialHangarMessage* messageWidget = new NoOfficialHangarMessage;
1239         connect(messageWidget, &NoOfficialHangarMessage::linkActivated,
1240                 this, &QtLauncher::onOfficialCatalogMessageLink);
1241
1242         QModelIndex index = m_aircraftProxy->mapFromSource(m_aircraftModel->officialHangarMessageIndex());
1243         m_ui->aircraftList->setIndexWidget(index, messageWidget);
1244     }
1245 }
1246
1247 void QtLauncher::onOfficialCatalogMessageLink(QUrl link)
1248 {
1249     QString s = link.toString();
1250     if (s == "action:hide") {
1251         QSettings settings;
1252         settings.setValue("hide-official-catalog-message", true);
1253     } else if (s == "action:add-official") {
1254         AddOnsPage::addDefaultCatalog(this);
1255     }
1256
1257     checkOfficialCatalogMessage();
1258 }
1259
1260 simgear::pkg::PackageRef QtLauncher::packageForAircraftURI(QUrl uri) const
1261 {
1262     if (uri.scheme() != "package") {
1263         qWarning() << "invalid URL scheme:" << uri;
1264         return simgear::pkg::PackageRef();
1265     }
1266
1267     QString ident = uri.path();
1268     return globals->packageRoot()->getPackageById(ident.toStdString());
1269 }
1270
1271 void QtLauncher::restartTheApp(QStringList fgArgs)
1272 {
1273     // Spawn a new instance of myApplication:
1274     QProcess proc;
1275     QStringList args;
1276
1277 #if defined(Q_OS_MAC)
1278     QDir dir(qApp->applicationDirPath()); // returns the 'MacOS' dir
1279     dir.cdUp(); // up to 'contents' dir
1280     dir.cdUp(); // up to .app dir
1281     // see 'man open' for details, but '-n' ensures we launch a new instance,
1282     // and we want to pass remaining arguments to us, not open.
1283     args << "-n" << dir.absolutePath() << "--args" << "--launcher" << fgArgs;
1284     qDebug() << "args" << args;
1285     proc.startDetached("open", args);
1286 #else
1287     args << "--launcher" << fgArgs;
1288     proc.startDetached(qApp->applicationFilePath(), args);
1289 #endif
1290     qApp->exit(-1);
1291 }
1292
1293 #include "QtLauncher.moc"