]> git.mxchange.org Git - flightgear.git/blob - src/GUI/QtLauncher.cxx
Async loading of NaturalEarth data for launcher.
[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 #include <QThread>
51
52 // Simgear
53 #include <simgear/timing/timestamp.hxx>
54 #include <simgear/props/props_io.hxx>
55 #include <simgear/structure/exception.hxx>
56 #include <simgear/structure/subsystem_mgr.hxx>
57 #include <simgear/misc/sg_path.hxx>
58 #include <simgear/package/Catalog.hxx>
59 #include <simgear/package/Package.hxx>
60 #include <simgear/package/Install.hxx>
61
62 #include "ui_Launcher.h"
63 #include "ui_NoOfficialHangar.h"
64
65 #include "EditRatingsFilterDialog.hxx"
66 #include "AircraftItemDelegate.hxx"
67 #include "AircraftModel.hxx"
68 #include "PathsDialog.hxx"
69 #include "EditCustomMPServerDialog.hxx"
70
71 #include <Main/globals.hxx>
72 #include <Main/fg_props.hxx>
73 #include <Navaids/NavDataCache.hxx>
74 #include <Navaids/navrecord.hxx>
75 #include <Navaids/SHPParser.hxx>
76
77 #include <Main/options.hxx>
78 #include <Main/fg_init.hxx>
79 #include <Viewer/WindowBuilder.hxx>
80 #include <Network/HTTPClient.hxx>
81 #include <Network/RemoteXMLRequest.hxx>
82
83 using namespace flightgear;
84 using namespace simgear::pkg;
85
86 const int MAX_RECENT_AIRCRAFT = 20;
87
88 namespace { // anonymous namespace
89
90 void initNavCache()
91 {
92     QString baseLabel = QT_TR_NOOP("Initialising navigation data, this may take several minutes");
93     NavDataCache* cache = NavDataCache::createInstance();
94     if (cache->isRebuildRequired()) {
95         QProgressDialog rebuildProgress(baseLabel,
96                                        QString() /* cancel text */,
97                                        0, 100, Q_NULLPTR,
98                                        Qt::Dialog
99                                            | Qt::CustomizeWindowHint
100                                            | Qt::WindowTitleHint
101                                            | Qt::WindowSystemMenuHint
102                                            | Qt::MSWindowsFixedSizeDialogHint);
103         rebuildProgress.setWindowModality(Qt::WindowModal);
104         rebuildProgress.show();
105
106         NavDataCache::RebuildPhase phase = cache->rebuild();
107
108         while (phase != NavDataCache::REBUILD_DONE) {
109             // sleep to give the rebuild thread more time
110             SGTimeStamp::sleepForMSec(50);
111             phase = cache->rebuild();
112
113             switch (phase) {
114             case NavDataCache::REBUILD_AIRPORTS:
115                 rebuildProgress.setLabelText(QT_TR_NOOP("Loading airport data"));
116                 break;
117
118             case NavDataCache::REBUILD_FIXES:
119                 rebuildProgress.setLabelText(QT_TR_NOOP("Loading waypoint data"));
120                 break;
121
122             case NavDataCache::REBUILD_NAVAIDS:
123                 rebuildProgress.setLabelText(QT_TR_NOOP("Loading navigation data"));
124                 break;
125
126
127             case NavDataCache::REBUILD_POIS:
128                 rebuildProgress.setLabelText(QT_TR_NOOP("Loading point-of-interest data"));
129                 break;
130
131             default:
132                 rebuildProgress.setLabelText(baseLabel);
133             }
134
135             if (phase == NavDataCache::REBUILD_UNKNOWN) {
136                 rebuildProgress.setValue(0);
137                 rebuildProgress.setMaximum(0);
138             } else {
139                 rebuildProgress.setValue(cache->rebuildPhaseCompletionPercentage());
140                 rebuildProgress.setMaximum(100);
141             }
142
143             QCoreApplication::processEvents();
144         }
145     }
146 }
147
148 class ArgumentsTokenizer
149 {
150 public:
151     class Arg
152     {
153     public:
154         explicit Arg(QString k, QString v = QString()) : arg(k), value(v) {}
155
156         QString arg;
157         QString value;
158     };
159
160     QList<Arg> tokenize(QString in) const
161     {
162         int index = 0;
163         const int len = in.count();
164         QChar c, nc;
165         State state = Start;
166         QString key, value;
167         QList<Arg> result;
168
169         for (; index < len; ++index) {
170             c = in.at(index);
171             nc = index < (len - 1) ? in.at(index + 1) : QChar();
172
173             switch (state) {
174             case Start:
175                 if (c == QChar('-')) {
176                     if (nc == QChar('-')) {
177                         state = Key;
178                         key.clear();
179                         ++index;
180                     } else {
181                         // should we pemit single hyphen arguments?
182                         // choosing to fail for now
183                         return QList<Arg>();
184                     }
185                 } else if (c == QChar('#')) {
186                     state = Comment;
187                     break;
188                 } else if (c.isSpace()) {
189                     break;
190                 }
191                 break;
192
193             case Key:
194                 if (c == QChar('=')) {
195                     state = Value;
196                     value.clear();
197                 } else if (c.isSpace()) {
198                     state = Start;
199                     result.append(Arg(key));
200                 } else {
201                     // could check for illegal charatcers here
202                     key.append(c);
203                 }
204                 break;
205
206             case Value:
207                 if (c == QChar('"')) {
208                     state = Quoted;
209                 } else if (c.isSpace()) {
210                     state = Start;
211                     result.append(Arg(key, value));
212                 } else {
213                     value.append(c);
214                 }
215                 break;
216
217             case Quoted:
218                 if (c == QChar('\\')) {
219                     // check for escaped double-quote inside quoted value
220                     if (nc == QChar('"')) {
221                         ++index;
222                     }
223                 } else if (c == QChar('"')) {
224                     state = Value;
225                 } else {
226                     value.append(c);
227                 }
228                 break;
229
230             case Comment:
231                 if ((c == QChar('\n')) || (c == QChar('\r'))) {
232                     state = Start;
233                     break;
234                 } else {
235                     // nothing to do, eat comment chars
236                 }
237                 break;
238             } // of state switch
239         } // of character loop
240
241         // ensure last argument isn't lost
242         if (state == Key) {
243             result.append(Arg(key));
244         } else if (state == Value) {
245             result.append(Arg(key, value));
246         }
247
248         return result;
249     }
250
251 private:
252     enum State {
253         Start = 0,
254         Key,
255         Value,
256         Quoted,
257         Comment
258     };
259 };
260
261 class NaturalEarthDataLoaderThread : public QThread
262 {
263     Q_OBJECT
264 public:
265
266     NaturalEarthDataLoaderThread()
267     {
268         connect(this, &QThread::finished, this, &NaturalEarthDataLoaderThread::onFinished);
269     }
270
271 protected:
272     virtual void run() Q_DECL_OVERRIDE
273     {
274         SGTimeStamp st;
275         st.stamp();
276
277         loadNaturalEarthFile("ne_10m_coastline.shp", flightgear::PolyLine::COASTLINE, false);
278         loadNaturalEarthFile("ne_10m_rivers_lake_centerlines.shp", flightgear::PolyLine::RIVER, false);
279         loadNaturalEarthFile("ne_10m_lakes.shp", flightgear::PolyLine::LAKE, true);
280
281         qDebug() << "load basic data took" << st.elapsedMSec();
282
283         st.stamp();
284         loadNaturalEarthFile("ne_10m_urban_areas.shp", flightgear::PolyLine::URBAN, true);
285
286         qDebug() << "loading urban areas took:" << st.elapsedMSec();
287
288     }
289
290 private:
291     void onFinished()
292     {
293         flightgear::PolyLine::bulkAddToSpatialIndex(m_parsedLines);
294         qDebug() << "finished loading Natural Earth data";
295         deleteLater(); // commit suicide
296     }
297
298     void loadNaturalEarthFile(const std::string& aFileName,
299                               flightgear::PolyLine::Type aType,
300                               bool areClosed)
301     {
302         SGPath path(globals->get_fg_root());
303         path.append( "Geodata" );
304         path.append(aFileName);
305         if (!path.exists())
306             return; // silently fail for now
307
308         flightgear::PolyLineList lines;
309         flightgear::SHPParser::parsePolyLines(path, aType, m_parsedLines, areClosed);
310     }
311     
312     flightgear::PolyLineList m_parsedLines;
313 };
314
315 } // of anonymous namespace
316
317 class AircraftProxyModel : public QSortFilterProxyModel
318 {
319     Q_OBJECT
320 public:
321     AircraftProxyModel(QObject* pr) :
322         QSortFilterProxyModel(pr),
323         m_ratingsFilter(true),
324         m_onlyShowInstalled(false)
325     {
326         for (int i=0; i<4; ++i) {
327             m_ratings[i] = 3;
328         }
329     }
330
331     void setRatings(int* ratings)
332     {
333         ::memcpy(m_ratings, ratings, sizeof(int) * 4);
334         invalidate();
335     }
336
337 public slots:
338     void setRatingFilterEnabled(bool e)
339     {
340         if (e == m_ratingsFilter) {
341             return;
342         }
343
344         m_ratingsFilter = e;
345         invalidate();
346     }
347
348     void setInstalledFilterEnabled(bool e)
349     {
350         if (e == m_onlyShowInstalled) {
351             return;
352         }
353
354         m_onlyShowInstalled = e;
355         invalidate();
356     }
357
358 protected:
359     bool filterAcceptsRow(int sourceRow, const QModelIndex &sourceParent) const
360     {
361         QModelIndex index = sourceModel()->index(sourceRow, 0, sourceParent);
362         QVariant v = index.data(AircraftPackageStatusRole);
363         AircraftItemStatus status = static_cast<AircraftItemStatus>(v.toInt());
364         if (status == NoOfficialCatalogMessage) {
365             return true;
366         }
367
368         if (!QSortFilterProxyModel::filterAcceptsRow(sourceRow, sourceParent)) {
369             return false;
370         }
371
372         if (m_onlyShowInstalled) {
373             QVariant v = index.data(AircraftPackageStatusRole);
374             AircraftItemStatus status = static_cast<AircraftItemStatus>(v.toInt());
375             if (status == PackageNotInstalled) {
376                 return false;
377             }
378         }
379
380         if (!m_onlyShowInstalled && m_ratingsFilter) {
381             for (int i=0; i<4; ++i) {
382                 if (m_ratings[i] > index.data(AircraftRatingRole + i).toInt()) {
383                     return false;
384                 }
385             }
386         }
387
388         return true;
389     }
390
391 private:
392     bool m_ratingsFilter;
393     bool m_onlyShowInstalled;
394     int m_ratings[4];
395 };
396
397 class NoOfficialHangarMessage : public QWidget
398 {
399     Q_OBJECT
400 public:
401     NoOfficialHangarMessage() :
402         m_ui(new Ui::NoOfficialHangarMessage)
403     {
404         m_ui->setupUi(this);
405         // proxy this signal upwards
406         connect(m_ui->label, &QLabel::linkActivated,
407                 this, &NoOfficialHangarMessage::linkActivated);
408     }
409
410 Q_SIGNALS:
411     void linkActivated(QUrl link);
412
413 private:
414     Ui::NoOfficialHangarMessage* m_ui;
415 };
416
417 static void initQtResources()
418 {
419     Q_INIT_RESOURCE(resources);
420 }
421
422 namespace flightgear
423 {
424
425 void initApp(int& argc, char** argv)
426 {
427     static bool qtInitDone = false;
428     static int s_argc;
429
430     if (!qtInitDone) {
431         qtInitDone = true;
432
433         sglog().setLogLevels( SG_ALL, SG_INFO );
434         initQtResources(); // can't be called from a namespace
435
436         s_argc = argc; // QApplication only stores a reference to argc,
437         // and may crash if it is freed
438         // http://doc.qt.io/qt-5/qguiapplication.html#QGuiApplication
439
440         QApplication* app = new QApplication(s_argc, argv);
441         app->setOrganizationName("FlightGear");
442         app->setApplicationName("FlightGear");
443         app->setOrganizationDomain("flightgear.org");
444
445         QSettings::setDefaultFormat(QSettings::IniFormat);
446         QSettings::setPath(QSettings::IniFormat, QSettings::UserScope,
447                            QString::fromStdString(globals->get_fg_home().utf8Str()));
448
449         // reset numeric / collation locales as described at:
450         // http://doc.qt.io/qt-5/qcoreapplication.html#details
451         ::setlocale(LC_NUMERIC, "C");
452         ::setlocale(LC_COLLATE, "C");
453
454         Qt::KeyboardModifiers mods = app->queryKeyboardModifiers();
455         if (mods & (Qt::AltModifier | Qt::ShiftModifier)) {
456             qWarning() << "Alt/shift pressed during launch";
457             QSettings settings;
458             settings.setValue("fg-root", "!ask");
459         }
460     }
461 }
462
463 bool runLauncherDialog()
464 {
465     // startup the nav-cache now. This pre-empts normal startup of
466     // the cache, but no harm done. (Providing scenery paths are consistent)
467
468     initNavCache();
469
470     QSettings settings;
471     QString downloadDir = settings.value("download-dir").toString();
472     if (!downloadDir.isEmpty()) {
473         flightgear::Options::sharedInstance()->setOption("download-dir", downloadDir.toStdString());
474     }
475
476     fgInitPackageRoot();
477
478     // startup the HTTP system now since packages needs it
479     FGHTTPClient* http = globals->add_new_subsystem<FGHTTPClient>();
480
481     // we guard against re-init in the global phase; bind and postinit
482     // will happen as normal
483     http->init();
484
485     NaturalEarthDataLoaderThread* naturalEarthLoader = new NaturalEarthDataLoaderThread;
486     naturalEarthLoader->start();
487
488     // avoid double Apple menu and other weirdness if both Qt and OSG
489     // try to initialise various Cocoa structures.
490     flightgear::WindowBuilder::setPoseAsStandaloneApp(false);
491
492     QtLauncher dlg;
493     dlg.show();
494
495     int appResult = qApp->exec();
496     if (appResult < 0) {
497         return false; // quit
498     }
499
500     // don't set scenery paths twice
501     globals->clear_fg_scenery();
502
503     return true;
504 }
505
506 bool runInAppLauncherDialog()
507 {
508     QtLauncher dlg;
509     dlg.setInAppMode();
510     dlg.exec();
511     if (dlg.result() != QDialog::Accepted) {
512         return false;
513     }
514
515     return true;
516 }
517
518 } // of namespace flightgear
519
520 QtLauncher::QtLauncher() :
521     QDialog(),
522     m_ui(NULL),
523     m_subsystemIdleTimer(NULL),
524     m_inAppMode(false),
525     m_doRestoreMPServer(false)
526 {
527     m_ui.reset(new Ui::Launcher);
528     m_ui->setupUi(this);
529
530 #if QT_VERSION >= 0x050300
531     // don't require Qt 5.3
532     m_ui->commandLineArgs->setPlaceholderText("--option=value --prop:/sim/name=value");
533 #endif
534
535 #if QT_VERSION >= 0x050200
536     m_ui->aircraftFilter->setClearButtonEnabled(true);
537 #endif
538
539     for (int i=0; i<4; ++i) {
540         m_ratingFilters[i] = 3;
541     }
542
543     m_subsystemIdleTimer = new QTimer(this);
544     m_subsystemIdleTimer->setInterval(0);
545     connect(m_subsystemIdleTimer, &QTimer::timeout,
546             this, &QtLauncher::onSubsytemIdleTimeout);
547     m_subsystemIdleTimer->start();
548
549     // create and configure the proxy model
550     m_aircraftProxy = new AircraftProxyModel(this);
551     connect(m_ui->ratingsFilterCheck, &QAbstractButton::toggled,
552             m_aircraftProxy, &AircraftProxyModel::setRatingFilterEnabled);
553     connect(m_ui->ratingsFilterCheck, &QAbstractButton::toggled,
554             this, &QtLauncher::maybeRestoreAircraftSelection);
555
556     connect(m_ui->onlyShowInstalledCheck, &QAbstractButton::toggled,
557             m_aircraftProxy, &AircraftProxyModel::setInstalledFilterEnabled);
558     connect(m_ui->aircraftFilter, &QLineEdit::textChanged,
559             m_aircraftProxy, &QSortFilterProxyModel::setFilterFixedString);
560
561     connect(m_ui->runButton, SIGNAL(clicked()), this, SLOT(onRun()));
562     connect(m_ui->quitButton, SIGNAL(clicked()), this, SLOT(onQuit()));
563
564     connect(m_ui->aircraftHistory, &QPushButton::clicked,
565           this, &QtLauncher::onPopupAircraftHistory);
566
567     connect(m_ui->location, &LocationWidget::descriptionChanged,
568             m_ui->locationDescription, &QLabel::setText);
569
570     QAction* qa = new QAction(this);
571     qa->setShortcut(QKeySequence("Ctrl+Q"));
572     connect(qa, &QAction::triggered, this, &QtLauncher::onQuit);
573     addAction(qa);
574
575     connect(m_ui->editRatingFilter, &QPushButton::clicked,
576             this, &QtLauncher::onEditRatingsFilter);
577     connect(m_ui->onlyShowInstalledCheck, &QCheckBox::toggled,
578             this, &QtLauncher::onShowInstalledAircraftToggled);
579
580     QIcon historyIcon(":/history-icon");
581     m_ui->aircraftHistory->setIcon(historyIcon);
582
583     connect(m_ui->timeOfDayCombo, SIGNAL(currentIndexChanged(int)),
584             this, SLOT(updateSettingsSummary()));
585     connect(m_ui->seasonCombo, SIGNAL(currentIndexChanged(int)),
586             this, SLOT(updateSettingsSummary()));
587     connect(m_ui->fetchRealWxrCheckbox, SIGNAL(toggled(bool)),
588             this, SLOT(updateSettingsSummary()));
589     connect(m_ui->rembrandtCheckbox, SIGNAL(toggled(bool)),
590             this, SLOT(updateSettingsSummary()));
591     connect(m_ui->terrasyncCheck, SIGNAL(toggled(bool)),
592             this, SLOT(updateSettingsSummary()));
593     connect(m_ui->startPausedCheck, SIGNAL(toggled(bool)),
594             this, SLOT(updateSettingsSummary()));
595     connect(m_ui->msaaCheckbox, SIGNAL(toggled(bool)),
596             this, SLOT(updateSettingsSummary()));
597
598     connect(m_ui->rembrandtCheckbox, SIGNAL(toggled(bool)),
599             this, SLOT(onRembrandtToggled(bool)));
600     connect(m_ui->terrasyncCheck, &QCheckBox::toggled,
601             this, &QtLauncher::onToggleTerrasync);
602     updateSettingsSummary();
603
604     connect(m_ui->mpServerCombo, SIGNAL(activated(int)),
605             this, SLOT(onMPServerActivated(int)));
606
607     m_aircraftModel = new AircraftItemModel(this);
608     m_aircraftProxy->setSourceModel(m_aircraftModel);
609
610     m_aircraftProxy->setFilterCaseSensitivity(Qt::CaseInsensitive);
611     m_aircraftProxy->setSortCaseSensitivity(Qt::CaseInsensitive);
612     m_aircraftProxy->setSortRole(Qt::DisplayRole);
613     m_aircraftProxy->setDynamicSortFilter(true);
614
615     m_ui->aircraftList->setModel(m_aircraftProxy);
616     m_ui->aircraftList->setHorizontalScrollBarPolicy(Qt::ScrollBarAlwaysOff);
617     AircraftItemDelegate* delegate = new AircraftItemDelegate(m_ui->aircraftList);
618     m_ui->aircraftList->setItemDelegate(delegate);
619     m_ui->aircraftList->setSelectionMode(QAbstractItemView::SingleSelection);
620     connect(m_ui->aircraftList, &QListView::clicked,
621             this, &QtLauncher::onAircraftSelected);
622     connect(delegate, &AircraftItemDelegate::variantChanged,
623             this, &QtLauncher::onAircraftSelected);
624     connect(delegate, &AircraftItemDelegate::requestInstall,
625             this, &QtLauncher::onRequestPackageInstall);
626     connect(delegate, &AircraftItemDelegate::cancelDownload,
627             this, &QtLauncher::onCancelDownload);
628
629     connect(m_aircraftModel, &AircraftItemModel::aircraftInstallCompleted,
630             this, &QtLauncher::onAircraftInstalledCompleted);
631     connect(m_aircraftModel, &AircraftItemModel::aircraftInstallFailed,
632             this, &QtLauncher::onAircraftInstallFailed);
633     connect(m_aircraftModel, &AircraftItemModel::scanCompleted,
634             this, &QtLauncher::updateSelectedAircraft);
635     connect(m_ui->restoreDefaultsButton, &QPushButton::clicked,
636             this, &QtLauncher::onRestoreDefaults);
637
638
639     AddOnsPage* addOnsPage = new AddOnsPage(NULL, globals->packageRoot());
640     connect(addOnsPage, &AddOnsPage::downloadDirChanged,
641             this, &QtLauncher::onDownloadDirChanged);
642     connect(addOnsPage, &AddOnsPage::sceneryPathsChanged,
643             this, &QtLauncher::setSceneryPaths);
644
645     m_ui->tabWidget->addTab(addOnsPage, tr("Add-ons"));
646     // after any kind of reset, try to restore selection and scroll
647     // to match the m_selectedAircraft. This needs to be delayed
648     // fractionally otherwise the scrollTo seems to be ignored,
649     // unfortunately.
650     connect(m_aircraftProxy, &AircraftProxyModel::modelReset,
651             this, &QtLauncher::delayedAircraftModelReset);
652
653     QSettings settings;
654     m_aircraftModel->setPaths(settings.value("aircraft-paths").toStringList());
655     m_aircraftModel->setPackageRoot(globals->packageRoot());
656     m_aircraftModel->scanDirs();
657
658     checkOfficialCatalogMessage();
659     restoreSettings();
660
661     onRefreshMPServers();
662 }
663
664 QtLauncher::~QtLauncher()
665 {
666
667 }
668
669 void QtLauncher::setSceneryPaths()
670 {
671     globals->clear_fg_scenery();
672
673 // mimic what optionss.cxx does, so we can find airport data for parking
674 // positions
675     QSettings settings;
676     // append explicit scenery paths
677     Q_FOREACH(QString path, settings.value("scenery-paths").toStringList()) {
678         globals->append_fg_scenery(path.toStdString());
679     }
680
681     // append the TerraSync path
682     QString downloadDir = settings.value("download-dir").toString();
683     if (downloadDir.isEmpty()) {
684         downloadDir = QString::fromStdString(flightgear::defaultDownloadDir().utf8Str());
685     }
686
687     SGPath terraSyncDir(downloadDir.toStdString());
688     terraSyncDir.append("TerraSync");
689     if (terraSyncDir.exists()) {
690         globals->append_fg_scenery(terraSyncDir);
691     }
692
693 }
694
695 void QtLauncher::setInAppMode()
696 {
697   m_inAppMode = true;
698   m_ui->tabWidget->removeTab(2);
699   m_ui->tabWidget->removeTab(2);
700
701   m_ui->runButton->setText(tr("Apply"));
702   m_ui->quitButton->setText(tr("Cancel"));
703
704   disconnect(m_ui->runButton, SIGNAL(clicked()), this, SLOT(onRun()));
705   connect(m_ui->runButton, SIGNAL(clicked()), this, SLOT(onApply()));
706 }
707
708 void QtLauncher::restoreSettings()
709 {
710     QSettings settings;
711     m_ui->rembrandtCheckbox->setChecked(settings.value("enable-rembrandt", false).toBool());
712     m_ui->terrasyncCheck->setChecked(settings.value("enable-terrasync", true).toBool());
713     m_ui->fullScreenCheckbox->setChecked(settings.value("start-fullscreen", false).toBool());
714     m_ui->msaaCheckbox->setChecked(settings.value("enable-msaa", false).toBool());
715     m_ui->fetchRealWxrCheckbox->setChecked(settings.value("enable-realwx", true).toBool());
716     m_ui->startPausedCheck->setChecked(settings.value("start-paused", false).toBool());
717     m_ui->timeOfDayCombo->setCurrentIndex(settings.value("timeofday", 0).toInt());
718     m_ui->seasonCombo->setCurrentIndex(settings.value("season", 0).toInt());
719
720     // full paths to -set.xml files
721     m_recentAircraft = QUrl::fromStringList(settings.value("recent-aircraft").toStringList());
722
723     if (!m_recentAircraft.empty()) {
724         m_selectedAircraft = m_recentAircraft.front();
725     } else {
726         // select the default C172p
727     }
728
729     if (!m_inAppMode) {
730         setSceneryPaths();
731     }
732
733     m_ui->location->restoreSettings();
734
735     // rating filters
736     m_ui->onlyShowInstalledCheck->setChecked(settings.value("only-show-installed", false).toBool());
737     if (m_ui->onlyShowInstalledCheck->isChecked()) {
738         m_ui->ratingsFilterCheck->setEnabled(false);
739     }
740
741     m_ui->ratingsFilterCheck->setChecked(settings.value("ratings-filter", true).toBool());
742     int index = 0;
743     Q_FOREACH(QVariant v, settings.value("min-ratings").toList()) {
744         m_ratingFilters[index++] = v.toInt();
745     }
746
747     m_aircraftProxy->setRatingFilterEnabled(m_ui->ratingsFilterCheck->isChecked());
748     m_aircraftProxy->setRatings(m_ratingFilters);
749
750     updateSelectedAircraft();
751     maybeRestoreAircraftSelection();
752
753     m_ui->commandLineArgs->setPlainText(settings.value("additional-args").toString());
754
755     m_ui->mpBox->setChecked(settings.value("mp-enabled").toBool());
756     m_ui->mpCallsign->setText(settings.value("mp-callsign").toString());
757     // don't restore MP server here, we do it after a refresh
758     m_doRestoreMPServer = true;
759 }
760
761 void QtLauncher::delayedAircraftModelReset()
762 {
763     QTimer::singleShot(1, this, SLOT(maybeRestoreAircraftSelection()));
764 }
765
766 void QtLauncher::maybeRestoreAircraftSelection()
767 {
768     QModelIndex aircraftIndex = m_aircraftModel->indexOfAircraftURI(m_selectedAircraft);
769     QModelIndex proxyIndex = m_aircraftProxy->mapFromSource(aircraftIndex);
770     if (proxyIndex.isValid()) {
771         m_ui->aircraftList->selectionModel()->setCurrentIndex(proxyIndex,
772                                                               QItemSelectionModel::ClearAndSelect);
773         m_ui->aircraftList->selectionModel()->select(proxyIndex,
774                                                      QItemSelectionModel::ClearAndSelect);
775         m_ui->aircraftList->scrollTo(proxyIndex);
776     }
777 }
778
779 void QtLauncher::saveSettings()
780 {
781     QSettings settings;
782     settings.setValue("enable-rembrandt", m_ui->rembrandtCheckbox->isChecked());
783     settings.setValue("enable-terrasync", m_ui->terrasyncCheck->isChecked());
784     settings.setValue("enable-msaa", m_ui->msaaCheckbox->isChecked());
785     settings.setValue("start-fullscreen", m_ui->fullScreenCheckbox->isChecked());
786     settings.setValue("enable-realwx", m_ui->fetchRealWxrCheckbox->isChecked());
787     settings.setValue("start-paused", m_ui->startPausedCheck->isChecked());
788     settings.setValue("ratings-filter", m_ui->ratingsFilterCheck->isChecked());
789     settings.setValue("only-show-installed", m_ui->onlyShowInstalledCheck->isChecked());
790     settings.setValue("recent-aircraft", QUrl::toStringList(m_recentAircraft));
791
792     settings.setValue("timeofday", m_ui->timeOfDayCombo->currentIndex());
793     settings.setValue("season", m_ui->seasonCombo->currentIndex());
794     settings.setValue("additional-args", m_ui->commandLineArgs->toPlainText());
795
796     m_ui->location->saveSettings();
797
798     settings.setValue("mp-callsign", m_ui->mpCallsign->text());
799     settings.setValue("mp-server", m_ui->mpServerCombo->currentData());
800     settings.setValue("mp-enabled", m_ui->mpBox->isChecked());
801 }
802
803 void QtLauncher::setEnableDisableOptionFromCheckbox(QCheckBox* cbox, QString name) const
804 {
805     flightgear::Options* opt = flightgear::Options::sharedInstance();
806     std::string stdName(name.toStdString());
807     if (cbox->isChecked()) {
808         opt->addOption("enable-" + stdName, "");
809     } else {
810         opt->addOption("disable-" + stdName, "");
811     }
812 }
813
814 void QtLauncher::closeEvent(QCloseEvent *event)
815 {
816     qApp->exit(-1);
817 }
818
819 void QtLauncher::reject()
820 {
821     qApp->exit(-1);
822 }
823
824 void QtLauncher::onRun()
825 {
826     flightgear::Options* opt = flightgear::Options::sharedInstance();
827     setEnableDisableOptionFromCheckbox(m_ui->terrasyncCheck, "terrasync");
828     setEnableDisableOptionFromCheckbox(m_ui->fetchRealWxrCheckbox, "real-weather-fetch");
829     setEnableDisableOptionFromCheckbox(m_ui->rembrandtCheckbox, "rembrandt");
830     setEnableDisableOptionFromCheckbox(m_ui->fullScreenCheckbox, "fullscreen");
831 //    setEnableDisableOptionFromCheckbox(m_ui->startPausedCheck, "freeze");
832
833     bool startPaused = m_ui->startPausedCheck->isChecked() ||
834             m_ui->location->shouldStartPaused();
835     if (startPaused) {
836         opt->addOption("enable-freeze", "");
837     }
838
839     // MSAA is more complex
840     if (!m_ui->rembrandtCheckbox->isChecked()) {
841         if (m_ui->msaaCheckbox->isChecked()) {
842             globals->get_props()->setIntValue("/sim/rendering/multi-sample-buffers", 1);
843             globals->get_props()->setIntValue("/sim/rendering/multi-samples", 4);
844         } else {
845             globals->get_props()->setIntValue("/sim/rendering/multi-sample-buffers", 0);
846         }
847     }
848
849     // aircraft
850     if (!m_selectedAircraft.isEmpty()) {
851         if (m_selectedAircraft.isLocalFile()) {
852             QFileInfo setFileInfo(m_selectedAircraft.toLocalFile());
853             opt->addOption("aircraft-dir", setFileInfo.dir().absolutePath().toStdString());
854             QString setFile = setFileInfo.fileName();
855             Q_ASSERT(setFile.endsWith("-set.xml"));
856             setFile.truncate(setFile.count() - 8); // drop the '-set.xml' portion
857             opt->addOption("aircraft", setFile.toStdString());
858         } else if (m_selectedAircraft.scheme() == "package") {
859             QString qualifiedId = m_selectedAircraft.path();
860             // no need to set aircraft-dir, handled by the corresponding code
861             // in fgInitAircraft
862             opt->addOption("aircraft", qualifiedId.toStdString());
863         } else {
864             qWarning() << "unsupported aircraft launch URL" << m_selectedAircraft;
865         }
866
867       // manage aircraft history
868         if (m_recentAircraft.contains(m_selectedAircraft))
869           m_recentAircraft.removeOne(m_selectedAircraft);
870         m_recentAircraft.prepend(m_selectedAircraft);
871         if (m_recentAircraft.size() > MAX_RECENT_AIRCRAFT)
872           m_recentAircraft.pop_back();
873     }
874
875     if (m_ui->mpBox->isChecked()) {
876         opt->addOption("callsign", m_ui->mpCallsign->text().toStdString());
877         QString host = m_ui->mpServerCombo->currentData().toString();
878         int port = 5000;
879         if (host == "custom") {
880             QSettings settings;
881             host = settings.value("mp-custom-host").toString();
882             port = settings.value("mp-custom-port").toInt();
883         } else {
884             port = findMPServerPort(host.toStdString());
885         }
886         globals->get_props()->setStringValue("/sim/multiplay/txhost", host.toStdString());
887         globals->get_props()->setIntValue("/sim/multiplay/txport", port);
888     }
889
890     m_ui->location->setLocationOptions();
891
892     // time of day
893     if (m_ui->timeOfDayCombo->currentIndex() != 0) {
894         QString dayval = m_ui->timeOfDayCombo->currentText().toLower();
895         opt->addOption("timeofday", dayval.toStdString());
896     }
897
898     if (m_ui->seasonCombo->currentIndex() != 0) {
899         QString seasonName = m_ui->seasonCombo->currentText().toLower();
900         opt->addOption("season", seasonName.toStdString());
901     }
902
903     QSettings settings;
904     QString downloadDir = settings.value("download-dir").toString();
905     if (!downloadDir.isEmpty()) {
906         QDir d(downloadDir);
907         if (!d.exists()) {
908             int result = QMessageBox::question(this, tr("Create download folder?"),
909                                   tr("The selected location for downloads does not exist. Create it?"),
910                                                QMessageBox::Yes | QMessageBox::No | QMessageBox::Cancel);
911             if (result == QMessageBox::Cancel) {
912                 return;
913             }
914
915             if (result == QMessageBox::Yes) {
916                 d.mkpath(downloadDir);
917             }
918         }
919
920         opt->addOption("download-dir", downloadDir.toStdString());
921     }
922
923     // scenery paths
924     Q_FOREACH(QString path, settings.value("scenery-paths").toStringList()) {
925         opt->addOption("fg-scenery", path.toStdString());
926     }
927
928     // aircraft paths
929     Q_FOREACH(QString path, settings.value("aircraft-paths").toStringList()) {
930         // can't use fg-aircraft for this, as it is processed before the launcher is run
931         globals->append_aircraft_path(path.toStdString());
932     }
933
934     // additional arguments
935     ArgumentsTokenizer tk;
936     Q_FOREACH(ArgumentsTokenizer::Arg a, tk.tokenize(m_ui->commandLineArgs->toPlainText())) {
937         if (a.arg.startsWith("prop:")) {
938             QString v = a.arg.mid(5) + "=" + a.value;
939             opt->addOption("prop", v.toStdString());
940         } else {
941             opt->addOption(a.arg.toStdString(), a.value.toStdString());
942         }
943     }
944
945     if (settings.contains("restore-defaults-on-run")) {
946         settings.remove("restore-defaults-on-run");
947         opt->addOption("restore-defaults", "");
948     }
949
950     saveSettings();
951
952     qApp->exit(0);
953 }
954
955
956 void QtLauncher::onApply()
957 {
958     accept();
959
960     // aircraft
961     if (!m_selectedAircraft.isEmpty()) {
962         std::string aircraftPropValue,
963             aircraftDir;
964
965         if (m_selectedAircraft.isLocalFile()) {
966             QFileInfo setFileInfo(m_selectedAircraft.toLocalFile());
967             QString setFile = setFileInfo.fileName();
968             Q_ASSERT(setFile.endsWith("-set.xml"));
969             setFile.truncate(setFile.count() - 8); // drop the '-set.xml' portion
970             aircraftDir = setFileInfo.dir().absolutePath().toStdString();
971             aircraftPropValue = setFile.toStdString();
972         } else if (m_selectedAircraft.scheme() == "package") {
973             // no need to set aircraft-dir, handled by the corresponding code
974             // in fgInitAircraft
975             aircraftPropValue = m_selectedAircraft.path().toStdString();
976         } else {
977             qWarning() << "unsupported aircraft launch URL" << m_selectedAircraft;
978         }
979
980         // manage aircraft history
981         if (m_recentAircraft.contains(m_selectedAircraft))
982             m_recentAircraft.removeOne(m_selectedAircraft);
983         m_recentAircraft.prepend(m_selectedAircraft);
984         if (m_recentAircraft.size() > MAX_RECENT_AIRCRAFT)
985             m_recentAircraft.pop_back();
986
987         globals->get_props()->setStringValue("/sim/aircraft", aircraftPropValue);
988         globals->get_props()->setStringValue("/sim/aircraft-dir", aircraftDir);
989     }
990
991
992     saveSettings();
993 }
994
995 void QtLauncher::onQuit()
996 {
997     qApp->exit(-1);
998 }
999
1000 void QtLauncher::onToggleTerrasync(bool enabled)
1001 {
1002     if (enabled) {
1003         QSettings settings;
1004         QString downloadDir = settings.value("download-dir").toString();
1005         if (downloadDir.isEmpty()) {
1006             downloadDir = QString::fromStdString(flightgear::defaultDownloadDir().utf8Str());
1007         }
1008
1009         QFileInfo info(downloadDir);
1010         if (!info.exists()) {
1011             QMessageBox msg;
1012             msg.setWindowTitle(tr("Create download folder?"));
1013             msg.setText(tr("The download folder '%1' does not exist, create it now?").arg(downloadDir));
1014             msg.addButton(QMessageBox::Yes);
1015             msg.addButton(QMessageBox::Cancel);
1016             int result = msg.exec();
1017
1018             if (result == QMessageBox::Cancel) {
1019                 m_ui->terrasyncCheck->setChecked(false);
1020                 return;
1021             }
1022
1023             QDir d(downloadDir);
1024             d.mkpath(downloadDir);
1025         }
1026     } // of is enabled
1027 }
1028
1029 void QtLauncher::onAircraftInstalledCompleted(QModelIndex index)
1030 {
1031     maybeUpdateSelectedAircraft(index);
1032 }
1033
1034 void QtLauncher::onRatingsFilterToggled()
1035 {
1036     QModelIndex aircraftIndex = m_aircraftModel->indexOfAircraftURI(m_selectedAircraft);
1037     QModelIndex proxyIndex = m_aircraftProxy->mapFromSource(aircraftIndex);
1038     if (proxyIndex.isValid()) {
1039         m_ui->aircraftList->scrollTo(proxyIndex);
1040     }
1041 }
1042
1043 void QtLauncher::onAircraftInstallFailed(QModelIndex index, QString errorMessage)
1044 {
1045     qWarning() << Q_FUNC_INFO << index.data(AircraftURIRole) << errorMessage;
1046
1047     QMessageBox msg;
1048     msg.setWindowTitle(tr("Aircraft installation failed"));
1049     msg.setText(tr("An error occurred installing the aircraft %1: %2").
1050                 arg(index.data(Qt::DisplayRole).toString()).arg(errorMessage));
1051     msg.addButton(QMessageBox::Ok);
1052     msg.exec();
1053
1054     maybeUpdateSelectedAircraft(index);
1055 }
1056
1057 void QtLauncher::onAircraftSelected(const QModelIndex& index)
1058 {
1059     m_selectedAircraft = index.data(AircraftURIRole).toUrl();
1060     updateSelectedAircraft();
1061 }
1062
1063 void QtLauncher::onRequestPackageInstall(const QModelIndex& index)
1064 {
1065     // also select, otherwise UI is confusing
1066     m_selectedAircraft = index.data(AircraftURIRole).toUrl();
1067     updateSelectedAircraft();
1068
1069     QString pkg = index.data(AircraftPackageIdRole).toString();
1070     simgear::pkg::PackageRef pref = globals->packageRoot()->getPackageById(pkg.toStdString());
1071     if (pref->isInstalled()) {
1072         InstallRef install = pref->existingInstall();
1073         if (install && install->hasUpdate()) {
1074             globals->packageRoot()->scheduleToUpdate(install);
1075         }
1076     } else {
1077         pref->install();
1078     }
1079 }
1080
1081 void QtLauncher::onCancelDownload(const QModelIndex& index)
1082 {
1083     QString pkg = index.data(AircraftPackageIdRole).toString();
1084     simgear::pkg::PackageRef pref = globals->packageRoot()->getPackageById(pkg.toStdString());
1085     simgear::pkg::InstallRef i = pref->existingInstall();
1086     i->cancelDownload();
1087 }
1088
1089 void QtLauncher::onRestoreDefaults()
1090 {
1091     QMessageBox mbox(this);
1092     mbox.setText(tr("Restore all settings to defaults?"));
1093     mbox.setInformativeText(tr("Restoring settings to their defaults may affect available add-ons such as scenery or aircraft."));
1094     QPushButton* quitButton = mbox.addButton(tr("Restore and restart now"), QMessageBox::YesRole);
1095     mbox.addButton(QMessageBox::Cancel);
1096     mbox.setDefaultButton(QMessageBox::Cancel);
1097     mbox.setIconPixmap(QPixmap(":/app-icon-large"));
1098
1099     mbox.exec();
1100     if (mbox.clickedButton() != quitButton) {
1101         return;
1102     }
1103
1104     {
1105         QSettings settings;
1106         settings.clear();
1107         settings.setValue("restore-defaults-on-run", true);
1108     }
1109
1110     restartTheApp(QStringList());
1111 }
1112
1113 void QtLauncher::maybeUpdateSelectedAircraft(QModelIndex index)
1114 {
1115     QUrl u = index.data(AircraftURIRole).toUrl();
1116     if (u == m_selectedAircraft) {
1117         // potentially enable the run button now!
1118         updateSelectedAircraft();
1119     }
1120 }
1121
1122 void QtLauncher::updateSelectedAircraft()
1123 {
1124     QModelIndex index = m_aircraftModel->indexOfAircraftURI(m_selectedAircraft);
1125     if (index.isValid()) {
1126         QPixmap pm = index.data(Qt::DecorationRole).value<QPixmap>();
1127         m_ui->thumbnail->setPixmap(pm);
1128         m_ui->aircraftDescription->setText(index.data(Qt::DisplayRole).toString());
1129
1130         int status = index.data(AircraftPackageStatusRole).toInt();
1131         bool canRun = (status == PackageInstalled);
1132         m_ui->runButton->setEnabled(canRun);
1133
1134         LauncherAircraftType aircraftType = Airplane;
1135         if (index.data(AircraftIsHelicopterRole).toBool()) {
1136             aircraftType = Helicopter;
1137         } else if (index.data(AircraftIsSeaplaneRole).toBool()) {
1138             aircraftType = Seaplane;
1139         }
1140
1141         m_ui->location->setAircraftType(aircraftType);
1142     } else {
1143         m_ui->thumbnail->setPixmap(QPixmap());
1144         m_ui->aircraftDescription->setText("");
1145         m_ui->runButton->setEnabled(false);
1146     }
1147 }
1148
1149 QModelIndex QtLauncher::proxyIndexForAircraftURI(QUrl uri) const
1150 {
1151   return m_aircraftProxy->mapFromSource(sourceIndexForAircraftURI(uri));
1152 }
1153
1154 QModelIndex QtLauncher::sourceIndexForAircraftURI(QUrl uri) const
1155 {
1156     AircraftItemModel* sourceModel = qobject_cast<AircraftItemModel*>(m_aircraftProxy->sourceModel());
1157     Q_ASSERT(sourceModel);
1158     return sourceModel->indexOfAircraftURI(uri);
1159 }
1160
1161 void QtLauncher::onPopupAircraftHistory()
1162 {
1163     if (m_recentAircraft.isEmpty()) {
1164         return;
1165     }
1166
1167     QMenu m;
1168     Q_FOREACH(QUrl uri, m_recentAircraft) {
1169         QModelIndex index = sourceIndexForAircraftURI(uri);
1170         if (!index.isValid()) {
1171             // not scanned yet
1172             continue;
1173         }
1174         QAction* act = m.addAction(index.data(Qt::DisplayRole).toString());
1175         act->setData(uri);
1176     }
1177
1178     QPoint popupPos = m_ui->aircraftHistory->mapToGlobal(m_ui->aircraftHistory->rect().bottomLeft());
1179     QAction* triggered = m.exec(popupPos);
1180     if (triggered) {
1181         m_selectedAircraft = triggered->data().toUrl();
1182         QModelIndex index = proxyIndexForAircraftURI(m_selectedAircraft);
1183         m_ui->aircraftList->selectionModel()->setCurrentIndex(index,
1184                                                               QItemSelectionModel::ClearAndSelect);
1185         m_ui->aircraftFilter->clear();
1186         updateSelectedAircraft();
1187     }
1188 }
1189
1190 void QtLauncher::onEditRatingsFilter()
1191 {
1192     EditRatingsFilterDialog dialog(this);
1193     dialog.setRatings(m_ratingFilters);
1194
1195     dialog.exec();
1196     if (dialog.result() == QDialog::Accepted) {
1197         QVariantList vl;
1198         for (int i=0; i<4; ++i) {
1199             m_ratingFilters[i] = dialog.getRating(i);
1200             vl.append(m_ratingFilters[i]);
1201         }
1202         m_aircraftProxy->setRatings(m_ratingFilters);
1203
1204         QSettings settings;
1205         settings.setValue("min-ratings", vl);
1206     }
1207 }
1208
1209 void QtLauncher::updateSettingsSummary()
1210 {
1211     QStringList summary;
1212     if (m_ui->timeOfDayCombo->currentIndex() > 0) {
1213         summary.append(QString(m_ui->timeOfDayCombo->currentText().toLower()));
1214     }
1215
1216     if (m_ui->seasonCombo->currentIndex() > 0) {
1217         summary.append(QString(m_ui->seasonCombo->currentText().toLower()));
1218     }
1219
1220     if (m_ui->rembrandtCheckbox->isChecked()) {
1221         summary.append("Rembrandt enabled");
1222     } else if (m_ui->msaaCheckbox->isChecked()) {
1223         summary.append("anti-aliasing");
1224     }
1225
1226     if (m_ui->fetchRealWxrCheckbox->isChecked()) {
1227         summary.append("live weather");
1228     }
1229
1230     if (m_ui->terrasyncCheck->isChecked()) {
1231         summary.append("automatic scenery downloads");
1232     }
1233
1234     if (m_ui->startPausedCheck->isChecked()) {
1235         summary.append("paused");
1236     }
1237
1238     QString s = summary.join(", ");
1239     s[0] = s[0].toUpper();
1240     m_ui->settingsDescription->setText(s);
1241 }
1242
1243 void QtLauncher::onRembrandtToggled(bool b)
1244 {
1245     // Rembrandt and multi-sample are exclusive
1246     m_ui->msaaCheckbox->setEnabled(!b);
1247 }
1248
1249 void QtLauncher::onShowInstalledAircraftToggled(bool b)
1250 {
1251     m_ui->ratingsFilterCheck->setEnabled(!b);
1252     maybeRestoreAircraftSelection();
1253 }
1254
1255 void QtLauncher::onSubsytemIdleTimeout()
1256 {
1257     globals->get_subsystem_mgr()->update(0.0);
1258 }
1259
1260 void QtLauncher::onDownloadDirChanged()
1261 {
1262
1263     // replace existing package root
1264     globals->get_subsystem<FGHTTPClient>()->shutdown();
1265     globals->setPackageRoot(simgear::pkg::RootRef());
1266
1267     // create new root with updated download-dir value
1268     fgInitPackageRoot();
1269
1270     globals->get_subsystem<FGHTTPClient>()->init();
1271
1272     QSettings settings;
1273     // re-scan the aircraft list
1274     m_aircraftModel->setPackageRoot(globals->packageRoot());
1275     m_aircraftModel->setPaths(settings.value("aircraft-paths").toStringList());
1276     m_aircraftModel->scanDirs();
1277
1278     checkOfficialCatalogMessage();
1279
1280     // re-set scenery dirs
1281     setSceneryPaths();
1282 }
1283
1284 void QtLauncher::checkOfficialCatalogMessage()
1285 {
1286     QSettings settings;
1287     bool showOfficialCatalogMesssage = !globals->get_subsystem<FGHTTPClient>()->isDefaultCatalogInstalled();
1288     if (settings.value("hide-official-catalog-message").toBool()) {
1289         showOfficialCatalogMesssage = false;
1290     }
1291
1292     m_aircraftModel->setOfficialHangarMessageVisible(showOfficialCatalogMesssage);
1293     if (showOfficialCatalogMesssage) {
1294         NoOfficialHangarMessage* messageWidget = new NoOfficialHangarMessage;
1295         connect(messageWidget, &NoOfficialHangarMessage::linkActivated,
1296                 this, &QtLauncher::onOfficialCatalogMessageLink);
1297
1298         QModelIndex index = m_aircraftProxy->mapFromSource(m_aircraftModel->officialHangarMessageIndex());
1299         m_ui->aircraftList->setIndexWidget(index, messageWidget);
1300     }
1301 }
1302
1303 void QtLauncher::onOfficialCatalogMessageLink(QUrl link)
1304 {
1305     QString s = link.toString();
1306     if (s == "action:hide") {
1307         QSettings settings;
1308         settings.setValue("hide-official-catalog-message", true);
1309     } else if (s == "action:add-official") {
1310         AddOnsPage::addDefaultCatalog(this);
1311     }
1312
1313     checkOfficialCatalogMessage();
1314 }
1315
1316 void QtLauncher::onRefreshMPServers()
1317 {
1318     if (m_mpServerRequest.get()) {
1319         return; // in-progress
1320     }
1321
1322     string url(fgGetString("/sim/multiplay/serverlist-url",
1323                            "http://liveries.flightgear.org/mpstatus/mpservers.xml"));
1324
1325     if (url.empty()) {
1326         SG_LOG(SG_IO, SG_ALERT, "do_multiplayer.refreshserverlist: no URL given");
1327         return;
1328     }
1329
1330     SGPropertyNode *targetnode = fgGetNode("/sim/multiplay/server-list", true);
1331     m_mpServerRequest.reset(new RemoteXMLRequest(url, targetnode));
1332     m_mpServerRequest->done(this, &QtLauncher::onRefreshMPServersDone);
1333     m_mpServerRequest->fail(this, &QtLauncher::onRefreshMPServersFailed);
1334     globals->get_subsystem<FGHTTPClient>()->makeRequest(m_mpServerRequest);
1335 }
1336
1337 void QtLauncher::onRefreshMPServersDone(simgear::HTTP::Request*)
1338 {
1339     // parse the properties
1340     SGPropertyNode *targetnode = fgGetNode("/sim/multiplay/server-list", true);
1341     m_ui->mpServerCombo->clear();
1342
1343     for (int i=0; i<targetnode->nChildren(); ++i) {
1344         SGPropertyNode* c = targetnode->getChild(i);
1345         if (c->getName() != std::string("server")) {
1346             continue;
1347         }
1348
1349         QString name = QString::fromStdString(c->getStringValue("name"));
1350         QString loc = QString::fromStdString(c->getStringValue("location"));
1351         QString host = QString::fromStdString(c->getStringValue("hostname"));
1352         m_ui->mpServerCombo->addItem(tr("%1 - %2").arg(name,loc), host);
1353     }
1354
1355     EditCustomMPServerDialog::addCustomItem(m_ui->mpServerCombo);
1356     restoreMPServerSelection();
1357
1358     m_mpServerRequest.clear();
1359 }
1360
1361 void QtLauncher::onRefreshMPServersFailed(simgear::HTTP::Request*)
1362 {
1363     qWarning() << "refreshing MP servers failed:" << QString::fromStdString(m_mpServerRequest->responseReason());
1364     m_mpServerRequest.clear();
1365     EditCustomMPServerDialog::addCustomItem(m_ui->mpServerCombo);
1366     restoreMPServerSelection();
1367 }
1368
1369 void QtLauncher::restoreMPServerSelection()
1370 {
1371     if (m_doRestoreMPServer) {
1372         QSettings settings;
1373         int index = m_ui->mpServerCombo->findData(settings.value("mp-server"));
1374         if (index >= 0) {
1375             m_ui->mpServerCombo->setCurrentIndex(index);
1376         }
1377         m_doRestoreMPServer = false;
1378     }
1379 }
1380
1381 void QtLauncher::onMPServerActivated(int index)
1382 {
1383     if (m_ui->mpServerCombo->itemData(index) == "custom") {
1384         EditCustomMPServerDialog dlg(this);
1385         dlg.exec();
1386         if (dlg.result() == QDialog::Accepted) {
1387             m_ui->mpServerCombo->setItemText(index, tr("Custom - %1").arg(dlg.hostname()));
1388         }
1389     }
1390 }
1391
1392 int QtLauncher::findMPServerPort(const std::string& host)
1393 {
1394     SGPropertyNode *targetnode = fgGetNode("/sim/multiplay/server-list", true);
1395     for (int i=0; i<targetnode->nChildren(); ++i) {
1396         SGPropertyNode* c = targetnode->getChild(i);
1397         if (c->getName() != std::string("server")) {
1398             continue;
1399         }
1400
1401         if (c->getStringValue("hostname") == host) {
1402             return c->getIntValue("port");
1403         }
1404     }
1405
1406     return 0;
1407 }
1408
1409 simgear::pkg::PackageRef QtLauncher::packageForAircraftURI(QUrl uri) const
1410 {
1411     if (uri.scheme() != "package") {
1412         qWarning() << "invalid URL scheme:" << uri;
1413         return simgear::pkg::PackageRef();
1414     }
1415
1416     QString ident = uri.path();
1417     return globals->packageRoot()->getPackageById(ident.toStdString());
1418 }
1419
1420 void QtLauncher::restartTheApp(QStringList fgArgs)
1421 {
1422     // Spawn a new instance of myApplication:
1423     QProcess proc;
1424     QStringList args;
1425
1426 #if defined(Q_OS_MAC)
1427     QDir dir(qApp->applicationDirPath()); // returns the 'MacOS' dir
1428     dir.cdUp(); // up to 'contents' dir
1429     dir.cdUp(); // up to .app dir
1430     // see 'man open' for details, but '-n' ensures we launch a new instance,
1431     // and we want to pass remaining arguments to us, not open.
1432     args << "-n" << dir.absolutePath() << "--args" << "--launcher" << fgArgs;
1433     qDebug() << "args" << args;
1434     proc.startDetached("open", args);
1435 #else
1436     args << "--launcher" << fgArgs;
1437     proc.startDetached(qApp->applicationFilePath(), args);
1438 #endif
1439     qApp->exit(-1);
1440 }
1441
1442 #include "QtLauncher.moc"