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