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