]> git.mxchange.org Git - flightgear.git/blob - src/GUI/QtLauncher.cxx
Trying to bullet-proof the traffic code.
[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     {
257         for (int i=0; i<4; ++i) {
258             m_ratings[i] = 3;
259         }
260     }
261
262     void setRatings(int* ratings)
263     {
264         ::memcpy(m_ratings, ratings, sizeof(int) * 4);
265         invalidate();
266     }
267
268 public slots:
269     void setRatingFilterEnabled(bool e)
270     {
271         if (e == m_ratingsFilter) {
272             return;
273         }
274
275         m_ratingsFilter = e;
276         invalidate();
277     }
278
279 protected:
280     bool filterAcceptsRow(int sourceRow, const QModelIndex &sourceParent) const
281     {
282         if (!QSortFilterProxyModel::filterAcceptsRow(sourceRow, sourceParent)) {
283             return false;
284         }
285
286         if (m_ratingsFilter) {
287             QModelIndex index = sourceModel()->index(sourceRow, 0, sourceParent);
288             for (int i=0; i<4; ++i) {
289                 if (m_ratings[i] > index.data(AircraftRatingRole + i).toInt()) {
290                     return false;
291                 }
292             }
293         }
294
295         return true;
296     }
297
298 private:
299     bool m_ratingsFilter;
300     int m_ratings[4];
301 };
302
303 static void initQtResources()
304 {
305     Q_INIT_RESOURCE(resources);
306 }
307
308 namespace flightgear
309 {
310
311 void initApp(int& argc, char** argv)
312 {
313     sglog().setLogLevels( SG_ALL, SG_INFO );
314     initQtResources(); // can't be called from a namespace
315
316     static bool qtInitDone = false;
317     static int s_argc;
318
319     if (!qtInitDone) {
320         qtInitDone = true;
321         s_argc = argc; // QApplication only stores a reference to argc,
322         // and may crash if it is freed
323         // http://doc.qt.io/qt-5/qguiapplication.html#QGuiApplication
324
325         QApplication* app = new QApplication(s_argc, argv);
326         app->setOrganizationName("FlightGear");
327         app->setApplicationName("FlightGear");
328         app->setOrganizationDomain("flightgear.org");
329
330         // avoid double Apple menu and other weirdness if both Qt and OSG
331         // try to initialise various Cocoa structures.
332         flightgear::WindowBuilder::setPoseAsStandaloneApp(false);
333
334         Qt::KeyboardModifiers mods = app->queryKeyboardModifiers();
335         if (mods & Qt::AltModifier) {
336             qWarning() << "Alt pressed during launch";
337
338             // wipe out our settings
339             QSettings settings;
340             settings.clear();
341
342
343             Options::sharedInstance()->addOption("restore-defaults", "");
344         }
345     }
346 }
347
348 void loadNaturalEarthFile(const std::string& aFileName,
349                           flightgear::PolyLine::Type aType,
350                           bool areClosed)
351 {
352     SGPath path(globals->get_fg_root());
353     path.append( "Geodata" );
354     path.append(aFileName);
355     if (!path.exists())
356         return; // silently fail for now
357
358     flightgear::PolyLineList lines;
359     flightgear::SHPParser::parsePolyLines(path, aType, lines, areClosed);
360     flightgear::PolyLine::bulkAddToSpatialIndex(lines);
361 }
362
363 void loadNaturalEarthData()
364 {
365     SGTimeStamp st;
366     st.stamp();
367
368     loadNaturalEarthFile("ne_10m_coastline.shp", flightgear::PolyLine::COASTLINE, false);
369     loadNaturalEarthFile("ne_10m_rivers_lake_centerlines.shp", flightgear::PolyLine::RIVER, false);
370     loadNaturalEarthFile("ne_10m_lakes.shp", flightgear::PolyLine::LAKE, true);
371
372     qDebug() << "load basic data took" << st.elapsedMSec();
373
374
375     st.stamp();
376     loadNaturalEarthFile("ne_10m_urban_areas.shp", flightgear::PolyLine::URBAN, true);
377
378     qDebug() << "loading urban areas took:" << st.elapsedMSec();
379 }
380
381 bool runLauncherDialog()
382 {
383     // startup the nav-cache now. This pre-empts normal startup of
384     // the cache, but no harm done. (Providing scenery paths are consistent)
385
386     initNavCache();
387
388     fgInitPackageRoot();
389
390     // startup the HTTP system now since packages needs it
391     FGHTTPClient* http = new FGHTTPClient;
392     globals->add_subsystem("http", http);
393     // we guard against re-init in the global phase; bind and postinit
394     // will happen as normal
395     http->init();
396
397     loadNaturalEarthData();
398
399     // setup scenery paths now, especially TerraSync path for airport
400     // parking locations (after they're downloaded)
401
402     QtLauncher dlg;
403     dlg.exec();
404     if (dlg.result() != QDialog::Accepted) {
405         return false;
406     }
407
408     return true;
409 }
410
411 bool runInAppLauncherDialog()
412 {
413     QtLauncher dlg;
414     dlg.setInAppMode();
415     dlg.exec();
416     if (dlg.result() != QDialog::Accepted) {
417         return false;
418     }
419
420     return true;
421 }
422
423 } // of namespace flightgear
424
425 QtLauncher::QtLauncher() :
426     QDialog(),
427     m_ui(NULL),
428     m_subsystemIdleTimer(NULL),
429     m_inAppMode(false)
430 {
431     m_ui.reset(new Ui::Launcher);
432     m_ui->setupUi(this);
433
434 #if QT_VERSION >= 0x050300
435     // don't require Qt 5.3
436     m_ui->commandLineArgs->setPlaceholderText("--option=value --prop:/sim/name=value");
437 #endif
438
439 #if QT_VERSION >= 0x050200
440     m_ui->aircraftFilter->setClearButtonEnabled(true);
441 #endif
442
443     for (int i=0; i<4; ++i) {
444         m_ratingFilters[i] = 3;
445     }
446
447     m_subsystemIdleTimer = new QTimer(this);
448     m_subsystemIdleTimer->setInterval(0);
449     connect(m_subsystemIdleTimer, &QTimer::timeout,
450             this, &QtLauncher::onSubsytemIdleTimeout);
451     m_subsystemIdleTimer->start();
452
453     // create and configure the proxy model
454     m_aircraftProxy = new AircraftProxyModel(this);
455     connect(m_ui->ratingsFilterCheck, &QAbstractButton::toggled,
456             m_aircraftProxy, &AircraftProxyModel::setRatingFilterEnabled);
457     connect(m_ui->aircraftFilter, &QLineEdit::textChanged,
458             m_aircraftProxy, &QSortFilterProxyModel::setFilterFixedString);
459
460     connect(m_ui->runButton, SIGNAL(clicked()), this, SLOT(onRun()));
461     connect(m_ui->quitButton, SIGNAL(clicked()), this, SLOT(onQuit()));
462
463     connect(m_ui->aircraftHistory, &QPushButton::clicked,
464           this, &QtLauncher::onPopupAircraftHistory);
465
466     connect(m_ui->location, &LocationWidget::descriptionChanged,
467             m_ui->locationDescription, &QLabel::setText);
468
469     QAction* qa = new QAction(this);
470     qa->setShortcut(QKeySequence("Ctrl+Q"));
471     connect(qa, &QAction::triggered, this, &QtLauncher::onQuit);
472     addAction(qa);
473
474     connect(m_ui->editRatingFilter, &QPushButton::clicked,
475             this, &QtLauncher::onEditRatingsFilter);
476
477     QIcon historyIcon(":/history-icon");
478     m_ui->aircraftHistory->setIcon(historyIcon);
479
480     connect(m_ui->timeOfDayCombo, SIGNAL(currentIndexChanged(int)),
481             this, SLOT(updateSettingsSummary()));
482     connect(m_ui->seasonCombo, SIGNAL(currentIndexChanged(int)),
483             this, SLOT(updateSettingsSummary()));
484     connect(m_ui->fetchRealWxrCheckbox, SIGNAL(toggled(bool)),
485             this, SLOT(updateSettingsSummary()));
486     connect(m_ui->rembrandtCheckbox, SIGNAL(toggled(bool)),
487             this, SLOT(updateSettingsSummary()));
488     connect(m_ui->terrasyncCheck, SIGNAL(toggled(bool)),
489             this, SLOT(updateSettingsSummary()));
490     connect(m_ui->startPausedCheck, SIGNAL(toggled(bool)),
491             this, SLOT(updateSettingsSummary()));
492     connect(m_ui->msaaCheckbox, SIGNAL(toggled(bool)),
493             this, SLOT(updateSettingsSummary()));
494
495     connect(m_ui->rembrandtCheckbox, SIGNAL(toggled(bool)),
496             this, SLOT(onRembrandtToggled(bool)));
497     connect(m_ui->terrasyncCheck, &QCheckBox::toggled,
498             this, &QtLauncher::onToggleTerrasync);
499     updateSettingsSummary();
500
501     m_aircraftModel = new AircraftItemModel(this, RootRef(globals->packageRoot()));
502     m_aircraftProxy->setSourceModel(m_aircraftModel);
503
504     m_aircraftProxy->setFilterCaseSensitivity(Qt::CaseInsensitive);
505     m_aircraftProxy->setSortCaseSensitivity(Qt::CaseInsensitive);
506     m_aircraftProxy->setSortRole(Qt::DisplayRole);
507     m_aircraftProxy->setDynamicSortFilter(true);
508
509     m_ui->aircraftList->setModel(m_aircraftProxy);
510     m_ui->aircraftList->setHorizontalScrollBarPolicy(Qt::ScrollBarAlwaysOff);
511     AircraftItemDelegate* delegate = new AircraftItemDelegate(m_ui->aircraftList);
512     m_ui->aircraftList->setItemDelegate(delegate);
513     m_ui->aircraftList->setSelectionMode(QAbstractItemView::SingleSelection);
514     connect(m_ui->aircraftList, &QListView::clicked,
515             this, &QtLauncher::onAircraftSelected);
516     connect(delegate, &AircraftItemDelegate::variantChanged,
517             this, &QtLauncher::onAircraftSelected);
518     connect(delegate, &AircraftItemDelegate::requestInstall,
519             this, &QtLauncher::onRequestPackageInstall);
520     connect(delegate, &AircraftItemDelegate::cancelDownload,
521             this, &QtLauncher::onCancelDownload);
522
523     connect(m_aircraftModel, &AircraftItemModel::aircraftInstallCompleted,
524             this, &QtLauncher::onAircraftInstalledCompleted);
525     connect(m_aircraftModel, &AircraftItemModel::aircraftInstallFailed,
526             this, &QtLauncher::onAircraftInstallFailed);
527     connect(m_aircraftModel, &AircraftItemModel::scanCompleted,
528             this, &QtLauncher::updateSelectedAircraft);
529     connect(m_ui->pathsButton, &QPushButton::clicked,
530             this, &QtLauncher::onEditPaths);
531
532     restoreSettings();
533
534     QSettings settings;
535     m_aircraftModel->setPaths(settings.value("aircraft-paths").toStringList());
536     m_aircraftModel->scanDirs();
537 }
538
539 QtLauncher::~QtLauncher()
540 {
541
542 }
543
544 void QtLauncher::setInAppMode()
545 {
546   m_inAppMode = true;
547   m_ui->tabWidget->removeTab(2);
548   m_ui->runButton->setText(tr("Apply"));
549   m_ui->quitButton->setText(tr("Cancel"));
550
551   disconnect(m_ui->runButton, SIGNAL(clicked()), this, SLOT(onRun()));
552   connect(m_ui->runButton, SIGNAL(clicked()), this, SLOT(onApply()));
553 }
554
555 void QtLauncher::restoreSettings()
556 {
557     QSettings settings;
558     m_ui->rembrandtCheckbox->setChecked(settings.value("enable-rembrandt", false).toBool());
559     m_ui->terrasyncCheck->setChecked(settings.value("enable-terrasync", true).toBool());
560     m_ui->fullScreenCheckbox->setChecked(settings.value("start-fullscreen", false).toBool());
561     m_ui->msaaCheckbox->setChecked(settings.value("enable-msaa", false).toBool());
562     m_ui->fetchRealWxrCheckbox->setChecked(settings.value("enable-realwx", true).toBool());
563     m_ui->startPausedCheck->setChecked(settings.value("start-paused", false).toBool());
564     m_ui->timeOfDayCombo->setCurrentIndex(settings.value("timeofday", 0).toInt());
565     m_ui->seasonCombo->setCurrentIndex(settings.value("season", 0).toInt());
566
567     // full paths to -set.xml files
568     m_recentAircraft = QUrl::fromStringList(settings.value("recent-aircraft").toStringList());
569
570     if (!m_recentAircraft.empty()) {
571         m_selectedAircraft = m_recentAircraft.front();
572     } else {
573         // select the default C172p
574     }
575
576     updateSelectedAircraft();
577     m_ui->location->restoreSettings();
578
579     // rating filters
580     m_ui->ratingsFilterCheck->setChecked(settings.value("ratings-filter", true).toBool());
581     int index = 0;
582     Q_FOREACH(QVariant v, settings.value("min-ratings").toList()) {
583         m_ratingFilters[index++] = v.toInt();
584     }
585
586     m_aircraftProxy->setRatingFilterEnabled(m_ui->ratingsFilterCheck->isChecked());
587     m_aircraftProxy->setRatings(m_ratingFilters);
588
589     m_ui->commandLineArgs->setPlainText(settings.value("additional-args").toString());
590 }
591
592 void QtLauncher::saveSettings()
593 {
594     QSettings settings;
595     settings.setValue("enable-rembrandt", m_ui->rembrandtCheckbox->isChecked());
596     settings.setValue("enable-terrasync", m_ui->terrasyncCheck->isChecked());
597     settings.setValue("enable-msaa", m_ui->msaaCheckbox->isChecked());
598     settings.setValue("start-fullscreen", m_ui->fullScreenCheckbox->isChecked());
599     settings.setValue("enable-realwx", m_ui->fetchRealWxrCheckbox->isChecked());
600     settings.setValue("start-paused", m_ui->startPausedCheck->isChecked());
601     settings.setValue("ratings-filter", m_ui->ratingsFilterCheck->isChecked());
602     settings.setValue("recent-aircraft", QUrl::toStringList(m_recentAircraft));
603
604     settings.setValue("timeofday", m_ui->timeOfDayCombo->currentIndex());
605     settings.setValue("season", m_ui->seasonCombo->currentIndex());
606     settings.setValue("additional-args", m_ui->commandLineArgs->toPlainText());
607
608     m_ui->location->saveSettings();
609 }
610
611 void QtLauncher::setEnableDisableOptionFromCheckbox(QCheckBox* cbox, QString name) const
612 {
613     flightgear::Options* opt = flightgear::Options::sharedInstance();
614     std::string stdName(name.toStdString());
615     if (cbox->isChecked()) {
616         opt->addOption("enable-" + stdName, "");
617     } else {
618         opt->addOption("disable-" + stdName, "");
619     }
620 }
621
622 void QtLauncher::onRun()
623 {
624     accept();
625
626     flightgear::Options* opt = flightgear::Options::sharedInstance();
627     setEnableDisableOptionFromCheckbox(m_ui->terrasyncCheck, "terrasync");
628     setEnableDisableOptionFromCheckbox(m_ui->fetchRealWxrCheckbox, "real-weather-fetch");
629     setEnableDisableOptionFromCheckbox(m_ui->rembrandtCheckbox, "rembrandt");
630     setEnableDisableOptionFromCheckbox(m_ui->fullScreenCheckbox, "fullscreen");
631 //    setEnableDisableOptionFromCheckbox(m_ui->startPausedCheck, "freeze");
632
633     bool startPaused = m_ui->startPausedCheck->isChecked() ||
634             m_ui->location->shouldStartPaused();
635     if (startPaused) {
636         opt->addOption("enable-freeze", "");
637     }
638
639     // MSAA is more complex
640     if (!m_ui->rembrandtCheckbox->isChecked()) {
641         if (m_ui->msaaCheckbox->isChecked()) {
642             globals->get_props()->setIntValue("/sim/rendering/multi-sample-buffers", 1);
643             globals->get_props()->setIntValue("/sim/rendering/multi-samples", 4);
644         } else {
645             globals->get_props()->setIntValue("/sim/rendering/multi-sample-buffers", 0);
646         }
647     }
648
649     // aircraft
650     if (!m_selectedAircraft.isEmpty()) {
651         if (m_selectedAircraft.isLocalFile()) {
652             QFileInfo setFileInfo(m_selectedAircraft.toLocalFile());
653             opt->addOption("aircraft-dir", setFileInfo.dir().absolutePath().toStdString());
654             QString setFile = setFileInfo.fileName();
655             Q_ASSERT(setFile.endsWith("-set.xml"));
656             setFile.truncate(setFile.count() - 8); // drop the '-set.xml' portion
657             opt->addOption("aircraft", setFile.toStdString());
658         } else if (m_selectedAircraft.scheme() == "package") {
659             PackageRef pkg = packageForAircraftURI(m_selectedAircraft);
660             // no need to set aircraft-dir, handled by the corresponding code
661             // in fgInitAircraft
662             opt->addOption("aircraft", pkg->qualifiedId());
663         } else {
664             qWarning() << "unsupported aircraft launch URL" << m_selectedAircraft;
665         }
666
667       // manage aircraft history
668         if (m_recentAircraft.contains(m_selectedAircraft))
669           m_recentAircraft.removeOne(m_selectedAircraft);
670         m_recentAircraft.prepend(m_selectedAircraft);
671         if (m_recentAircraft.size() > MAX_RECENT_AIRCRAFT)
672           m_recentAircraft.pop_back();
673     }
674
675     m_ui->location->setLocationOptions();
676
677     // time of day
678     if (m_ui->timeOfDayCombo->currentIndex() != 0) {
679         QString dayval = m_ui->timeOfDayCombo->currentText().toLower();
680         opt->addOption("timeofday", dayval.toStdString());
681     }
682
683     if (m_ui->seasonCombo->currentIndex() != 0) {
684         QString dayval = m_ui->timeOfDayCombo->currentText().toLower();
685         opt->addOption("season", dayval.toStdString());
686     }
687
688     QSettings settings;
689     QString downloadDir = settings.value("download-dir").toString();
690     if (!downloadDir.isEmpty()) {
691         QDir d(downloadDir);
692         if (!d.exists()) {
693             int result = QMessageBox::question(this, tr("Create download folder?"),
694                                   tr("The selected location for downloads does not exist. Create it?"),
695                                                QMessageBox::Yes | QMessageBox::No | QMessageBox::Cancel);
696             if (result == QMessageBox::Cancel) {
697                 return;
698             }
699
700             if (result == QMessageBox::Yes) {
701                 d.mkpath(downloadDir);
702             }
703         }
704
705         opt->addOption("download-dir", downloadDir.toStdString());
706     }
707
708     // scenery paths
709     Q_FOREACH(QString path, settings.value("scenery-paths").toStringList()) {
710         opt->addOption("fg-scenery", path.toStdString());
711     }
712
713     // aircraft paths
714     Q_FOREACH(QString path, settings.value("aircraft-paths").toStringList()) {
715         // can't use fg-aircraft for this, as it is processed before the launcher is run
716         globals->append_aircraft_path(path.toStdString());
717     }
718
719     // additional arguments
720     ArgumentsTokenizer tk;
721     Q_FOREACH(ArgumentsTokenizer::Arg a, tk.tokenize(m_ui->commandLineArgs->toPlainText())) {
722         if (a.arg.startsWith("prop:")) {
723             QString v = a.arg.mid(5) + "=" + a.value;
724             opt->addOption("prop", v.toStdString());
725         } else {
726             opt->addOption(a.arg.toStdString(), a.value.toStdString());
727         }
728     }
729
730     saveSettings();
731 }
732
733
734 void QtLauncher::onApply()
735 {
736     accept();
737
738     // aircraft
739     if (!m_selectedAircraft.isEmpty()) {
740         std::string aircraftPropValue,
741             aircraftDir;
742
743         if (m_selectedAircraft.isLocalFile()) {
744             QFileInfo setFileInfo(m_selectedAircraft.toLocalFile());
745             QString setFile = setFileInfo.fileName();
746             Q_ASSERT(setFile.endsWith("-set.xml"));
747             setFile.truncate(setFile.count() - 8); // drop the '-set.xml' portion
748             aircraftDir = setFileInfo.dir().absolutePath().toStdString();
749             aircraftPropValue = setFile.toStdString();
750         } else if (m_selectedAircraft.scheme() == "package") {
751             PackageRef pkg = packageForAircraftURI(m_selectedAircraft);
752             // no need to set aircraft-dir, handled by the corresponding code
753             // in fgInitAircraft
754             aircraftPropValue = pkg->qualifiedId();
755         } else {
756             qWarning() << "unsupported aircraft launch URL" << m_selectedAircraft;
757         }
758
759         // manage aircraft history
760         if (m_recentAircraft.contains(m_selectedAircraft))
761             m_recentAircraft.removeOne(m_selectedAircraft);
762         m_recentAircraft.prepend(m_selectedAircraft);
763         if (m_recentAircraft.size() > MAX_RECENT_AIRCRAFT)
764             m_recentAircraft.pop_back();
765
766         globals->get_props()->setStringValue("/sim/aircraft", aircraftPropValue);
767         globals->get_props()->setStringValue("/sim/aircraft-dir", aircraftDir);
768     }
769
770
771     saveSettings();
772 }
773
774 void QtLauncher::onQuit()
775 {
776     reject();
777 }
778
779 void QtLauncher::onToggleTerrasync(bool enabled)
780 {
781     if (enabled) {
782         QSettings settings;
783         QString downloadDir = settings.value("download-dir").toString();
784         if (downloadDir.isEmpty()) {
785             downloadDir = QString::fromStdString(flightgear::defaultDownloadDir());
786         }
787
788         QFileInfo info(downloadDir);
789         if (!info.exists()) {
790             QMessageBox msg;
791             msg.setWindowTitle(tr("Create download folder?"));
792             msg.setText(tr("The download folder '%1' does not exist, create it now? "
793                            "Click 'change location' to choose another folder "
794                            "to store downloaded files").arg(downloadDir));
795             msg.addButton(QMessageBox::Yes);
796             msg.addButton(QMessageBox::Cancel);
797             msg.addButton(tr("Change location"), QMessageBox::ActionRole);
798             int result = msg.exec();
799
800             if (result == QMessageBox::Cancel) {
801                 m_ui->terrasyncCheck->setChecked(false);
802                 return;
803             }
804
805             if (result == QMessageBox::ActionRole) {
806                 onEditPaths();
807                 return;
808             }
809
810             QDir d(downloadDir);
811             d.mkpath(downloadDir);
812         }
813     } // of is enabled
814 }
815
816 void QtLauncher::onAircraftInstalledCompleted(QModelIndex index)
817 {
818     maybeUpdateSelectedAircraft(index);
819 }
820
821 void QtLauncher::onAircraftInstallFailed(QModelIndex index, QString errorMessage)
822 {
823     qWarning() << Q_FUNC_INFO << index.data(AircraftURIRole) << errorMessage;
824
825     QMessageBox msg;
826     msg.setWindowTitle(tr("Aircraft installation failed"));
827     msg.setText(tr("An error occurred installing the aircraft %1: %2").
828                 arg(index.data(Qt::DisplayRole).toString()).arg(errorMessage));
829     msg.addButton(QMessageBox::Ok);
830     msg.exec();
831
832     maybeUpdateSelectedAircraft(index);
833 }
834
835 void QtLauncher::onAircraftSelected(const QModelIndex& index)
836 {
837     m_selectedAircraft = index.data(AircraftURIRole).toUrl();
838     updateSelectedAircraft();
839 }
840
841 void QtLauncher::onRequestPackageInstall(const QModelIndex& index)
842 {
843     QString pkg = index.data(AircraftPackageIdRole).toString();
844     simgear::pkg::PackageRef pref = globals->packageRoot()->getPackageById(pkg.toStdString());
845     if (pref->isInstalled()) {
846         InstallRef install = pref->existingInstall();
847         if (install && install->hasUpdate()) {
848             globals->packageRoot()->scheduleToUpdate(install);
849         }
850     } else {
851         pref->install();
852     }
853 }
854
855 void QtLauncher::onCancelDownload(const QModelIndex& index)
856 {
857     QString pkg = index.data(AircraftPackageIdRole).toString();
858     simgear::pkg::PackageRef pref = globals->packageRoot()->getPackageById(pkg.toStdString());
859     simgear::pkg::InstallRef i = pref->existingInstall();
860     i->cancelDownload();
861 }
862
863 void QtLauncher::maybeUpdateSelectedAircraft(QModelIndex index)
864 {
865     QUrl u = index.data(AircraftURIRole).toUrl();
866     if (u == m_selectedAircraft) {
867         // potentially enable the run button now!
868         updateSelectedAircraft();
869     }
870 }
871
872 void QtLauncher::updateSelectedAircraft()
873 {
874     QModelIndex index = m_aircraftModel->indexOfAircraftURI(m_selectedAircraft);
875     if (index.isValid()) {
876         QPixmap pm = index.data(Qt::DecorationRole).value<QPixmap>();
877         m_ui->thumbnail->setPixmap(pm);
878         m_ui->aircraftDescription->setText(index.data(Qt::DisplayRole).toString());
879
880         int status = index.data(AircraftPackageStatusRole).toInt();
881         bool canRun = (status == PackageInstalled);
882         m_ui->runButton->setEnabled(canRun);
883
884         LauncherAircraftType aircraftType = Airplane;
885         if (index.data(AircraftIsHelicopterRole).toBool()) {
886             aircraftType = Helicopter;
887         } else if (index.data(AircraftIsSeaplaneRole).toBool()) {
888             aircraftType = Seaplane;
889         }
890
891         m_ui->location->setAircraftType(aircraftType);
892     } else {
893         m_ui->thumbnail->setPixmap(QPixmap());
894         m_ui->aircraftDescription->setText("");
895         m_ui->runButton->setEnabled(false);
896     }
897 }
898
899 QModelIndex QtLauncher::proxyIndexForAircraftURI(QUrl uri) const
900 {
901   return m_aircraftProxy->mapFromSource(sourceIndexForAircraftURI(uri));
902 }
903
904 QModelIndex QtLauncher::sourceIndexForAircraftURI(QUrl uri) const
905 {
906     AircraftItemModel* sourceModel = qobject_cast<AircraftItemModel*>(m_aircraftProxy->sourceModel());
907     Q_ASSERT(sourceModel);
908     return sourceModel->indexOfAircraftURI(uri);
909 }
910
911 void QtLauncher::onPopupAircraftHistory()
912 {
913     if (m_recentAircraft.isEmpty()) {
914         return;
915     }
916
917     QMenu m;
918     Q_FOREACH(QUrl uri, m_recentAircraft) {
919         QModelIndex index = sourceIndexForAircraftURI(uri);
920         if (!index.isValid()) {
921             // not scanned yet
922             continue;
923         }
924         QAction* act = m.addAction(index.data(Qt::DisplayRole).toString());
925         act->setData(uri);
926     }
927
928     QPoint popupPos = m_ui->aircraftHistory->mapToGlobal(m_ui->aircraftHistory->rect().bottomLeft());
929     QAction* triggered = m.exec(popupPos);
930     if (triggered) {
931         m_selectedAircraft = triggered->data().toUrl();
932         QModelIndex index = proxyIndexForAircraftURI(m_selectedAircraft);
933         m_ui->aircraftList->selectionModel()->setCurrentIndex(index,
934                                                               QItemSelectionModel::ClearAndSelect);
935         m_ui->aircraftFilter->clear();
936         updateSelectedAircraft();
937     }
938 }
939
940 void QtLauncher::onEditRatingsFilter()
941 {
942     EditRatingsFilterDialog dialog(this);
943     dialog.setRatings(m_ratingFilters);
944
945     dialog.exec();
946     if (dialog.result() == QDialog::Accepted) {
947         QVariantList vl;
948         for (int i=0; i<4; ++i) {
949             m_ratingFilters[i] = dialog.getRating(i);
950             vl.append(m_ratingFilters[i]);
951         }
952         m_aircraftProxy->setRatings(m_ratingFilters);
953
954         QSettings settings;
955         settings.setValue("min-ratings", vl);
956     }
957 }
958
959 void QtLauncher::updateSettingsSummary()
960 {
961     QStringList summary;
962     if (m_ui->timeOfDayCombo->currentIndex() > 0) {
963         summary.append(QString(m_ui->timeOfDayCombo->currentText().toLower()));
964     }
965
966     if (m_ui->seasonCombo->currentIndex() > 0) {
967         summary.append(QString(m_ui->seasonCombo->currentText().toLower()));
968     }
969
970     if (m_ui->rembrandtCheckbox->isChecked()) {
971         summary.append("Rembrandt enabled");
972     } else if (m_ui->msaaCheckbox->isChecked()) {
973         summary.append("anti-aliasing");
974     }
975
976     if (m_ui->fetchRealWxrCheckbox->isChecked()) {
977         summary.append("live weather");
978     }
979
980     if (m_ui->terrasyncCheck->isChecked()) {
981         summary.append("automatic scenery downloads");
982     }
983
984     if (m_ui->startPausedCheck->isChecked()) {
985         summary.append("paused");
986     }
987
988     QString s = summary.join(", ");
989     s[0] = s[0].toUpper();
990     m_ui->settingsDescription->setText(s);
991 }
992
993 void QtLauncher::onRembrandtToggled(bool b)
994 {
995     // Rembrandt and multi-sample are exclusive
996     m_ui->msaaCheckbox->setEnabled(!b);
997 }
998
999 void QtLauncher::onSubsytemIdleTimeout()
1000 {
1001     globals->get_subsystem_mgr()->update(0.0);
1002 }
1003
1004 void QtLauncher::onEditPaths()
1005 {
1006     PathsDialog dlg(this, globals->packageRoot());
1007     dlg.exec();
1008     if (dlg.result() == QDialog::Accepted) {
1009         // re-scan the aircraft list
1010         QSettings settings;
1011         m_aircraftModel->setPaths(settings.value("aircraft-paths").toStringList());
1012         m_aircraftModel->scanDirs();
1013     }
1014 }
1015
1016 simgear::pkg::PackageRef QtLauncher::packageForAircraftURI(QUrl uri) const
1017 {
1018     if (uri.scheme() != "package") {
1019         qWarning() << "invalid URL scheme:" << uri;
1020         return simgear::pkg::PackageRef();
1021     }
1022
1023     QString ident = uri.path();
1024     return globals->packageRoot()->getPackageById(ident.toStdString());
1025 }
1026
1027
1028 #include "QtLauncher.moc"