]> git.mxchange.org Git - flightgear.git/blob - src/GUI/QtLauncher.cxx
Launcher: select season.
[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 } // of anonymous namespace
400
401 class AirportSearchModel : public QAbstractListModel
402 {
403     Q_OBJECT
404 public:
405     AirportSearchModel() :
406         m_searchActive(false)
407     {
408     }
409
410     void setSearch(QString t)
411     {
412         beginResetModel();
413
414         m_airports.clear();
415         m_ids.clear();
416
417         std::string term(t.toUpper().toStdString());
418         // try ICAO lookup first
419         FGAirportRef ref = FGAirport::findByIdent(term);
420         if (ref) {
421             m_ids.push_back(ref->guid());
422             m_airports.push_back(ref);
423         } else {
424             m_search.reset(new NavDataCache::ThreadedAirportSearch(term));
425             QTimer::singleShot(100, this, SLOT(onSearchResultsPoll()));
426             m_searchActive = true;
427         }
428
429         endResetModel();
430     }
431
432     bool isSearchActive() const
433     {
434         return m_searchActive;
435     }
436
437     virtual int rowCount(const QModelIndex&) const
438     {
439         // if empty, return 1 for special 'no matches'?
440         return m_ids.size();
441     }
442
443     virtual QVariant data(const QModelIndex& index, int role) const
444     {
445         if (!index.isValid())
446             return QVariant();
447         
448         FGAirportRef apt = m_airports[index.row()];
449         if (!apt.valid()) {
450             apt = FGPositioned::loadById<FGAirport>(m_ids[index.row()]);
451             m_airports[index.row()] = apt;
452         }
453
454         if (role == Qt::DisplayRole) {
455             QString name = QString::fromStdString(apt->name());
456             return QString("%1: %2").arg(QString::fromStdString(apt->ident())).arg(name);
457         }
458
459         if (role == Qt::EditRole) {
460             return QString::fromStdString(apt->ident());
461         }
462
463         if (role == Qt::UserRole) {
464             return static_cast<qlonglong>(m_ids[index.row()]);
465         }
466
467         return QVariant();
468     }
469
470     QString firstIdent() const
471     {
472         if (m_ids.empty())
473             return QString();
474
475         if (!m_airports.front().valid()) {
476             m_airports[0] = FGPositioned::loadById<FGAirport>(m_ids.front());
477         }
478
479         return QString::fromStdString(m_airports.front()->ident());
480     }
481
482 Q_SIGNALS:
483     void searchComplete();
484
485 private slots:
486     void onSearchResultsPoll()
487     {
488         PositionedIDVec newIds = m_search->results();
489         
490         beginInsertRows(QModelIndex(), m_ids.size(), newIds.size() - 1);
491         for (unsigned int i=m_ids.size(); i < newIds.size(); ++i) {
492             m_ids.push_back(newIds[i]);
493             m_airports.push_back(FGAirportRef()); // null ref
494         }
495         endInsertRows();
496
497         if (m_search->isComplete()) {
498             m_searchActive = false;
499             m_search.reset();
500             emit searchComplete();
501         } else {
502             QTimer::singleShot(100, this, SLOT(onSearchResultsPoll()));
503         }
504     }
505
506 private:
507     PositionedIDVec m_ids;
508     mutable std::vector<FGAirportRef> m_airports;
509     bool m_searchActive;
510     QScopedPointer<NavDataCache::ThreadedAirportSearch> m_search;
511 };
512
513 class AircraftProxyModel : public QSortFilterProxyModel
514 {
515     Q_OBJECT
516 public:
517     AircraftProxyModel(QObject* pr) :
518         QSortFilterProxyModel(pr),
519         m_ratingsFilter(true)
520     {
521         for (int i=0; i<4; ++i) {
522             m_ratings[i] = 3;
523         }
524     }
525
526     void setRatings(int* ratings)
527     {
528         ::memcpy(m_ratings, ratings, sizeof(int) * 4);
529         invalidate();
530     }
531
532 public slots:
533     void setRatingFilterEnabled(bool e)
534     {
535         if (e == m_ratingsFilter) {
536             return;
537         }
538
539         m_ratingsFilter = e;
540         invalidate();
541     }
542
543 protected:
544     bool filterAcceptsRow(int sourceRow, const QModelIndex &sourceParent) const
545     {
546         if (!QSortFilterProxyModel::filterAcceptsRow(sourceRow, sourceParent)) {
547             return false;
548         }
549
550         if (m_ratingsFilter) {
551             QModelIndex index = sourceModel()->index(sourceRow, 0, sourceParent);
552             for (int i=0; i<4; ++i) {
553                 if (m_ratings[i] > index.data(AircraftRatingRole + i).toInt()) {
554                     return false;
555                 }
556             }
557         }
558
559         return true;
560     }
561
562 private:
563     bool m_ratingsFilter;
564     int m_ratings[4];
565 };
566
567 QtLauncher::QtLauncher() :
568     QDialog(),
569     m_ui(NULL)
570 {
571     m_ui.reset(new Ui::Launcher);
572     m_ui->setupUi(this);
573
574     for (int i=0; i<4; ++i) {
575         m_ratingFilters[i] = 3;
576     }
577
578     m_airportsModel = new AirportSearchModel;
579     m_ui->searchList->setModel(m_airportsModel);
580     connect(m_ui->searchList, &QListView::clicked,
581             this, &QtLauncher::onAirportChoiceSelected);
582     connect(m_airportsModel, &AirportSearchModel::searchComplete,
583             this, &QtLauncher::onAirportSearchComplete);
584
585     SGPath p = SGPath::documents();
586     p.append("FlightGear");
587     p.append("Aircraft");
588     m_customAircraftDir = QString::fromStdString(p.str());
589     m_ui->customAircraftDirLabel->setText(QString("Custom aircraft folder: %1").arg(m_customAircraftDir));
590
591     globals->append_aircraft_path(m_customAircraftDir.toStdString());
592
593     // create and configure the proxy model
594     m_aircraftProxy = new AircraftProxyModel(this);
595     m_aircraftProxy->setSourceModel(new AircraftItemModel(this));
596
597     m_aircraftProxy->setFilterCaseSensitivity(Qt::CaseInsensitive);
598     m_aircraftProxy->setSortCaseSensitivity(Qt::CaseInsensitive);
599     m_aircraftProxy->setSortRole(Qt::DisplayRole);
600     m_aircraftProxy->setDynamicSortFilter(true);
601
602     m_ui->aircraftList->setModel(m_aircraftProxy);
603     m_ui->aircraftList->setHorizontalScrollBarPolicy(Qt::ScrollBarAlwaysOff);
604     m_ui->aircraftList->setItemDelegate(new AircraftItemDelegate);
605     m_ui->aircraftList->setSelectionMode(QAbstractItemView::SingleSelection);
606     connect(m_ui->aircraftList, &QListView::clicked,
607             this, &QtLauncher::onAircraftSelected);
608
609     connect(m_ui->runwayCombo, SIGNAL(currentIndexChanged(int)),
610             this, SLOT(updateAirportDescription()));
611     connect(m_ui->parkingCombo, SIGNAL(currentIndexChanged(int)),
612             this, SLOT(updateAirportDescription()));
613     connect(m_ui->runwayRadio, SIGNAL(toggled(bool)),
614             this, SLOT(updateAirportDescription()));
615     connect(m_ui->parkingRadio, SIGNAL(toggled(bool)),
616             this, SLOT(updateAirportDescription()));
617     connect(m_ui->onFinalCheckbox, SIGNAL(toggled(bool)),
618             this, SLOT(updateAirportDescription()));
619
620
621     connect(m_ui->runButton, SIGNAL(clicked()), this, SLOT(onRun()));
622     connect(m_ui->quitButton, SIGNAL(clicked()), this, SLOT(onQuit()));
623     connect(m_ui->airportEdit, SIGNAL(returnPressed()),
624             this, SLOT(onSearchAirports()));
625
626     connect(m_ui->aircraftFilter, &QLineEdit::textChanged,
627             m_aircraftProxy, &QSortFilterProxyModel::setFilterFixedString);
628
629     connect(m_ui->airportHistory, &QPushButton::clicked,
630             this, &QtLauncher::onPopupAirportHistory);
631     connect(m_ui->aircraftHistory, &QPushButton::clicked,
632           this, &QtLauncher::onPopupAircraftHistory);
633
634     restoreSettings();
635
636     connect(m_ui->openAircraftDirButton, &QPushButton::clicked,
637           this, &QtLauncher::onOpenCustomAircraftDir);
638
639     QAction* qa = new QAction(this);
640     qa->setShortcut(QKeySequence("Ctrl+Q"));
641     connect(qa, &QAction::triggered, this, &QtLauncher::onQuit);
642     addAction(qa);
643
644     connect(m_ui->editRatingFilter, &QPushButton::clicked,
645             this, &QtLauncher::onEditRatingsFilter);
646     connect(m_ui->ratingsFilterCheck, &QAbstractButton::toggled,
647             m_aircraftProxy, &AircraftProxyModel::setRatingFilterEnabled);
648
649     QIcon historyIcon(":/history-icon");
650     m_ui->aircraftHistory->setIcon(historyIcon);
651     m_ui->airportHistory->setIcon(historyIcon);
652
653     m_ui->searchIcon->setPixmap(QPixmap(":/search-icon"));
654
655     connect(m_ui->timeOfDayCombo, SIGNAL(currentIndexChanged(int)),
656             this, SLOT(updateSettingsSummary()));
657     connect(m_ui->seasonCombo, SIGNAL(currentIndexChanged(int)),
658             this, SLOT(updateSettingsSummary()));
659     connect(m_ui->fetchRealWxrCheckbox, SIGNAL(toggled(bool)),
660             this, SLOT(updateSettingsSummary()));
661     connect(m_ui->rembrandtCheckbox, SIGNAL(toggled(bool)),
662             this, SLOT(updateSettingsSummary()));
663     connect(m_ui->terrasyncCheck, SIGNAL(toggled(bool)),
664             this, SLOT(updateSettingsSummary()));
665     connect(m_ui->startPausedCheck, SIGNAL(toggled(bool)),
666             this, SLOT(updateSettingsSummary()));
667     connect(m_ui->msaaCheckbox, SIGNAL(toggled(bool)),
668             this, SLOT(updateSettingsSummary()));
669
670     connect(m_ui->rembrandtCheckbox, SIGNAL(toggled(bool)),
671             this, SLOT(onRembrandtToggled(bool)));
672
673     updateSettingsSummary();
674
675     connect(m_ui->addSceneryPath, &QToolButton::clicked,
676             this, &QtLauncher::onAddSceneryPath);
677     connect(m_ui->removeSceneryPath, &QToolButton::clicked,
678             this, &QtLauncher::onRemoveSceneryPath);
679 }
680
681 QtLauncher::~QtLauncher()
682 {
683     
684 }
685
686 bool QtLauncher::runLauncherDialog()
687 {
688      Q_INIT_RESOURCE(resources);
689
690     // startup the nav-cache now. This pre-empts normal startup of
691     // the cache, but no harm done. (Providing scenery paths are consistent)
692
693     initNavCache();
694
695   // setup scenery paths now, especially TerraSync path for airport
696   // parking locations (after they're downloaded)
697
698     QtLauncher dlg;
699     dlg.exec();
700     if (dlg.result() != QDialog::Accepted) {
701         return false;
702     }
703
704     return true;
705 }
706
707 void QtLauncher::restoreSettings()
708 {
709     QSettings settings;
710     m_ui->rembrandtCheckbox->setChecked(settings.value("enable-rembrandt", false).toBool());
711     m_ui->terrasyncCheck->setChecked(settings.value("enable-terrasync", true).toBool());
712     m_ui->fullScreenCheckbox->setChecked(settings.value("start-fullscreen", false).toBool());
713     m_ui->msaaCheckbox->setChecked(settings.value("enable-msaa", false).toBool());
714     m_ui->fetchRealWxrCheckbox->setChecked(settings.value("enable-realwx", true).toBool());
715     m_ui->startPausedCheck->setChecked(settings.value("start-paused", false).toBool());
716     m_ui->timeOfDayCombo->setCurrentIndex(settings.value("timeofday", 0).toInt());
717     m_ui->seasonCombo->setCurrentIndex(settings.value("season", 0).toInt());
718
719     // full paths to -set.xml files
720     m_recentAircraft = settings.value("recent-aircraft").toStringList();
721
722     if (!m_recentAircraft.empty()) {
723         m_selectedAircraft = m_recentAircraft.front();
724     } else {
725         // select the default C172p
726     }
727
728     updateSelectedAircraft();
729
730     // ICAO identifiers
731     m_recentAirports = settings.value("recent-airports").toStringList();
732     if (!m_recentAirports.empty()) {
733         setAirport(FGAirport::findByIdent(m_recentAirports.front().toStdString()));
734     }
735     updateAirportDescription();
736
737     // rating filters
738     m_ui->ratingsFilterCheck->setChecked(settings.value("ratings-filter", true).toBool());
739     int index = 0;
740     Q_FOREACH(QVariant v, settings.value("min-ratings").toList()) {
741         m_ratingFilters[index++] = v.toInt();
742     }
743
744     m_aircraftProxy->setRatingFilterEnabled(m_ui->ratingsFilterCheck->isChecked());
745     m_aircraftProxy->setRatings(m_ratingFilters);
746
747     QStringList sceneryPaths = settings.value("scenery-paths").toStringList();
748     m_ui->sceneryPathsList->addItems(sceneryPaths);
749 }
750
751 void QtLauncher::saveSettings()
752 {
753     QSettings settings;
754     settings.setValue("enable-rembrandt", m_ui->rembrandtCheckbox->isChecked());
755     settings.setValue("enable-terrasync", m_ui->terrasyncCheck->isChecked());
756     settings.setValue("enable-msaa", m_ui->msaaCheckbox->isChecked());
757     settings.setValue("start-fullscreen", m_ui->fullScreenCheckbox->isChecked());
758     settings.setValue("enable-realwx", m_ui->fetchRealWxrCheckbox->isChecked());
759     settings.setValue("start-paused", m_ui->startPausedCheck->isChecked());
760     settings.setValue("ratings-filter", m_ui->ratingsFilterCheck->isChecked());
761     settings.setValue("recent-aircraft", m_recentAircraft);
762     settings.setValue("recent-airports", m_recentAirports);
763     settings.setValue("timeofday", m_ui->timeOfDayCombo->currentIndex());
764     settings.setValue("season", m_ui->seasonCombo->currentIndex());
765
766     QStringList paths;
767     for (int i=0; i<m_ui->sceneryPathsList->count(); ++i) {
768         paths.append(m_ui->sceneryPathsList->item(i)->text());
769     }
770
771     settings.setValue("scenery-paths", paths);
772 }
773
774 void QtLauncher::setEnableDisableOptionFromCheckbox(QCheckBox* cbox, QString name) const
775 {
776     flightgear::Options* opt = flightgear::Options::sharedInstance();
777     std::string stdName(name.toStdString());
778     if (cbox->isChecked()) {
779         opt->addOption("enable-" + stdName, "");
780     } else {
781         opt->addOption("disable-" + stdName, "");
782     }
783 }
784
785 void QtLauncher::onRun()
786 {
787     accept();
788
789     flightgear::Options* opt = flightgear::Options::sharedInstance();
790     setEnableDisableOptionFromCheckbox(m_ui->terrasyncCheck, "terrasync");
791     setEnableDisableOptionFromCheckbox(m_ui->fetchRealWxrCheckbox, "real-weather-fetch");
792     setEnableDisableOptionFromCheckbox(m_ui->rembrandtCheckbox, "rembrandt");
793     setEnableDisableOptionFromCheckbox(m_ui->fullScreenCheckbox, "fullscreen");
794     setEnableDisableOptionFromCheckbox(m_ui->startPausedCheck, "freeze");
795
796     // MSAA is more complex
797     if (!m_ui->rembrandtCheckbox->isChecked()) {
798         if (m_ui->msaaCheckbox->isChecked()) {
799             globals->get_props()->setIntValue("/sim/rendering/multi-sample-buffers", 1);
800             globals->get_props()->setIntValue("/sim/rendering/multi-samples", 4);
801         } else {
802             globals->get_props()->setIntValue("/sim/rendering/multi-sample-buffers", 0);
803         }
804     }
805
806     // aircraft
807     if (!m_selectedAircraft.isEmpty()) {
808         QFileInfo setFileInfo(m_selectedAircraft);
809         opt->addOption("aircraft-dir", setFileInfo.dir().absolutePath().toStdString());
810         QString setFile = setFileInfo.fileName();
811         Q_ASSERT(setFile.endsWith("-set.xml"));
812         setFile.truncate(setFile.count() - 8); // drop the '-set.xml' portion
813         opt->addOption("aircraft", setFile.toStdString());
814
815       // manage aircraft history
816         if (m_recentAircraft.contains(m_selectedAircraft))
817           m_recentAircraft.removeOne(m_selectedAircraft);
818         m_recentAircraft.prepend(m_selectedAircraft);
819         if (m_recentAircraft.size() > MAX_RECENT_AIRCRAFT)
820           m_recentAircraft.pop_back();
821     }
822
823     // airport / location
824     if (m_selectedAirport) {
825         opt->addOption("airport", m_selectedAirport->ident());
826     }
827
828     if (m_ui->runwayRadio->isChecked()) {
829         int index = m_ui->runwayCombo->currentData().toInt();
830         if (index >= 0) {
831             // explicit runway choice
832             opt->addOption("runway", m_selectedAirport->getRunwayByIndex(index)->ident());
833         }
834
835         if (m_ui->onFinalCheckbox->isChecked()) {
836             opt->addOption("glideslope", "3.0");
837             opt->addOption("offset-distance", "10.0"); // in nautical miles
838         }
839     } else if (m_ui->parkingRadio->isChecked()) {
840         // parking selection
841         opt->addOption("parkpos", m_ui->parkingCombo->currentText().toStdString());
842     }
843
844     // time of day
845     if (m_ui->timeOfDayCombo->currentIndex() != 0) {
846         QString dayval = m_ui->timeOfDayCombo->currentText().toLower();
847         opt->addOption("timeofday", dayval.toStdString());
848     }
849
850     if (m_ui->seasonCombo->currentIndex() != 0) {
851         QString dayval = m_ui->timeOfDayCombo->currentText().toLower();
852         opt->addOption("season", dayval.toStdString());
853     }
854
855     // scenery paths
856     for (int i=0; i<m_ui->sceneryPathsList->count(); ++i) {
857         QString path = m_ui->sceneryPathsList->item(i)->text();
858         opt->addOption("fg-scenery", path.toStdString());
859     }
860
861     saveSettings();
862 }
863
864 void QtLauncher::onQuit()
865 {
866     reject();
867 }
868
869 void QtLauncher::onSearchAirports()
870 {
871     QString search = m_ui->airportEdit->text();
872     m_airportsModel->setSearch(search);
873
874     if (m_airportsModel->isSearchActive()) {
875         m_ui->searchStatusText->setText(QString("Searching for '%1'").arg(search));
876         m_ui->locationStack->setCurrentIndex(2);
877     } else if (m_airportsModel->rowCount(QModelIndex()) == 1) {
878         QString ident = m_airportsModel->firstIdent();
879         setAirport(FGAirport::findByIdent(ident.toStdString()));
880         m_ui->locationStack->setCurrentIndex(0);
881     }
882 }
883
884 void QtLauncher::onAirportSearchComplete()
885 {
886     int numResults = m_airportsModel->rowCount(QModelIndex());
887     if (numResults == 0) {
888         m_ui->searchStatusText->setText(QString("No matching airports for '%1'").arg(m_ui->airportEdit->text()));
889     } else if (numResults == 1) {
890         QString ident = m_airportsModel->firstIdent();
891         setAirport(FGAirport::findByIdent(ident.toStdString()));
892         m_ui->locationStack->setCurrentIndex(0);
893     } else {
894         m_ui->locationStack->setCurrentIndex(1);
895     }
896 }
897
898 void QtLauncher::onAirportChanged()
899 {
900     m_ui->runwayCombo->setEnabled(m_selectedAirport);
901     m_ui->parkingCombo->setEnabled(m_selectedAirport);
902     m_ui->airportDiagram->setAirport(m_selectedAirport);
903
904     m_ui->runwayRadio->setChecked(true); // default back to runway mode
905     // unelss multiplayer is enabled ?
906
907     if (!m_selectedAirport) {
908         m_ui->airportDescription->setText(QString());
909         m_ui->airportDiagram->setEnabled(false);
910         return;
911     }
912
913     m_ui->airportDiagram->setEnabled(true);
914
915     m_ui->runwayCombo->clear();
916     m_ui->runwayCombo->addItem("Automatic", -1);
917     for (unsigned int r=0; r<m_selectedAirport->numRunways(); ++r) {
918         FGRunwayRef rwy = m_selectedAirport->getRunwayByIndex(r);
919         // add runway with index as data role
920         m_ui->runwayCombo->addItem(QString::fromStdString(rwy->ident()), r);
921
922         m_ui->airportDiagram->addRunway(rwy);
923     }
924
925     m_ui->parkingCombo->clear();
926     FGAirportDynamics* dynamics = m_selectedAirport->getDynamics();
927     PositionedIDVec parkings = NavDataCache::instance()->airportItemsOfType(
928                                                                             m_selectedAirport->guid(),
929                                                                             FGPositioned::PARKING);
930     if (parkings.empty()) {
931         m_ui->parkingCombo->setEnabled(false);
932         m_ui->parkingRadio->setEnabled(false);
933     } else {
934         m_ui->parkingCombo->setEnabled(true);
935         m_ui->parkingRadio->setEnabled(true);
936         Q_FOREACH(PositionedID parking, parkings) {
937             FGParking* park = dynamics->getParking(parking);
938             m_ui->parkingCombo->addItem(QString::fromStdString(park->getName()),
939                                         static_cast<qlonglong>(parking));
940
941             m_ui->airportDiagram->addParking(park);
942         }
943     }
944 }
945
946 void QtLauncher::updateAirportDescription()
947 {
948     if (!m_selectedAirport) {
949         m_ui->airportDescription->setText(QString("No airport selected"));
950         return;
951     }
952
953     QString ident = QString::fromStdString(m_selectedAirport->ident()),
954         name = QString::fromStdString(m_selectedAirport->name());
955     QString locationOnAirport;
956     if (m_ui->runwayRadio->isChecked()) {
957         bool onFinal = m_ui->onFinalCheckbox->isChecked();
958         QString runwayName = (m_ui->runwayCombo->currentIndex() == 0) ?
959             "active runway" :
960             QString("runway %1").arg(m_ui->runwayCombo->currentText());
961
962         if (onFinal) {
963             locationOnAirport = QString("on 10-mile final to %1").arg(runwayName);
964         } else {
965             locationOnAirport = QString("on %1").arg(runwayName);
966         }
967     } else if (m_ui->parkingRadio->isChecked()) {
968         locationOnAirport =  QString("at parking position %1").arg(m_ui->parkingCombo->currentText());
969     }
970
971     m_ui->airportDescription->setText(QString("%2 (%1): %3").arg(ident).arg(name).arg(locationOnAirport));
972 }
973
974 void QtLauncher::onAirportChoiceSelected(const QModelIndex& index)
975 {
976     m_ui->locationStack->setCurrentIndex(0);
977     setAirport(FGPositioned::loadById<FGAirport>(index.data(Qt::UserRole).toULongLong()));
978 }
979
980 void QtLauncher::onAircraftSelected(const QModelIndex& index)
981 {
982     m_selectedAircraft = index.data(AircraftPathRole).toString();
983     updateSelectedAircraft();
984 }
985
986 void QtLauncher::updateSelectedAircraft()
987 {
988     try {
989         QFileInfo info(m_selectedAircraft);
990         AircraftItem item(info.dir(), m_selectedAircraft);
991         m_ui->thumbnail->setPixmap(item.thumbnail);
992         m_ui->aircraftDescription->setText(item.description);
993     } catch (sg_exception& e) {
994         m_ui->thumbnail->setPixmap(QPixmap());
995         m_ui->aircraftDescription->setText("");
996     }
997 }
998
999 void QtLauncher::onPopupAirportHistory()
1000 {
1001     if (m_recentAirports.isEmpty()) {
1002         return;
1003     }
1004
1005     QMenu m;
1006     Q_FOREACH(QString aptCode, m_recentAirports) {
1007         FGAirportRef apt = FGAirport::findByIdent(aptCode.toStdString());
1008         QString name = QString::fromStdString(apt->name());
1009         QAction* act = m.addAction(QString("%1 - %2").arg(aptCode).arg(name));
1010         act->setData(aptCode);
1011     }
1012
1013     QPoint popupPos = m_ui->airportHistory->mapToGlobal(m_ui->airportHistory->rect().bottomLeft());
1014     QAction* triggered = m.exec(popupPos);
1015     if (triggered) {
1016         FGAirportRef apt = FGAirport::findByIdent(triggered->data().toString().toStdString());
1017         setAirport(apt);
1018         m_ui->airportEdit->clear();
1019         m_ui->locationStack->setCurrentIndex(0);
1020     }
1021 }
1022
1023 QModelIndex QtLauncher::proxyIndexForAircraftPath(QString path) const
1024 {
1025   return m_aircraftProxy->mapFromSource(sourceIndexForAircraftPath(path));
1026 }
1027
1028 QModelIndex QtLauncher::sourceIndexForAircraftPath(QString path) const
1029 {
1030     AircraftItemModel* sourceModel = qobject_cast<AircraftItemModel*>(m_aircraftProxy->sourceModel());
1031     Q_ASSERT(sourceModel);
1032     return sourceModel->indexOfAircraftPath(path);
1033 }
1034
1035 void QtLauncher::onPopupAircraftHistory()
1036 {
1037     if (m_recentAircraft.isEmpty()) {
1038         return;
1039     }
1040
1041     QMenu m;
1042     Q_FOREACH(QString path, m_recentAircraft) {
1043         QModelIndex index = sourceIndexForAircraftPath(path);
1044         if (!index.isValid()) {
1045             // not scanned yet
1046             continue;
1047         }
1048         QAction* act = m.addAction(index.data(Qt::DisplayRole).toString());
1049         act->setData(path);
1050     }
1051
1052     QPoint popupPos = m_ui->aircraftHistory->mapToGlobal(m_ui->aircraftHistory->rect().bottomLeft());
1053     QAction* triggered = m.exec(popupPos);
1054     if (triggered) {
1055         m_selectedAircraft = triggered->data().toString();
1056         QModelIndex index = proxyIndexForAircraftPath(m_selectedAircraft);
1057         m_ui->aircraftList->selectionModel()->setCurrentIndex(index,
1058                                                               QItemSelectionModel::ClearAndSelect);
1059         m_ui->aircraftFilter->clear();
1060         updateSelectedAircraft();
1061     }
1062 }
1063
1064 void QtLauncher::setAirport(FGAirportRef ref)
1065 {
1066     if (m_selectedAirport == ref)
1067         return;
1068
1069     m_selectedAirport = ref;
1070     onAirportChanged();
1071
1072     if (ref.valid()) {
1073         // maintain the recent airport list
1074         QString icao = QString::fromStdString(ref->ident());
1075         if (m_recentAirports.contains(icao)) {
1076             // move to front
1077             m_recentAirports.removeOne(icao);
1078             m_recentAirports.push_front(icao);
1079         } else {
1080             // insert and trim list if necessary
1081             m_recentAirports.push_front(icao);
1082             if (m_recentAirports.size() > MAX_RECENT_AIRPORTS) {
1083                 m_recentAirports.pop_back();
1084             }
1085         }
1086     }
1087
1088     updateAirportDescription();
1089 }
1090
1091 void QtLauncher::onOpenCustomAircraftDir()
1092 {
1093     QFileInfo info(m_customAircraftDir);
1094     if (!info.exists()) {
1095         int result = QMessageBox::question(this, "Create folder?",
1096                                            "The custom aircraft folder does not exist, create it now?",
1097                                            QMessageBox::Yes | QMessageBox::No,
1098                                            QMessageBox::Yes);
1099         if (result == QMessageBox::No) {
1100             return;
1101         }
1102
1103         QDir d(m_customAircraftDir);
1104         d.mkpath(m_customAircraftDir);
1105     }
1106
1107   QUrl u = QUrl::fromLocalFile(m_customAircraftDir);
1108   QDesktopServices::openUrl(u);
1109 }
1110
1111 void QtLauncher::onEditRatingsFilter()
1112 {
1113     EditRatingsFilterDialog dialog(this);
1114     dialog.setRatings(m_ratingFilters);
1115
1116     dialog.exec();
1117     if (dialog.result() == QDialog::Accepted) {
1118         QVariantList vl;
1119         for (int i=0; i<4; ++i) {
1120             m_ratingFilters[i] = dialog.getRating(i);
1121             vl.append(m_ratingFilters[i]);
1122         }
1123         m_aircraftProxy->setRatings(m_ratingFilters);
1124
1125         QSettings settings;
1126         settings.setValue("min-ratings", vl);
1127     }
1128 }
1129
1130 void QtLauncher::updateSettingsSummary()
1131 {
1132     QStringList summary;
1133     if (m_ui->timeOfDayCombo->currentIndex() > 0) {
1134         summary.append(QString(m_ui->timeOfDayCombo->currentText().toLower()));
1135     }
1136
1137     if (m_ui->seasonCombo->currentIndex() > 0) {
1138         summary.append(QString(m_ui->seasonCombo->currentText().toLower()));
1139     }
1140
1141     if (m_ui->rembrandtCheckbox->isChecked()) {
1142         summary.append("Rembrandt enabled");
1143     } else if (m_ui->msaaCheckbox->isChecked()) {
1144         summary.append("anti-aliasing");
1145     }
1146
1147     if (m_ui->fetchRealWxrCheckbox->isChecked()) {
1148         summary.append("live weather");
1149     }
1150
1151     if (m_ui->terrasyncCheck->isChecked()) {
1152         summary.append("automatic scenery downloads");
1153     }
1154
1155     if (m_ui->startPausedCheck->isChecked()) {
1156         summary.append("paused");
1157     }
1158
1159     QString s = summary.join(", ");
1160     s[0] = s[0].toUpper();
1161     m_ui->settingsDescription->setText(s);
1162 }
1163
1164 void QtLauncher::onAddSceneryPath()
1165 {
1166     QString path = QFileDialog::getExistingDirectory(this, tr("Choose scenery folder"));
1167     if (!path.isEmpty()) {
1168         m_ui->sceneryPathsList->addItem(path);
1169         saveSettings();
1170     }
1171 }
1172
1173 void QtLauncher::onRemoveSceneryPath()
1174 {
1175     if (m_ui->sceneryPathsList->currentItem()) {
1176         delete m_ui->sceneryPathsList->currentItem();
1177         saveSettings();
1178     }
1179 }
1180
1181 void QtLauncher::onRembrandtToggled(bool b)
1182 {
1183     // Rembrandt and multi-sample are exclusive
1184     m_ui->msaaCheckbox->setEnabled(!b);
1185 }
1186
1187 #include "QtLauncher.moc"
1188