1 #include "QtLauncher.hxx"
4 #include <QProgressDialog>
5 #include <QCoreApplication>
6 #include <QAbstractListModel>
15 #include <QMutexLocker>
19 #include <QSortFilterProxyModel>
21 #include <QDesktopServices>
24 #include <QStyledItemDelegate>
25 #include <QLinearGradient>
26 #include <QFileDialog>
27 #include <QMessageBox>
28 #include <QDataStream>
32 #include <simgear/timing/timestamp.hxx>
33 #include <simgear/props/props_io.hxx>
34 #include <simgear/structure/exception.hxx>
35 #include <simgear/misc/sg_path.hxx>
37 #include "ui_Launcher.h"
38 #include "EditRatingsFilterDialog.hxx"
40 #include <Main/globals.hxx>
41 #include <Navaids/NavDataCache.hxx>
42 #include <Airports/airport.hxx>
43 #include <Airports/dynamics.hxx> // for parking
44 #include <Main/options.hxx>
46 using namespace flightgear;
48 const int MAX_RECENT_AIRPORTS = 32;
49 const int MAX_RECENT_AIRCRAFT = 20;
51 namespace { // anonymous namespace
53 const int AircraftPathRole = Qt::UserRole + 1;
54 const int AircraftAuthorsRole = Qt::UserRole + 2;
55 const int AircraftVariantRole = Qt::UserRole + 3;
56 const int AircraftVariantCountRole = Qt::UserRole + 4;
57 const int AircraftRatingRole = Qt::UserRole + 100;
58 const int AircraftVariantDescriptionRole = Qt::UserRole + 200;
62 NavDataCache* cache = NavDataCache::instance();
63 if (cache->isRebuildRequired()) {
64 QProgressDialog rebuildProgress("Initialising navigation data, this may take several minutes",
65 QString() /* cancel text */,
67 rebuildProgress.setWindowModality(Qt::WindowModal);
68 rebuildProgress.show();
70 while (!cache->rebuild()) {
71 // sleep to give the rebuild thread more time
72 SGTimeStamp::sleepForMSec(50);
73 rebuildProgress.setValue(0);
74 QCoreApplication::processEvents();
83 // oh for C++11 initialisers
84 for (int i=0; i<4; ++i) ratings[i] = 0;
87 AircraftItem(QDir dir, QString filePath)
89 for (int i=0; i<4; ++i) ratings[i] = 0;
92 readProperties(filePath.toStdString(), &root);
94 if (!root.hasChild("sim")) {
95 throw sg_io_exception(std::string("Malformed -set.xml file"), filePath.toStdString());
98 SGPropertyNode_ptr sim = root.getNode("sim");
101 pathModTime = QFileInfo(path).lastModified();
103 description = sim->getStringValue("description");
104 authors = sim->getStringValue("author");
106 if (sim->hasChild("rating")) {
107 parseRatings(sim->getNode("rating"));
110 if (sim->hasChild("variant-of")) {
111 variantOf = sim->getStringValue("variant-of");
115 // the file-name without -set.xml suffix
116 QString baseName() const
118 QString fn = QFileInfo(path).fileName();
119 fn.truncate(fn.count() - 8);
123 void fromDataStream(QDataStream& ds)
125 ds >> path >> description >> authors >> variantOf;
126 for (int i=0; i<4; ++i) ds >> ratings[i];
130 void toDataStream(QDataStream& ds) const
132 ds << path << description << authors << variantOf;
133 for (int i=0; i<4; ++i) ds << ratings[i];
137 QPixmap thumbnail() const
139 if (m_thumbnail.isNull()) {
140 QFileInfo info(path);
141 QDir dir = info.dir();
142 if (dir.exists("thumbnail.jpg")) {
143 m_thumbnail.load(dir.filePath("thumbnail.jpg"));
144 // resize to the standard size
145 if (m_thumbnail.height() > 128) {
146 m_thumbnail = m_thumbnail.scaledToHeight(128);
159 QDateTime pathModTime;
161 QList<AircraftItem*> variants;
163 mutable QPixmap m_thumbnail;
166 void parseRatings(SGPropertyNode_ptr ratingsNode)
168 ratings[0] = ratingsNode->getIntValue("FDM");
169 ratings[1] = ratingsNode->getIntValue("systems");
170 ratings[2] = ratingsNode->getIntValue("cockpit");
171 ratings[3] = ratingsNode->getIntValue("model");
175 static int CACHE_VERSION = 2;
177 class AircraftScanThread : public QThread
181 AircraftScanThread(QStringList dirsToScan) :
187 ~AircraftScanThread()
191 /** thread-safe access to items already scanned */
192 QList<AircraftItem*> items()
194 QList<AircraftItem*> result;
195 QMutexLocker g(&m_lock);
196 result.swap(m_items);
213 Q_FOREACH(QString d, m_dirs) {
214 scanAircraftDir(QDir(d));
227 QByteArray cacheData = settings.value("aircraft-cache").toByteArray();
228 if (!cacheData.isEmpty()) {
229 QDataStream ds(cacheData);
230 quint32 count, cacheVersion;
231 ds >> cacheVersion >> count;
233 if (cacheVersion != CACHE_VERSION) {
234 return; // mis-matched cache, version, drop
237 for (int i=0; i<count; ++i) {
238 AircraftItem* item = new AircraftItem;
239 item->fromDataStream(ds);
241 QFileInfo finfo(item->path);
242 if (!finfo.exists() || (finfo.lastModified() != item->pathModTime)) {
245 // corresponding -set.xml file still exists and is
247 m_cachedItems[item->path] = item;
249 } // of cached item iteration
256 QByteArray cacheData;
258 QDataStream ds(&cacheData, QIODevice::WriteOnly);
259 quint32 count = m_nextCache.count();
260 ds << CACHE_VERSION << count;
262 Q_FOREACH(AircraftItem* item, m_nextCache.values()) {
263 item->toDataStream(ds);
267 settings.setValue("aircraft-cache", cacheData);
270 void scanAircraftDir(QDir path)
276 filters << "*-set.xml";
277 Q_FOREACH(QFileInfo child, path.entryInfoList(QDir::Dirs | QDir::NoDotAndDotDot)) {
278 QDir childDir(child.absoluteFilePath());
279 QMap<QString, AircraftItem*> baseAircraft;
280 QList<AircraftItem*> variants;
282 Q_FOREACH(QFileInfo xmlChild, childDir.entryInfoList(filters, QDir::Files)) {
284 QString absolutePath = xmlChild.absoluteFilePath();
285 AircraftItem* item = NULL;
287 if (m_cachedItems.contains(absolutePath)) {
288 item = m_cachedItems.value(absolutePath);
290 item = new AircraftItem(childDir, absolutePath);
293 m_nextCache[absolutePath] = item;
295 if (item->variantOf.isNull()) {
296 baseAircraft.insert(item->baseName(), item);
298 variants.append(item);
300 } catch (sg_exception& e) {
307 } // of set.xml iteration
309 // bind variants to their principals
310 Q_FOREACH(AircraftItem* item, variants) {
311 if (!baseAircraft.contains(item->variantOf)) {
312 qWarning() << "can't find principal aircraft " << item->variantOf << " for variant:" << item->path;
317 baseAircraft.value(item->variantOf)->variants.append(item);
320 // lock mutex while we modify the items array
322 QMutexLocker g(&m_lock);
323 m_items.append(baseAircraft.values());
327 } // of subdir iteration
329 qDebug() << "scan of" << path << "took" << t.elapsed();
334 QList<AircraftItem*> m_items;
336 QMap<QString, AircraftItem* > m_cachedItems;
337 QMap<QString, AircraftItem* > m_nextCache;
342 class AircraftItemModel : public QAbstractListModel
346 AircraftItemModel(QObject* pr) :
347 QAbstractListModel(pr)
350 Q_FOREACH(std::string ap, globals->get_aircraft_paths()) {
351 dirs << QString::fromStdString(ap);
354 SGPath rootAircraft(globals->get_fg_root());
355 rootAircraft.append("Aircraft");
356 dirs << QString::fromStdString(rootAircraft.str());
358 m_scanThread = new AircraftScanThread(dirs);
359 connect(m_scanThread, &AircraftScanThread::finished, this,
360 &AircraftItemModel::onScanFinished);
361 connect(m_scanThread, &AircraftScanThread::addedItems,
362 this, &AircraftItemModel::onScanResults);
363 m_scanThread->start();
369 m_scanThread->setDone();
370 m_scanThread->wait(1000);
375 virtual int rowCount(const QModelIndex& parent) const
377 return m_items.size();
380 virtual QVariant data(const QModelIndex& index, int role) const
382 if (role == AircraftVariantRole) {
383 return m_activeVariant.at(index.row());
386 const AircraftItem* item(m_items.at(index.row()));
388 if (role == AircraftVariantCountRole) {
389 return item->variants.count();
392 if (role >= AircraftVariantDescriptionRole) {
393 int variantIndex = role - AircraftVariantDescriptionRole;
394 return item->variants.at(variantIndex)->description;
397 quint32 variantIndex = m_activeVariant.at(index.row());
399 if (variantIndex <= item->variants.count()) {
400 // show the selected variant
401 item = item->variants.at(variantIndex - 1);
405 if (role == Qt::DisplayRole) {
406 return item->description;
407 } else if (role == Qt::DecorationRole) {
408 return item->thumbnail();
409 } else if (role == AircraftPathRole) {
411 } else if (role == AircraftAuthorsRole) {
412 return item->authors;
413 } else if ((role >= AircraftRatingRole) && (role < AircraftVariantDescriptionRole)) {
414 return item->ratings[role - AircraftRatingRole];
415 } else if (role == Qt::ToolTipRole) {
422 virtual bool setData(const QModelIndex &index, const QVariant &value, int role)
424 if (role == AircraftVariantRole) {
425 m_activeVariant[index.row()] = value.toInt();
426 emit dataChanged(index, index);
433 QModelIndex indexOfAircraftPath(QString path) const
435 for (int row=0; row <m_items.size(); ++row) {
436 const AircraftItem* item(m_items.at(row));
437 if (item->path == path) {
442 return QModelIndex();
448 QList<AircraftItem*> newItems = m_scanThread->items();
449 if (newItems.isEmpty())
452 int firstRow = m_items.count();
453 int lastRow = firstRow + newItems.count() - 1;
454 beginInsertRows(QModelIndex(), firstRow, lastRow);
455 m_items.append(newItems);
457 // default variants in all cases
458 for (int i=0; i< newItems.count(); ++i) {
459 m_activeVariant.append(0);
464 void onScanFinished()
471 AircraftScanThread* m_scanThread;
472 QList<AircraftItem*> m_items;
473 QList<quint32> m_activeVariant;
476 class AircraftItemDelegate : public QStyledItemDelegate
480 static const int MARGIN = 4;
481 static const int ARROW_SIZE = 20;
483 AircraftItemDelegate(QListView* view) :
486 view->viewport()->installEventFilter(this);
488 m_leftArrowIcon.load(":/left-arrow-icon");
489 m_rightArrowIcon.load(":/right-arrow-icon");
492 virtual void paint(QPainter * painter, const QStyleOptionViewItem & option, const QModelIndex & index) const
494 // selection feedback rendering
495 if (option.state & QStyle::State_Selected) {
496 QLinearGradient grad(option.rect.topLeft(), option.rect.bottomLeft());
497 grad.setColorAt(0.0, QColor(152, 163, 180));
498 grad.setColorAt(1.0, QColor(90, 107, 131));
500 QBrush backgroundBrush(grad);
501 painter->fillRect(option.rect, backgroundBrush);
503 painter->setPen(QColor(90, 107, 131));
504 painter->drawLine(option.rect.topLeft(), option.rect.topRight());
508 QRect contentRect = option.rect.adjusted(MARGIN, MARGIN, -MARGIN, -MARGIN);
510 QPixmap thumbnail = index.data(Qt::DecorationRole).value<QPixmap>();
511 painter->drawPixmap(contentRect.topLeft(), thumbnail);
514 painter->setPen(QColor(0x7f, 0x7f, 0x7f));
515 painter->setBrush(Qt::NoBrush);
516 painter->drawRect(contentRect.left(), contentRect.top(), thumbnail.width(), thumbnail.height());
518 int variantCount = index.data(AircraftVariantCountRole).toInt();
519 int currentVariant =index.data(AircraftVariantRole).toInt();
520 QString description = index.data(Qt::DisplayRole).toString();
521 contentRect.setLeft(contentRect.left() + MARGIN + thumbnail.width());
523 painter->setPen(Qt::black);
528 QRect descriptionRect = contentRect.adjusted(ARROW_SIZE, 0, -ARROW_SIZE, 0),
531 if (variantCount > 0) {
532 bool canLeft = (currentVariant > 0);
533 bool canRight = (currentVariant < variantCount );
535 QRect leftArrowRect = leftCycleArrowRect(option.rect, index);
537 painter->drawPixmap(leftArrowRect.topLeft() + QPoint(2, 2), m_leftArrowIcon);
540 QRect rightArrowRect = rightCycleArrowRect(option.rect, index);
542 painter->drawPixmap(rightArrowRect.topLeft() + QPoint(2, 2), m_rightArrowIcon);
546 painter->drawText(descriptionRect, Qt::TextWordWrap, description, &actualBounds);
548 QString authors = index.data(AircraftAuthorsRole).toString();
553 QRect authorsRect = descriptionRect;
554 authorsRect.moveTop(actualBounds.bottom() + MARGIN);
555 painter->drawText(authorsRect, Qt::TextWordWrap,
556 QString("by: %1").arg(authors),
559 QRect r = contentRect;
560 r.setWidth(contentRect.width() / 2);
561 r.moveTop(actualBounds.bottom() + MARGIN);
564 drawRating(painter, "Flight model:", r, index.data(AircraftRatingRole).toInt());
565 r.moveTop(r.bottom());
566 drawRating(painter, "Systems:", r, index.data(AircraftRatingRole + 1).toInt());
568 r.moveTop(actualBounds.bottom() + MARGIN);
569 r.moveLeft(r.right());
570 drawRating(painter, "Cockpit:", r, index.data(AircraftRatingRole + 2).toInt());
571 r.moveTop(r.bottom());
572 drawRating(painter, "Exterior model:", r, index.data(AircraftRatingRole + 3).toInt());
575 virtual QSize sizeHint(const QStyleOptionViewItem & option, const QModelIndex & index) const
577 return QSize(500, 128 + (MARGIN * 2));
580 virtual bool eventFilter( QObject*, QEvent* event )
582 if ( event->type() == QEvent::MouseButtonPress || event->type() == QEvent::MouseButtonRelease )
584 QMouseEvent* me = static_cast< QMouseEvent* >( event );
585 QModelIndex index = m_view->indexAt( me->pos() );
586 int variantCount = index.data(AircraftVariantCountRole).toInt();
587 int variantIndex = index.data(AircraftVariantRole).toInt();
589 if ( (event->type() == QEvent::MouseButtonRelease) && (variantCount > 0) )
591 QRect vr = m_view->visualRect(index);
592 QRect leftCycleRect = leftCycleArrowRect(vr, index),
593 rightCycleRect = rightCycleArrowRect(vr, index);
595 if ((variantIndex > 0) && leftCycleRect.contains(me->pos())) {
596 m_view->model()->setData(index, variantIndex - 1, AircraftVariantRole);
597 emit variantChanged(index);
599 } else if ((variantIndex < variantCount) && rightCycleRect.contains(me->pos())) {
600 m_view->model()->setData(index, variantIndex + 1, AircraftVariantRole);
601 emit variantChanged(index);
605 } // of mouse button press or release
611 void variantChanged(const QModelIndex& index);
614 QRect leftCycleArrowRect(const QRect& visualRect, const QModelIndex& index) const
616 QRect contentRect = visualRect.adjusted(MARGIN, MARGIN, -MARGIN, -MARGIN);
617 QPixmap thumbnail = index.data(Qt::DecorationRole).value<QPixmap>();
618 contentRect.setLeft(contentRect.left() + MARGIN + thumbnail.width());
620 QRect r = contentRect;
621 r.setRight(r.left() + ARROW_SIZE);
622 r.setBottom(r.top() + ARROW_SIZE);
627 QRect rightCycleArrowRect(const QRect& visualRect, const QModelIndex& index) const
629 QRect contentRect = visualRect.adjusted(MARGIN, MARGIN, -MARGIN, -MARGIN);
630 QPixmap thumbnail = index.data(Qt::DecorationRole).value<QPixmap>();
631 contentRect.setLeft(contentRect.left() + MARGIN + thumbnail.width());
633 QRect r = contentRect;
634 r.setLeft(r.right() - ARROW_SIZE);
635 r.setBottom(r.top() + ARROW_SIZE);
640 void drawRating(QPainter* painter, QString label, const QRect& box, int value) const
642 const int DOT_SIZE = 10;
643 const int DOT_MARGIN = 4;
646 dotBox.setLeft(box.right() - (DOT_MARGIN * 6 + DOT_SIZE * 5));
648 painter->setPen(Qt::black);
650 textBox.setRight(dotBox.left() - DOT_MARGIN);
651 painter->drawText(textBox, Qt::AlignVCenter | Qt::AlignRight, label);
653 painter->setPen(Qt::NoPen);
654 QRect dot(dotBox.left() + DOT_MARGIN,
655 dotBox.center().y() - (DOT_SIZE / 2),
658 for (int i=0; i<5; ++i) {
659 painter->setBrush((i < value) ? QColor(0x3f, 0x3f, 0x3f) : QColor(0xaf, 0xaf, 0xaf));
660 painter->drawEllipse(dot);
661 dot.moveLeft(dot.right() + DOT_MARGIN);
666 QPixmap m_leftArrowIcon,
670 class ArgumentsTokenizer
676 explicit Arg(QString k, QString v = QString()) : arg(k), value(v) {}
682 QList<Arg> tokenize(QString in) const
685 const int len = in.count();
691 for (; index < len; ++index) {
693 nc = index < (len - 1) ? in.at(index + 1) : QChar();
697 if (c == QChar('-')) {
698 if (nc == QChar('-')) {
703 // should we pemit single hyphen arguments?
704 // choosing to fail for now
707 } else if (c.isSpace()) {
713 if (c == QChar('=')) {
716 } else if (c.isSpace()) {
718 result.append(Arg(key));
720 // could check for illegal charatcers here
726 if (c == QChar('"')) {
728 } else if (c.isSpace()) {
730 result.append(Arg(key, value));
737 if (c == QChar('\\')) {
738 // check for escaped double-quote inside quoted value
739 if (nc == QChar('"')) {
742 } else if (c == QChar('"')) {
749 } // of character loop
751 // ensure last argument isn't lost
753 result.append(Arg(key));
754 } else if (state == Value) {
755 result.append(Arg(key, value));
770 } // of anonymous namespace
772 class AirportSearchModel : public QAbstractListModel
776 AirportSearchModel() :
777 m_searchActive(false)
781 void setSearch(QString t)
788 std::string term(t.toUpper().toStdString());
789 // try ICAO lookup first
790 FGAirportRef ref = FGAirport::findByIdent(term);
792 m_ids.push_back(ref->guid());
793 m_airports.push_back(ref);
795 m_search.reset(new NavDataCache::ThreadedAirportSearch(term));
796 QTimer::singleShot(100, this, SLOT(onSearchResultsPoll()));
797 m_searchActive = true;
803 bool isSearchActive() const
805 return m_searchActive;
808 virtual int rowCount(const QModelIndex&) const
810 // if empty, return 1 for special 'no matches'?
814 virtual QVariant data(const QModelIndex& index, int role) const
816 if (!index.isValid())
819 FGAirportRef apt = m_airports[index.row()];
821 apt = FGPositioned::loadById<FGAirport>(m_ids[index.row()]);
822 m_airports[index.row()] = apt;
825 if (role == Qt::DisplayRole) {
826 QString name = QString::fromStdString(apt->name());
827 return QString("%1: %2").arg(QString::fromStdString(apt->ident())).arg(name);
830 if (role == Qt::EditRole) {
831 return QString::fromStdString(apt->ident());
834 if (role == Qt::UserRole) {
835 return static_cast<qlonglong>(m_ids[index.row()]);
841 QString firstIdent() const
846 if (!m_airports.front().valid()) {
847 m_airports[0] = FGPositioned::loadById<FGAirport>(m_ids.front());
850 return QString::fromStdString(m_airports.front()->ident());
854 void searchComplete();
857 void onSearchResultsPoll()
859 PositionedIDVec newIds = m_search->results();
861 beginInsertRows(QModelIndex(), m_ids.size(), newIds.size() - 1);
862 for (unsigned int i=m_ids.size(); i < newIds.size(); ++i) {
863 m_ids.push_back(newIds[i]);
864 m_airports.push_back(FGAirportRef()); // null ref
868 if (m_search->isComplete()) {
869 m_searchActive = false;
871 emit searchComplete();
873 QTimer::singleShot(100, this, SLOT(onSearchResultsPoll()));
878 PositionedIDVec m_ids;
879 mutable std::vector<FGAirportRef> m_airports;
881 QScopedPointer<NavDataCache::ThreadedAirportSearch> m_search;
884 class AircraftProxyModel : public QSortFilterProxyModel
888 AircraftProxyModel(QObject* pr) :
889 QSortFilterProxyModel(pr),
890 m_ratingsFilter(true)
892 for (int i=0; i<4; ++i) {
897 void setRatings(int* ratings)
899 ::memcpy(m_ratings, ratings, sizeof(int) * 4);
904 void setRatingFilterEnabled(bool e)
906 if (e == m_ratingsFilter) {
915 bool filterAcceptsRow(int sourceRow, const QModelIndex &sourceParent) const
917 if (!QSortFilterProxyModel::filterAcceptsRow(sourceRow, sourceParent)) {
921 if (m_ratingsFilter) {
922 QModelIndex index = sourceModel()->index(sourceRow, 0, sourceParent);
923 for (int i=0; i<4; ++i) {
924 if (m_ratings[i] > index.data(AircraftRatingRole + i).toInt()) {
934 bool m_ratingsFilter;
938 QtLauncher::QtLauncher() :
942 m_ui.reset(new Ui::Launcher);
945 #if QT_VERSION >= 0x050300
946 // don't require Qt 5.3
947 m_ui->commandLineArgs->setPlaceholderText("--option=value --prop:/sim/name=value");
950 #if QT_VERSION >= 0x050200
951 m_ui->aircraftFilter->setClearButtonEnabled(true);
954 for (int i=0; i<4; ++i) {
955 m_ratingFilters[i] = 3;
958 m_airportsModel = new AirportSearchModel;
959 m_ui->searchList->setModel(m_airportsModel);
960 connect(m_ui->searchList, &QListView::clicked,
961 this, &QtLauncher::onAirportChoiceSelected);
962 connect(m_airportsModel, &AirportSearchModel::searchComplete,
963 this, &QtLauncher::onAirportSearchComplete);
965 SGPath p = SGPath::documents();
966 p.append("FlightGear");
967 p.append("Aircraft");
968 m_customAircraftDir = QString::fromStdString(p.str());
969 m_ui->customAircraftDirLabel->setText(QString("Custom aircraft folder: %1").arg(m_customAircraftDir));
971 globals->append_aircraft_path(m_customAircraftDir.toStdString());
973 // create and configure the proxy model
974 m_aircraftProxy = new AircraftProxyModel(this);
975 m_aircraftProxy->setSourceModel(new AircraftItemModel(this));
977 m_aircraftProxy->setFilterCaseSensitivity(Qt::CaseInsensitive);
978 m_aircraftProxy->setSortCaseSensitivity(Qt::CaseInsensitive);
979 m_aircraftProxy->setSortRole(Qt::DisplayRole);
980 m_aircraftProxy->setDynamicSortFilter(true);
982 m_ui->aircraftList->setModel(m_aircraftProxy);
983 m_ui->aircraftList->setHorizontalScrollBarPolicy(Qt::ScrollBarAlwaysOff);
984 AircraftItemDelegate* delegate = new AircraftItemDelegate(m_ui->aircraftList);
985 m_ui->aircraftList->setItemDelegate(delegate);
986 m_ui->aircraftList->setSelectionMode(QAbstractItemView::SingleSelection);
987 connect(m_ui->aircraftList, &QListView::clicked,
988 this, &QtLauncher::onAircraftSelected);
989 connect(delegate, &AircraftItemDelegate::variantChanged,
990 this, &QtLauncher::onAircraftSelected);
992 connect(m_ui->runwayCombo, SIGNAL(currentIndexChanged(int)),
993 this, SLOT(updateAirportDescription()));
994 connect(m_ui->parkingCombo, SIGNAL(currentIndexChanged(int)),
995 this, SLOT(updateAirportDescription()));
996 connect(m_ui->runwayRadio, SIGNAL(toggled(bool)),
997 this, SLOT(updateAirportDescription()));
998 connect(m_ui->parkingRadio, SIGNAL(toggled(bool)),
999 this, SLOT(updateAirportDescription()));
1000 connect(m_ui->onFinalCheckbox, SIGNAL(toggled(bool)),
1001 this, SLOT(updateAirportDescription()));
1004 connect(m_ui->runButton, SIGNAL(clicked()), this, SLOT(onRun()));
1005 connect(m_ui->quitButton, SIGNAL(clicked()), this, SLOT(onQuit()));
1006 connect(m_ui->airportEdit, SIGNAL(returnPressed()),
1007 this, SLOT(onSearchAirports()));
1009 connect(m_ui->aircraftFilter, &QLineEdit::textChanged,
1010 m_aircraftProxy, &QSortFilterProxyModel::setFilterFixedString);
1012 connect(m_ui->airportHistory, &QPushButton::clicked,
1013 this, &QtLauncher::onPopupAirportHistory);
1014 connect(m_ui->aircraftHistory, &QPushButton::clicked,
1015 this, &QtLauncher::onPopupAircraftHistory);
1019 connect(m_ui->openAircraftDirButton, &QPushButton::clicked,
1020 this, &QtLauncher::onOpenCustomAircraftDir);
1022 QAction* qa = new QAction(this);
1023 qa->setShortcut(QKeySequence("Ctrl+Q"));
1024 connect(qa, &QAction::triggered, this, &QtLauncher::onQuit);
1027 connect(m_ui->editRatingFilter, &QPushButton::clicked,
1028 this, &QtLauncher::onEditRatingsFilter);
1029 connect(m_ui->ratingsFilterCheck, &QAbstractButton::toggled,
1030 m_aircraftProxy, &AircraftProxyModel::setRatingFilterEnabled);
1032 QIcon historyIcon(":/history-icon");
1033 m_ui->aircraftHistory->setIcon(historyIcon);
1034 m_ui->airportHistory->setIcon(historyIcon);
1036 m_ui->searchIcon->setPixmap(QPixmap(":/search-icon"));
1038 connect(m_ui->timeOfDayCombo, SIGNAL(currentIndexChanged(int)),
1039 this, SLOT(updateSettingsSummary()));
1040 connect(m_ui->seasonCombo, SIGNAL(currentIndexChanged(int)),
1041 this, SLOT(updateSettingsSummary()));
1042 connect(m_ui->fetchRealWxrCheckbox, SIGNAL(toggled(bool)),
1043 this, SLOT(updateSettingsSummary()));
1044 connect(m_ui->rembrandtCheckbox, SIGNAL(toggled(bool)),
1045 this, SLOT(updateSettingsSummary()));
1046 connect(m_ui->terrasyncCheck, SIGNAL(toggled(bool)),
1047 this, SLOT(updateSettingsSummary()));
1048 connect(m_ui->startPausedCheck, SIGNAL(toggled(bool)),
1049 this, SLOT(updateSettingsSummary()));
1050 connect(m_ui->msaaCheckbox, SIGNAL(toggled(bool)),
1051 this, SLOT(updateSettingsSummary()));
1053 connect(m_ui->rembrandtCheckbox, SIGNAL(toggled(bool)),
1054 this, SLOT(onRembrandtToggled(bool)));
1056 updateSettingsSummary();
1058 connect(m_ui->addSceneryPath, &QToolButton::clicked,
1059 this, &QtLauncher::onAddSceneryPath);
1060 connect(m_ui->removeSceneryPath, &QToolButton::clicked,
1061 this, &QtLauncher::onRemoveSceneryPath);
1064 QtLauncher::~QtLauncher()
1069 bool QtLauncher::runLauncherDialog()
1071 Q_INIT_RESOURCE(resources);
1073 // startup the nav-cache now. This pre-empts normal startup of
1074 // the cache, but no harm done. (Providing scenery paths are consistent)
1078 // setup scenery paths now, especially TerraSync path for airport
1079 // parking locations (after they're downloaded)
1083 if (dlg.result() != QDialog::Accepted) {
1090 void QtLauncher::restoreSettings()
1093 m_ui->rembrandtCheckbox->setChecked(settings.value("enable-rembrandt", false).toBool());
1094 m_ui->terrasyncCheck->setChecked(settings.value("enable-terrasync", true).toBool());
1095 m_ui->fullScreenCheckbox->setChecked(settings.value("start-fullscreen", false).toBool());
1096 m_ui->msaaCheckbox->setChecked(settings.value("enable-msaa", false).toBool());
1097 m_ui->fetchRealWxrCheckbox->setChecked(settings.value("enable-realwx", true).toBool());
1098 m_ui->startPausedCheck->setChecked(settings.value("start-paused", false).toBool());
1099 m_ui->timeOfDayCombo->setCurrentIndex(settings.value("timeofday", 0).toInt());
1100 m_ui->seasonCombo->setCurrentIndex(settings.value("season", 0).toInt());
1102 // full paths to -set.xml files
1103 m_recentAircraft = settings.value("recent-aircraft").toStringList();
1105 if (!m_recentAircraft.empty()) {
1106 m_selectedAircraft = m_recentAircraft.front();
1108 // select the default C172p
1111 updateSelectedAircraft();
1114 m_recentAirports = settings.value("recent-airports").toStringList();
1115 if (!m_recentAirports.empty()) {
1116 setAirport(FGAirport::findByIdent(m_recentAirports.front().toStdString()));
1118 updateAirportDescription();
1121 m_ui->ratingsFilterCheck->setChecked(settings.value("ratings-filter", true).toBool());
1123 Q_FOREACH(QVariant v, settings.value("min-ratings").toList()) {
1124 m_ratingFilters[index++] = v.toInt();
1127 m_aircraftProxy->setRatingFilterEnabled(m_ui->ratingsFilterCheck->isChecked());
1128 m_aircraftProxy->setRatings(m_ratingFilters);
1130 QStringList sceneryPaths = settings.value("scenery-paths").toStringList();
1131 m_ui->sceneryPathsList->addItems(sceneryPaths);
1133 m_ui->commandLineArgs->setPlainText(settings.value("additional-args").toString());
1136 void QtLauncher::saveSettings()
1139 settings.setValue("enable-rembrandt", m_ui->rembrandtCheckbox->isChecked());
1140 settings.setValue("enable-terrasync", m_ui->terrasyncCheck->isChecked());
1141 settings.setValue("enable-msaa", m_ui->msaaCheckbox->isChecked());
1142 settings.setValue("start-fullscreen", m_ui->fullScreenCheckbox->isChecked());
1143 settings.setValue("enable-realwx", m_ui->fetchRealWxrCheckbox->isChecked());
1144 settings.setValue("start-paused", m_ui->startPausedCheck->isChecked());
1145 settings.setValue("ratings-filter", m_ui->ratingsFilterCheck->isChecked());
1146 settings.setValue("recent-aircraft", m_recentAircraft);
1147 settings.setValue("recent-airports", m_recentAirports);
1148 settings.setValue("timeofday", m_ui->timeOfDayCombo->currentIndex());
1149 settings.setValue("season", m_ui->seasonCombo->currentIndex());
1152 for (int i=0; i<m_ui->sceneryPathsList->count(); ++i) {
1153 paths.append(m_ui->sceneryPathsList->item(i)->text());
1156 settings.setValue("scenery-paths", paths);
1157 settings.setValue("additional-args", m_ui->commandLineArgs->toPlainText());
1160 void QtLauncher::setEnableDisableOptionFromCheckbox(QCheckBox* cbox, QString name) const
1162 flightgear::Options* opt = flightgear::Options::sharedInstance();
1163 std::string stdName(name.toStdString());
1164 if (cbox->isChecked()) {
1165 opt->addOption("enable-" + stdName, "");
1167 opt->addOption("disable-" + stdName, "");
1171 void QtLauncher::onRun()
1175 flightgear::Options* opt = flightgear::Options::sharedInstance();
1176 setEnableDisableOptionFromCheckbox(m_ui->terrasyncCheck, "terrasync");
1177 setEnableDisableOptionFromCheckbox(m_ui->fetchRealWxrCheckbox, "real-weather-fetch");
1178 setEnableDisableOptionFromCheckbox(m_ui->rembrandtCheckbox, "rembrandt");
1179 setEnableDisableOptionFromCheckbox(m_ui->fullScreenCheckbox, "fullscreen");
1180 setEnableDisableOptionFromCheckbox(m_ui->startPausedCheck, "freeze");
1182 // MSAA is more complex
1183 if (!m_ui->rembrandtCheckbox->isChecked()) {
1184 if (m_ui->msaaCheckbox->isChecked()) {
1185 globals->get_props()->setIntValue("/sim/rendering/multi-sample-buffers", 1);
1186 globals->get_props()->setIntValue("/sim/rendering/multi-samples", 4);
1188 globals->get_props()->setIntValue("/sim/rendering/multi-sample-buffers", 0);
1193 if (!m_selectedAircraft.isEmpty()) {
1194 QFileInfo setFileInfo(m_selectedAircraft);
1195 opt->addOption("aircraft-dir", setFileInfo.dir().absolutePath().toStdString());
1196 QString setFile = setFileInfo.fileName();
1197 Q_ASSERT(setFile.endsWith("-set.xml"));
1198 setFile.truncate(setFile.count() - 8); // drop the '-set.xml' portion
1199 opt->addOption("aircraft", setFile.toStdString());
1201 // manage aircraft history
1202 if (m_recentAircraft.contains(m_selectedAircraft))
1203 m_recentAircraft.removeOne(m_selectedAircraft);
1204 m_recentAircraft.prepend(m_selectedAircraft);
1205 if (m_recentAircraft.size() > MAX_RECENT_AIRCRAFT)
1206 m_recentAircraft.pop_back();
1209 // airport / location
1210 if (m_selectedAirport) {
1211 opt->addOption("airport", m_selectedAirport->ident());
1214 if (m_ui->runwayRadio->isChecked()) {
1215 int index = m_ui->runwayCombo->itemData(m_ui->runwayCombo->currentIndex()).toInt();
1216 if ((index >= 0) && m_selectedAirport) {
1217 // explicit runway choice
1218 opt->addOption("runway", m_selectedAirport->getRunwayByIndex(index)->ident());
1221 if (m_ui->onFinalCheckbox->isChecked()) {
1222 opt->addOption("glideslope", "3.0");
1223 opt->addOption("offset-distance", "10.0"); // in nautical miles
1225 } else if (m_ui->parkingRadio->isChecked()) {
1226 // parking selection
1227 opt->addOption("parkpos", m_ui->parkingCombo->currentText().toStdString());
1231 if (m_ui->timeOfDayCombo->currentIndex() != 0) {
1232 QString dayval = m_ui->timeOfDayCombo->currentText().toLower();
1233 opt->addOption("timeofday", dayval.toStdString());
1236 if (m_ui->seasonCombo->currentIndex() != 0) {
1237 QString dayval = m_ui->timeOfDayCombo->currentText().toLower();
1238 opt->addOption("season", dayval.toStdString());
1242 for (int i=0; i<m_ui->sceneryPathsList->count(); ++i) {
1243 QString path = m_ui->sceneryPathsList->item(i)->text();
1244 opt->addOption("fg-scenery", path.toStdString());
1247 // additional arguments
1248 ArgumentsTokenizer tk;
1249 Q_FOREACH(ArgumentsTokenizer::Arg a, tk.tokenize(m_ui->commandLineArgs->toPlainText())) {
1250 if (a.arg.startsWith("prop:")) {
1251 QString v = a.arg.mid(5) + "=" + a.value;
1252 opt->addOption("prop", v.toStdString());
1254 opt->addOption(a.arg.toStdString(), a.value.toStdString());
1261 void QtLauncher::onQuit()
1266 void QtLauncher::onSearchAirports()
1268 QString search = m_ui->airportEdit->text();
1269 m_airportsModel->setSearch(search);
1271 if (m_airportsModel->isSearchActive()) {
1272 m_ui->searchStatusText->setText(QString("Searching for '%1'").arg(search));
1273 m_ui->locationStack->setCurrentIndex(2);
1274 } else if (m_airportsModel->rowCount(QModelIndex()) == 1) {
1275 QString ident = m_airportsModel->firstIdent();
1276 setAirport(FGAirport::findByIdent(ident.toStdString()));
1277 m_ui->locationStack->setCurrentIndex(0);
1281 void QtLauncher::onAirportSearchComplete()
1283 int numResults = m_airportsModel->rowCount(QModelIndex());
1284 if (numResults == 0) {
1285 m_ui->searchStatusText->setText(QString("No matching airports for '%1'").arg(m_ui->airportEdit->text()));
1286 } else if (numResults == 1) {
1287 QString ident = m_airportsModel->firstIdent();
1288 setAirport(FGAirport::findByIdent(ident.toStdString()));
1289 m_ui->locationStack->setCurrentIndex(0);
1291 m_ui->locationStack->setCurrentIndex(1);
1295 void QtLauncher::onAirportChanged()
1297 m_ui->runwayCombo->setEnabled(m_selectedAirport);
1298 m_ui->parkingCombo->setEnabled(m_selectedAirport);
1299 m_ui->airportDiagram->setAirport(m_selectedAirport);
1301 m_ui->runwayRadio->setChecked(true); // default back to runway mode
1302 // unelss multiplayer is enabled ?
1304 if (!m_selectedAirport) {
1305 m_ui->airportDescription->setText(QString());
1306 m_ui->airportDiagram->setEnabled(false);
1310 m_ui->airportDiagram->setEnabled(true);
1312 m_ui->runwayCombo->clear();
1313 m_ui->runwayCombo->addItem("Automatic", -1);
1314 for (unsigned int r=0; r<m_selectedAirport->numRunways(); ++r) {
1315 FGRunwayRef rwy = m_selectedAirport->getRunwayByIndex(r);
1316 // add runway with index as data role
1317 m_ui->runwayCombo->addItem(QString::fromStdString(rwy->ident()), r);
1319 m_ui->airportDiagram->addRunway(rwy);
1322 m_ui->parkingCombo->clear();
1323 FGAirportDynamics* dynamics = m_selectedAirport->getDynamics();
1324 PositionedIDVec parkings = NavDataCache::instance()->airportItemsOfType(
1325 m_selectedAirport->guid(),
1326 FGPositioned::PARKING);
1327 if (parkings.empty()) {
1328 m_ui->parkingCombo->setEnabled(false);
1329 m_ui->parkingRadio->setEnabled(false);
1331 m_ui->parkingCombo->setEnabled(true);
1332 m_ui->parkingRadio->setEnabled(true);
1333 Q_FOREACH(PositionedID parking, parkings) {
1334 FGParking* park = dynamics->getParking(parking);
1335 m_ui->parkingCombo->addItem(QString::fromStdString(park->getName()),
1336 static_cast<qlonglong>(parking));
1338 m_ui->airportDiagram->addParking(park);
1343 void QtLauncher::updateAirportDescription()
1345 if (!m_selectedAirport) {
1346 m_ui->airportDescription->setText(QString("No airport selected"));
1350 QString ident = QString::fromStdString(m_selectedAirport->ident()),
1351 name = QString::fromStdString(m_selectedAirport->name());
1352 QString locationOnAirport;
1353 if (m_ui->runwayRadio->isChecked()) {
1354 bool onFinal = m_ui->onFinalCheckbox->isChecked();
1355 QString runwayName = (m_ui->runwayCombo->currentIndex() == 0) ?
1357 QString("runway %1").arg(m_ui->runwayCombo->currentText());
1360 locationOnAirport = QString("on 10-mile final to %1").arg(runwayName);
1362 locationOnAirport = QString("on %1").arg(runwayName);
1364 } else if (m_ui->parkingRadio->isChecked()) {
1365 locationOnAirport = QString("at parking position %1").arg(m_ui->parkingCombo->currentText());
1368 m_ui->airportDescription->setText(QString("%2 (%1): %3").arg(ident).arg(name).arg(locationOnAirport));
1371 void QtLauncher::onAirportChoiceSelected(const QModelIndex& index)
1373 m_ui->locationStack->setCurrentIndex(0);
1374 setAirport(FGPositioned::loadById<FGAirport>(index.data(Qt::UserRole).toULongLong()));
1377 void QtLauncher::onAircraftSelected(const QModelIndex& index)
1379 m_selectedAircraft = index.data(AircraftPathRole).toString();
1380 updateSelectedAircraft();
1383 void QtLauncher::updateSelectedAircraft()
1386 QFileInfo info(m_selectedAircraft);
1387 AircraftItem item(info.dir(), m_selectedAircraft);
1388 m_ui->thumbnail->setPixmap(item.thumbnail());
1389 m_ui->aircraftDescription->setText(item.description);
1390 } catch (sg_exception& e) {
1391 m_ui->thumbnail->setPixmap(QPixmap());
1392 m_ui->aircraftDescription->setText("");
1396 void QtLauncher::onPopupAirportHistory()
1398 if (m_recentAirports.isEmpty()) {
1403 Q_FOREACH(QString aptCode, m_recentAirports) {
1404 FGAirportRef apt = FGAirport::findByIdent(aptCode.toStdString());
1405 QString name = QString::fromStdString(apt->name());
1406 QAction* act = m.addAction(QString("%1 - %2").arg(aptCode).arg(name));
1407 act->setData(aptCode);
1410 QPoint popupPos = m_ui->airportHistory->mapToGlobal(m_ui->airportHistory->rect().bottomLeft());
1411 QAction* triggered = m.exec(popupPos);
1413 FGAirportRef apt = FGAirport::findByIdent(triggered->data().toString().toStdString());
1415 m_ui->airportEdit->clear();
1416 m_ui->locationStack->setCurrentIndex(0);
1420 QModelIndex QtLauncher::proxyIndexForAircraftPath(QString path) const
1422 return m_aircraftProxy->mapFromSource(sourceIndexForAircraftPath(path));
1425 QModelIndex QtLauncher::sourceIndexForAircraftPath(QString path) const
1427 AircraftItemModel* sourceModel = qobject_cast<AircraftItemModel*>(m_aircraftProxy->sourceModel());
1428 Q_ASSERT(sourceModel);
1429 return sourceModel->indexOfAircraftPath(path);
1432 void QtLauncher::onPopupAircraftHistory()
1434 if (m_recentAircraft.isEmpty()) {
1439 Q_FOREACH(QString path, m_recentAircraft) {
1440 QModelIndex index = sourceIndexForAircraftPath(path);
1441 if (!index.isValid()) {
1445 QAction* act = m.addAction(index.data(Qt::DisplayRole).toString());
1449 QPoint popupPos = m_ui->aircraftHistory->mapToGlobal(m_ui->aircraftHistory->rect().bottomLeft());
1450 QAction* triggered = m.exec(popupPos);
1452 m_selectedAircraft = triggered->data().toString();
1453 QModelIndex index = proxyIndexForAircraftPath(m_selectedAircraft);
1454 m_ui->aircraftList->selectionModel()->setCurrentIndex(index,
1455 QItemSelectionModel::ClearAndSelect);
1456 m_ui->aircraftFilter->clear();
1457 updateSelectedAircraft();
1461 void QtLauncher::setAirport(FGAirportRef ref)
1463 if (m_selectedAirport == ref)
1466 m_selectedAirport = ref;
1470 // maintain the recent airport list
1471 QString icao = QString::fromStdString(ref->ident());
1472 if (m_recentAirports.contains(icao)) {
1474 m_recentAirports.removeOne(icao);
1475 m_recentAirports.push_front(icao);
1477 // insert and trim list if necessary
1478 m_recentAirports.push_front(icao);
1479 if (m_recentAirports.size() > MAX_RECENT_AIRPORTS) {
1480 m_recentAirports.pop_back();
1485 updateAirportDescription();
1488 void QtLauncher::onOpenCustomAircraftDir()
1490 QFileInfo info(m_customAircraftDir);
1491 if (!info.exists()) {
1492 int result = QMessageBox::question(this, "Create folder?",
1493 "The custom aircraft folder does not exist, create it now?",
1494 QMessageBox::Yes | QMessageBox::No,
1496 if (result == QMessageBox::No) {
1500 QDir d(m_customAircraftDir);
1501 d.mkpath(m_customAircraftDir);
1504 QUrl u = QUrl::fromLocalFile(m_customAircraftDir);
1505 QDesktopServices::openUrl(u);
1508 void QtLauncher::onEditRatingsFilter()
1510 EditRatingsFilterDialog dialog(this);
1511 dialog.setRatings(m_ratingFilters);
1514 if (dialog.result() == QDialog::Accepted) {
1516 for (int i=0; i<4; ++i) {
1517 m_ratingFilters[i] = dialog.getRating(i);
1518 vl.append(m_ratingFilters[i]);
1520 m_aircraftProxy->setRatings(m_ratingFilters);
1523 settings.setValue("min-ratings", vl);
1527 void QtLauncher::updateSettingsSummary()
1529 QStringList summary;
1530 if (m_ui->timeOfDayCombo->currentIndex() > 0) {
1531 summary.append(QString(m_ui->timeOfDayCombo->currentText().toLower()));
1534 if (m_ui->seasonCombo->currentIndex() > 0) {
1535 summary.append(QString(m_ui->seasonCombo->currentText().toLower()));
1538 if (m_ui->rembrandtCheckbox->isChecked()) {
1539 summary.append("Rembrandt enabled");
1540 } else if (m_ui->msaaCheckbox->isChecked()) {
1541 summary.append("anti-aliasing");
1544 if (m_ui->fetchRealWxrCheckbox->isChecked()) {
1545 summary.append("live weather");
1548 if (m_ui->terrasyncCheck->isChecked()) {
1549 summary.append("automatic scenery downloads");
1552 if (m_ui->startPausedCheck->isChecked()) {
1553 summary.append("paused");
1556 QString s = summary.join(", ");
1557 s[0] = s[0].toUpper();
1558 m_ui->settingsDescription->setText(s);
1561 void QtLauncher::onAddSceneryPath()
1563 QString path = QFileDialog::getExistingDirectory(this, tr("Choose scenery folder"));
1564 if (!path.isEmpty()) {
1565 m_ui->sceneryPathsList->addItem(path);
1570 void QtLauncher::onRemoveSceneryPath()
1572 if (m_ui->sceneryPathsList->currentItem()) {
1573 delete m_ui->sceneryPathsList->currentItem();
1578 void QtLauncher::onRembrandtToggled(bool b)
1580 // Rembrandt and multi-sample are exclusive
1581 m_ui->msaaCheckbox->setEnabled(!b);
1584 #include "QtLauncher.moc"