]> git.mxchange.org Git - flightgear.git/blob - src/GUI/QtLauncher.cxx
Qt launcher: additional arguments UI
[flightgear.git] / src / GUI / QtLauncher.cxx
1 #include "QtLauncher.hxx"
2
3 // Qt
4 #include <QProgressDialog>
5 #include <QCoreApplication>
6 #include <QAbstractListModel>
7 #include <QDir>
8 #include <QFileInfo>
9 #include <QPixmap>
10 #include <QTimer>
11 #include <QDebug>
12 #include <QCompleter>
13 #include <QThread>
14 #include <QMutex>
15 #include <QMutexLocker>
16 #include <QListView>
17 #include <QSettings>
18 #include <QPainter>
19 #include <QSortFilterProxyModel>
20 #include <QMenu>
21 #include <QDesktopServices>
22 #include <QUrl>
23 #include <QAction>
24 #include <QStyledItemDelegate>
25 #include <QLinearGradient>
26 #include <QFileDialog>
27 #include <QMessageBox>
28
29 // Simgear
30 #include <simgear/timing/timestamp.hxx>
31 #include <simgear/props/props_io.hxx>
32 #include <simgear/structure/exception.hxx>
33 #include <simgear/misc/sg_path.hxx>
34
35 #include "ui_Launcher.h"
36 #include "EditRatingsFilterDialog.hxx"
37
38 #include <Main/globals.hxx>
39 #include <Navaids/NavDataCache.hxx>
40 #include <Airports/airport.hxx>
41 #include <Airports/dynamics.hxx> // for parking
42 #include <Main/options.hxx>
43
44 using namespace flightgear;
45
46 const int MAX_RECENT_AIRPORTS = 32;
47 const int MAX_RECENT_AIRCRAFT = 20;
48
49 namespace { // anonymous namespace
50
51 const int AircraftPathRole = Qt::UserRole + 1;
52 const int AircraftAuthorsRole = Qt::UserRole + 2;
53 const int AircraftRatingRole = Qt::UserRole + 100;
54
55 void initNavCache()
56 {
57     NavDataCache* cache = NavDataCache::instance();
58     if (cache->isRebuildRequired()) {
59         QProgressDialog rebuildProgress("Initialising navigation data, this may take several minutes",
60                                        QString() /* cancel text */,
61                                        0, 0);
62         rebuildProgress.setWindowModality(Qt::WindowModal);
63         rebuildProgress.show();
64
65         while (!cache->rebuild()) {
66             // sleep to give the rebuild thread more time
67             SGTimeStamp::sleepForMSec(50);
68             rebuildProgress.setValue(0);
69             QCoreApplication::processEvents();
70         }
71     }
72 }
73
74 struct AircraftItem
75 {
76     AircraftItem() {
77         // oh for C++11 initialisers
78         for (int i=0; i<4; ++i) ratings[i] = 0;
79     }
80
81     AircraftItem(QDir dir, QString filePath)
82     {
83         for (int i=0; i<4; ++i) ratings[i] = 0;
84
85         SGPropertyNode root;
86         readProperties(filePath.toStdString(), &root);
87
88         if (!root.hasChild("sim")) {
89             throw sg_io_exception(std::string("Malformed -set.xml file"), filePath.toStdString());
90         }
91
92         SGPropertyNode_ptr sim = root.getNode("sim");
93
94         path = filePath;
95         description = sim->getStringValue("description");
96         authors =  sim->getStringValue("author");
97
98         if (sim->hasChild("rating")) {
99             parseRatings(sim->getNode("rating"));
100         }
101
102         if (dir.exists("thumbnail.jpg")) {
103             thumbnail.load(dir.filePath("thumbnail.jpg"));
104             // resize to the standard size
105             if (thumbnail.height() > 128) {
106                 thumbnail = thumbnail.scaledToHeight(128);
107             }
108         }
109
110     }
111
112     QString path;
113     QPixmap thumbnail;
114     QString description;
115     QString authors;
116     int ratings[4];
117
118 private:
119     void parseRatings(SGPropertyNode_ptr ratingsNode)
120     {
121         ratings[0] = ratingsNode->getIntValue("FDM");
122         ratings[1] = ratingsNode->getIntValue("systems");
123         ratings[2] = ratingsNode->getIntValue("cockpit");
124         ratings[3] = ratingsNode->getIntValue("model");
125     }
126 };
127
128 class AircraftScanThread : public QThread
129 {
130     Q_OBJECT
131 public:
132     AircraftScanThread(QStringList dirsToScan) :
133         m_dirs(dirsToScan),
134         m_done(false)
135     {
136
137     }
138
139     /** thread-safe access to items already scanned */
140     QList<AircraftItem> items()
141     {
142         QList<AircraftItem> result;
143         QMutexLocker g(&m_lock);
144         result.swap(m_items);
145         g.unlock();
146         return result;
147     }
148
149     void setDone()
150     {
151         m_done = true;
152     }
153 Q_SIGNALS:
154     void addedItems();
155
156 protected:
157     virtual void run()
158     {
159         Q_FOREACH(QString d, m_dirs) {
160             scanAircraftDir(QDir(d));
161             if (m_done) {
162                 return;
163             }
164         }
165     }
166
167 private:
168     void scanAircraftDir(QDir path)
169     {
170         QStringList filters;
171         filters << "*-set.xml";
172         Q_FOREACH(QFileInfo child, path.entryInfoList(QDir::Dirs | QDir::NoDotAndDotDot)) {
173             QDir childDir(child.absoluteFilePath());
174             Q_FOREACH(QFileInfo xmlChild, childDir.entryInfoList(filters, QDir::Files)) {
175                 try {
176                     AircraftItem item(childDir, xmlChild.absoluteFilePath());
177                     // lock mutex whil we modify the items array
178                     {
179                         QMutexLocker g(&m_lock);
180                         m_items.append(item);
181                     }
182                 } catch (sg_exception& e) {
183                     continue;
184                 }
185
186                 if (m_done) {
187                     return;
188                 }
189             } // of set.xml iteration
190
191             emit addedItems();
192         } // of subdir iteration
193     }
194
195     QMutex m_lock;
196     QStringList m_dirs;
197     QList<AircraftItem> m_items;
198     bool m_done;
199 };
200
201 class AircraftItemModel : public QAbstractListModel
202 {
203     Q_OBJECT
204 public:
205     AircraftItemModel(QObject* pr) :
206         QAbstractListModel(pr)
207     {
208         QStringList dirs;
209         Q_FOREACH(std::string ap, globals->get_aircraft_paths()) {
210             dirs << QString::fromStdString(ap);
211         }
212
213         SGPath rootAircraft(globals->get_fg_root());
214         rootAircraft.append("Aircraft");
215         dirs << QString::fromStdString(rootAircraft.str());
216
217         m_scanThread = new AircraftScanThread(dirs);
218         connect(m_scanThread, &AircraftScanThread::finished, this,
219                 &AircraftItemModel::onScanFinished);
220         connect(m_scanThread, &AircraftScanThread::addedItems,
221                 this, &AircraftItemModel::onScanResults);
222         m_scanThread->start();
223     }
224
225     ~AircraftItemModel()
226     {
227         if (m_scanThread) {
228             m_scanThread->setDone();
229             m_scanThread->wait(1000);
230             delete m_scanThread;
231         }
232     }
233
234     virtual int rowCount(const QModelIndex& parent) const
235     {
236         return m_items.size();
237     }
238
239     virtual QVariant data(const QModelIndex& index, int role) const
240     {
241         const AircraftItem& item(m_items.at(index.row()));
242         if (role == Qt::DisplayRole) {
243             return item.description;
244         } else if (role == Qt::DecorationRole) {
245             return item.thumbnail;
246         } else if (role == AircraftPathRole) {
247             return item.path;
248         } else if (role == AircraftAuthorsRole) {
249             return item.authors;
250         } else if (role >= AircraftRatingRole) {
251             return item.ratings[role - AircraftRatingRole];
252         } else if (role == Qt::ToolTipRole) {
253             return item.path;
254         }
255
256         return QVariant();
257     }
258
259   QModelIndex indexOfAircraftPath(QString path) const
260   {
261       for (int row=0; row <m_items.size(); ++row) {
262           const AircraftItem& item(m_items.at(row));
263           if (item.path == path) {
264               return index(row);
265           }
266       }
267
268       return QModelIndex();
269   }
270
271 private slots:
272     void onScanResults()
273     {
274         QList<AircraftItem> newItems = m_scanThread->items();
275         if (newItems.isEmpty())
276             return;
277
278         int firstRow = m_items.count();
279         int lastRow = firstRow + newItems.count() - 1;
280         beginInsertRows(QModelIndex(), firstRow, lastRow);
281         m_items.append(newItems);
282         endInsertRows();
283     }
284
285     void onScanFinished()
286     {
287         delete m_scanThread;
288         m_scanThread = NULL;
289     }
290
291 private:
292     AircraftScanThread* m_scanThread;
293     QList<AircraftItem> m_items;
294 };
295
296 class AircraftItemDelegate : public QStyledItemDelegate
297 {
298 public:
299     static const int MARGIN = 4;
300
301     virtual void paint(QPainter * painter, const QStyleOptionViewItem & option, const QModelIndex & index) const
302     {
303         // selection feedback rendering
304         if (option.state & QStyle::State_Selected) {
305             QLinearGradient grad(option.rect.topLeft(), option.rect.bottomLeft());
306             grad.setColorAt(0.0, QColor(152, 163, 180));
307             grad.setColorAt(1.0, QColor(90, 107, 131));
308
309             QBrush backgroundBrush(grad);
310             painter->fillRect(option.rect, backgroundBrush);
311
312             painter->setPen(QColor(90, 107, 131));
313             painter->drawLine(option.rect.topLeft(), option.rect.topRight());
314
315         }
316
317         QRect contentRect = option.rect.adjusted(MARGIN, MARGIN, -MARGIN, -MARGIN);
318
319         QPixmap thumbnail = index.data(Qt::DecorationRole).value<QPixmap>();
320         painter->drawPixmap(contentRect.topLeft(), thumbnail);
321
322         // draw 1px frame
323         painter->setPen(QColor(0x7f, 0x7f, 0x7f));
324         painter->setBrush(Qt::NoBrush);
325         painter->drawRect(contentRect.left(), contentRect.top(), thumbnail.width(), thumbnail.height());
326
327         QString description = index.data(Qt::DisplayRole).toString();
328         contentRect.setLeft(contentRect.left() + MARGIN + thumbnail.width());
329
330         painter->setPen(Qt::black);
331         QFont f;
332         f.setPointSize(18);
333         painter->setFont(f);
334
335         QRect actualBounds;
336         painter->drawText(contentRect, Qt::TextWordWrap, description, &actualBounds);
337
338         QString authors = index.data(AircraftAuthorsRole).toString();
339
340         f.setPointSize(12);
341         painter->setFont(f);
342
343         QRect authorsRect = contentRect;
344         authorsRect.moveTop(actualBounds.bottom() + MARGIN);
345         painter->drawText(authorsRect, Qt::TextWordWrap,
346                           QString("by: %1").arg(authors),
347                           &actualBounds);
348
349         QRect r = contentRect;
350         r.setWidth(contentRect.width() / 2);
351         r.moveTop(actualBounds.bottom() + MARGIN);
352         r.setHeight(24);
353
354         drawRating(painter, "Flight model:", r, index.data(AircraftRatingRole).toInt());
355         r.moveTop(r.bottom());
356         drawRating(painter, "Systems:", r, index.data(AircraftRatingRole + 1).toInt());
357
358         r.moveTop(actualBounds.bottom() + MARGIN);
359         r.moveLeft(r.right());
360         drawRating(painter, "Cockpit:", r, index.data(AircraftRatingRole + 2).toInt());
361         r.moveTop(r.bottom());
362         drawRating(painter, "Exterior model:", r, index.data(AircraftRatingRole + 3).toInt());
363
364
365     }
366
367     virtual QSize sizeHint(const QStyleOptionViewItem & option, const QModelIndex & index) const
368     {
369         return QSize(500, 128 + (MARGIN * 2));
370     }
371
372 private:
373     void drawRating(QPainter* painter, QString label, const QRect& box, int value) const
374     {
375         const int DOT_SIZE = 10;
376         const int DOT_MARGIN = 4;
377
378         QRect dotBox = box;
379         dotBox.setLeft(box.right() - (DOT_MARGIN * 6 + DOT_SIZE * 5));
380
381         painter->setPen(Qt::black);
382         QRect textBox = box;
383         textBox.setRight(dotBox.left() - DOT_MARGIN);
384         painter->drawText(textBox, Qt::AlignVCenter | Qt::AlignRight, label);
385
386         painter->setPen(Qt::NoPen);
387         QRect dot(dotBox.left() + DOT_MARGIN,
388                   dotBox.center().y() - (DOT_SIZE / 2),
389                   DOT_SIZE,
390                   DOT_SIZE);
391         for (int i=0; i<5; ++i) {
392             painter->setBrush((i < value) ? QColor(0x3f, 0x3f, 0x3f) : QColor(0xaf, 0xaf, 0xaf));
393             painter->drawEllipse(dot);
394             dot.moveLeft(dot.right() + DOT_MARGIN);
395         }
396     }
397 };
398
399 class ArgumentsTokenizer
400 {
401 public:
402     class Arg
403     {
404     public:
405         explicit Arg(QString k, QString v = QString()) : arg(k), value(v) {}
406
407         QString arg;
408         QString value;
409     };
410
411     QList<Arg> tokenize(QString in) const
412     {
413         int index = 0;
414         const int len = in.count();
415         QChar c, nc;
416         State state = Start;
417         QString key, value;
418         QList<Arg> result;
419
420         for (; index < len; ++index) {
421             c = in.at(index);
422             nc = index < (len - 1) ? in.at(index + 1) : QChar();
423
424             switch (state) {
425             case Start:
426                 if (c == QChar('-')) {
427                     if (nc == QChar('-')) {
428                         state = Key;
429                         key.clear();
430                         ++index;
431                     } else {
432                         // should we pemit single hyphen arguments?
433                         // choosing to fail for now
434                         return QList<Arg>();
435                     }
436                 } else if (c.isSpace()) {
437                     break;
438                 }
439                 break;
440
441             case Key:
442                 if (c == QChar('=')) {
443                     state = Value;
444                     value.clear();
445                 } else if (c.isSpace()) {
446                     state = Start;
447                     result.append(Arg(key));
448                 } else {
449                     // could check for illegal charatcers here
450                     key.append(c);
451                 }
452                 break;
453
454             case Value:
455                 if (c == QChar('"')) {
456                     state = Quoted;
457                 } else if (c.isSpace()) {
458                     state = Start;
459                     result.append(Arg(key, value));
460                 } else {
461                     value.append(c);
462                 }
463                 break;
464
465             case Quoted:
466                 if (c == QChar('\\')) {
467                     // check for escaped double-quote inside quoted value
468                     if (nc == QChar('"')) {
469                         ++index;
470                     }
471                 } else if (c == QChar('"')) {
472                     state = Value;
473                 } else {
474                     value.append(c);
475                 }
476                 break;
477             } // of state switch
478         } // of character loop
479
480         // ensure last argument isn't lost
481         if (state == Key) {
482             result.append(Arg(key));
483         } else if (state == Value) {
484             result.append(Arg(key, value));
485         }
486
487         return result;
488     }
489
490 private:
491     enum State {
492         Start = 0,
493         Key,
494         Value,
495         Quoted
496     };
497 };
498
499 } // of anonymous namespace
500
501 class AirportSearchModel : public QAbstractListModel
502 {
503     Q_OBJECT
504 public:
505     AirportSearchModel() :
506         m_searchActive(false)
507     {
508     }
509
510     void setSearch(QString t)
511     {
512         beginResetModel();
513
514         m_airports.clear();
515         m_ids.clear();
516
517         std::string term(t.toUpper().toStdString());
518         // try ICAO lookup first
519         FGAirportRef ref = FGAirport::findByIdent(term);
520         if (ref) {
521             m_ids.push_back(ref->guid());
522             m_airports.push_back(ref);
523         } else {
524             m_search.reset(new NavDataCache::ThreadedAirportSearch(term));
525             QTimer::singleShot(100, this, SLOT(onSearchResultsPoll()));
526             m_searchActive = true;
527         }
528
529         endResetModel();
530     }
531
532     bool isSearchActive() const
533     {
534         return m_searchActive;
535     }
536
537     virtual int rowCount(const QModelIndex&) const
538     {
539         // if empty, return 1 for special 'no matches'?
540         return m_ids.size();
541     }
542
543     virtual QVariant data(const QModelIndex& index, int role) const
544     {
545         if (!index.isValid())
546             return QVariant();
547         
548         FGAirportRef apt = m_airports[index.row()];
549         if (!apt.valid()) {
550             apt = FGPositioned::loadById<FGAirport>(m_ids[index.row()]);
551             m_airports[index.row()] = apt;
552         }
553
554         if (role == Qt::DisplayRole) {
555             QString name = QString::fromStdString(apt->name());
556             return QString("%1: %2").arg(QString::fromStdString(apt->ident())).arg(name);
557         }
558
559         if (role == Qt::EditRole) {
560             return QString::fromStdString(apt->ident());
561         }
562
563         if (role == Qt::UserRole) {
564             return static_cast<qlonglong>(m_ids[index.row()]);
565         }
566
567         return QVariant();
568     }
569
570     QString firstIdent() const
571     {
572         if (m_ids.empty())
573             return QString();
574
575         if (!m_airports.front().valid()) {
576             m_airports[0] = FGPositioned::loadById<FGAirport>(m_ids.front());
577         }
578
579         return QString::fromStdString(m_airports.front()->ident());
580     }
581
582 Q_SIGNALS:
583     void searchComplete();
584
585 private slots:
586     void onSearchResultsPoll()
587     {
588         PositionedIDVec newIds = m_search->results();
589         
590         beginInsertRows(QModelIndex(), m_ids.size(), newIds.size() - 1);
591         for (unsigned int i=m_ids.size(); i < newIds.size(); ++i) {
592             m_ids.push_back(newIds[i]);
593             m_airports.push_back(FGAirportRef()); // null ref
594         }
595         endInsertRows();
596
597         if (m_search->isComplete()) {
598             m_searchActive = false;
599             m_search.reset();
600             emit searchComplete();
601         } else {
602             QTimer::singleShot(100, this, SLOT(onSearchResultsPoll()));
603         }
604     }
605
606 private:
607     PositionedIDVec m_ids;
608     mutable std::vector<FGAirportRef> m_airports;
609     bool m_searchActive;
610     QScopedPointer<NavDataCache::ThreadedAirportSearch> m_search;
611 };
612
613 class AircraftProxyModel : public QSortFilterProxyModel
614 {
615     Q_OBJECT
616 public:
617     AircraftProxyModel(QObject* pr) :
618         QSortFilterProxyModel(pr),
619         m_ratingsFilter(true)
620     {
621         for (int i=0; i<4; ++i) {
622             m_ratings[i] = 3;
623         }
624     }
625
626     void setRatings(int* ratings)
627     {
628         ::memcpy(m_ratings, ratings, sizeof(int) * 4);
629         invalidate();
630     }
631
632 public slots:
633     void setRatingFilterEnabled(bool e)
634     {
635         if (e == m_ratingsFilter) {
636             return;
637         }
638
639         m_ratingsFilter = e;
640         invalidate();
641     }
642
643 protected:
644     bool filterAcceptsRow(int sourceRow, const QModelIndex &sourceParent) const
645     {
646         if (!QSortFilterProxyModel::filterAcceptsRow(sourceRow, sourceParent)) {
647             return false;
648         }
649
650         if (m_ratingsFilter) {
651             QModelIndex index = sourceModel()->index(sourceRow, 0, sourceParent);
652             for (int i=0; i<4; ++i) {
653                 if (m_ratings[i] > index.data(AircraftRatingRole + i).toInt()) {
654                     return false;
655                 }
656             }
657         }
658
659         return true;
660     }
661
662 private:
663     bool m_ratingsFilter;
664     int m_ratings[4];
665 };
666
667 QtLauncher::QtLauncher() :
668     QDialog(),
669     m_ui(NULL)
670 {
671     m_ui.reset(new Ui::Launcher);
672     m_ui->setupUi(this);
673
674     for (int i=0; i<4; ++i) {
675         m_ratingFilters[i] = 3;
676     }
677
678     m_airportsModel = new AirportSearchModel;
679     m_ui->searchList->setModel(m_airportsModel);
680     connect(m_ui->searchList, &QListView::clicked,
681             this, &QtLauncher::onAirportChoiceSelected);
682     connect(m_airportsModel, &AirportSearchModel::searchComplete,
683             this, &QtLauncher::onAirportSearchComplete);
684
685     SGPath p = SGPath::documents();
686     p.append("FlightGear");
687     p.append("Aircraft");
688     m_customAircraftDir = QString::fromStdString(p.str());
689     m_ui->customAircraftDirLabel->setText(QString("Custom aircraft folder: %1").arg(m_customAircraftDir));
690
691     globals->append_aircraft_path(m_customAircraftDir.toStdString());
692
693     // create and configure the proxy model
694     m_aircraftProxy = new AircraftProxyModel(this);
695     m_aircraftProxy->setSourceModel(new AircraftItemModel(this));
696
697     m_aircraftProxy->setFilterCaseSensitivity(Qt::CaseInsensitive);
698     m_aircraftProxy->setSortCaseSensitivity(Qt::CaseInsensitive);
699     m_aircraftProxy->setSortRole(Qt::DisplayRole);
700     m_aircraftProxy->setDynamicSortFilter(true);
701
702     m_ui->aircraftList->setModel(m_aircraftProxy);
703     m_ui->aircraftList->setHorizontalScrollBarPolicy(Qt::ScrollBarAlwaysOff);
704     m_ui->aircraftList->setItemDelegate(new AircraftItemDelegate);
705     m_ui->aircraftList->setSelectionMode(QAbstractItemView::SingleSelection);
706     connect(m_ui->aircraftList, &QListView::clicked,
707             this, &QtLauncher::onAircraftSelected);
708
709     connect(m_ui->runwayCombo, SIGNAL(currentIndexChanged(int)),
710             this, SLOT(updateAirportDescription()));
711     connect(m_ui->parkingCombo, SIGNAL(currentIndexChanged(int)),
712             this, SLOT(updateAirportDescription()));
713     connect(m_ui->runwayRadio, SIGNAL(toggled(bool)),
714             this, SLOT(updateAirportDescription()));
715     connect(m_ui->parkingRadio, SIGNAL(toggled(bool)),
716             this, SLOT(updateAirportDescription()));
717     connect(m_ui->onFinalCheckbox, SIGNAL(toggled(bool)),
718             this, SLOT(updateAirportDescription()));
719
720
721     connect(m_ui->runButton, SIGNAL(clicked()), this, SLOT(onRun()));
722     connect(m_ui->quitButton, SIGNAL(clicked()), this, SLOT(onQuit()));
723     connect(m_ui->airportEdit, SIGNAL(returnPressed()),
724             this, SLOT(onSearchAirports()));
725
726     connect(m_ui->aircraftFilter, &QLineEdit::textChanged,
727             m_aircraftProxy, &QSortFilterProxyModel::setFilterFixedString);
728
729     connect(m_ui->airportHistory, &QPushButton::clicked,
730             this, &QtLauncher::onPopupAirportHistory);
731     connect(m_ui->aircraftHistory, &QPushButton::clicked,
732           this, &QtLauncher::onPopupAircraftHistory);
733
734     restoreSettings();
735
736     connect(m_ui->openAircraftDirButton, &QPushButton::clicked,
737           this, &QtLauncher::onOpenCustomAircraftDir);
738
739     QAction* qa = new QAction(this);
740     qa->setShortcut(QKeySequence("Ctrl+Q"));
741     connect(qa, &QAction::triggered, this, &QtLauncher::onQuit);
742     addAction(qa);
743
744     connect(m_ui->editRatingFilter, &QPushButton::clicked,
745             this, &QtLauncher::onEditRatingsFilter);
746     connect(m_ui->ratingsFilterCheck, &QAbstractButton::toggled,
747             m_aircraftProxy, &AircraftProxyModel::setRatingFilterEnabled);
748
749     QIcon historyIcon(":/history-icon");
750     m_ui->aircraftHistory->setIcon(historyIcon);
751     m_ui->airportHistory->setIcon(historyIcon);
752
753     m_ui->searchIcon->setPixmap(QPixmap(":/search-icon"));
754
755     connect(m_ui->timeOfDayCombo, SIGNAL(currentIndexChanged(int)),
756             this, SLOT(updateSettingsSummary()));
757     connect(m_ui->seasonCombo, SIGNAL(currentIndexChanged(int)),
758             this, SLOT(updateSettingsSummary()));
759     connect(m_ui->fetchRealWxrCheckbox, SIGNAL(toggled(bool)),
760             this, SLOT(updateSettingsSummary()));
761     connect(m_ui->rembrandtCheckbox, SIGNAL(toggled(bool)),
762             this, SLOT(updateSettingsSummary()));
763     connect(m_ui->terrasyncCheck, SIGNAL(toggled(bool)),
764             this, SLOT(updateSettingsSummary()));
765     connect(m_ui->startPausedCheck, SIGNAL(toggled(bool)),
766             this, SLOT(updateSettingsSummary()));
767     connect(m_ui->msaaCheckbox, SIGNAL(toggled(bool)),
768             this, SLOT(updateSettingsSummary()));
769
770     connect(m_ui->rembrandtCheckbox, SIGNAL(toggled(bool)),
771             this, SLOT(onRembrandtToggled(bool)));
772
773     updateSettingsSummary();
774
775     connect(m_ui->addSceneryPath, &QToolButton::clicked,
776             this, &QtLauncher::onAddSceneryPath);
777     connect(m_ui->removeSceneryPath, &QToolButton::clicked,
778             this, &QtLauncher::onRemoveSceneryPath);
779 }
780
781 QtLauncher::~QtLauncher()
782 {
783     
784 }
785
786 bool QtLauncher::runLauncherDialog()
787 {
788      Q_INIT_RESOURCE(resources);
789
790     // startup the nav-cache now. This pre-empts normal startup of
791     // the cache, but no harm done. (Providing scenery paths are consistent)
792
793     initNavCache();
794
795   // setup scenery paths now, especially TerraSync path for airport
796   // parking locations (after they're downloaded)
797
798     QtLauncher dlg;
799     dlg.exec();
800     if (dlg.result() != QDialog::Accepted) {
801         return false;
802     }
803
804     return true;
805 }
806
807 void QtLauncher::restoreSettings()
808 {
809     QSettings settings;
810     m_ui->rembrandtCheckbox->setChecked(settings.value("enable-rembrandt", false).toBool());
811     m_ui->terrasyncCheck->setChecked(settings.value("enable-terrasync", true).toBool());
812     m_ui->fullScreenCheckbox->setChecked(settings.value("start-fullscreen", false).toBool());
813     m_ui->msaaCheckbox->setChecked(settings.value("enable-msaa", false).toBool());
814     m_ui->fetchRealWxrCheckbox->setChecked(settings.value("enable-realwx", true).toBool());
815     m_ui->startPausedCheck->setChecked(settings.value("start-paused", false).toBool());
816     m_ui->timeOfDayCombo->setCurrentIndex(settings.value("timeofday", 0).toInt());
817     m_ui->seasonCombo->setCurrentIndex(settings.value("season", 0).toInt());
818
819     // full paths to -set.xml files
820     m_recentAircraft = settings.value("recent-aircraft").toStringList();
821
822     if (!m_recentAircraft.empty()) {
823         m_selectedAircraft = m_recentAircraft.front();
824     } else {
825         // select the default C172p
826     }
827
828     updateSelectedAircraft();
829
830     // ICAO identifiers
831     m_recentAirports = settings.value("recent-airports").toStringList();
832     if (!m_recentAirports.empty()) {
833         setAirport(FGAirport::findByIdent(m_recentAirports.front().toStdString()));
834     }
835     updateAirportDescription();
836
837     // rating filters
838     m_ui->ratingsFilterCheck->setChecked(settings.value("ratings-filter", true).toBool());
839     int index = 0;
840     Q_FOREACH(QVariant v, settings.value("min-ratings").toList()) {
841         m_ratingFilters[index++] = v.toInt();
842     }
843
844     m_aircraftProxy->setRatingFilterEnabled(m_ui->ratingsFilterCheck->isChecked());
845     m_aircraftProxy->setRatings(m_ratingFilters);
846
847     QStringList sceneryPaths = settings.value("scenery-paths").toStringList();
848     m_ui->sceneryPathsList->addItems(sceneryPaths);
849
850     m_ui->commandLineArgs->setPlainText(settings.value("additional-args").toString());
851 }
852
853 void QtLauncher::saveSettings()
854 {
855     QSettings settings;
856     settings.setValue("enable-rembrandt", m_ui->rembrandtCheckbox->isChecked());
857     settings.setValue("enable-terrasync", m_ui->terrasyncCheck->isChecked());
858     settings.setValue("enable-msaa", m_ui->msaaCheckbox->isChecked());
859     settings.setValue("start-fullscreen", m_ui->fullScreenCheckbox->isChecked());
860     settings.setValue("enable-realwx", m_ui->fetchRealWxrCheckbox->isChecked());
861     settings.setValue("start-paused", m_ui->startPausedCheck->isChecked());
862     settings.setValue("ratings-filter", m_ui->ratingsFilterCheck->isChecked());
863     settings.setValue("recent-aircraft", m_recentAircraft);
864     settings.setValue("recent-airports", m_recentAirports);
865     settings.setValue("timeofday", m_ui->timeOfDayCombo->currentIndex());
866     settings.setValue("season", m_ui->seasonCombo->currentIndex());
867
868     QStringList paths;
869     for (int i=0; i<m_ui->sceneryPathsList->count(); ++i) {
870         paths.append(m_ui->sceneryPathsList->item(i)->text());
871     }
872
873     settings.setValue("scenery-paths", paths);
874     settings.setValue("additional-args", m_ui->commandLineArgs->toPlainText());
875 }
876
877 void QtLauncher::setEnableDisableOptionFromCheckbox(QCheckBox* cbox, QString name) const
878 {
879     flightgear::Options* opt = flightgear::Options::sharedInstance();
880     std::string stdName(name.toStdString());
881     if (cbox->isChecked()) {
882         opt->addOption("enable-" + stdName, "");
883     } else {
884         opt->addOption("disable-" + stdName, "");
885     }
886 }
887
888 void QtLauncher::onRun()
889 {
890     accept();
891
892     flightgear::Options* opt = flightgear::Options::sharedInstance();
893     setEnableDisableOptionFromCheckbox(m_ui->terrasyncCheck, "terrasync");
894     setEnableDisableOptionFromCheckbox(m_ui->fetchRealWxrCheckbox, "real-weather-fetch");
895     setEnableDisableOptionFromCheckbox(m_ui->rembrandtCheckbox, "rembrandt");
896     setEnableDisableOptionFromCheckbox(m_ui->fullScreenCheckbox, "fullscreen");
897     setEnableDisableOptionFromCheckbox(m_ui->startPausedCheck, "freeze");
898
899     // MSAA is more complex
900     if (!m_ui->rembrandtCheckbox->isChecked()) {
901         if (m_ui->msaaCheckbox->isChecked()) {
902             globals->get_props()->setIntValue("/sim/rendering/multi-sample-buffers", 1);
903             globals->get_props()->setIntValue("/sim/rendering/multi-samples", 4);
904         } else {
905             globals->get_props()->setIntValue("/sim/rendering/multi-sample-buffers", 0);
906         }
907     }
908
909     // aircraft
910     if (!m_selectedAircraft.isEmpty()) {
911         QFileInfo setFileInfo(m_selectedAircraft);
912         opt->addOption("aircraft-dir", setFileInfo.dir().absolutePath().toStdString());
913         QString setFile = setFileInfo.fileName();
914         Q_ASSERT(setFile.endsWith("-set.xml"));
915         setFile.truncate(setFile.count() - 8); // drop the '-set.xml' portion
916         opt->addOption("aircraft", setFile.toStdString());
917
918       // manage aircraft history
919         if (m_recentAircraft.contains(m_selectedAircraft))
920           m_recentAircraft.removeOne(m_selectedAircraft);
921         m_recentAircraft.prepend(m_selectedAircraft);
922         if (m_recentAircraft.size() > MAX_RECENT_AIRCRAFT)
923           m_recentAircraft.pop_back();
924     }
925
926     // airport / location
927     if (m_selectedAirport) {
928         opt->addOption("airport", m_selectedAirport->ident());
929     }
930
931     if (m_ui->runwayRadio->isChecked()) {
932         int index = m_ui->runwayCombo->currentData().toInt();
933         if (index >= 0) {
934             // explicit runway choice
935             opt->addOption("runway", m_selectedAirport->getRunwayByIndex(index)->ident());
936         }
937
938         if (m_ui->onFinalCheckbox->isChecked()) {
939             opt->addOption("glideslope", "3.0");
940             opt->addOption("offset-distance", "10.0"); // in nautical miles
941         }
942     } else if (m_ui->parkingRadio->isChecked()) {
943         // parking selection
944         opt->addOption("parkpos", m_ui->parkingCombo->currentText().toStdString());
945     }
946
947     // time of day
948     if (m_ui->timeOfDayCombo->currentIndex() != 0) {
949         QString dayval = m_ui->timeOfDayCombo->currentText().toLower();
950         opt->addOption("timeofday", dayval.toStdString());
951     }
952
953     if (m_ui->seasonCombo->currentIndex() != 0) {
954         QString dayval = m_ui->timeOfDayCombo->currentText().toLower();
955         opt->addOption("season", dayval.toStdString());
956     }
957
958     // scenery paths
959     for (int i=0; i<m_ui->sceneryPathsList->count(); ++i) {
960         QString path = m_ui->sceneryPathsList->item(i)->text();
961         opt->addOption("fg-scenery", path.toStdString());
962     }
963
964     // additional arguments
965     ArgumentsTokenizer tk;
966     Q_FOREACH(ArgumentsTokenizer::Arg a, tk.tokenize(m_ui->commandLineArgs->toPlainText())) {
967         if (a.arg.startsWith("prop:")) {
968             QString v = a.arg.mid(5) + "=" + a.value;
969             opt->addOption("prop", v.toStdString());
970         } else {
971             opt->addOption(a.arg.toStdString(), a.value.toStdString());
972         }
973     }
974
975     saveSettings();
976 }
977
978 void QtLauncher::onQuit()
979 {
980     reject();
981 }
982
983 void QtLauncher::onSearchAirports()
984 {
985     QString search = m_ui->airportEdit->text();
986     m_airportsModel->setSearch(search);
987
988     if (m_airportsModel->isSearchActive()) {
989         m_ui->searchStatusText->setText(QString("Searching for '%1'").arg(search));
990         m_ui->locationStack->setCurrentIndex(2);
991     } else if (m_airportsModel->rowCount(QModelIndex()) == 1) {
992         QString ident = m_airportsModel->firstIdent();
993         setAirport(FGAirport::findByIdent(ident.toStdString()));
994         m_ui->locationStack->setCurrentIndex(0);
995     }
996 }
997
998 void QtLauncher::onAirportSearchComplete()
999 {
1000     int numResults = m_airportsModel->rowCount(QModelIndex());
1001     if (numResults == 0) {
1002         m_ui->searchStatusText->setText(QString("No matching airports for '%1'").arg(m_ui->airportEdit->text()));
1003     } else if (numResults == 1) {
1004         QString ident = m_airportsModel->firstIdent();
1005         setAirport(FGAirport::findByIdent(ident.toStdString()));
1006         m_ui->locationStack->setCurrentIndex(0);
1007     } else {
1008         m_ui->locationStack->setCurrentIndex(1);
1009     }
1010 }
1011
1012 void QtLauncher::onAirportChanged()
1013 {
1014     m_ui->runwayCombo->setEnabled(m_selectedAirport);
1015     m_ui->parkingCombo->setEnabled(m_selectedAirport);
1016     m_ui->airportDiagram->setAirport(m_selectedAirport);
1017
1018     m_ui->runwayRadio->setChecked(true); // default back to runway mode
1019     // unelss multiplayer is enabled ?
1020
1021     if (!m_selectedAirport) {
1022         m_ui->airportDescription->setText(QString());
1023         m_ui->airportDiagram->setEnabled(false);
1024         return;
1025     }
1026
1027     m_ui->airportDiagram->setEnabled(true);
1028
1029     m_ui->runwayCombo->clear();
1030     m_ui->runwayCombo->addItem("Automatic", -1);
1031     for (unsigned int r=0; r<m_selectedAirport->numRunways(); ++r) {
1032         FGRunwayRef rwy = m_selectedAirport->getRunwayByIndex(r);
1033         // add runway with index as data role
1034         m_ui->runwayCombo->addItem(QString::fromStdString(rwy->ident()), r);
1035
1036         m_ui->airportDiagram->addRunway(rwy);
1037     }
1038
1039     m_ui->parkingCombo->clear();
1040     FGAirportDynamics* dynamics = m_selectedAirport->getDynamics();
1041     PositionedIDVec parkings = NavDataCache::instance()->airportItemsOfType(
1042                                                                             m_selectedAirport->guid(),
1043                                                                             FGPositioned::PARKING);
1044     if (parkings.empty()) {
1045         m_ui->parkingCombo->setEnabled(false);
1046         m_ui->parkingRadio->setEnabled(false);
1047     } else {
1048         m_ui->parkingCombo->setEnabled(true);
1049         m_ui->parkingRadio->setEnabled(true);
1050         Q_FOREACH(PositionedID parking, parkings) {
1051             FGParking* park = dynamics->getParking(parking);
1052             m_ui->parkingCombo->addItem(QString::fromStdString(park->getName()),
1053                                         static_cast<qlonglong>(parking));
1054
1055             m_ui->airportDiagram->addParking(park);
1056         }
1057     }
1058 }
1059
1060 void QtLauncher::updateAirportDescription()
1061 {
1062     if (!m_selectedAirport) {
1063         m_ui->airportDescription->setText(QString("No airport selected"));
1064         return;
1065     }
1066
1067     QString ident = QString::fromStdString(m_selectedAirport->ident()),
1068         name = QString::fromStdString(m_selectedAirport->name());
1069     QString locationOnAirport;
1070     if (m_ui->runwayRadio->isChecked()) {
1071         bool onFinal = m_ui->onFinalCheckbox->isChecked();
1072         QString runwayName = (m_ui->runwayCombo->currentIndex() == 0) ?
1073             "active runway" :
1074             QString("runway %1").arg(m_ui->runwayCombo->currentText());
1075
1076         if (onFinal) {
1077             locationOnAirport = QString("on 10-mile final to %1").arg(runwayName);
1078         } else {
1079             locationOnAirport = QString("on %1").arg(runwayName);
1080         }
1081     } else if (m_ui->parkingRadio->isChecked()) {
1082         locationOnAirport =  QString("at parking position %1").arg(m_ui->parkingCombo->currentText());
1083     }
1084
1085     m_ui->airportDescription->setText(QString("%2 (%1): %3").arg(ident).arg(name).arg(locationOnAirport));
1086 }
1087
1088 void QtLauncher::onAirportChoiceSelected(const QModelIndex& index)
1089 {
1090     m_ui->locationStack->setCurrentIndex(0);
1091     setAirport(FGPositioned::loadById<FGAirport>(index.data(Qt::UserRole).toULongLong()));
1092 }
1093
1094 void QtLauncher::onAircraftSelected(const QModelIndex& index)
1095 {
1096     m_selectedAircraft = index.data(AircraftPathRole).toString();
1097     updateSelectedAircraft();
1098 }
1099
1100 void QtLauncher::updateSelectedAircraft()
1101 {
1102     try {
1103         QFileInfo info(m_selectedAircraft);
1104         AircraftItem item(info.dir(), m_selectedAircraft);
1105         m_ui->thumbnail->setPixmap(item.thumbnail);
1106         m_ui->aircraftDescription->setText(item.description);
1107     } catch (sg_exception& e) {
1108         m_ui->thumbnail->setPixmap(QPixmap());
1109         m_ui->aircraftDescription->setText("");
1110     }
1111 }
1112
1113 void QtLauncher::onPopupAirportHistory()
1114 {
1115     if (m_recentAirports.isEmpty()) {
1116         return;
1117     }
1118
1119     QMenu m;
1120     Q_FOREACH(QString aptCode, m_recentAirports) {
1121         FGAirportRef apt = FGAirport::findByIdent(aptCode.toStdString());
1122         QString name = QString::fromStdString(apt->name());
1123         QAction* act = m.addAction(QString("%1 - %2").arg(aptCode).arg(name));
1124         act->setData(aptCode);
1125     }
1126
1127     QPoint popupPos = m_ui->airportHistory->mapToGlobal(m_ui->airportHistory->rect().bottomLeft());
1128     QAction* triggered = m.exec(popupPos);
1129     if (triggered) {
1130         FGAirportRef apt = FGAirport::findByIdent(triggered->data().toString().toStdString());
1131         setAirport(apt);
1132         m_ui->airportEdit->clear();
1133         m_ui->locationStack->setCurrentIndex(0);
1134     }
1135 }
1136
1137 QModelIndex QtLauncher::proxyIndexForAircraftPath(QString path) const
1138 {
1139   return m_aircraftProxy->mapFromSource(sourceIndexForAircraftPath(path));
1140 }
1141
1142 QModelIndex QtLauncher::sourceIndexForAircraftPath(QString path) const
1143 {
1144     AircraftItemModel* sourceModel = qobject_cast<AircraftItemModel*>(m_aircraftProxy->sourceModel());
1145     Q_ASSERT(sourceModel);
1146     return sourceModel->indexOfAircraftPath(path);
1147 }
1148
1149 void QtLauncher::onPopupAircraftHistory()
1150 {
1151     if (m_recentAircraft.isEmpty()) {
1152         return;
1153     }
1154
1155     QMenu m;
1156     Q_FOREACH(QString path, m_recentAircraft) {
1157         QModelIndex index = sourceIndexForAircraftPath(path);
1158         if (!index.isValid()) {
1159             // not scanned yet
1160             continue;
1161         }
1162         QAction* act = m.addAction(index.data(Qt::DisplayRole).toString());
1163         act->setData(path);
1164     }
1165
1166     QPoint popupPos = m_ui->aircraftHistory->mapToGlobal(m_ui->aircraftHistory->rect().bottomLeft());
1167     QAction* triggered = m.exec(popupPos);
1168     if (triggered) {
1169         m_selectedAircraft = triggered->data().toString();
1170         QModelIndex index = proxyIndexForAircraftPath(m_selectedAircraft);
1171         m_ui->aircraftList->selectionModel()->setCurrentIndex(index,
1172                                                               QItemSelectionModel::ClearAndSelect);
1173         m_ui->aircraftFilter->clear();
1174         updateSelectedAircraft();
1175     }
1176 }
1177
1178 void QtLauncher::setAirport(FGAirportRef ref)
1179 {
1180     if (m_selectedAirport == ref)
1181         return;
1182
1183     m_selectedAirport = ref;
1184     onAirportChanged();
1185
1186     if (ref.valid()) {
1187         // maintain the recent airport list
1188         QString icao = QString::fromStdString(ref->ident());
1189         if (m_recentAirports.contains(icao)) {
1190             // move to front
1191             m_recentAirports.removeOne(icao);
1192             m_recentAirports.push_front(icao);
1193         } else {
1194             // insert and trim list if necessary
1195             m_recentAirports.push_front(icao);
1196             if (m_recentAirports.size() > MAX_RECENT_AIRPORTS) {
1197                 m_recentAirports.pop_back();
1198             }
1199         }
1200     }
1201
1202     updateAirportDescription();
1203 }
1204
1205 void QtLauncher::onOpenCustomAircraftDir()
1206 {
1207     QFileInfo info(m_customAircraftDir);
1208     if (!info.exists()) {
1209         int result = QMessageBox::question(this, "Create folder?",
1210                                            "The custom aircraft folder does not exist, create it now?",
1211                                            QMessageBox::Yes | QMessageBox::No,
1212                                            QMessageBox::Yes);
1213         if (result == QMessageBox::No) {
1214             return;
1215         }
1216
1217         QDir d(m_customAircraftDir);
1218         d.mkpath(m_customAircraftDir);
1219     }
1220
1221   QUrl u = QUrl::fromLocalFile(m_customAircraftDir);
1222   QDesktopServices::openUrl(u);
1223 }
1224
1225 void QtLauncher::onEditRatingsFilter()
1226 {
1227     EditRatingsFilterDialog dialog(this);
1228     dialog.setRatings(m_ratingFilters);
1229
1230     dialog.exec();
1231     if (dialog.result() == QDialog::Accepted) {
1232         QVariantList vl;
1233         for (int i=0; i<4; ++i) {
1234             m_ratingFilters[i] = dialog.getRating(i);
1235             vl.append(m_ratingFilters[i]);
1236         }
1237         m_aircraftProxy->setRatings(m_ratingFilters);
1238
1239         QSettings settings;
1240         settings.setValue("min-ratings", vl);
1241     }
1242 }
1243
1244 void QtLauncher::updateSettingsSummary()
1245 {
1246     QStringList summary;
1247     if (m_ui->timeOfDayCombo->currentIndex() > 0) {
1248         summary.append(QString(m_ui->timeOfDayCombo->currentText().toLower()));
1249     }
1250
1251     if (m_ui->seasonCombo->currentIndex() > 0) {
1252         summary.append(QString(m_ui->seasonCombo->currentText().toLower()));
1253     }
1254
1255     if (m_ui->rembrandtCheckbox->isChecked()) {
1256         summary.append("Rembrandt enabled");
1257     } else if (m_ui->msaaCheckbox->isChecked()) {
1258         summary.append("anti-aliasing");
1259     }
1260
1261     if (m_ui->fetchRealWxrCheckbox->isChecked()) {
1262         summary.append("live weather");
1263     }
1264
1265     if (m_ui->terrasyncCheck->isChecked()) {
1266         summary.append("automatic scenery downloads");
1267     }
1268
1269     if (m_ui->startPausedCheck->isChecked()) {
1270         summary.append("paused");
1271     }
1272
1273     QString s = summary.join(", ");
1274     s[0] = s[0].toUpper();
1275     m_ui->settingsDescription->setText(s);
1276 }
1277
1278 void QtLauncher::onAddSceneryPath()
1279 {
1280     QString path = QFileDialog::getExistingDirectory(this, tr("Choose scenery folder"));
1281     if (!path.isEmpty()) {
1282         m_ui->sceneryPathsList->addItem(path);
1283         saveSettings();
1284     }
1285 }
1286
1287 void QtLauncher::onRemoveSceneryPath()
1288 {
1289     if (m_ui->sceneryPathsList->currentItem()) {
1290         delete m_ui->sceneryPathsList->currentItem();
1291         saveSettings();
1292     }
1293 }
1294
1295 void QtLauncher::onRembrandtToggled(bool b)
1296 {
1297     // Rembrandt and multi-sample are exclusive
1298     m_ui->msaaCheckbox->setEnabled(!b);
1299 }
1300
1301 #include "QtLauncher.moc"
1302