]> git.mxchange.org Git - flightgear.git/blob - src/GUI/QtLauncher.cxx
Testing if this change broke Mac deployment.
[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 #if 0
383         QSettings::setDefaultFormat(QSettings::IniFormat);
384         QSettings::setPath(QSettings::IniFormat, QSettings::UserScope,
385                            QString::fromStdString(globals->get_fg_home()));
386 #endif
387         QApplication* app = new QApplication(s_argc, argv);
388         app->setOrganizationName("FlightGear");
389         app->setApplicationName("FlightGear");
390         app->setOrganizationDomain("flightgear.org");
391
392         // reset numeric / collation locales as described at:
393         // http://doc.qt.io/qt-5/qcoreapplication.html#details
394         ::setlocale(LC_NUMERIC, "C");
395         ::setlocale(LC_COLLATE, "C");
396
397         Qt::KeyboardModifiers mods = app->queryKeyboardModifiers();
398         if (mods & (Qt::AltModifier | Qt::ShiftModifier)) {
399             qWarning() << "Alt/shift pressed during launch";
400             QSettings settings;
401             settings.setValue("fg-root", "!ask");
402         }
403     }
404 }
405
406 void loadNaturalEarthFile(const std::string& aFileName,
407                           flightgear::PolyLine::Type aType,
408                           bool areClosed)
409 {
410     SGPath path(globals->get_fg_root());
411     path.append( "Geodata" );
412     path.append(aFileName);
413     if (!path.exists())
414         return; // silently fail for now
415
416     flightgear::PolyLineList lines;
417     flightgear::SHPParser::parsePolyLines(path, aType, lines, areClosed);
418     flightgear::PolyLine::bulkAddToSpatialIndex(lines);
419 }
420
421 void loadNaturalEarthData()
422 {
423     SGTimeStamp st;
424     st.stamp();
425
426     loadNaturalEarthFile("ne_10m_coastline.shp", flightgear::PolyLine::COASTLINE, false);
427     loadNaturalEarthFile("ne_10m_rivers_lake_centerlines.shp", flightgear::PolyLine::RIVER, false);
428     loadNaturalEarthFile("ne_10m_lakes.shp", flightgear::PolyLine::LAKE, true);
429
430     qDebug() << "load basic data took" << st.elapsedMSec();
431
432
433     st.stamp();
434     loadNaturalEarthFile("ne_10m_urban_areas.shp", flightgear::PolyLine::URBAN, true);
435
436     qDebug() << "loading urban areas took:" << st.elapsedMSec();
437 }
438
439 bool runLauncherDialog()
440 {
441     // startup the nav-cache now. This pre-empts normal startup of
442     // the cache, but no harm done. (Providing scenery paths are consistent)
443
444     initNavCache();
445
446     QSettings settings;
447     QString downloadDir = settings.value("download-dir").toString();
448     if (!downloadDir.isEmpty()) {
449         flightgear::Options::sharedInstance()->setOption("download-dir", downloadDir.toStdString());
450     }
451
452     fgInitPackageRoot();
453
454     // startup the HTTP system now since packages needs it
455     FGHTTPClient* http = globals->add_new_subsystem<FGHTTPClient>();
456     
457     // we guard against re-init in the global phase; bind and postinit
458     // will happen as normal
459     http->init();
460
461     loadNaturalEarthData();
462
463     // avoid double Apple menu and other weirdness if both Qt and OSG
464     // try to initialise various Cocoa structures.
465     flightgear::WindowBuilder::setPoseAsStandaloneApp(false);
466
467     QtLauncher dlg;
468     dlg.show();
469
470     int appResult = qApp->exec();
471     if (appResult < 0) {
472         return false; // quit
473     }
474
475     // don't set scenery paths twice
476     globals->clear_fg_scenery();
477
478     return true;
479 }
480
481 bool runInAppLauncherDialog()
482 {
483     QtLauncher dlg;
484     dlg.setInAppMode();
485     dlg.exec();
486     if (dlg.result() != QDialog::Accepted) {
487         return false;
488     }
489
490     return true;
491 }
492
493 } // of namespace flightgear
494
495 QtLauncher::QtLauncher() :
496     QDialog(),
497     m_ui(NULL),
498     m_subsystemIdleTimer(NULL),
499     m_inAppMode(false)
500 {
501     m_ui.reset(new Ui::Launcher);
502     m_ui->setupUi(this);
503
504 #if QT_VERSION >= 0x050300
505     // don't require Qt 5.3
506     m_ui->commandLineArgs->setPlaceholderText("--option=value --prop:/sim/name=value");
507 #endif
508
509 #if QT_VERSION >= 0x050200
510     m_ui->aircraftFilter->setClearButtonEnabled(true);
511 #endif
512
513     for (int i=0; i<4; ++i) {
514         m_ratingFilters[i] = 3;
515     }
516
517     m_subsystemIdleTimer = new QTimer(this);
518     m_subsystemIdleTimer->setInterval(0);
519     connect(m_subsystemIdleTimer, &QTimer::timeout,
520             this, &QtLauncher::onSubsytemIdleTimeout);
521     m_subsystemIdleTimer->start();
522
523     // create and configure the proxy model
524     m_aircraftProxy = new AircraftProxyModel(this);
525     connect(m_ui->ratingsFilterCheck, &QAbstractButton::toggled,
526             m_aircraftProxy, &AircraftProxyModel::setRatingFilterEnabled);
527     connect(m_ui->ratingsFilterCheck, &QAbstractButton::toggled,
528             this, &QtLauncher::maybeRestoreAircraftSelection);
529
530     connect(m_ui->onlyShowInstalledCheck, &QAbstractButton::toggled,
531             m_aircraftProxy, &AircraftProxyModel::setInstalledFilterEnabled);
532     connect(m_ui->aircraftFilter, &QLineEdit::textChanged,
533             m_aircraftProxy, &QSortFilterProxyModel::setFilterFixedString);
534
535     connect(m_ui->runButton, SIGNAL(clicked()), this, SLOT(onRun()));
536     connect(m_ui->quitButton, SIGNAL(clicked()), this, SLOT(onQuit()));
537
538     connect(m_ui->aircraftHistory, &QPushButton::clicked,
539           this, &QtLauncher::onPopupAircraftHistory);
540
541     connect(m_ui->location, &LocationWidget::descriptionChanged,
542             m_ui->locationDescription, &QLabel::setText);
543
544     QAction* qa = new QAction(this);
545     qa->setShortcut(QKeySequence("Ctrl+Q"));
546     connect(qa, &QAction::triggered, this, &QtLauncher::onQuit);
547     addAction(qa);
548
549     connect(m_ui->editRatingFilter, &QPushButton::clicked,
550             this, &QtLauncher::onEditRatingsFilter);
551     connect(m_ui->onlyShowInstalledCheck, &QCheckBox::toggled,
552             this, &QtLauncher::onShowInstalledAircraftToggled);
553
554     QIcon historyIcon(":/history-icon");
555     m_ui->aircraftHistory->setIcon(historyIcon);
556
557     connect(m_ui->timeOfDayCombo, SIGNAL(currentIndexChanged(int)),
558             this, SLOT(updateSettingsSummary()));
559     connect(m_ui->seasonCombo, SIGNAL(currentIndexChanged(int)),
560             this, SLOT(updateSettingsSummary()));
561     connect(m_ui->fetchRealWxrCheckbox, SIGNAL(toggled(bool)),
562             this, SLOT(updateSettingsSummary()));
563     connect(m_ui->rembrandtCheckbox, SIGNAL(toggled(bool)),
564             this, SLOT(updateSettingsSummary()));
565     connect(m_ui->terrasyncCheck, SIGNAL(toggled(bool)),
566             this, SLOT(updateSettingsSummary()));
567     connect(m_ui->startPausedCheck, SIGNAL(toggled(bool)),
568             this, SLOT(updateSettingsSummary()));
569     connect(m_ui->msaaCheckbox, SIGNAL(toggled(bool)),
570             this, SLOT(updateSettingsSummary()));
571
572     connect(m_ui->rembrandtCheckbox, SIGNAL(toggled(bool)),
573             this, SLOT(onRembrandtToggled(bool)));
574     connect(m_ui->terrasyncCheck, &QCheckBox::toggled,
575             this, &QtLauncher::onToggleTerrasync);
576     updateSettingsSummary();
577
578     m_aircraftModel = new AircraftItemModel(this);
579     m_aircraftProxy->setSourceModel(m_aircraftModel);
580
581     m_aircraftProxy->setFilterCaseSensitivity(Qt::CaseInsensitive);
582     m_aircraftProxy->setSortCaseSensitivity(Qt::CaseInsensitive);
583     m_aircraftProxy->setSortRole(Qt::DisplayRole);
584     m_aircraftProxy->setDynamicSortFilter(true);
585
586     m_ui->aircraftList->setModel(m_aircraftProxy);
587     m_ui->aircraftList->setHorizontalScrollBarPolicy(Qt::ScrollBarAlwaysOff);
588     AircraftItemDelegate* delegate = new AircraftItemDelegate(m_ui->aircraftList);
589     m_ui->aircraftList->setItemDelegate(delegate);
590     m_ui->aircraftList->setSelectionMode(QAbstractItemView::SingleSelection);
591     connect(m_ui->aircraftList, &QListView::clicked,
592             this, &QtLauncher::onAircraftSelected);
593     connect(delegate, &AircraftItemDelegate::variantChanged,
594             this, &QtLauncher::onAircraftSelected);
595     connect(delegate, &AircraftItemDelegate::requestInstall,
596             this, &QtLauncher::onRequestPackageInstall);
597     connect(delegate, &AircraftItemDelegate::cancelDownload,
598             this, &QtLauncher::onCancelDownload);
599
600     connect(m_aircraftModel, &AircraftItemModel::aircraftInstallCompleted,
601             this, &QtLauncher::onAircraftInstalledCompleted);
602     connect(m_aircraftModel, &AircraftItemModel::aircraftInstallFailed,
603             this, &QtLauncher::onAircraftInstallFailed);
604     connect(m_aircraftModel, &AircraftItemModel::scanCompleted,
605             this, &QtLauncher::updateSelectedAircraft);
606     connect(m_ui->restoreDefaultsButton, &QPushButton::clicked,
607             this, &QtLauncher::onRestoreDefaults);
608
609
610     AddOnsPage* addOnsPage = new AddOnsPage(NULL, globals->packageRoot());
611     connect(addOnsPage, &AddOnsPage::downloadDirChanged,
612             this, &QtLauncher::onDownloadDirChanged);
613     connect(addOnsPage, &AddOnsPage::sceneryPathsChanged,
614             this, &QtLauncher::setSceneryPaths);
615
616     m_ui->tabWidget->addTab(addOnsPage, tr("Add-ons"));
617     // after any kind of reset, try to restore selection and scroll
618     // to match the m_selectedAircraft. This needs to be delayed
619     // fractionally otherwise the scrollTo seems to be ignored,
620     // unfortunately.
621     connect(m_aircraftProxy, &AircraftProxyModel::modelReset,
622             this, &QtLauncher::delayedAircraftModelReset);
623
624     QSettings settings;
625     m_aircraftModel->setPaths(settings.value("aircraft-paths").toStringList());
626     m_aircraftModel->setPackageRoot(globals->packageRoot());
627     m_aircraftModel->scanDirs();
628
629     checkOfficialCatalogMessage();
630     restoreSettings();
631 }
632
633 QtLauncher::~QtLauncher()
634 {
635
636 }
637
638 void QtLauncher::setSceneryPaths()
639 {
640     globals->clear_fg_scenery();
641
642 // mimic what optionss.cxx does, so we can find airport data for parking
643 // positions
644     QSettings settings;
645     // append explicit scenery paths
646     Q_FOREACH(QString path, settings.value("scenery-paths").toStringList()) {
647         globals->append_fg_scenery(path.toStdString());
648     }
649
650     // append the TerraSync path
651     QString downloadDir = settings.value("download-dir").toString();
652     if (downloadDir.isEmpty()) {
653         downloadDir = QString::fromStdString(flightgear::defaultDownloadDir());
654     }
655
656     SGPath terraSyncDir(downloadDir.toStdString());
657     terraSyncDir.append("TerraSync");
658     if (terraSyncDir.exists()) {
659         globals->append_fg_scenery(terraSyncDir.str());
660     }
661
662 }
663
664 void QtLauncher::setInAppMode()
665 {
666   m_inAppMode = true;
667   m_ui->tabWidget->removeTab(2);
668   m_ui->runButton->setText(tr("Apply"));
669   m_ui->quitButton->setText(tr("Cancel"));
670
671   disconnect(m_ui->runButton, SIGNAL(clicked()), this, SLOT(onRun()));
672   connect(m_ui->runButton, SIGNAL(clicked()), this, SLOT(onApply()));
673 }
674
675 void QtLauncher::restoreSettings()
676 {
677     QSettings settings;
678     m_ui->rembrandtCheckbox->setChecked(settings.value("enable-rembrandt", false).toBool());
679     m_ui->terrasyncCheck->setChecked(settings.value("enable-terrasync", true).toBool());
680     m_ui->fullScreenCheckbox->setChecked(settings.value("start-fullscreen", false).toBool());
681     m_ui->msaaCheckbox->setChecked(settings.value("enable-msaa", false).toBool());
682     m_ui->fetchRealWxrCheckbox->setChecked(settings.value("enable-realwx", true).toBool());
683     m_ui->startPausedCheck->setChecked(settings.value("start-paused", false).toBool());
684     m_ui->timeOfDayCombo->setCurrentIndex(settings.value("timeofday", 0).toInt());
685     m_ui->seasonCombo->setCurrentIndex(settings.value("season", 0).toInt());
686
687     // full paths to -set.xml files
688     m_recentAircraft = QUrl::fromStringList(settings.value("recent-aircraft").toStringList());
689
690     if (!m_recentAircraft.empty()) {
691         m_selectedAircraft = m_recentAircraft.front();
692     } else {
693         // select the default C172p
694     }
695
696     if (!m_inAppMode) {
697         setSceneryPaths();
698     }
699
700     m_ui->location->restoreSettings();
701
702     // rating filters
703     m_ui->onlyShowInstalledCheck->setChecked(settings.value("only-show-installed", false).toBool());
704     if (m_ui->onlyShowInstalledCheck->isChecked()) {
705         m_ui->ratingsFilterCheck->setEnabled(false);
706     }
707
708     m_ui->ratingsFilterCheck->setChecked(settings.value("ratings-filter", true).toBool());
709     int index = 0;
710     Q_FOREACH(QVariant v, settings.value("min-ratings").toList()) {
711         m_ratingFilters[index++] = v.toInt();
712     }
713
714     m_aircraftProxy->setRatingFilterEnabled(m_ui->ratingsFilterCheck->isChecked());
715     m_aircraftProxy->setRatings(m_ratingFilters);
716
717     updateSelectedAircraft();
718     maybeRestoreAircraftSelection();
719
720     m_ui->commandLineArgs->setPlainText(settings.value("additional-args").toString());
721 }
722
723 void QtLauncher::delayedAircraftModelReset()
724 {
725     QTimer::singleShot(1, this, SLOT(maybeRestoreAircraftSelection()));
726 }
727
728 void QtLauncher::maybeRestoreAircraftSelection()
729 {
730     QModelIndex aircraftIndex = m_aircraftModel->indexOfAircraftURI(m_selectedAircraft);
731     QModelIndex proxyIndex = m_aircraftProxy->mapFromSource(aircraftIndex);
732     if (proxyIndex.isValid()) {
733         m_ui->aircraftList->selectionModel()->setCurrentIndex(proxyIndex,
734                                                               QItemSelectionModel::ClearAndSelect);
735         m_ui->aircraftList->selectionModel()->select(proxyIndex,
736                                                      QItemSelectionModel::ClearAndSelect);
737         m_ui->aircraftList->scrollTo(proxyIndex);
738     }
739 }
740
741 void QtLauncher::saveSettings()
742 {
743     QSettings settings;
744     settings.setValue("enable-rembrandt", m_ui->rembrandtCheckbox->isChecked());
745     settings.setValue("enable-terrasync", m_ui->terrasyncCheck->isChecked());
746     settings.setValue("enable-msaa", m_ui->msaaCheckbox->isChecked());
747     settings.setValue("start-fullscreen", m_ui->fullScreenCheckbox->isChecked());
748     settings.setValue("enable-realwx", m_ui->fetchRealWxrCheckbox->isChecked());
749     settings.setValue("start-paused", m_ui->startPausedCheck->isChecked());
750     settings.setValue("ratings-filter", m_ui->ratingsFilterCheck->isChecked());
751     settings.setValue("only-show-installed", m_ui->onlyShowInstalledCheck->isChecked());
752     settings.setValue("recent-aircraft", QUrl::toStringList(m_recentAircraft));
753
754     settings.setValue("timeofday", m_ui->timeOfDayCombo->currentIndex());
755     settings.setValue("season", m_ui->seasonCombo->currentIndex());
756     settings.setValue("additional-args", m_ui->commandLineArgs->toPlainText());
757
758     m_ui->location->saveSettings();
759 }
760
761 void QtLauncher::setEnableDisableOptionFromCheckbox(QCheckBox* cbox, QString name) const
762 {
763     flightgear::Options* opt = flightgear::Options::sharedInstance();
764     std::string stdName(name.toStdString());
765     if (cbox->isChecked()) {
766         opt->addOption("enable-" + stdName, "");
767     } else {
768         opt->addOption("disable-" + stdName, "");
769     }
770 }
771
772 void QtLauncher::closeEvent(QCloseEvent *event)
773 {
774     qApp->exit(-1);
775 }
776
777 void QtLauncher::reject()
778 {
779     qApp->exit(-1);
780 }
781
782 void QtLauncher::onRun()
783 {
784     flightgear::Options* opt = flightgear::Options::sharedInstance();
785     setEnableDisableOptionFromCheckbox(m_ui->terrasyncCheck, "terrasync");
786     setEnableDisableOptionFromCheckbox(m_ui->fetchRealWxrCheckbox, "real-weather-fetch");
787     setEnableDisableOptionFromCheckbox(m_ui->rembrandtCheckbox, "rembrandt");
788     setEnableDisableOptionFromCheckbox(m_ui->fullScreenCheckbox, "fullscreen");
789 //    setEnableDisableOptionFromCheckbox(m_ui->startPausedCheck, "freeze");
790
791     bool startPaused = m_ui->startPausedCheck->isChecked() ||
792             m_ui->location->shouldStartPaused();
793     if (startPaused) {
794         opt->addOption("enable-freeze", "");
795     }
796
797     // MSAA is more complex
798     if (!m_ui->rembrandtCheckbox->isChecked()) {
799         if (m_ui->msaaCheckbox->isChecked()) {
800             globals->get_props()->setIntValue("/sim/rendering/multi-sample-buffers", 1);
801             globals->get_props()->setIntValue("/sim/rendering/multi-samples", 4);
802         } else {
803             globals->get_props()->setIntValue("/sim/rendering/multi-sample-buffers", 0);
804         }
805     }
806
807     // aircraft
808     if (!m_selectedAircraft.isEmpty()) {
809         if (m_selectedAircraft.isLocalFile()) {
810             QFileInfo setFileInfo(m_selectedAircraft.toLocalFile());
811             opt->addOption("aircraft-dir", setFileInfo.dir().absolutePath().toStdString());
812             QString setFile = setFileInfo.fileName();
813             Q_ASSERT(setFile.endsWith("-set.xml"));
814             setFile.truncate(setFile.count() - 8); // drop the '-set.xml' portion
815             opt->addOption("aircraft", setFile.toStdString());
816         } else if (m_selectedAircraft.scheme() == "package") {
817             QString qualifiedId = m_selectedAircraft.path();
818             // no need to set aircraft-dir, handled by the corresponding code
819             // in fgInitAircraft
820             opt->addOption("aircraft", qualifiedId.toStdString());
821         } else {
822             qWarning() << "unsupported aircraft launch URL" << m_selectedAircraft;
823         }
824
825       // manage aircraft history
826         if (m_recentAircraft.contains(m_selectedAircraft))
827           m_recentAircraft.removeOne(m_selectedAircraft);
828         m_recentAircraft.prepend(m_selectedAircraft);
829         if (m_recentAircraft.size() > MAX_RECENT_AIRCRAFT)
830           m_recentAircraft.pop_back();
831     }
832
833     m_ui->location->setLocationOptions();
834
835     // time of day
836     if (m_ui->timeOfDayCombo->currentIndex() != 0) {
837         QString dayval = m_ui->timeOfDayCombo->currentText().toLower();
838         opt->addOption("timeofday", dayval.toStdString());
839     }
840
841     if (m_ui->seasonCombo->currentIndex() != 0) {
842         QString seasonName = m_ui->seasonCombo->currentText().toLower();
843         opt->addOption("season", seasonName.toStdString());
844     }
845
846     QSettings settings;
847     QString downloadDir = settings.value("download-dir").toString();
848     if (!downloadDir.isEmpty()) {
849         QDir d(downloadDir);
850         if (!d.exists()) {
851             int result = QMessageBox::question(this, tr("Create download folder?"),
852                                   tr("The selected location for downloads does not exist. Create it?"),
853                                                QMessageBox::Yes | QMessageBox::No | QMessageBox::Cancel);
854             if (result == QMessageBox::Cancel) {
855                 return;
856             }
857
858             if (result == QMessageBox::Yes) {
859                 d.mkpath(downloadDir);
860             }
861         }
862
863         opt->addOption("download-dir", downloadDir.toStdString());
864     }
865
866     // scenery paths
867     Q_FOREACH(QString path, settings.value("scenery-paths").toStringList()) {
868         opt->addOption("fg-scenery", path.toStdString());
869     }
870
871     // aircraft paths
872     Q_FOREACH(QString path, settings.value("aircraft-paths").toStringList()) {
873         // can't use fg-aircraft for this, as it is processed before the launcher is run
874         globals->append_aircraft_path(path.toStdString());
875     }
876
877     // additional arguments
878     ArgumentsTokenizer tk;
879     Q_FOREACH(ArgumentsTokenizer::Arg a, tk.tokenize(m_ui->commandLineArgs->toPlainText())) {
880         if (a.arg.startsWith("prop:")) {
881             QString v = a.arg.mid(5) + "=" + a.value;
882             opt->addOption("prop", v.toStdString());
883         } else {
884             opt->addOption(a.arg.toStdString(), a.value.toStdString());
885         }
886     }
887
888     if (settings.contains("restore-defaults-on-run")) {
889         settings.remove("restore-defaults-on-run");
890         opt->addOption("restore-defaults", "");
891     }
892
893     saveSettings();
894
895     qApp->exit(0);
896 }
897
898
899 void QtLauncher::onApply()
900 {
901     accept();
902
903     // aircraft
904     if (!m_selectedAircraft.isEmpty()) {
905         std::string aircraftPropValue,
906             aircraftDir;
907
908         if (m_selectedAircraft.isLocalFile()) {
909             QFileInfo setFileInfo(m_selectedAircraft.toLocalFile());
910             QString setFile = setFileInfo.fileName();
911             Q_ASSERT(setFile.endsWith("-set.xml"));
912             setFile.truncate(setFile.count() - 8); // drop the '-set.xml' portion
913             aircraftDir = setFileInfo.dir().absolutePath().toStdString();
914             aircraftPropValue = setFile.toStdString();
915         } else if (m_selectedAircraft.scheme() == "package") {
916             // no need to set aircraft-dir, handled by the corresponding code
917             // in fgInitAircraft
918             aircraftPropValue = m_selectedAircraft.path().toStdString();
919         } else {
920             qWarning() << "unsupported aircraft launch URL" << m_selectedAircraft;
921         }
922
923         // manage aircraft history
924         if (m_recentAircraft.contains(m_selectedAircraft))
925             m_recentAircraft.removeOne(m_selectedAircraft);
926         m_recentAircraft.prepend(m_selectedAircraft);
927         if (m_recentAircraft.size() > MAX_RECENT_AIRCRAFT)
928             m_recentAircraft.pop_back();
929
930         globals->get_props()->setStringValue("/sim/aircraft", aircraftPropValue);
931         globals->get_props()->setStringValue("/sim/aircraft-dir", aircraftDir);
932     }
933
934
935     saveSettings();
936 }
937
938 void QtLauncher::onQuit()
939 {
940     qApp->exit(-1);
941 }
942
943 void QtLauncher::onToggleTerrasync(bool enabled)
944 {
945     if (enabled) {
946         QSettings settings;
947         QString downloadDir = settings.value("download-dir").toString();
948         if (downloadDir.isEmpty()) {
949             downloadDir = QString::fromStdString(flightgear::defaultDownloadDir());
950         }
951
952         QFileInfo info(downloadDir);
953         if (!info.exists()) {
954             QMessageBox msg;
955             msg.setWindowTitle(tr("Create download folder?"));
956             msg.setText(tr("The download folder '%1' does not exist, create it now?").arg(downloadDir));
957             msg.addButton(QMessageBox::Yes);
958             msg.addButton(QMessageBox::Cancel);
959             int result = msg.exec();
960
961             if (result == QMessageBox::Cancel) {
962                 m_ui->terrasyncCheck->setChecked(false);
963                 return;
964             }
965
966             QDir d(downloadDir);
967             d.mkpath(downloadDir);
968         }
969     } // of is enabled
970 }
971
972 void QtLauncher::onAircraftInstalledCompleted(QModelIndex index)
973 {
974     maybeUpdateSelectedAircraft(index);
975 }
976
977 void QtLauncher::onRatingsFilterToggled()
978 {
979     QModelIndex aircraftIndex = m_aircraftModel->indexOfAircraftURI(m_selectedAircraft);
980     QModelIndex proxyIndex = m_aircraftProxy->mapFromSource(aircraftIndex);
981     if (proxyIndex.isValid()) {
982         m_ui->aircraftList->scrollTo(proxyIndex);
983     }
984 }
985
986 void QtLauncher::onAircraftInstallFailed(QModelIndex index, QString errorMessage)
987 {
988     qWarning() << Q_FUNC_INFO << index.data(AircraftURIRole) << errorMessage;
989
990     QMessageBox msg;
991     msg.setWindowTitle(tr("Aircraft installation failed"));
992     msg.setText(tr("An error occurred installing the aircraft %1: %2").
993                 arg(index.data(Qt::DisplayRole).toString()).arg(errorMessage));
994     msg.addButton(QMessageBox::Ok);
995     msg.exec();
996
997     maybeUpdateSelectedAircraft(index);
998 }
999
1000 void QtLauncher::onAircraftSelected(const QModelIndex& index)
1001 {
1002     m_selectedAircraft = index.data(AircraftURIRole).toUrl();
1003     updateSelectedAircraft();
1004 }
1005
1006 void QtLauncher::onRequestPackageInstall(const QModelIndex& index)
1007 {
1008     // also select, otherwise UI is confusing
1009     m_selectedAircraft = index.data(AircraftURIRole).toUrl();
1010     updateSelectedAircraft();
1011
1012     QString pkg = index.data(AircraftPackageIdRole).toString();
1013     simgear::pkg::PackageRef pref = globals->packageRoot()->getPackageById(pkg.toStdString());
1014     if (pref->isInstalled()) {
1015         InstallRef install = pref->existingInstall();
1016         if (install && install->hasUpdate()) {
1017             globals->packageRoot()->scheduleToUpdate(install);
1018         }
1019     } else {
1020         pref->install();
1021     }
1022 }
1023
1024 void QtLauncher::onCancelDownload(const QModelIndex& index)
1025 {
1026     QString pkg = index.data(AircraftPackageIdRole).toString();
1027     simgear::pkg::PackageRef pref = globals->packageRoot()->getPackageById(pkg.toStdString());
1028     simgear::pkg::InstallRef i = pref->existingInstall();
1029     i->cancelDownload();
1030 }
1031
1032 void QtLauncher::onRestoreDefaults()
1033 {
1034     QMessageBox mbox(this);
1035     mbox.setText(tr("Restore all settings to defaults?"));
1036     mbox.setInformativeText(tr("Restoring settings to their defaults may affect available add-ons such as scenery or aircraft."));
1037     QPushButton* quitButton = mbox.addButton(tr("Restore and restart now"), QMessageBox::YesRole);
1038     mbox.addButton(QMessageBox::Cancel);
1039     mbox.setDefaultButton(QMessageBox::Cancel);
1040     mbox.setIconPixmap(QPixmap(":/app-icon-large"));
1041
1042     mbox.exec();
1043     if (mbox.clickedButton() != quitButton) {
1044         return;
1045     }
1046
1047     {
1048         QSettings settings;
1049         settings.clear();
1050         settings.setValue("restore-defaults-on-run", true);
1051     }
1052
1053     restartTheApp(QStringList());
1054 }
1055
1056 void QtLauncher::maybeUpdateSelectedAircraft(QModelIndex index)
1057 {
1058     QUrl u = index.data(AircraftURIRole).toUrl();
1059     if (u == m_selectedAircraft) {
1060         // potentially enable the run button now!
1061         updateSelectedAircraft();
1062     }
1063 }
1064
1065 void QtLauncher::updateSelectedAircraft()
1066 {
1067     QModelIndex index = m_aircraftModel->indexOfAircraftURI(m_selectedAircraft);
1068     if (index.isValid()) {
1069         QPixmap pm = index.data(Qt::DecorationRole).value<QPixmap>();
1070         m_ui->thumbnail->setPixmap(pm);
1071         m_ui->aircraftDescription->setText(index.data(Qt::DisplayRole).toString());
1072
1073         int status = index.data(AircraftPackageStatusRole).toInt();
1074         bool canRun = (status == PackageInstalled);
1075         m_ui->runButton->setEnabled(canRun);
1076
1077         LauncherAircraftType aircraftType = Airplane;
1078         if (index.data(AircraftIsHelicopterRole).toBool()) {
1079             aircraftType = Helicopter;
1080         } else if (index.data(AircraftIsSeaplaneRole).toBool()) {
1081             aircraftType = Seaplane;
1082         }
1083
1084         m_ui->location->setAircraftType(aircraftType);
1085     } else {
1086         m_ui->thumbnail->setPixmap(QPixmap());
1087         m_ui->aircraftDescription->setText("");
1088         m_ui->runButton->setEnabled(false);
1089     }
1090 }
1091
1092 QModelIndex QtLauncher::proxyIndexForAircraftURI(QUrl uri) const
1093 {
1094   return m_aircraftProxy->mapFromSource(sourceIndexForAircraftURI(uri));
1095 }
1096
1097 QModelIndex QtLauncher::sourceIndexForAircraftURI(QUrl uri) const
1098 {
1099     AircraftItemModel* sourceModel = qobject_cast<AircraftItemModel*>(m_aircraftProxy->sourceModel());
1100     Q_ASSERT(sourceModel);
1101     return sourceModel->indexOfAircraftURI(uri);
1102 }
1103
1104 void QtLauncher::onPopupAircraftHistory()
1105 {
1106     if (m_recentAircraft.isEmpty()) {
1107         return;
1108     }
1109
1110     QMenu m;
1111     Q_FOREACH(QUrl uri, m_recentAircraft) {
1112         QModelIndex index = sourceIndexForAircraftURI(uri);
1113         if (!index.isValid()) {
1114             // not scanned yet
1115             continue;
1116         }
1117         QAction* act = m.addAction(index.data(Qt::DisplayRole).toString());
1118         act->setData(uri);
1119     }
1120
1121     QPoint popupPos = m_ui->aircraftHistory->mapToGlobal(m_ui->aircraftHistory->rect().bottomLeft());
1122     QAction* triggered = m.exec(popupPos);
1123     if (triggered) {
1124         m_selectedAircraft = triggered->data().toUrl();
1125         QModelIndex index = proxyIndexForAircraftURI(m_selectedAircraft);
1126         m_ui->aircraftList->selectionModel()->setCurrentIndex(index,
1127                                                               QItemSelectionModel::ClearAndSelect);
1128         m_ui->aircraftFilter->clear();
1129         updateSelectedAircraft();
1130     }
1131 }
1132
1133 void QtLauncher::onEditRatingsFilter()
1134 {
1135     EditRatingsFilterDialog dialog(this);
1136     dialog.setRatings(m_ratingFilters);
1137
1138     dialog.exec();
1139     if (dialog.result() == QDialog::Accepted) {
1140         QVariantList vl;
1141         for (int i=0; i<4; ++i) {
1142             m_ratingFilters[i] = dialog.getRating(i);
1143             vl.append(m_ratingFilters[i]);
1144         }
1145         m_aircraftProxy->setRatings(m_ratingFilters);
1146
1147         QSettings settings;
1148         settings.setValue("min-ratings", vl);
1149     }
1150 }
1151
1152 void QtLauncher::updateSettingsSummary()
1153 {
1154     QStringList summary;
1155     if (m_ui->timeOfDayCombo->currentIndex() > 0) {
1156         summary.append(QString(m_ui->timeOfDayCombo->currentText().toLower()));
1157     }
1158
1159     if (m_ui->seasonCombo->currentIndex() > 0) {
1160         summary.append(QString(m_ui->seasonCombo->currentText().toLower()));
1161     }
1162
1163     if (m_ui->rembrandtCheckbox->isChecked()) {
1164         summary.append("Rembrandt enabled");
1165     } else if (m_ui->msaaCheckbox->isChecked()) {
1166         summary.append("anti-aliasing");
1167     }
1168
1169     if (m_ui->fetchRealWxrCheckbox->isChecked()) {
1170         summary.append("live weather");
1171     }
1172
1173     if (m_ui->terrasyncCheck->isChecked()) {
1174         summary.append("automatic scenery downloads");
1175     }
1176
1177     if (m_ui->startPausedCheck->isChecked()) {
1178         summary.append("paused");
1179     }
1180
1181     QString s = summary.join(", ");
1182     s[0] = s[0].toUpper();
1183     m_ui->settingsDescription->setText(s);
1184 }
1185
1186 void QtLauncher::onRembrandtToggled(bool b)
1187 {
1188     // Rembrandt and multi-sample are exclusive
1189     m_ui->msaaCheckbox->setEnabled(!b);
1190 }
1191
1192 void QtLauncher::onShowInstalledAircraftToggled(bool b)
1193 {
1194     m_ui->ratingsFilterCheck->setEnabled(!b);
1195     maybeRestoreAircraftSelection();
1196 }
1197
1198 void QtLauncher::onSubsytemIdleTimeout()
1199 {
1200     globals->get_subsystem_mgr()->update(0.0);
1201 }
1202
1203 void QtLauncher::onDownloadDirChanged()
1204 {
1205
1206     // replace existing package root
1207     globals->get_subsystem<FGHTTPClient>()->shutdown();
1208     globals->setPackageRoot(simgear::pkg::RootRef());
1209
1210     // create new root with updated download-dir value
1211     fgInitPackageRoot();
1212
1213     globals->get_subsystem<FGHTTPClient>()->init();
1214
1215     QSettings settings;
1216     // re-scan the aircraft list
1217     m_aircraftModel->setPackageRoot(globals->packageRoot());
1218     m_aircraftModel->setPaths(settings.value("aircraft-paths").toStringList());
1219     m_aircraftModel->scanDirs();
1220
1221     checkOfficialCatalogMessage();
1222     
1223     // re-set scenery dirs
1224     setSceneryPaths();
1225 }
1226
1227 void QtLauncher::checkOfficialCatalogMessage()
1228 {
1229     QSettings settings;
1230     bool showOfficialCatalogMesssage = !globals->get_subsystem<FGHTTPClient>()->isDefaultCatalogInstalled();
1231     if (settings.value("hide-official-catalog-message").toBool()) {
1232         showOfficialCatalogMesssage = false;
1233     }
1234
1235     m_aircraftModel->setOfficialHangarMessageVisible(showOfficialCatalogMesssage);
1236     if (showOfficialCatalogMesssage) {
1237         NoOfficialHangarMessage* messageWidget = new NoOfficialHangarMessage;
1238         connect(messageWidget, &NoOfficialHangarMessage::linkActivated,
1239                 this, &QtLauncher::onOfficialCatalogMessageLink);
1240
1241         QModelIndex index = m_aircraftProxy->mapFromSource(m_aircraftModel->officialHangarMessageIndex());
1242         m_ui->aircraftList->setIndexWidget(index, messageWidget);
1243     }
1244 }
1245
1246 void QtLauncher::onOfficialCatalogMessageLink(QUrl link)
1247 {
1248     QString s = link.toString();
1249     if (s == "action:hide") {
1250         QSettings settings;
1251         settings.setValue("hide-official-catalog-message", true);
1252     } else if (s == "action:add-official") {
1253         AddOnsPage::addDefaultCatalog(this);
1254     }
1255
1256     checkOfficialCatalogMessage();
1257 }
1258
1259 simgear::pkg::PackageRef QtLauncher::packageForAircraftURI(QUrl uri) const
1260 {
1261     if (uri.scheme() != "package") {
1262         qWarning() << "invalid URL scheme:" << uri;
1263         return simgear::pkg::PackageRef();
1264     }
1265
1266     QString ident = uri.path();
1267     return globals->packageRoot()->getPackageById(ident.toStdString());
1268 }
1269
1270 void QtLauncher::restartTheApp(QStringList fgArgs)
1271 {
1272     // Spawn a new instance of myApplication:
1273     QProcess proc;
1274     QStringList args;
1275
1276 #if defined(Q_OS_MAC)
1277     QDir dir(qApp->applicationDirPath()); // returns the 'MacOS' dir
1278     dir.cdUp(); // up to 'contents' dir
1279     dir.cdUp(); // up to .app dir
1280     // see 'man open' for details, but '-n' ensures we launch a new instance,
1281     // and we want to pass remaining arguments to us, not open.
1282     args << "-n" << dir.absolutePath() << "--args" << "--launcher" << fgArgs;
1283     qDebug() << "args" << args;
1284     proc.startDetached("open", args);
1285 #else
1286     args << "--launcher" << fgArgs;
1287     proc.startDetached(qApp->applicationFilePath(), args);
1288 #endif
1289     qApp->exit(-1);
1290 }
1291
1292 #include "QtLauncher.moc"