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