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