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