]> git.mxchange.org Git - flightgear.git/blob - src/GUI/QtLauncher.cxx
Fix a couple more Qt version issues.
[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 #if QT_VERSION >= 0x050300
675     // don't require Qt 5.3
676     m_ui->commandLineArgs->setPlaceholderText("--option=value --prop:/sim/name=value");
677 #endif
678
679 #if QT_VERSION >= 0x050200
680     m_ui->aircraftFilter->setClearButtonEnabled(true);
681 #endif
682
683     for (int i=0; i<4; ++i) {
684         m_ratingFilters[i] = 3;
685     }
686
687     m_airportsModel = new AirportSearchModel;
688     m_ui->searchList->setModel(m_airportsModel);
689     connect(m_ui->searchList, &QListView::clicked,
690             this, &QtLauncher::onAirportChoiceSelected);
691     connect(m_airportsModel, &AirportSearchModel::searchComplete,
692             this, &QtLauncher::onAirportSearchComplete);
693
694     SGPath p = SGPath::documents();
695     p.append("FlightGear");
696     p.append("Aircraft");
697     m_customAircraftDir = QString::fromStdString(p.str());
698     m_ui->customAircraftDirLabel->setText(QString("Custom aircraft folder: %1").arg(m_customAircraftDir));
699
700     globals->append_aircraft_path(m_customAircraftDir.toStdString());
701
702     // create and configure the proxy model
703     m_aircraftProxy = new AircraftProxyModel(this);
704     m_aircraftProxy->setSourceModel(new AircraftItemModel(this));
705
706     m_aircraftProxy->setFilterCaseSensitivity(Qt::CaseInsensitive);
707     m_aircraftProxy->setSortCaseSensitivity(Qt::CaseInsensitive);
708     m_aircraftProxy->setSortRole(Qt::DisplayRole);
709     m_aircraftProxy->setDynamicSortFilter(true);
710
711     m_ui->aircraftList->setModel(m_aircraftProxy);
712     m_ui->aircraftList->setHorizontalScrollBarPolicy(Qt::ScrollBarAlwaysOff);
713     m_ui->aircraftList->setItemDelegate(new AircraftItemDelegate);
714     m_ui->aircraftList->setSelectionMode(QAbstractItemView::SingleSelection);
715     connect(m_ui->aircraftList, &QListView::clicked,
716             this, &QtLauncher::onAircraftSelected);
717
718     connect(m_ui->runwayCombo, SIGNAL(currentIndexChanged(int)),
719             this, SLOT(updateAirportDescription()));
720     connect(m_ui->parkingCombo, SIGNAL(currentIndexChanged(int)),
721             this, SLOT(updateAirportDescription()));
722     connect(m_ui->runwayRadio, SIGNAL(toggled(bool)),
723             this, SLOT(updateAirportDescription()));
724     connect(m_ui->parkingRadio, SIGNAL(toggled(bool)),
725             this, SLOT(updateAirportDescription()));
726     connect(m_ui->onFinalCheckbox, SIGNAL(toggled(bool)),
727             this, SLOT(updateAirportDescription()));
728
729
730     connect(m_ui->runButton, SIGNAL(clicked()), this, SLOT(onRun()));
731     connect(m_ui->quitButton, SIGNAL(clicked()), this, SLOT(onQuit()));
732     connect(m_ui->airportEdit, SIGNAL(returnPressed()),
733             this, SLOT(onSearchAirports()));
734
735     connect(m_ui->aircraftFilter, &QLineEdit::textChanged,
736             m_aircraftProxy, &QSortFilterProxyModel::setFilterFixedString);
737
738     connect(m_ui->airportHistory, &QPushButton::clicked,
739             this, &QtLauncher::onPopupAirportHistory);
740     connect(m_ui->aircraftHistory, &QPushButton::clicked,
741           this, &QtLauncher::onPopupAircraftHistory);
742
743     restoreSettings();
744
745     connect(m_ui->openAircraftDirButton, &QPushButton::clicked,
746           this, &QtLauncher::onOpenCustomAircraftDir);
747
748     QAction* qa = new QAction(this);
749     qa->setShortcut(QKeySequence("Ctrl+Q"));
750     connect(qa, &QAction::triggered, this, &QtLauncher::onQuit);
751     addAction(qa);
752
753     connect(m_ui->editRatingFilter, &QPushButton::clicked,
754             this, &QtLauncher::onEditRatingsFilter);
755     connect(m_ui->ratingsFilterCheck, &QAbstractButton::toggled,
756             m_aircraftProxy, &AircraftProxyModel::setRatingFilterEnabled);
757
758     QIcon historyIcon(":/history-icon");
759     m_ui->aircraftHistory->setIcon(historyIcon);
760     m_ui->airportHistory->setIcon(historyIcon);
761
762     m_ui->searchIcon->setPixmap(QPixmap(":/search-icon"));
763
764     connect(m_ui->timeOfDayCombo, SIGNAL(currentIndexChanged(int)),
765             this, SLOT(updateSettingsSummary()));
766     connect(m_ui->seasonCombo, SIGNAL(currentIndexChanged(int)),
767             this, SLOT(updateSettingsSummary()));
768     connect(m_ui->fetchRealWxrCheckbox, SIGNAL(toggled(bool)),
769             this, SLOT(updateSettingsSummary()));
770     connect(m_ui->rembrandtCheckbox, SIGNAL(toggled(bool)),
771             this, SLOT(updateSettingsSummary()));
772     connect(m_ui->terrasyncCheck, SIGNAL(toggled(bool)),
773             this, SLOT(updateSettingsSummary()));
774     connect(m_ui->startPausedCheck, SIGNAL(toggled(bool)),
775             this, SLOT(updateSettingsSummary()));
776     connect(m_ui->msaaCheckbox, SIGNAL(toggled(bool)),
777             this, SLOT(updateSettingsSummary()));
778
779     connect(m_ui->rembrandtCheckbox, SIGNAL(toggled(bool)),
780             this, SLOT(onRembrandtToggled(bool)));
781
782     updateSettingsSummary();
783
784     connect(m_ui->addSceneryPath, &QToolButton::clicked,
785             this, &QtLauncher::onAddSceneryPath);
786     connect(m_ui->removeSceneryPath, &QToolButton::clicked,
787             this, &QtLauncher::onRemoveSceneryPath);
788 }
789
790 QtLauncher::~QtLauncher()
791 {
792     
793 }
794
795 bool QtLauncher::runLauncherDialog()
796 {
797      Q_INIT_RESOURCE(resources);
798
799     // startup the nav-cache now. This pre-empts normal startup of
800     // the cache, but no harm done. (Providing scenery paths are consistent)
801
802     initNavCache();
803
804   // setup scenery paths now, especially TerraSync path for airport
805   // parking locations (after they're downloaded)
806
807     QtLauncher dlg;
808     dlg.exec();
809     if (dlg.result() != QDialog::Accepted) {
810         return false;
811     }
812
813     return true;
814 }
815
816 void QtLauncher::restoreSettings()
817 {
818     QSettings settings;
819     m_ui->rembrandtCheckbox->setChecked(settings.value("enable-rembrandt", false).toBool());
820     m_ui->terrasyncCheck->setChecked(settings.value("enable-terrasync", true).toBool());
821     m_ui->fullScreenCheckbox->setChecked(settings.value("start-fullscreen", false).toBool());
822     m_ui->msaaCheckbox->setChecked(settings.value("enable-msaa", false).toBool());
823     m_ui->fetchRealWxrCheckbox->setChecked(settings.value("enable-realwx", true).toBool());
824     m_ui->startPausedCheck->setChecked(settings.value("start-paused", false).toBool());
825     m_ui->timeOfDayCombo->setCurrentIndex(settings.value("timeofday", 0).toInt());
826     m_ui->seasonCombo->setCurrentIndex(settings.value("season", 0).toInt());
827
828     // full paths to -set.xml files
829     m_recentAircraft = settings.value("recent-aircraft").toStringList();
830
831     if (!m_recentAircraft.empty()) {
832         m_selectedAircraft = m_recentAircraft.front();
833     } else {
834         // select the default C172p
835     }
836
837     updateSelectedAircraft();
838
839     // ICAO identifiers
840     m_recentAirports = settings.value("recent-airports").toStringList();
841     if (!m_recentAirports.empty()) {
842         setAirport(FGAirport::findByIdent(m_recentAirports.front().toStdString()));
843     }
844     updateAirportDescription();
845
846     // rating filters
847     m_ui->ratingsFilterCheck->setChecked(settings.value("ratings-filter", true).toBool());
848     int index = 0;
849     Q_FOREACH(QVariant v, settings.value("min-ratings").toList()) {
850         m_ratingFilters[index++] = v.toInt();
851     }
852
853     m_aircraftProxy->setRatingFilterEnabled(m_ui->ratingsFilterCheck->isChecked());
854     m_aircraftProxy->setRatings(m_ratingFilters);
855
856     QStringList sceneryPaths = settings.value("scenery-paths").toStringList();
857     m_ui->sceneryPathsList->addItems(sceneryPaths);
858
859     m_ui->commandLineArgs->setPlainText(settings.value("additional-args").toString());
860 }
861
862 void QtLauncher::saveSettings()
863 {
864     QSettings settings;
865     settings.setValue("enable-rembrandt", m_ui->rembrandtCheckbox->isChecked());
866     settings.setValue("enable-terrasync", m_ui->terrasyncCheck->isChecked());
867     settings.setValue("enable-msaa", m_ui->msaaCheckbox->isChecked());
868     settings.setValue("start-fullscreen", m_ui->fullScreenCheckbox->isChecked());
869     settings.setValue("enable-realwx", m_ui->fetchRealWxrCheckbox->isChecked());
870     settings.setValue("start-paused", m_ui->startPausedCheck->isChecked());
871     settings.setValue("ratings-filter", m_ui->ratingsFilterCheck->isChecked());
872     settings.setValue("recent-aircraft", m_recentAircraft);
873     settings.setValue("recent-airports", m_recentAirports);
874     settings.setValue("timeofday", m_ui->timeOfDayCombo->currentIndex());
875     settings.setValue("season", m_ui->seasonCombo->currentIndex());
876
877     QStringList paths;
878     for (int i=0; i<m_ui->sceneryPathsList->count(); ++i) {
879         paths.append(m_ui->sceneryPathsList->item(i)->text());
880     }
881
882     settings.setValue("scenery-paths", paths);
883     settings.setValue("additional-args", m_ui->commandLineArgs->toPlainText());
884 }
885
886 void QtLauncher::setEnableDisableOptionFromCheckbox(QCheckBox* cbox, QString name) const
887 {
888     flightgear::Options* opt = flightgear::Options::sharedInstance();
889     std::string stdName(name.toStdString());
890     if (cbox->isChecked()) {
891         opt->addOption("enable-" + stdName, "");
892     } else {
893         opt->addOption("disable-" + stdName, "");
894     }
895 }
896
897 void QtLauncher::onRun()
898 {
899     accept();
900
901     flightgear::Options* opt = flightgear::Options::sharedInstance();
902     setEnableDisableOptionFromCheckbox(m_ui->terrasyncCheck, "terrasync");
903     setEnableDisableOptionFromCheckbox(m_ui->fetchRealWxrCheckbox, "real-weather-fetch");
904     setEnableDisableOptionFromCheckbox(m_ui->rembrandtCheckbox, "rembrandt");
905     setEnableDisableOptionFromCheckbox(m_ui->fullScreenCheckbox, "fullscreen");
906     setEnableDisableOptionFromCheckbox(m_ui->startPausedCheck, "freeze");
907
908     // MSAA is more complex
909     if (!m_ui->rembrandtCheckbox->isChecked()) {
910         if (m_ui->msaaCheckbox->isChecked()) {
911             globals->get_props()->setIntValue("/sim/rendering/multi-sample-buffers", 1);
912             globals->get_props()->setIntValue("/sim/rendering/multi-samples", 4);
913         } else {
914             globals->get_props()->setIntValue("/sim/rendering/multi-sample-buffers", 0);
915         }
916     }
917
918     // aircraft
919     if (!m_selectedAircraft.isEmpty()) {
920         QFileInfo setFileInfo(m_selectedAircraft);
921         opt->addOption("aircraft-dir", setFileInfo.dir().absolutePath().toStdString());
922         QString setFile = setFileInfo.fileName();
923         Q_ASSERT(setFile.endsWith("-set.xml"));
924         setFile.truncate(setFile.count() - 8); // drop the '-set.xml' portion
925         opt->addOption("aircraft", setFile.toStdString());
926
927       // manage aircraft history
928         if (m_recentAircraft.contains(m_selectedAircraft))
929           m_recentAircraft.removeOne(m_selectedAircraft);
930         m_recentAircraft.prepend(m_selectedAircraft);
931         if (m_recentAircraft.size() > MAX_RECENT_AIRCRAFT)
932           m_recentAircraft.pop_back();
933     }
934
935     // airport / location
936     if (m_selectedAirport) {
937         opt->addOption("airport", m_selectedAirport->ident());
938     }
939
940     if (m_ui->runwayRadio->isChecked()) {
941         int index = m_ui->runwayCombo->itemData(m_ui->runwayCombo->currentIndex()).toInt();
942         if ((index >= 0) && m_selectedAirport) {
943             // explicit runway choice
944             opt->addOption("runway", m_selectedAirport->getRunwayByIndex(index)->ident());
945         }
946
947         if (m_ui->onFinalCheckbox->isChecked()) {
948             opt->addOption("glideslope", "3.0");
949             opt->addOption("offset-distance", "10.0"); // in nautical miles
950         }
951     } else if (m_ui->parkingRadio->isChecked()) {
952         // parking selection
953         opt->addOption("parkpos", m_ui->parkingCombo->currentText().toStdString());
954     }
955
956     // time of day
957     if (m_ui->timeOfDayCombo->currentIndex() != 0) {
958         QString dayval = m_ui->timeOfDayCombo->currentText().toLower();
959         opt->addOption("timeofday", dayval.toStdString());
960     }
961
962     if (m_ui->seasonCombo->currentIndex() != 0) {
963         QString dayval = m_ui->timeOfDayCombo->currentText().toLower();
964         opt->addOption("season", dayval.toStdString());
965     }
966
967     // scenery paths
968     for (int i=0; i<m_ui->sceneryPathsList->count(); ++i) {
969         QString path = m_ui->sceneryPathsList->item(i)->text();
970         opt->addOption("fg-scenery", path.toStdString());
971     }
972
973     // additional arguments
974     ArgumentsTokenizer tk;
975     Q_FOREACH(ArgumentsTokenizer::Arg a, tk.tokenize(m_ui->commandLineArgs->toPlainText())) {
976         if (a.arg.startsWith("prop:")) {
977             QString v = a.arg.mid(5) + "=" + a.value;
978             opt->addOption("prop", v.toStdString());
979         } else {
980             opt->addOption(a.arg.toStdString(), a.value.toStdString());
981         }
982     }
983
984     saveSettings();
985 }
986
987 void QtLauncher::onQuit()
988 {
989     reject();
990 }
991
992 void QtLauncher::onSearchAirports()
993 {
994     QString search = m_ui->airportEdit->text();
995     m_airportsModel->setSearch(search);
996
997     if (m_airportsModel->isSearchActive()) {
998         m_ui->searchStatusText->setText(QString("Searching for '%1'").arg(search));
999         m_ui->locationStack->setCurrentIndex(2);
1000     } else if (m_airportsModel->rowCount(QModelIndex()) == 1) {
1001         QString ident = m_airportsModel->firstIdent();
1002         setAirport(FGAirport::findByIdent(ident.toStdString()));
1003         m_ui->locationStack->setCurrentIndex(0);
1004     }
1005 }
1006
1007 void QtLauncher::onAirportSearchComplete()
1008 {
1009     int numResults = m_airportsModel->rowCount(QModelIndex());
1010     if (numResults == 0) {
1011         m_ui->searchStatusText->setText(QString("No matching airports for '%1'").arg(m_ui->airportEdit->text()));
1012     } else if (numResults == 1) {
1013         QString ident = m_airportsModel->firstIdent();
1014         setAirport(FGAirport::findByIdent(ident.toStdString()));
1015         m_ui->locationStack->setCurrentIndex(0);
1016     } else {
1017         m_ui->locationStack->setCurrentIndex(1);
1018     }
1019 }
1020
1021 void QtLauncher::onAirportChanged()
1022 {
1023     m_ui->runwayCombo->setEnabled(m_selectedAirport);
1024     m_ui->parkingCombo->setEnabled(m_selectedAirport);
1025     m_ui->airportDiagram->setAirport(m_selectedAirport);
1026
1027     m_ui->runwayRadio->setChecked(true); // default back to runway mode
1028     // unelss multiplayer is enabled ?
1029
1030     if (!m_selectedAirport) {
1031         m_ui->airportDescription->setText(QString());
1032         m_ui->airportDiagram->setEnabled(false);
1033         return;
1034     }
1035
1036     m_ui->airportDiagram->setEnabled(true);
1037
1038     m_ui->runwayCombo->clear();
1039     m_ui->runwayCombo->addItem("Automatic", -1);
1040     for (unsigned int r=0; r<m_selectedAirport->numRunways(); ++r) {
1041         FGRunwayRef rwy = m_selectedAirport->getRunwayByIndex(r);
1042         // add runway with index as data role
1043         m_ui->runwayCombo->addItem(QString::fromStdString(rwy->ident()), r);
1044
1045         m_ui->airportDiagram->addRunway(rwy);
1046     }
1047
1048     m_ui->parkingCombo->clear();
1049     FGAirportDynamics* dynamics = m_selectedAirport->getDynamics();
1050     PositionedIDVec parkings = NavDataCache::instance()->airportItemsOfType(
1051                                                                             m_selectedAirport->guid(),
1052                                                                             FGPositioned::PARKING);
1053     if (parkings.empty()) {
1054         m_ui->parkingCombo->setEnabled(false);
1055         m_ui->parkingRadio->setEnabled(false);
1056     } else {
1057         m_ui->parkingCombo->setEnabled(true);
1058         m_ui->parkingRadio->setEnabled(true);
1059         Q_FOREACH(PositionedID parking, parkings) {
1060             FGParking* park = dynamics->getParking(parking);
1061             m_ui->parkingCombo->addItem(QString::fromStdString(park->getName()),
1062                                         static_cast<qlonglong>(parking));
1063
1064             m_ui->airportDiagram->addParking(park);
1065         }
1066     }
1067 }
1068
1069 void QtLauncher::updateAirportDescription()
1070 {
1071     if (!m_selectedAirport) {
1072         m_ui->airportDescription->setText(QString("No airport selected"));
1073         return;
1074     }
1075
1076     QString ident = QString::fromStdString(m_selectedAirport->ident()),
1077         name = QString::fromStdString(m_selectedAirport->name());
1078     QString locationOnAirport;
1079     if (m_ui->runwayRadio->isChecked()) {
1080         bool onFinal = m_ui->onFinalCheckbox->isChecked();
1081         QString runwayName = (m_ui->runwayCombo->currentIndex() == 0) ?
1082             "active runway" :
1083             QString("runway %1").arg(m_ui->runwayCombo->currentText());
1084
1085         if (onFinal) {
1086             locationOnAirport = QString("on 10-mile final to %1").arg(runwayName);
1087         } else {
1088             locationOnAirport = QString("on %1").arg(runwayName);
1089         }
1090     } else if (m_ui->parkingRadio->isChecked()) {
1091         locationOnAirport =  QString("at parking position %1").arg(m_ui->parkingCombo->currentText());
1092     }
1093
1094     m_ui->airportDescription->setText(QString("%2 (%1): %3").arg(ident).arg(name).arg(locationOnAirport));
1095 }
1096
1097 void QtLauncher::onAirportChoiceSelected(const QModelIndex& index)
1098 {
1099     m_ui->locationStack->setCurrentIndex(0);
1100     setAirport(FGPositioned::loadById<FGAirport>(index.data(Qt::UserRole).toULongLong()));
1101 }
1102
1103 void QtLauncher::onAircraftSelected(const QModelIndex& index)
1104 {
1105     m_selectedAircraft = index.data(AircraftPathRole).toString();
1106     updateSelectedAircraft();
1107 }
1108
1109 void QtLauncher::updateSelectedAircraft()
1110 {
1111     try {
1112         QFileInfo info(m_selectedAircraft);
1113         AircraftItem item(info.dir(), m_selectedAircraft);
1114         m_ui->thumbnail->setPixmap(item.thumbnail);
1115         m_ui->aircraftDescription->setText(item.description);
1116     } catch (sg_exception& e) {
1117         m_ui->thumbnail->setPixmap(QPixmap());
1118         m_ui->aircraftDescription->setText("");
1119     }
1120 }
1121
1122 void QtLauncher::onPopupAirportHistory()
1123 {
1124     if (m_recentAirports.isEmpty()) {
1125         return;
1126     }
1127
1128     QMenu m;
1129     Q_FOREACH(QString aptCode, m_recentAirports) {
1130         FGAirportRef apt = FGAirport::findByIdent(aptCode.toStdString());
1131         QString name = QString::fromStdString(apt->name());
1132         QAction* act = m.addAction(QString("%1 - %2").arg(aptCode).arg(name));
1133         act->setData(aptCode);
1134     }
1135
1136     QPoint popupPos = m_ui->airportHistory->mapToGlobal(m_ui->airportHistory->rect().bottomLeft());
1137     QAction* triggered = m.exec(popupPos);
1138     if (triggered) {
1139         FGAirportRef apt = FGAirport::findByIdent(triggered->data().toString().toStdString());
1140         setAirport(apt);
1141         m_ui->airportEdit->clear();
1142         m_ui->locationStack->setCurrentIndex(0);
1143     }
1144 }
1145
1146 QModelIndex QtLauncher::proxyIndexForAircraftPath(QString path) const
1147 {
1148   return m_aircraftProxy->mapFromSource(sourceIndexForAircraftPath(path));
1149 }
1150
1151 QModelIndex QtLauncher::sourceIndexForAircraftPath(QString path) const
1152 {
1153     AircraftItemModel* sourceModel = qobject_cast<AircraftItemModel*>(m_aircraftProxy->sourceModel());
1154     Q_ASSERT(sourceModel);
1155     return sourceModel->indexOfAircraftPath(path);
1156 }
1157
1158 void QtLauncher::onPopupAircraftHistory()
1159 {
1160     if (m_recentAircraft.isEmpty()) {
1161         return;
1162     }
1163
1164     QMenu m;
1165     Q_FOREACH(QString path, m_recentAircraft) {
1166         QModelIndex index = sourceIndexForAircraftPath(path);
1167         if (!index.isValid()) {
1168             // not scanned yet
1169             continue;
1170         }
1171         QAction* act = m.addAction(index.data(Qt::DisplayRole).toString());
1172         act->setData(path);
1173     }
1174
1175     QPoint popupPos = m_ui->aircraftHistory->mapToGlobal(m_ui->aircraftHistory->rect().bottomLeft());
1176     QAction* triggered = m.exec(popupPos);
1177     if (triggered) {
1178         m_selectedAircraft = triggered->data().toString();
1179         QModelIndex index = proxyIndexForAircraftPath(m_selectedAircraft);
1180         m_ui->aircraftList->selectionModel()->setCurrentIndex(index,
1181                                                               QItemSelectionModel::ClearAndSelect);
1182         m_ui->aircraftFilter->clear();
1183         updateSelectedAircraft();
1184     }
1185 }
1186
1187 void QtLauncher::setAirport(FGAirportRef ref)
1188 {
1189     if (m_selectedAirport == ref)
1190         return;
1191
1192     m_selectedAirport = ref;
1193     onAirportChanged();
1194
1195     if (ref.valid()) {
1196         // maintain the recent airport list
1197         QString icao = QString::fromStdString(ref->ident());
1198         if (m_recentAirports.contains(icao)) {
1199             // move to front
1200             m_recentAirports.removeOne(icao);
1201             m_recentAirports.push_front(icao);
1202         } else {
1203             // insert and trim list if necessary
1204             m_recentAirports.push_front(icao);
1205             if (m_recentAirports.size() > MAX_RECENT_AIRPORTS) {
1206                 m_recentAirports.pop_back();
1207             }
1208         }
1209     }
1210
1211     updateAirportDescription();
1212 }
1213
1214 void QtLauncher::onOpenCustomAircraftDir()
1215 {
1216     QFileInfo info(m_customAircraftDir);
1217     if (!info.exists()) {
1218         int result = QMessageBox::question(this, "Create folder?",
1219                                            "The custom aircraft folder does not exist, create it now?",
1220                                            QMessageBox::Yes | QMessageBox::No,
1221                                            QMessageBox::Yes);
1222         if (result == QMessageBox::No) {
1223             return;
1224         }
1225
1226         QDir d(m_customAircraftDir);
1227         d.mkpath(m_customAircraftDir);
1228     }
1229
1230   QUrl u = QUrl::fromLocalFile(m_customAircraftDir);
1231   QDesktopServices::openUrl(u);
1232 }
1233
1234 void QtLauncher::onEditRatingsFilter()
1235 {
1236     EditRatingsFilterDialog dialog(this);
1237     dialog.setRatings(m_ratingFilters);
1238
1239     dialog.exec();
1240     if (dialog.result() == QDialog::Accepted) {
1241         QVariantList vl;
1242         for (int i=0; i<4; ++i) {
1243             m_ratingFilters[i] = dialog.getRating(i);
1244             vl.append(m_ratingFilters[i]);
1245         }
1246         m_aircraftProxy->setRatings(m_ratingFilters);
1247
1248         QSettings settings;
1249         settings.setValue("min-ratings", vl);
1250     }
1251 }
1252
1253 void QtLauncher::updateSettingsSummary()
1254 {
1255     QStringList summary;
1256     if (m_ui->timeOfDayCombo->currentIndex() > 0) {
1257         summary.append(QString(m_ui->timeOfDayCombo->currentText().toLower()));
1258     }
1259
1260     if (m_ui->seasonCombo->currentIndex() > 0) {
1261         summary.append(QString(m_ui->seasonCombo->currentText().toLower()));
1262     }
1263
1264     if (m_ui->rembrandtCheckbox->isChecked()) {
1265         summary.append("Rembrandt enabled");
1266     } else if (m_ui->msaaCheckbox->isChecked()) {
1267         summary.append("anti-aliasing");
1268     }
1269
1270     if (m_ui->fetchRealWxrCheckbox->isChecked()) {
1271         summary.append("live weather");
1272     }
1273
1274     if (m_ui->terrasyncCheck->isChecked()) {
1275         summary.append("automatic scenery downloads");
1276     }
1277
1278     if (m_ui->startPausedCheck->isChecked()) {
1279         summary.append("paused");
1280     }
1281
1282     QString s = summary.join(", ");
1283     s[0] = s[0].toUpper();
1284     m_ui->settingsDescription->setText(s);
1285 }
1286
1287 void QtLauncher::onAddSceneryPath()
1288 {
1289     QString path = QFileDialog::getExistingDirectory(this, tr("Choose scenery folder"));
1290     if (!path.isEmpty()) {
1291         m_ui->sceneryPathsList->addItem(path);
1292         saveSettings();
1293     }
1294 }
1295
1296 void QtLauncher::onRemoveSceneryPath()
1297 {
1298     if (m_ui->sceneryPathsList->currentItem()) {
1299         delete m_ui->sceneryPathsList->currentItem();
1300         saveSettings();
1301     }
1302 }
1303
1304 void QtLauncher::onRembrandtToggled(bool b)
1305 {
1306     // Rembrandt and multi-sample are exclusive
1307     m_ui->msaaCheckbox->setEnabled(!b);
1308 }
1309
1310 #include "QtLauncher.moc"
1311