]> git.mxchange.org Git - flightgear.git/blob - src/GUI/QtLauncher.cxx
Improve download-dir behaviour.
[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     QSettings settings;
416     QString downloadDir = settings.value("download-dir").toString();
417     if (!downloadDir.isEmpty()) {
418         flightgear::Options::sharedInstance()->setOption("download-dir", downloadDir.toStdString());
419     }
420
421     fgInitPackageRoot();
422
423     // startup the HTTP system now since packages needs it
424     FGHTTPClient* http = globals->add_new_subsystem<FGHTTPClient>();
425     
426     // we guard against re-init in the global phase; bind and postinit
427     // will happen as normal
428     http->init();
429
430     loadNaturalEarthData();
431
432     // avoid double Apple menu and other weirdness if both Qt and OSG
433     // try to initialise various Cocoa structures.
434     flightgear::WindowBuilder::setPoseAsStandaloneApp(false);
435     
436     QtLauncher dlg;
437     dlg.show();
438
439     int appResult = qApp->exec();
440     if (appResult < 0) {
441         return false; // quit
442     }
443
444     // don't set scenery paths twice
445     globals->clear_fg_scenery();
446
447     return true;
448 }
449
450 bool runInAppLauncherDialog()
451 {
452     QtLauncher dlg;
453     dlg.setInAppMode();
454     dlg.exec();
455     if (dlg.result() != QDialog::Accepted) {
456         return false;
457     }
458
459     return true;
460 }
461
462 } // of namespace flightgear
463
464 QtLauncher::QtLauncher() :
465     QDialog(),
466     m_ui(NULL),
467     m_subsystemIdleTimer(NULL),
468     m_inAppMode(false)
469 {
470     m_ui.reset(new Ui::Launcher);
471     m_ui->setupUi(this);
472
473 #if QT_VERSION >= 0x050300
474     // don't require Qt 5.3
475     m_ui->commandLineArgs->setPlaceholderText("--option=value --prop:/sim/name=value");
476 #endif
477
478 #if QT_VERSION >= 0x050200
479     m_ui->aircraftFilter->setClearButtonEnabled(true);
480 #endif
481
482     for (int i=0; i<4; ++i) {
483         m_ratingFilters[i] = 3;
484     }
485
486     m_subsystemIdleTimer = new QTimer(this);
487     m_subsystemIdleTimer->setInterval(0);
488     connect(m_subsystemIdleTimer, &QTimer::timeout,
489             this, &QtLauncher::onSubsytemIdleTimeout);
490     m_subsystemIdleTimer->start();
491
492     // create and configure the proxy model
493     m_aircraftProxy = new AircraftProxyModel(this);
494     connect(m_ui->ratingsFilterCheck, &QAbstractButton::toggled,
495             m_aircraftProxy, &AircraftProxyModel::setRatingFilterEnabled);
496     connect(m_ui->ratingsFilterCheck, &QAbstractButton::toggled,
497             this, &QtLauncher::maybeRestoreAircraftSelection);
498
499     connect(m_ui->onlyShowInstalledCheck, &QAbstractButton::toggled,
500             m_aircraftProxy, &AircraftProxyModel::setInstalledFilterEnabled);
501     connect(m_ui->aircraftFilter, &QLineEdit::textChanged,
502             m_aircraftProxy, &QSortFilterProxyModel::setFilterFixedString);
503
504     connect(m_ui->runButton, SIGNAL(clicked()), this, SLOT(onRun()));
505     connect(m_ui->quitButton, SIGNAL(clicked()), this, SLOT(onQuit()));
506
507     connect(m_ui->changeRootButton, SIGNAL(clicked()), this, SLOT(onChangeRoot()));
508
509     connect(m_ui->aircraftHistory, &QPushButton::clicked,
510           this, &QtLauncher::onPopupAircraftHistory);
511
512     connect(m_ui->location, &LocationWidget::descriptionChanged,
513             m_ui->locationDescription, &QLabel::setText);
514
515     QAction* qa = new QAction(this);
516     qa->setShortcut(QKeySequence("Ctrl+Q"));
517     connect(qa, &QAction::triggered, this, &QtLauncher::onQuit);
518     addAction(qa);
519
520     connect(m_ui->editRatingFilter, &QPushButton::clicked,
521             this, &QtLauncher::onEditRatingsFilter);
522     connect(m_ui->onlyShowInstalledCheck, &QCheckBox::toggled,
523             this, &QtLauncher::onShowInstalledAircraftToggled);
524
525     QIcon historyIcon(":/history-icon");
526     m_ui->aircraftHistory->setIcon(historyIcon);
527
528     connect(m_ui->timeOfDayCombo, SIGNAL(currentIndexChanged(int)),
529             this, SLOT(updateSettingsSummary()));
530     connect(m_ui->seasonCombo, SIGNAL(currentIndexChanged(int)),
531             this, SLOT(updateSettingsSummary()));
532     connect(m_ui->fetchRealWxrCheckbox, SIGNAL(toggled(bool)),
533             this, SLOT(updateSettingsSummary()));
534     connect(m_ui->rembrandtCheckbox, SIGNAL(toggled(bool)),
535             this, SLOT(updateSettingsSummary()));
536     connect(m_ui->terrasyncCheck, SIGNAL(toggled(bool)),
537             this, SLOT(updateSettingsSummary()));
538     connect(m_ui->startPausedCheck, SIGNAL(toggled(bool)),
539             this, SLOT(updateSettingsSummary()));
540     connect(m_ui->msaaCheckbox, SIGNAL(toggled(bool)),
541             this, SLOT(updateSettingsSummary()));
542
543     connect(m_ui->rembrandtCheckbox, SIGNAL(toggled(bool)),
544             this, SLOT(onRembrandtToggled(bool)));
545     connect(m_ui->terrasyncCheck, &QCheckBox::toggled,
546             this, &QtLauncher::onToggleTerrasync);
547     updateSettingsSummary();
548
549     m_aircraftModel = new AircraftItemModel(this);
550     m_aircraftProxy->setSourceModel(m_aircraftModel);
551
552     m_aircraftProxy->setFilterCaseSensitivity(Qt::CaseInsensitive);
553     m_aircraftProxy->setSortCaseSensitivity(Qt::CaseInsensitive);
554     m_aircraftProxy->setSortRole(Qt::DisplayRole);
555     m_aircraftProxy->setDynamicSortFilter(true);
556
557     m_ui->aircraftList->setModel(m_aircraftProxy);
558     m_ui->aircraftList->setHorizontalScrollBarPolicy(Qt::ScrollBarAlwaysOff);
559     AircraftItemDelegate* delegate = new AircraftItemDelegate(m_ui->aircraftList);
560     m_ui->aircraftList->setItemDelegate(delegate);
561     m_ui->aircraftList->setSelectionMode(QAbstractItemView::SingleSelection);
562     connect(m_ui->aircraftList, &QListView::clicked,
563             this, &QtLauncher::onAircraftSelected);
564     connect(delegate, &AircraftItemDelegate::variantChanged,
565             this, &QtLauncher::onAircraftSelected);
566     connect(delegate, &AircraftItemDelegate::requestInstall,
567             this, &QtLauncher::onRequestPackageInstall);
568     connect(delegate, &AircraftItemDelegate::cancelDownload,
569             this, &QtLauncher::onCancelDownload);
570
571     connect(m_aircraftModel, &AircraftItemModel::aircraftInstallCompleted,
572             this, &QtLauncher::onAircraftInstalledCompleted);
573     connect(m_aircraftModel, &AircraftItemModel::aircraftInstallFailed,
574             this, &QtLauncher::onAircraftInstallFailed);
575     connect(m_aircraftModel, &AircraftItemModel::scanCompleted,
576             this, &QtLauncher::updateSelectedAircraft);
577     connect(m_ui->pathsButton, &QPushButton::clicked,
578             this, &QtLauncher::onEditPaths);
579
580     // after any kind of reset, try to restore selection and scroll
581     // to match the m_selectedAircraft. This needs to be delayed
582     // fractionally otherwise the scrollTo seems to be ignored,
583     // unfortunately.
584     connect(m_aircraftProxy, &AircraftProxyModel::modelReset,
585             this, &QtLauncher::delayedAircraftModelReset);
586
587     QSettings settings;
588     m_aircraftModel->setPaths(settings.value("aircraft-paths").toStringList());
589     m_aircraftModel->setPackageRoot(globals->packageRoot());
590     m_aircraftModel->scanDirs();
591
592     restoreSettings();
593 }
594
595 QtLauncher::~QtLauncher()
596 {
597
598 }
599
600 void QtLauncher::setSceneryPaths()
601 {
602     globals->clear_fg_scenery();
603
604 // mimic what optionss.cxx does, so we can find airport data for parking
605 // positions
606     QSettings settings;
607     // append explicit scenery paths
608     Q_FOREACH(QString path, settings.value("scenery-paths").toStringList()) {
609         globals->append_fg_scenery(path.toStdString());
610     }
611
612     // append the TerraSync path
613     QString downloadDir = settings.value("download-dir").toString();
614     if (downloadDir.isEmpty()) {
615         downloadDir = QString::fromStdString(flightgear::defaultDownloadDir());
616     }
617
618     SGPath terraSyncDir(downloadDir.toStdString());
619     terraSyncDir.append("TerraSync");
620     if (terraSyncDir.exists()) {
621         globals->append_fg_scenery(terraSyncDir.str());
622     }
623
624 }
625
626 void QtLauncher::setInAppMode()
627 {
628   m_inAppMode = true;
629   m_ui->tabWidget->removeTab(2);
630   m_ui->runButton->setText(tr("Apply"));
631   m_ui->quitButton->setText(tr("Cancel"));
632
633   disconnect(m_ui->runButton, SIGNAL(clicked()), this, SLOT(onRun()));
634   connect(m_ui->runButton, SIGNAL(clicked()), this, SLOT(onApply()));
635 }
636
637 void QtLauncher::restoreSettings()
638 {
639     QSettings settings;
640     m_ui->rembrandtCheckbox->setChecked(settings.value("enable-rembrandt", false).toBool());
641     m_ui->terrasyncCheck->setChecked(settings.value("enable-terrasync", true).toBool());
642     m_ui->fullScreenCheckbox->setChecked(settings.value("start-fullscreen", false).toBool());
643     m_ui->msaaCheckbox->setChecked(settings.value("enable-msaa", false).toBool());
644     m_ui->fetchRealWxrCheckbox->setChecked(settings.value("enable-realwx", true).toBool());
645     m_ui->startPausedCheck->setChecked(settings.value("start-paused", false).toBool());
646     m_ui->timeOfDayCombo->setCurrentIndex(settings.value("timeofday", 0).toInt());
647     m_ui->seasonCombo->setCurrentIndex(settings.value("season", 0).toInt());
648
649     // full paths to -set.xml files
650     m_recentAircraft = QUrl::fromStringList(settings.value("recent-aircraft").toStringList());
651
652     if (!m_recentAircraft.empty()) {
653         m_selectedAircraft = m_recentAircraft.front();
654     } else {
655         // select the default C172p
656     }
657
658     if (!m_inAppMode) {
659         setSceneryPaths();
660     }
661
662     m_ui->location->restoreSettings();
663
664     // rating filters
665     m_ui->onlyShowInstalledCheck->setChecked(settings.value("only-show-installed", false).toBool());
666     if (m_ui->onlyShowInstalledCheck->isChecked()) {
667         m_ui->ratingsFilterCheck->setEnabled(false);
668     }
669
670     m_ui->ratingsFilterCheck->setChecked(settings.value("ratings-filter", true).toBool());
671     int index = 0;
672     Q_FOREACH(QVariant v, settings.value("min-ratings").toList()) {
673         m_ratingFilters[index++] = v.toInt();
674     }
675
676     m_aircraftProxy->setRatingFilterEnabled(m_ui->ratingsFilterCheck->isChecked());
677     m_aircraftProxy->setRatings(m_ratingFilters);
678
679     updateSelectedAircraft();
680     maybeRestoreAircraftSelection();
681
682     m_ui->commandLineArgs->setPlainText(settings.value("additional-args").toString());
683 }
684
685 void QtLauncher::delayedAircraftModelReset()
686 {
687     QTimer::singleShot(1, this, SLOT(maybeRestoreAircraftSelection()));
688 }
689
690 void QtLauncher::maybeRestoreAircraftSelection()
691 {
692     QModelIndex aircraftIndex = m_aircraftModel->indexOfAircraftURI(m_selectedAircraft);
693     QModelIndex proxyIndex = m_aircraftProxy->mapFromSource(aircraftIndex);
694     if (proxyIndex.isValid()) {
695         m_ui->aircraftList->selectionModel()->setCurrentIndex(proxyIndex,
696                                                               QItemSelectionModel::ClearAndSelect);
697         m_ui->aircraftList->selectionModel()->select(proxyIndex,
698                                                      QItemSelectionModel::ClearAndSelect);
699         m_ui->aircraftList->scrollTo(proxyIndex);
700     }
701 }
702
703 void QtLauncher::saveSettings()
704 {
705     QSettings settings;
706     settings.setValue("enable-rembrandt", m_ui->rembrandtCheckbox->isChecked());
707     settings.setValue("enable-terrasync", m_ui->terrasyncCheck->isChecked());
708     settings.setValue("enable-msaa", m_ui->msaaCheckbox->isChecked());
709     settings.setValue("start-fullscreen", m_ui->fullScreenCheckbox->isChecked());
710     settings.setValue("enable-realwx", m_ui->fetchRealWxrCheckbox->isChecked());
711     settings.setValue("start-paused", m_ui->startPausedCheck->isChecked());
712     settings.setValue("ratings-filter", m_ui->ratingsFilterCheck->isChecked());
713     settings.setValue("only-show-installed", m_ui->onlyShowInstalledCheck->isChecked());
714     settings.setValue("recent-aircraft", QUrl::toStringList(m_recentAircraft));
715
716     settings.setValue("timeofday", m_ui->timeOfDayCombo->currentIndex());
717     settings.setValue("season", m_ui->seasonCombo->currentIndex());
718     settings.setValue("additional-args", m_ui->commandLineArgs->toPlainText());
719
720     m_ui->location->saveSettings();
721 }
722
723 void QtLauncher::setEnableDisableOptionFromCheckbox(QCheckBox* cbox, QString name) const
724 {
725     flightgear::Options* opt = flightgear::Options::sharedInstance();
726     std::string stdName(name.toStdString());
727     if (cbox->isChecked()) {
728         opt->addOption("enable-" + stdName, "");
729     } else {
730         opt->addOption("disable-" + stdName, "");
731     }
732 }
733
734 void QtLauncher::closeEvent(QCloseEvent *event)
735 {
736     qApp->exit(-1);
737 }
738
739 void QtLauncher::onRun()
740 {
741     flightgear::Options* opt = flightgear::Options::sharedInstance();
742     setEnableDisableOptionFromCheckbox(m_ui->terrasyncCheck, "terrasync");
743     setEnableDisableOptionFromCheckbox(m_ui->fetchRealWxrCheckbox, "real-weather-fetch");
744     setEnableDisableOptionFromCheckbox(m_ui->rembrandtCheckbox, "rembrandt");
745     setEnableDisableOptionFromCheckbox(m_ui->fullScreenCheckbox, "fullscreen");
746 //    setEnableDisableOptionFromCheckbox(m_ui->startPausedCheck, "freeze");
747
748     bool startPaused = m_ui->startPausedCheck->isChecked() ||
749             m_ui->location->shouldStartPaused();
750     if (startPaused) {
751         opt->addOption("enable-freeze", "");
752     }
753
754     // MSAA is more complex
755     if (!m_ui->rembrandtCheckbox->isChecked()) {
756         if (m_ui->msaaCheckbox->isChecked()) {
757             globals->get_props()->setIntValue("/sim/rendering/multi-sample-buffers", 1);
758             globals->get_props()->setIntValue("/sim/rendering/multi-samples", 4);
759         } else {
760             globals->get_props()->setIntValue("/sim/rendering/multi-sample-buffers", 0);
761         }
762     }
763
764     // aircraft
765     if (!m_selectedAircraft.isEmpty()) {
766         if (m_selectedAircraft.isLocalFile()) {
767             QFileInfo setFileInfo(m_selectedAircraft.toLocalFile());
768             opt->addOption("aircraft-dir", setFileInfo.dir().absolutePath().toStdString());
769             QString setFile = setFileInfo.fileName();
770             Q_ASSERT(setFile.endsWith("-set.xml"));
771             setFile.truncate(setFile.count() - 8); // drop the '-set.xml' portion
772             opt->addOption("aircraft", setFile.toStdString());
773         } else if (m_selectedAircraft.scheme() == "package") {
774             QString qualifiedId = m_selectedAircraft.path();
775             // no need to set aircraft-dir, handled by the corresponding code
776             // in fgInitAircraft
777             opt->addOption("aircraft", qualifiedId.toStdString());
778         } else {
779             qWarning() << "unsupported aircraft launch URL" << m_selectedAircraft;
780         }
781
782       // manage aircraft history
783         if (m_recentAircraft.contains(m_selectedAircraft))
784           m_recentAircraft.removeOne(m_selectedAircraft);
785         m_recentAircraft.prepend(m_selectedAircraft);
786         if (m_recentAircraft.size() > MAX_RECENT_AIRCRAFT)
787           m_recentAircraft.pop_back();
788     }
789
790     m_ui->location->setLocationOptions();
791
792     // time of day
793     if (m_ui->timeOfDayCombo->currentIndex() != 0) {
794         QString dayval = m_ui->timeOfDayCombo->currentText().toLower();
795         opt->addOption("timeofday", dayval.toStdString());
796     }
797
798     if (m_ui->seasonCombo->currentIndex() != 0) {
799         QString seasonName = m_ui->seasonCombo->currentText().toLower();
800         opt->addOption("season", seasonName.toStdString());
801     }
802
803     QSettings settings;
804     QString downloadDir = settings.value("download-dir").toString();
805     if (!downloadDir.isEmpty()) {
806         QDir d(downloadDir);
807         if (!d.exists()) {
808             int result = QMessageBox::question(this, tr("Create download folder?"),
809                                   tr("The selected location for downloads does not exist. Create it?"),
810                                                QMessageBox::Yes | QMessageBox::No | QMessageBox::Cancel);
811             if (result == QMessageBox::Cancel) {
812                 return;
813             }
814
815             if (result == QMessageBox::Yes) {
816                 d.mkpath(downloadDir);
817             }
818         }
819
820         opt->addOption("download-dir", downloadDir.toStdString());
821     }
822
823     // scenery paths
824     Q_FOREACH(QString path, settings.value("scenery-paths").toStringList()) {
825         opt->addOption("fg-scenery", path.toStdString());
826     }
827
828     // aircraft paths
829     Q_FOREACH(QString path, settings.value("aircraft-paths").toStringList()) {
830         // can't use fg-aircraft for this, as it is processed before the launcher is run
831         globals->append_aircraft_path(path.toStdString());
832     }
833
834     // additional arguments
835     ArgumentsTokenizer tk;
836     Q_FOREACH(ArgumentsTokenizer::Arg a, tk.tokenize(m_ui->commandLineArgs->toPlainText())) {
837         if (a.arg.startsWith("prop:")) {
838             QString v = a.arg.mid(5) + "=" + a.value;
839             opt->addOption("prop", v.toStdString());
840         } else {
841             opt->addOption(a.arg.toStdString(), a.value.toStdString());
842         }
843     }
844
845     saveSettings();
846
847     qApp->exit(0);
848 }
849
850
851 void QtLauncher::onApply()
852 {
853     accept();
854
855     // aircraft
856     if (!m_selectedAircraft.isEmpty()) {
857         std::string aircraftPropValue,
858             aircraftDir;
859
860         if (m_selectedAircraft.isLocalFile()) {
861             QFileInfo setFileInfo(m_selectedAircraft.toLocalFile());
862             QString setFile = setFileInfo.fileName();
863             Q_ASSERT(setFile.endsWith("-set.xml"));
864             setFile.truncate(setFile.count() - 8); // drop the '-set.xml' portion
865             aircraftDir = setFileInfo.dir().absolutePath().toStdString();
866             aircraftPropValue = setFile.toStdString();
867         } else if (m_selectedAircraft.scheme() == "package") {
868             // no need to set aircraft-dir, handled by the corresponding code
869             // in fgInitAircraft
870             aircraftPropValue = m_selectedAircraft.path().toStdString();
871         } else {
872             qWarning() << "unsupported aircraft launch URL" << m_selectedAircraft;
873         }
874
875         // manage aircraft history
876         if (m_recentAircraft.contains(m_selectedAircraft))
877             m_recentAircraft.removeOne(m_selectedAircraft);
878         m_recentAircraft.prepend(m_selectedAircraft);
879         if (m_recentAircraft.size() > MAX_RECENT_AIRCRAFT)
880             m_recentAircraft.pop_back();
881
882         globals->get_props()->setStringValue("/sim/aircraft", aircraftPropValue);
883         globals->get_props()->setStringValue("/sim/aircraft-dir", aircraftDir);
884     }
885
886
887     saveSettings();
888 }
889
890 void QtLauncher::onQuit()
891 {
892     qApp->exit(-1);
893 }
894
895 void QtLauncher::onToggleTerrasync(bool enabled)
896 {
897     if (enabled) {
898         QSettings settings;
899         QString downloadDir = settings.value("download-dir").toString();
900         if (downloadDir.isEmpty()) {
901             downloadDir = QString::fromStdString(flightgear::defaultDownloadDir());
902         }
903
904         QFileInfo info(downloadDir);
905         if (!info.exists()) {
906             QMessageBox msg;
907             msg.setWindowTitle(tr("Create download folder?"));
908             msg.setText(tr("The download folder '%1' does not exist, create it now? "
909                            "Click 'change location' to choose another folder "
910                            "to store downloaded files").arg(downloadDir));
911             msg.addButton(QMessageBox::Yes);
912             msg.addButton(QMessageBox::Cancel);
913             msg.addButton(tr("Change location"), QMessageBox::ActionRole);
914             int result = msg.exec();
915
916             if (result == QMessageBox::Cancel) {
917                 m_ui->terrasyncCheck->setChecked(false);
918                 return;
919             }
920
921             if (result == QMessageBox::ActionRole) {
922                 onEditPaths();
923                 return;
924             }
925
926             QDir d(downloadDir);
927             d.mkpath(downloadDir);
928         }
929     } // of is enabled
930 }
931
932 void QtLauncher::onAircraftInstalledCompleted(QModelIndex index)
933 {
934     maybeUpdateSelectedAircraft(index);
935 }
936
937 void QtLauncher::onRatingsFilterToggled()
938 {
939     QModelIndex aircraftIndex = m_aircraftModel->indexOfAircraftURI(m_selectedAircraft);
940     QModelIndex proxyIndex = m_aircraftProxy->mapFromSource(aircraftIndex);
941     if (proxyIndex.isValid()) {
942         m_ui->aircraftList->scrollTo(proxyIndex);
943     }
944 }
945
946 void QtLauncher::onAircraftInstallFailed(QModelIndex index, QString errorMessage)
947 {
948     qWarning() << Q_FUNC_INFO << index.data(AircraftURIRole) << errorMessage;
949
950     QMessageBox msg;
951     msg.setWindowTitle(tr("Aircraft installation failed"));
952     msg.setText(tr("An error occurred installing the aircraft %1: %2").
953                 arg(index.data(Qt::DisplayRole).toString()).arg(errorMessage));
954     msg.addButton(QMessageBox::Ok);
955     msg.exec();
956
957     maybeUpdateSelectedAircraft(index);
958 }
959
960 void QtLauncher::onAircraftSelected(const QModelIndex& index)
961 {
962     m_selectedAircraft = index.data(AircraftURIRole).toUrl();
963     updateSelectedAircraft();
964 }
965
966 void QtLauncher::onRequestPackageInstall(const QModelIndex& index)
967 {
968     // also select, otherwise UI is confusing
969     m_selectedAircraft = index.data(AircraftURIRole).toUrl();
970     updateSelectedAircraft();
971
972     QString pkg = index.data(AircraftPackageIdRole).toString();
973     simgear::pkg::PackageRef pref = globals->packageRoot()->getPackageById(pkg.toStdString());
974     if (pref->isInstalled()) {
975         InstallRef install = pref->existingInstall();
976         if (install && install->hasUpdate()) {
977             globals->packageRoot()->scheduleToUpdate(install);
978         }
979     } else {
980         pref->install();
981     }
982 }
983
984 void QtLauncher::onCancelDownload(const QModelIndex& index)
985 {
986     QString pkg = index.data(AircraftPackageIdRole).toString();
987     simgear::pkg::PackageRef pref = globals->packageRoot()->getPackageById(pkg.toStdString());
988     simgear::pkg::InstallRef i = pref->existingInstall();
989     i->cancelDownload();
990 }
991
992 void QtLauncher::maybeUpdateSelectedAircraft(QModelIndex index)
993 {
994     QUrl u = index.data(AircraftURIRole).toUrl();
995     if (u == m_selectedAircraft) {
996         // potentially enable the run button now!
997         updateSelectedAircraft();
998     }
999 }
1000
1001 void QtLauncher::updateSelectedAircraft()
1002 {
1003     QModelIndex index = m_aircraftModel->indexOfAircraftURI(m_selectedAircraft);
1004     if (index.isValid()) {
1005         QPixmap pm = index.data(Qt::DecorationRole).value<QPixmap>();
1006         m_ui->thumbnail->setPixmap(pm);
1007         m_ui->aircraftDescription->setText(index.data(Qt::DisplayRole).toString());
1008
1009         int status = index.data(AircraftPackageStatusRole).toInt();
1010         bool canRun = (status == PackageInstalled);
1011         m_ui->runButton->setEnabled(canRun);
1012
1013         LauncherAircraftType aircraftType = Airplane;
1014         if (index.data(AircraftIsHelicopterRole).toBool()) {
1015             aircraftType = Helicopter;
1016         } else if (index.data(AircraftIsSeaplaneRole).toBool()) {
1017             aircraftType = Seaplane;
1018         }
1019
1020         m_ui->location->setAircraftType(aircraftType);
1021     } else {
1022         m_ui->thumbnail->setPixmap(QPixmap());
1023         m_ui->aircraftDescription->setText("");
1024         m_ui->runButton->setEnabled(false);
1025     }
1026 }
1027
1028 QModelIndex QtLauncher::proxyIndexForAircraftURI(QUrl uri) const
1029 {
1030   return m_aircraftProxy->mapFromSource(sourceIndexForAircraftURI(uri));
1031 }
1032
1033 QModelIndex QtLauncher::sourceIndexForAircraftURI(QUrl uri) const
1034 {
1035     AircraftItemModel* sourceModel = qobject_cast<AircraftItemModel*>(m_aircraftProxy->sourceModel());
1036     Q_ASSERT(sourceModel);
1037     return sourceModel->indexOfAircraftURI(uri);
1038 }
1039
1040 void QtLauncher::onPopupAircraftHistory()
1041 {
1042     if (m_recentAircraft.isEmpty()) {
1043         return;
1044     }
1045
1046     QMenu m;
1047     Q_FOREACH(QUrl uri, m_recentAircraft) {
1048         QModelIndex index = sourceIndexForAircraftURI(uri);
1049         if (!index.isValid()) {
1050             // not scanned yet
1051             continue;
1052         }
1053         QAction* act = m.addAction(index.data(Qt::DisplayRole).toString());
1054         act->setData(uri);
1055     }
1056
1057     QPoint popupPos = m_ui->aircraftHistory->mapToGlobal(m_ui->aircraftHistory->rect().bottomLeft());
1058     QAction* triggered = m.exec(popupPos);
1059     if (triggered) {
1060         m_selectedAircraft = triggered->data().toUrl();
1061         QModelIndex index = proxyIndexForAircraftURI(m_selectedAircraft);
1062         m_ui->aircraftList->selectionModel()->setCurrentIndex(index,
1063                                                               QItemSelectionModel::ClearAndSelect);
1064         m_ui->aircraftFilter->clear();
1065         updateSelectedAircraft();
1066     }
1067 }
1068
1069 void QtLauncher::onEditRatingsFilter()
1070 {
1071     EditRatingsFilterDialog dialog(this);
1072     dialog.setRatings(m_ratingFilters);
1073
1074     dialog.exec();
1075     if (dialog.result() == QDialog::Accepted) {
1076         QVariantList vl;
1077         for (int i=0; i<4; ++i) {
1078             m_ratingFilters[i] = dialog.getRating(i);
1079             vl.append(m_ratingFilters[i]);
1080         }
1081         m_aircraftProxy->setRatings(m_ratingFilters);
1082
1083         QSettings settings;
1084         settings.setValue("min-ratings", vl);
1085     }
1086 }
1087
1088 void QtLauncher::updateSettingsSummary()
1089 {
1090     QStringList summary;
1091     if (m_ui->timeOfDayCombo->currentIndex() > 0) {
1092         summary.append(QString(m_ui->timeOfDayCombo->currentText().toLower()));
1093     }
1094
1095     if (m_ui->seasonCombo->currentIndex() > 0) {
1096         summary.append(QString(m_ui->seasonCombo->currentText().toLower()));
1097     }
1098
1099     if (m_ui->rembrandtCheckbox->isChecked()) {
1100         summary.append("Rembrandt enabled");
1101     } else if (m_ui->msaaCheckbox->isChecked()) {
1102         summary.append("anti-aliasing");
1103     }
1104
1105     if (m_ui->fetchRealWxrCheckbox->isChecked()) {
1106         summary.append("live weather");
1107     }
1108
1109     if (m_ui->terrasyncCheck->isChecked()) {
1110         summary.append("automatic scenery downloads");
1111     }
1112
1113     if (m_ui->startPausedCheck->isChecked()) {
1114         summary.append("paused");
1115     }
1116
1117     QString s = summary.join(", ");
1118     s[0] = s[0].toUpper();
1119     m_ui->settingsDescription->setText(s);
1120 }
1121
1122 void QtLauncher::onRembrandtToggled(bool b)
1123 {
1124     // Rembrandt and multi-sample are exclusive
1125     m_ui->msaaCheckbox->setEnabled(!b);
1126 }
1127
1128 void QtLauncher::onShowInstalledAircraftToggled(bool b)
1129 {
1130     m_ui->ratingsFilterCheck->setEnabled(!b);
1131     maybeRestoreAircraftSelection();
1132 }
1133
1134 void QtLauncher::onSubsytemIdleTimeout()
1135 {
1136     globals->get_subsystem_mgr()->update(0.0);
1137 }
1138
1139 void QtLauncher::onEditPaths()
1140 {
1141     QSettings settings;
1142     QString previousDownloadDir = settings.value("download-dir").toString();
1143
1144     PathsDialog dlg(this, globals->packageRoot());
1145     dlg.exec();
1146     if (dlg.result() == QDialog::Accepted) {
1147         QString dd = settings.value("download-dir").toString();
1148         bool downloadDirChanged = (previousDownloadDir != dd);
1149         if (downloadDirChanged) {
1150             qDebug() << "download dir changed, resetting package root";
1151
1152             if (dd.isEmpty()) {
1153                 flightgear::Options::sharedInstance()->clearOption("download-dir");
1154             } else {
1155                 flightgear::Options::sharedInstance()->setOption("download-dir", dd.toStdString());
1156             }
1157
1158             // replace existing package root
1159             globals->get_subsystem<FGHTTPClient>()->shutdown();
1160             globals->setPackageRoot(simgear::pkg::RootRef());
1161
1162             // create new root with updated download-dir value
1163             fgInitPackageRoot();
1164
1165             globals->get_subsystem<FGHTTPClient>()->init();
1166         }
1167
1168         // re-scan the aircraft list
1169         m_aircraftModel->setPackageRoot(globals->packageRoot());
1170         m_aircraftModel->setPaths(settings.value("aircraft-paths").toStringList());
1171         m_aircraftModel->scanDirs();
1172
1173         // re-set scenery dirs
1174         setSceneryPaths();
1175     }
1176 }
1177
1178 void QtLauncher::onChangeRoot()
1179 {
1180     QMessageBox mbox(this);
1181     mbox.setText(tr("Change the data files location used by FlightGear?"));
1182     mbox.setInformativeText(tr("FlightGear cannot work without its data files. "
1183                                "(Also called the base package) "
1184                                "To change which files are used, quit FlightGear and open it again, "
1185                                "while holding down the 'shift' key, and you will be able to choose a "
1186                                "different data files location, or restore the default setting."));
1187     QPushButton* quitButton = mbox.addButton(tr("Quit FlightGear now"), QMessageBox::YesRole);
1188     mbox.addButton(QMessageBox::Cancel);
1189     mbox.setDefaultButton(QMessageBox::Cancel);
1190     mbox.setIconPixmap(QPixmap(":/app-icon-large"));
1191
1192     mbox.exec();
1193     if (mbox.clickedButton() != quitButton) {
1194         return;
1195     }
1196
1197     // following code doesn't work reliably, so we take the simpler
1198     // option of asking the user to re-launch us while holding down
1199     // the hot-key (shift)
1200 #if 0
1201     {
1202         QSettings settings;
1203         // set the option to the magic marker value
1204         settings.setValue("fg-root", "!ask");
1205     } // scope the ensure settings are written nicel
1206
1207     // Spawn a new instance of myApplication:
1208     QProcess proc;
1209 #if defined(Q_OS_MAC)
1210     QStringList args;
1211
1212     QDir dir(qApp->applicationDirPath()); // returns the 'MacOS' dir
1213     dir.cdUp(); // up to 'contents' dir
1214     dir.cdUp(); // up to .app dir
1215     args << dir.absolutePath();
1216     proc.startDetached("open", args);
1217 #else
1218     proc.startDetached(qApp->applicationFilePath());
1219 #endif
1220 #endif
1221
1222     qDebug() << "doing app exit";
1223     qApp->exit(-1);
1224 }
1225
1226 simgear::pkg::PackageRef QtLauncher::packageForAircraftURI(QUrl uri) const
1227 {
1228     if (uri.scheme() != "package") {
1229         qWarning() << "invalid URL scheme:" << uri;
1230         return simgear::pkg::PackageRef();
1231     }
1232
1233     QString ident = uri.path();
1234     return globals->packageRoot()->getPackageById(ident.toStdString());
1235 }
1236
1237
1238 #include "QtLauncher.moc"