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