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