]> git.mxchange.org Git - flightgear.git/blob - src/GUI/QtLauncher.cxx
Code cleanups, code updates and fix at least on (possible) devide-by-zero
[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.str());
659     }
660
661 }
662
663 void QtLauncher::setInAppMode()
664 {
665   m_inAppMode = true;
666   m_ui->tabWidget->removeTab(2);
667   m_ui->runButton->setText(tr("Apply"));
668   m_ui->quitButton->setText(tr("Cancel"));
669
670   disconnect(m_ui->runButton, SIGNAL(clicked()), this, SLOT(onRun()));
671   connect(m_ui->runButton, SIGNAL(clicked()), this, SLOT(onApply()));
672 }
673
674 void QtLauncher::restoreSettings()
675 {
676     QSettings settings;
677     m_ui->rembrandtCheckbox->setChecked(settings.value("enable-rembrandt", false).toBool());
678     m_ui->terrasyncCheck->setChecked(settings.value("enable-terrasync", true).toBool());
679     m_ui->fullScreenCheckbox->setChecked(settings.value("start-fullscreen", false).toBool());
680     m_ui->msaaCheckbox->setChecked(settings.value("enable-msaa", false).toBool());
681     m_ui->fetchRealWxrCheckbox->setChecked(settings.value("enable-realwx", true).toBool());
682     m_ui->startPausedCheck->setChecked(settings.value("start-paused", false).toBool());
683     m_ui->timeOfDayCombo->setCurrentIndex(settings.value("timeofday", 0).toInt());
684     m_ui->seasonCombo->setCurrentIndex(settings.value("season", 0).toInt());
685
686     // full paths to -set.xml files
687     m_recentAircraft = QUrl::fromStringList(settings.value("recent-aircraft").toStringList());
688
689     if (!m_recentAircraft.empty()) {
690         m_selectedAircraft = m_recentAircraft.front();
691     } else {
692         // select the default C172p
693     }
694
695     if (!m_inAppMode) {
696         setSceneryPaths();
697     }
698
699     m_ui->location->restoreSettings();
700
701     // rating filters
702     m_ui->onlyShowInstalledCheck->setChecked(settings.value("only-show-installed", false).toBool());
703     if (m_ui->onlyShowInstalledCheck->isChecked()) {
704         m_ui->ratingsFilterCheck->setEnabled(false);
705     }
706
707     m_ui->ratingsFilterCheck->setChecked(settings.value("ratings-filter", true).toBool());
708     int index = 0;
709     Q_FOREACH(QVariant v, settings.value("min-ratings").toList()) {
710         m_ratingFilters[index++] = v.toInt();
711     }
712
713     m_aircraftProxy->setRatingFilterEnabled(m_ui->ratingsFilterCheck->isChecked());
714     m_aircraftProxy->setRatings(m_ratingFilters);
715
716     updateSelectedAircraft();
717     maybeRestoreAircraftSelection();
718
719     m_ui->commandLineArgs->setPlainText(settings.value("additional-args").toString());
720 }
721
722 void QtLauncher::delayedAircraftModelReset()
723 {
724     QTimer::singleShot(1, this, SLOT(maybeRestoreAircraftSelection()));
725 }
726
727 void QtLauncher::maybeRestoreAircraftSelection()
728 {
729     QModelIndex aircraftIndex = m_aircraftModel->indexOfAircraftURI(m_selectedAircraft);
730     QModelIndex proxyIndex = m_aircraftProxy->mapFromSource(aircraftIndex);
731     if (proxyIndex.isValid()) {
732         m_ui->aircraftList->selectionModel()->setCurrentIndex(proxyIndex,
733                                                               QItemSelectionModel::ClearAndSelect);
734         m_ui->aircraftList->selectionModel()->select(proxyIndex,
735                                                      QItemSelectionModel::ClearAndSelect);
736         m_ui->aircraftList->scrollTo(proxyIndex);
737     }
738 }
739
740 void QtLauncher::saveSettings()
741 {
742     QSettings settings;
743     settings.setValue("enable-rembrandt", m_ui->rembrandtCheckbox->isChecked());
744     settings.setValue("enable-terrasync", m_ui->terrasyncCheck->isChecked());
745     settings.setValue("enable-msaa", m_ui->msaaCheckbox->isChecked());
746     settings.setValue("start-fullscreen", m_ui->fullScreenCheckbox->isChecked());
747     settings.setValue("enable-realwx", m_ui->fetchRealWxrCheckbox->isChecked());
748     settings.setValue("start-paused", m_ui->startPausedCheck->isChecked());
749     settings.setValue("ratings-filter", m_ui->ratingsFilterCheck->isChecked());
750     settings.setValue("only-show-installed", m_ui->onlyShowInstalledCheck->isChecked());
751     settings.setValue("recent-aircraft", QUrl::toStringList(m_recentAircraft));
752
753     settings.setValue("timeofday", m_ui->timeOfDayCombo->currentIndex());
754     settings.setValue("season", m_ui->seasonCombo->currentIndex());
755     settings.setValue("additional-args", m_ui->commandLineArgs->toPlainText());
756
757     m_ui->location->saveSettings();
758 }
759
760 void QtLauncher::setEnableDisableOptionFromCheckbox(QCheckBox* cbox, QString name) const
761 {
762     flightgear::Options* opt = flightgear::Options::sharedInstance();
763     std::string stdName(name.toStdString());
764     if (cbox->isChecked()) {
765         opt->addOption("enable-" + stdName, "");
766     } else {
767         opt->addOption("disable-" + stdName, "");
768     }
769 }
770
771 void QtLauncher::closeEvent(QCloseEvent *event)
772 {
773     qApp->exit(-1);
774 }
775
776 void QtLauncher::reject()
777 {
778     qApp->exit(-1);
779 }
780
781 void QtLauncher::onRun()
782 {
783     flightgear::Options* opt = flightgear::Options::sharedInstance();
784     setEnableDisableOptionFromCheckbox(m_ui->terrasyncCheck, "terrasync");
785     setEnableDisableOptionFromCheckbox(m_ui->fetchRealWxrCheckbox, "real-weather-fetch");
786     setEnableDisableOptionFromCheckbox(m_ui->rembrandtCheckbox, "rembrandt");
787     setEnableDisableOptionFromCheckbox(m_ui->fullScreenCheckbox, "fullscreen");
788 //    setEnableDisableOptionFromCheckbox(m_ui->startPausedCheck, "freeze");
789
790     bool startPaused = m_ui->startPausedCheck->isChecked() ||
791             m_ui->location->shouldStartPaused();
792     if (startPaused) {
793         opt->addOption("enable-freeze", "");
794     }
795
796     // MSAA is more complex
797     if (!m_ui->rembrandtCheckbox->isChecked()) {
798         if (m_ui->msaaCheckbox->isChecked()) {
799             globals->get_props()->setIntValue("/sim/rendering/multi-sample-buffers", 1);
800             globals->get_props()->setIntValue("/sim/rendering/multi-samples", 4);
801         } else {
802             globals->get_props()->setIntValue("/sim/rendering/multi-sample-buffers", 0);
803         }
804     }
805
806     // aircraft
807     if (!m_selectedAircraft.isEmpty()) {
808         if (m_selectedAircraft.isLocalFile()) {
809             QFileInfo setFileInfo(m_selectedAircraft.toLocalFile());
810             opt->addOption("aircraft-dir", setFileInfo.dir().absolutePath().toStdString());
811             QString setFile = setFileInfo.fileName();
812             Q_ASSERT(setFile.endsWith("-set.xml"));
813             setFile.truncate(setFile.count() - 8); // drop the '-set.xml' portion
814             opt->addOption("aircraft", setFile.toStdString());
815         } else if (m_selectedAircraft.scheme() == "package") {
816             QString qualifiedId = m_selectedAircraft.path();
817             // no need to set aircraft-dir, handled by the corresponding code
818             // in fgInitAircraft
819             opt->addOption("aircraft", qualifiedId.toStdString());
820         } else {
821             qWarning() << "unsupported aircraft launch URL" << m_selectedAircraft;
822         }
823
824       // manage aircraft history
825         if (m_recentAircraft.contains(m_selectedAircraft))
826           m_recentAircraft.removeOne(m_selectedAircraft);
827         m_recentAircraft.prepend(m_selectedAircraft);
828         if (m_recentAircraft.size() > MAX_RECENT_AIRCRAFT)
829           m_recentAircraft.pop_back();
830     }
831
832     m_ui->location->setLocationOptions();
833
834     // time of day
835     if (m_ui->timeOfDayCombo->currentIndex() != 0) {
836         QString dayval = m_ui->timeOfDayCombo->currentText().toLower();
837         opt->addOption("timeofday", dayval.toStdString());
838     }
839
840     if (m_ui->seasonCombo->currentIndex() != 0) {
841         QString seasonName = m_ui->seasonCombo->currentText().toLower();
842         opt->addOption("season", seasonName.toStdString());
843     }
844
845     QSettings settings;
846     QString downloadDir = settings.value("download-dir").toString();
847     if (!downloadDir.isEmpty()) {
848         QDir d(downloadDir);
849         if (!d.exists()) {
850             int result = QMessageBox::question(this, tr("Create download folder?"),
851                                   tr("The selected location for downloads does not exist. Create it?"),
852                                                QMessageBox::Yes | QMessageBox::No | QMessageBox::Cancel);
853             if (result == QMessageBox::Cancel) {
854                 return;
855             }
856
857             if (result == QMessageBox::Yes) {
858                 d.mkpath(downloadDir);
859             }
860         }
861
862         opt->addOption("download-dir", downloadDir.toStdString());
863     }
864
865     // scenery paths
866     Q_FOREACH(QString path, settings.value("scenery-paths").toStringList()) {
867         opt->addOption("fg-scenery", path.toStdString());
868     }
869
870     // aircraft paths
871     Q_FOREACH(QString path, settings.value("aircraft-paths").toStringList()) {
872         // can't use fg-aircraft for this, as it is processed before the launcher is run
873         globals->append_aircraft_path(path.toStdString());
874     }
875
876     // additional arguments
877     ArgumentsTokenizer tk;
878     Q_FOREACH(ArgumentsTokenizer::Arg a, tk.tokenize(m_ui->commandLineArgs->toPlainText())) {
879         if (a.arg.startsWith("prop:")) {
880             QString v = a.arg.mid(5) + "=" + a.value;
881             opt->addOption("prop", v.toStdString());
882         } else {
883             opt->addOption(a.arg.toStdString(), a.value.toStdString());
884         }
885     }
886
887     if (settings.contains("restore-defaults-on-run")) {
888         settings.remove("restore-defaults-on-run");
889         opt->addOption("restore-defaults", "");
890     }
891
892     saveSettings();
893
894     qApp->exit(0);
895 }
896
897
898 void QtLauncher::onApply()
899 {
900     accept();
901
902     // aircraft
903     if (!m_selectedAircraft.isEmpty()) {
904         std::string aircraftPropValue,
905             aircraftDir;
906
907         if (m_selectedAircraft.isLocalFile()) {
908             QFileInfo setFileInfo(m_selectedAircraft.toLocalFile());
909             QString setFile = setFileInfo.fileName();
910             Q_ASSERT(setFile.endsWith("-set.xml"));
911             setFile.truncate(setFile.count() - 8); // drop the '-set.xml' portion
912             aircraftDir = setFileInfo.dir().absolutePath().toStdString();
913             aircraftPropValue = setFile.toStdString();
914         } else if (m_selectedAircraft.scheme() == "package") {
915             // no need to set aircraft-dir, handled by the corresponding code
916             // in fgInitAircraft
917             aircraftPropValue = m_selectedAircraft.path().toStdString();
918         } else {
919             qWarning() << "unsupported aircraft launch URL" << m_selectedAircraft;
920         }
921
922         // manage aircraft history
923         if (m_recentAircraft.contains(m_selectedAircraft))
924             m_recentAircraft.removeOne(m_selectedAircraft);
925         m_recentAircraft.prepend(m_selectedAircraft);
926         if (m_recentAircraft.size() > MAX_RECENT_AIRCRAFT)
927             m_recentAircraft.pop_back();
928
929         globals->get_props()->setStringValue("/sim/aircraft", aircraftPropValue);
930         globals->get_props()->setStringValue("/sim/aircraft-dir", aircraftDir);
931     }
932
933
934     saveSettings();
935 }
936
937 void QtLauncher::onQuit()
938 {
939     qApp->exit(-1);
940 }
941
942 void QtLauncher::onToggleTerrasync(bool enabled)
943 {
944     if (enabled) {
945         QSettings settings;
946         QString downloadDir = settings.value("download-dir").toString();
947         if (downloadDir.isEmpty()) {
948             downloadDir = QString::fromStdString(flightgear::defaultDownloadDir());
949         }
950
951         QFileInfo info(downloadDir);
952         if (!info.exists()) {
953             QMessageBox msg;
954             msg.setWindowTitle(tr("Create download folder?"));
955             msg.setText(tr("The download folder '%1' does not exist, create it now?").arg(downloadDir));
956             msg.addButton(QMessageBox::Yes);
957             msg.addButton(QMessageBox::Cancel);
958             int result = msg.exec();
959
960             if (result == QMessageBox::Cancel) {
961                 m_ui->terrasyncCheck->setChecked(false);
962                 return;
963             }
964
965             QDir d(downloadDir);
966             d.mkpath(downloadDir);
967         }
968     } // of is enabled
969 }
970
971 void QtLauncher::onAircraftInstalledCompleted(QModelIndex index)
972 {
973     maybeUpdateSelectedAircraft(index);
974 }
975
976 void QtLauncher::onRatingsFilterToggled()
977 {
978     QModelIndex aircraftIndex = m_aircraftModel->indexOfAircraftURI(m_selectedAircraft);
979     QModelIndex proxyIndex = m_aircraftProxy->mapFromSource(aircraftIndex);
980     if (proxyIndex.isValid()) {
981         m_ui->aircraftList->scrollTo(proxyIndex);
982     }
983 }
984
985 void QtLauncher::onAircraftInstallFailed(QModelIndex index, QString errorMessage)
986 {
987     qWarning() << Q_FUNC_INFO << index.data(AircraftURIRole) << errorMessage;
988
989     QMessageBox msg;
990     msg.setWindowTitle(tr("Aircraft installation failed"));
991     msg.setText(tr("An error occurred installing the aircraft %1: %2").
992                 arg(index.data(Qt::DisplayRole).toString()).arg(errorMessage));
993     msg.addButton(QMessageBox::Ok);
994     msg.exec();
995
996     maybeUpdateSelectedAircraft(index);
997 }
998
999 void QtLauncher::onAircraftSelected(const QModelIndex& index)
1000 {
1001     m_selectedAircraft = index.data(AircraftURIRole).toUrl();
1002     updateSelectedAircraft();
1003 }
1004
1005 void QtLauncher::onRequestPackageInstall(const QModelIndex& index)
1006 {
1007     // also select, otherwise UI is confusing
1008     m_selectedAircraft = index.data(AircraftURIRole).toUrl();
1009     updateSelectedAircraft();
1010
1011     QString pkg = index.data(AircraftPackageIdRole).toString();
1012     simgear::pkg::PackageRef pref = globals->packageRoot()->getPackageById(pkg.toStdString());
1013     if (pref->isInstalled()) {
1014         InstallRef install = pref->existingInstall();
1015         if (install && install->hasUpdate()) {
1016             globals->packageRoot()->scheduleToUpdate(install);
1017         }
1018     } else {
1019         pref->install();
1020     }
1021 }
1022
1023 void QtLauncher::onCancelDownload(const QModelIndex& index)
1024 {
1025     QString pkg = index.data(AircraftPackageIdRole).toString();
1026     simgear::pkg::PackageRef pref = globals->packageRoot()->getPackageById(pkg.toStdString());
1027     simgear::pkg::InstallRef i = pref->existingInstall();
1028     i->cancelDownload();
1029 }
1030
1031 void QtLauncher::onRestoreDefaults()
1032 {
1033     QMessageBox mbox(this);
1034     mbox.setText(tr("Restore all settings to defaults?"));
1035     mbox.setInformativeText(tr("Restoring settings to their defaults may affect available add-ons such as scenery or aircraft."));
1036     QPushButton* quitButton = mbox.addButton(tr("Restore and restart now"), QMessageBox::YesRole);
1037     mbox.addButton(QMessageBox::Cancel);
1038     mbox.setDefaultButton(QMessageBox::Cancel);
1039     mbox.setIconPixmap(QPixmap(":/app-icon-large"));
1040
1041     mbox.exec();
1042     if (mbox.clickedButton() != quitButton) {
1043         return;
1044     }
1045
1046     {
1047         QSettings settings;
1048         settings.clear();
1049         settings.setValue("restore-defaults-on-run", true);
1050     }
1051
1052     restartTheApp(QStringList());
1053 }
1054
1055 void QtLauncher::maybeUpdateSelectedAircraft(QModelIndex index)
1056 {
1057     QUrl u = index.data(AircraftURIRole).toUrl();
1058     if (u == m_selectedAircraft) {
1059         // potentially enable the run button now!
1060         updateSelectedAircraft();
1061     }
1062 }
1063
1064 void QtLauncher::updateSelectedAircraft()
1065 {
1066     QModelIndex index = m_aircraftModel->indexOfAircraftURI(m_selectedAircraft);
1067     if (index.isValid()) {
1068         QPixmap pm = index.data(Qt::DecorationRole).value<QPixmap>();
1069         m_ui->thumbnail->setPixmap(pm);
1070         m_ui->aircraftDescription->setText(index.data(Qt::DisplayRole).toString());
1071
1072         int status = index.data(AircraftPackageStatusRole).toInt();
1073         bool canRun = (status == PackageInstalled);
1074         m_ui->runButton->setEnabled(canRun);
1075
1076         LauncherAircraftType aircraftType = Airplane;
1077         if (index.data(AircraftIsHelicopterRole).toBool()) {
1078             aircraftType = Helicopter;
1079         } else if (index.data(AircraftIsSeaplaneRole).toBool()) {
1080             aircraftType = Seaplane;
1081         }
1082
1083         m_ui->location->setAircraftType(aircraftType);
1084     } else {
1085         m_ui->thumbnail->setPixmap(QPixmap());
1086         m_ui->aircraftDescription->setText("");
1087         m_ui->runButton->setEnabled(false);
1088     }
1089 }
1090
1091 QModelIndex QtLauncher::proxyIndexForAircraftURI(QUrl uri) const
1092 {
1093   return m_aircraftProxy->mapFromSource(sourceIndexForAircraftURI(uri));
1094 }
1095
1096 QModelIndex QtLauncher::sourceIndexForAircraftURI(QUrl uri) const
1097 {
1098     AircraftItemModel* sourceModel = qobject_cast<AircraftItemModel*>(m_aircraftProxy->sourceModel());
1099     Q_ASSERT(sourceModel);
1100     return sourceModel->indexOfAircraftURI(uri);
1101 }
1102
1103 void QtLauncher::onPopupAircraftHistory()
1104 {
1105     if (m_recentAircraft.isEmpty()) {
1106         return;
1107     }
1108
1109     QMenu m;
1110     Q_FOREACH(QUrl uri, m_recentAircraft) {
1111         QModelIndex index = sourceIndexForAircraftURI(uri);
1112         if (!index.isValid()) {
1113             // not scanned yet
1114             continue;
1115         }
1116         QAction* act = m.addAction(index.data(Qt::DisplayRole).toString());
1117         act->setData(uri);
1118     }
1119
1120     QPoint popupPos = m_ui->aircraftHistory->mapToGlobal(m_ui->aircraftHistory->rect().bottomLeft());
1121     QAction* triggered = m.exec(popupPos);
1122     if (triggered) {
1123         m_selectedAircraft = triggered->data().toUrl();
1124         QModelIndex index = proxyIndexForAircraftURI(m_selectedAircraft);
1125         m_ui->aircraftList->selectionModel()->setCurrentIndex(index,
1126                                                               QItemSelectionModel::ClearAndSelect);
1127         m_ui->aircraftFilter->clear();
1128         updateSelectedAircraft();
1129     }
1130 }
1131
1132 void QtLauncher::onEditRatingsFilter()
1133 {
1134     EditRatingsFilterDialog dialog(this);
1135     dialog.setRatings(m_ratingFilters);
1136
1137     dialog.exec();
1138     if (dialog.result() == QDialog::Accepted) {
1139         QVariantList vl;
1140         for (int i=0; i<4; ++i) {
1141             m_ratingFilters[i] = dialog.getRating(i);
1142             vl.append(m_ratingFilters[i]);
1143         }
1144         m_aircraftProxy->setRatings(m_ratingFilters);
1145
1146         QSettings settings;
1147         settings.setValue("min-ratings", vl);
1148     }
1149 }
1150
1151 void QtLauncher::updateSettingsSummary()
1152 {
1153     QStringList summary;
1154     if (m_ui->timeOfDayCombo->currentIndex() > 0) {
1155         summary.append(QString(m_ui->timeOfDayCombo->currentText().toLower()));
1156     }
1157
1158     if (m_ui->seasonCombo->currentIndex() > 0) {
1159         summary.append(QString(m_ui->seasonCombo->currentText().toLower()));
1160     }
1161
1162     if (m_ui->rembrandtCheckbox->isChecked()) {
1163         summary.append("Rembrandt enabled");
1164     } else if (m_ui->msaaCheckbox->isChecked()) {
1165         summary.append("anti-aliasing");
1166     }
1167
1168     if (m_ui->fetchRealWxrCheckbox->isChecked()) {
1169         summary.append("live weather");
1170     }
1171
1172     if (m_ui->terrasyncCheck->isChecked()) {
1173         summary.append("automatic scenery downloads");
1174     }
1175
1176     if (m_ui->startPausedCheck->isChecked()) {
1177         summary.append("paused");
1178     }
1179
1180     QString s = summary.join(", ");
1181     s[0] = s[0].toUpper();
1182     m_ui->settingsDescription->setText(s);
1183 }
1184
1185 void QtLauncher::onRembrandtToggled(bool b)
1186 {
1187     // Rembrandt and multi-sample are exclusive
1188     m_ui->msaaCheckbox->setEnabled(!b);
1189 }
1190
1191 void QtLauncher::onShowInstalledAircraftToggled(bool b)
1192 {
1193     m_ui->ratingsFilterCheck->setEnabled(!b);
1194     maybeRestoreAircraftSelection();
1195 }
1196
1197 void QtLauncher::onSubsytemIdleTimeout()
1198 {
1199     globals->get_subsystem_mgr()->update(0.0);
1200 }
1201
1202 void QtLauncher::onDownloadDirChanged()
1203 {
1204
1205     // replace existing package root
1206     globals->get_subsystem<FGHTTPClient>()->shutdown();
1207     globals->setPackageRoot(simgear::pkg::RootRef());
1208
1209     // create new root with updated download-dir value
1210     fgInitPackageRoot();
1211
1212     globals->get_subsystem<FGHTTPClient>()->init();
1213
1214     QSettings settings;
1215     // re-scan the aircraft list
1216     m_aircraftModel->setPackageRoot(globals->packageRoot());
1217     m_aircraftModel->setPaths(settings.value("aircraft-paths").toStringList());
1218     m_aircraftModel->scanDirs();
1219
1220     checkOfficialCatalogMessage();
1221     
1222     // re-set scenery dirs
1223     setSceneryPaths();
1224 }
1225
1226 void QtLauncher::checkOfficialCatalogMessage()
1227 {
1228     QSettings settings;
1229     bool showOfficialCatalogMesssage = !globals->get_subsystem<FGHTTPClient>()->isDefaultCatalogInstalled();
1230     if (settings.value("hide-official-catalog-message").toBool()) {
1231         showOfficialCatalogMesssage = false;
1232     }
1233
1234     m_aircraftModel->setOfficialHangarMessageVisible(showOfficialCatalogMesssage);
1235     if (showOfficialCatalogMesssage) {
1236         NoOfficialHangarMessage* messageWidget = new NoOfficialHangarMessage;
1237         connect(messageWidget, &NoOfficialHangarMessage::linkActivated,
1238                 this, &QtLauncher::onOfficialCatalogMessageLink);
1239
1240         QModelIndex index = m_aircraftProxy->mapFromSource(m_aircraftModel->officialHangarMessageIndex());
1241         m_ui->aircraftList->setIndexWidget(index, messageWidget);
1242     }
1243 }
1244
1245 void QtLauncher::onOfficialCatalogMessageLink(QUrl link)
1246 {
1247     QString s = link.toString();
1248     if (s == "action:hide") {
1249         QSettings settings;
1250         settings.setValue("hide-official-catalog-message", true);
1251     } else if (s == "action:add-official") {
1252         AddOnsPage::addDefaultCatalog(this);
1253     }
1254
1255     checkOfficialCatalogMessage();
1256 }
1257
1258 simgear::pkg::PackageRef QtLauncher::packageForAircraftURI(QUrl uri) const
1259 {
1260     if (uri.scheme() != "package") {
1261         qWarning() << "invalid URL scheme:" << uri;
1262         return simgear::pkg::PackageRef();
1263     }
1264
1265     QString ident = uri.path();
1266     return globals->packageRoot()->getPackageById(ident.toStdString());
1267 }
1268
1269 void QtLauncher::restartTheApp(QStringList fgArgs)
1270 {
1271     // Spawn a new instance of myApplication:
1272     QProcess proc;
1273     QStringList args;
1274
1275 #if defined(Q_OS_MAC)
1276     QDir dir(qApp->applicationDirPath()); // returns the 'MacOS' dir
1277     dir.cdUp(); // up to 'contents' dir
1278     dir.cdUp(); // up to .app dir
1279     // see 'man open' for details, but '-n' ensures we launch a new instance,
1280     // and we want to pass remaining arguments to us, not open.
1281     args << "-n" << dir.absolutePath() << "--args" << "--launcher" << fgArgs;
1282     qDebug() << "args" << args;
1283     proc.startDetached("open", args);
1284 #else
1285     args << "--launcher" << fgArgs;
1286     proc.startDetached(qApp->applicationFilePath(), args);
1287 #endif
1288     qApp->exit(-1);
1289 }
1290
1291 #include "QtLauncher.moc"