]> git.mxchange.org Git - flightgear.git/blob - src/GUI/LocationWidget.cxx
ILS drawing in the airport diagram
[flightgear.git] / src / GUI / LocationWidget.cxx
1 // LocationWidget.cxx - GUI launcher dialog using Qt5
2 //
3 // Written by James Turner, started October 2015.
4 //
5 // Copyright (C) 2015 James Turner <zakalawe@mac.com>
6 //
7 // This program is free software; you can redistribute it and/or
8 // modify it under the terms of the GNU General Public License as
9 // published by the Free Software Foundation; either version 2 of the
10 // License, or (at your option) any later version.
11 //
12 // This program is distributed in the hope that it will be useful, but
13 // WITHOUT ANY WARRANTY; without even the implied warranty of
14 // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
15 // General Public License for more details.
16 //
17 // You should have received a copy of the GNU General Public License
18 // along with this program; if not, write to the Free Software
19 // Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301, USA.
20
21 #include "LocationWidget.hxx"
22 #include "ui_LocationWidget.h"
23
24 #include <QSettings>
25 #include <QAbstractListModel>
26 #include <QTimer>
27 #include <QDebug>
28 #include <QToolButton>
29
30 #include "AirportDiagram.hxx"
31 #include "NavaidDiagram.hxx"
32
33 #include <Airports/airport.hxx>
34 #include <Airports/dynamics.hxx> // for parking
35 #include <Main/globals.hxx>
36 #include <Navaids/NavDataCache.hxx>
37 #include <Navaids/navrecord.hxx>
38 #include <Main/options.hxx>
39 #include <Main/fg_init.hxx>
40
41 const int MAX_RECENT_AIRPORTS = 32;
42
43 using namespace flightgear;
44
45 QString fixNavaidName(QString s)
46 {
47     // split into words
48     QStringList words = s.split(QChar(' '));
49     QStringList changedWords;
50     Q_FOREACH(QString w, words) {
51         QString up = w.toUpper();
52
53         // expand common abbreviations
54         if (up == "FLD") {
55             changedWords.append("Field");
56             continue;
57         }
58
59         if (up == "MUNI") {
60             changedWords.append("Municipal");
61             continue;
62         }
63
64         if (up == "RGNL") {
65             changedWords.append("Regional");
66             continue;
67         }
68
69         if (up == "CTR") {
70             changedWords.append("Center");
71             continue;
72         }
73
74         if (up == "INTL") {
75             changedWords.append("International");
76             continue;
77         }
78
79         // occurs in many Australian airport names in our DB
80         if (up == "(NSW)") {
81             changedWords.append("(New South Wales)");
82             continue;
83         }
84
85         if ((up == "VOR") || (up == "NDB") || (up == "VOR-DME") || (up == "VORTAC") || (up == "NDB-DME")) {
86             changedWords.append(w);
87             continue;
88         }
89
90         QChar firstChar = w.at(0).toUpper();
91         w = w.mid(1).toLower();
92         w.prepend(firstChar);
93
94         changedWords.append(w);
95     }
96
97     return changedWords.join(QChar(' '));
98 }
99
100 QString formatGeodAsString(const SGGeod& geod)
101 {
102     QChar ns = (geod.getLatitudeDeg() > 0.0) ? 'N' : 'S';
103     QChar ew = (geod.getLongitudeDeg() > 0.0) ? 'E' : 'W';
104
105     return QString::number(fabs(geod.getLongitudeDeg()), 'f',2 ) + ew + " " +
106             QString::number(fabs(geod.getLatitudeDeg()), 'f',2 ) + ns;
107 }
108
109 class IdentSearchFilter : public FGPositioned::TypeFilter
110 {
111 public:
112     IdentSearchFilter()
113     {
114         addType(FGPositioned::AIRPORT);
115         addType(FGPositioned::SEAPORT);
116         addType(FGPositioned::HELIPAD);
117         addType(FGPositioned::VOR);
118         addType(FGPositioned::FIX);
119         addType(FGPositioned::NDB);
120     }
121 };
122
123 class NavSearchModel : public QAbstractListModel
124 {
125     Q_OBJECT
126 public:
127     NavSearchModel() :
128         m_searchActive(false)
129     {
130     }
131
132     void setSearch(QString t)
133     {
134         beginResetModel();
135
136         m_items.clear();
137         m_ids.clear();
138
139         std::string term(t.toUpper().toStdString());
140
141         IdentSearchFilter filter;
142         FGPositionedList exactMatches = NavDataCache::instance()->findAllWithIdent(term, &filter, true);
143
144         for (unsigned int i=0; i<exactMatches.size(); ++i) {
145             m_ids.push_back(exactMatches[i]->guid());
146             m_items.push_back(exactMatches[i]);
147         }
148         endResetModel();
149
150
151         m_search.reset(new NavDataCache::ThreadedGUISearch(term));
152         QTimer::singleShot(100, this, &NavSearchModel::onSearchResultsPoll);
153         m_searchActive = true;
154         endResetModel();
155     }
156
157     bool isSearchActive() const
158     {
159         return m_searchActive;
160     }
161
162     virtual int rowCount(const QModelIndex&) const
163     {
164         // if empty, return 1 for special 'no matches'?
165         return m_ids.size();
166     }
167
168     virtual QVariant data(const QModelIndex& index, int role) const
169     {
170         if (!index.isValid())
171             return QVariant();
172
173         FGPositionedRef pos = itemAtRow(index.row());
174         if (role == Qt::DisplayRole) {
175             if (pos->type() == FGPositioned::FIX) {
176                 // fixes don't have a name, show position instead
177                 return QString("Fix %1 (%2)").arg(QString::fromStdString(pos->ident()))
178                         .arg(formatGeodAsString(pos->geod()));
179             } else {
180                 QString name = fixNavaidName(QString::fromStdString(pos->name()));
181                 return QString("%1: %2").arg(QString::fromStdString(pos->ident())).arg(name);
182             }
183         }
184
185         if (role == Qt::EditRole) {
186             return QString::fromStdString(pos->ident());
187         }
188
189         if (role == Qt::UserRole) {
190             return static_cast<qlonglong>(m_ids[index.row()]);
191         }
192
193         return QVariant();
194     }
195
196     FGPositionedRef itemAtRow(unsigned int row) const
197     {
198         FGPositionedRef pos = m_items[row];
199         if (!pos.valid()) {
200             pos = NavDataCache::instance()->loadById(m_ids[row]);
201             m_items[row] = pos;
202         }
203
204         return pos;
205     }
206 Q_SIGNALS:
207     void searchComplete();
208
209 private:
210
211
212     void onSearchResultsPoll()
213     {
214         PositionedIDVec newIds = m_search->results();
215
216         beginInsertRows(QModelIndex(), m_ids.size(), newIds.size() - 1);
217         for (unsigned int i=m_ids.size(); i < newIds.size(); ++i) {
218             m_ids.push_back(newIds[i]);
219             m_items.push_back(FGPositionedRef()); // null ref
220         }
221         endInsertRows();
222
223         if (m_search->isComplete()) {
224             m_searchActive = false;
225             m_search.reset();
226             emit searchComplete();
227         } else {
228             QTimer::singleShot(100, this, &NavSearchModel::onSearchResultsPoll);
229         }
230     }
231
232 private:
233     PositionedIDVec m_ids;
234     mutable FGPositionedList m_items;
235     bool m_searchActive;
236     QScopedPointer<NavDataCache::ThreadedGUISearch> m_search;
237 };
238
239
240 LocationWidget::LocationWidget(QWidget *parent) :
241     QWidget(parent),
242     m_ui(new Ui::LocationWidget)
243 {
244     m_ui->setupUi(this);
245
246
247     QIcon historyIcon(":/history-icon");
248     m_ui->searchHistory->setIcon(historyIcon);
249
250     m_ui->searchIcon->setPixmap(QPixmap(":/search-icon"));
251
252     m_searchModel = new NavSearchModel;
253     m_ui->searchResultsList->setModel(m_searchModel);
254     connect(m_ui->searchResultsList, &QListView::clicked,
255             this, &LocationWidget::onSearchResultSelected);
256     connect(m_searchModel, &NavSearchModel::searchComplete,
257             this, &LocationWidget::onSearchComplete);
258
259     connect(m_ui->runwayCombo, SIGNAL(currentIndexChanged(int)),
260             this, SLOT(updateDescription()));
261     connect(m_ui->parkingCombo, SIGNAL(currentIndexChanged(int)),
262             this, SLOT(updateDescription()));
263     connect(m_ui->runwayRadio, SIGNAL(toggled(bool)),
264             this, SLOT(updateDescription()));
265     connect(m_ui->parkingRadio, SIGNAL(toggled(bool)),
266             this, SLOT(updateDescription()));
267     connect(m_ui->onFinalCheckbox, SIGNAL(toggled(bool)),
268             this, SLOT(updateDescription()));
269     connect(m_ui->approachDistanceSpin, SIGNAL(valueChanged(int)),
270             this, SLOT(updateDescription()));
271
272     connect(m_ui->airportDiagram, &AirportDiagram::clickedRunway,
273             this, &LocationWidget::onAirportDiagramClicked);
274
275     connect(m_ui->locationSearchEdit, &QLineEdit::returnPressed,
276             this, &LocationWidget::onSearch);
277
278     connect(m_ui->searchHistory, &QPushButton::clicked,
279             this, &LocationWidget::onPopupHistory);
280
281     connect(m_ui->trueBearing, &QCheckBox::toggled,
282             this, &LocationWidget::onOffsetBearingTrueChanged);
283     connect(m_ui->offsetGroup, &QGroupBox::toggled,
284             this, &LocationWidget::onOffsetEnabledToggled);
285     connect(m_ui->trueBearing, &QCheckBox::toggled, this,
286             &LocationWidget::onOffsetDataChanged);
287     connect(m_ui->offsetBearingSpinbox, SIGNAL(valueChanged(int)),
288             this, SLOT(onOffsetDataChanged()));
289     connect(m_ui->offsetNmSpinbox, SIGNAL(valueChanged(double)),
290             this, SLOT(onOffsetDataChanged()));
291
292     m_backButton = new QToolButton(this);
293     m_backButton->setGeometry(0, 0, 32, 32);
294     m_backButton->setIcon(QIcon(":/search-icon"));
295     m_backButton->raise();
296
297     connect(m_backButton, &QAbstractButton::clicked,
298             this, &LocationWidget::onBackToSearch);
299
300 // force various pieces of UI into sync
301     onOffsetEnabledToggled(m_ui->offsetGroup->isChecked());
302     onBackToSearch();
303 }
304
305 LocationWidget::~LocationWidget()
306 {
307     delete m_ui;
308 }
309
310 void LocationWidget::restoreSettings()
311 {
312     QSettings settings;
313     Q_FOREACH(QVariant v, settings.value("recent-locations").toList()) {
314         m_recentAirports.push_back(v.toLongLong());
315     }
316
317     if (!m_recentAirports.empty()) {
318         setBaseLocation(NavDataCache::instance()->loadById(m_recentAirports.front()));
319     }
320
321     updateDescription();
322 }
323
324 bool LocationWidget::shouldStartPaused() const
325 {
326     qWarning() << Q_FUNC_INFO << "implement me";
327     return false;
328 }
329
330 void LocationWidget::saveSettings()
331 {
332     QSettings settings;
333
334     QVariantList locations;
335     Q_FOREACH(PositionedID v, m_recentAirports) {
336         locations.push_back(v);
337     }
338
339     settings.setValue("recent-airports", locations);
340 }
341
342 void LocationWidget::setLocationOptions()
343 {
344     flightgear::Options* opt = flightgear::Options::sharedInstance();
345
346     if (!m_location) {
347         return;
348     }
349
350     if (FGAirport::isAirportType(m_location.ptr())) {
351         FGAirport* apt = static_cast<FGAirport*>(m_location.ptr());
352         opt->addOption("airport", apt->ident());
353
354         if (m_ui->runwayRadio->isChecked()) {
355             int index = m_ui->runwayCombo->itemData(m_ui->runwayCombo->currentIndex()).toInt();
356             if (index >= 0) {
357                 // explicit runway choice
358                 opt->addOption("runway", apt->getRunwayByIndex(index)->ident());
359             }
360
361             if (m_ui->onFinalCheckbox->isChecked()) {
362                 opt->addOption("glideslope", "3.0");
363                 opt->addOption("offset-distance", "10.0"); // in nautical miles
364             }
365         } else if (m_ui->parkingRadio->isChecked()) {
366             // parking selection
367             opt->addOption("parkpos", m_ui->parkingCombo->currentText().toStdString());
368         }
369         // of location is an airport
370     }
371
372     FGPositioned::Type ty = m_location->type();
373     switch (ty) {
374     case FGPositioned::VOR:
375     case FGPositioned::NDB:
376     case FGPositioned::FIX:
377         // set disambiguation property
378         globals->get_props()->setIntValue("/sim/presets/navaid-id",
379                                           static_cast<int>(m_location->guid()));
380
381         // we always set 'fix', but really this is just to force positionInit
382         // code to check for the navaid-id value above.
383         opt->addOption("fix", m_location->ident());
384         break;
385     default:
386         break;
387     }
388 }
389
390 void LocationWidget::onSearch()
391 {
392     QString search = m_ui->locationSearchEdit->text();
393     m_searchModel->setSearch(search);
394
395     if (m_searchModel->isSearchActive()) {
396         m_ui->searchStatusText->setText(QString("Searching for '%1'").arg(search));
397         m_ui->searchIcon->setVisible(true);
398     } else if (m_searchModel->rowCount(QModelIndex()) == 1) {
399         setBaseLocation(m_searchModel->itemAtRow(0));
400     }
401 }
402
403 void LocationWidget::onSearchComplete()
404 {
405     QString search = m_ui->locationSearchEdit->text();
406     m_ui->searchIcon->setVisible(false);
407     m_ui->searchStatusText->setText(QString("Results for '%1'").arg(search));
408
409     int numResults = m_searchModel->rowCount(QModelIndex());
410     if (numResults == 0) {
411         m_ui->searchStatusText->setText(QString("No matches for '%1'").arg(search));
412     } else if (numResults == 1) {
413         setBaseLocation(m_searchModel->itemAtRow(0));
414     }
415 }
416
417 void LocationWidget::onLocationChanged()
418 {
419     bool locIsAirport = FGAirport::isAirportType(m_location.ptr());
420     m_backButton->show();
421
422     if (locIsAirport) {
423         m_ui->stack->setCurrentIndex(0);
424         FGAirport* apt = static_cast<FGAirport*>(m_location.ptr());
425         m_ui->airportDiagram->setAirport(apt);
426
427         m_ui->runwayRadio->setChecked(true); // default back to runway mode
428         // unless multiplayer is enabled ?
429         m_ui->airportDiagram->setEnabled(true);
430
431         m_ui->runwayCombo->clear();
432         m_ui->runwayCombo->addItem("Automatic", -1);
433         for (unsigned int r=0; r<apt->numRunways(); ++r) {
434             FGRunwayRef rwy = apt->getRunwayByIndex(r);
435             // add runway with index as data role
436             m_ui->runwayCombo->addItem(QString::fromStdString(rwy->ident()), r);
437
438             m_ui->airportDiagram->addRunway(rwy);
439         }
440
441         m_ui->parkingCombo->clear();
442         FGAirportDynamics* dynamics = apt->getDynamics();
443         PositionedIDVec parkings = NavDataCache::instance()->airportItemsOfType(m_location->guid(),
444                                                                                 FGPositioned::PARKING);
445         if (parkings.empty()) {
446             m_ui->parkingCombo->setEnabled(false);
447             m_ui->parkingRadio->setEnabled(false);
448         } else {
449             m_ui->parkingCombo->setEnabled(true);
450             m_ui->parkingRadio->setEnabled(true);
451             Q_FOREACH(PositionedID parking, parkings) {
452                 FGParking* park = dynamics->getParking(parking);
453                 m_ui->parkingCombo->addItem(QString::fromStdString(park->getName()),
454                                             static_cast<qlonglong>(parking));
455
456                 m_ui->airportDiagram->addParking(park);
457             }
458         }
459
460
461     } else {// of location is airport
462         // navaid
463         m_ui->stack->setCurrentIndex(1);
464         m_ui->navaidDiagram->setNavaid(m_location);
465     }
466 }
467
468 void LocationWidget::onOffsetEnabledToggled(bool on)
469 {
470     m_ui->offsetDistanceLabel->setEnabled(on);
471 //    m_ui->offsetNmSpinbox->setEnabled(on);
472 //    m_ui->offsetBearingSpinbox->setEnabled(on);
473 //    m_ui->trueBearing->setEnabled(on);
474 //    m_ui->offsetBearingLabel->setEnabled(on);
475 //    m_ui->offsetDistanceLabel->setEnabled(on);
476 }
477
478 void LocationWidget::onAirportDiagramClicked(FGRunwayRef rwy)
479 {
480     if (rwy) {
481         m_ui->runwayRadio->setChecked(true);
482         int rwyIndex = m_ui->runwayCombo->findText(QString::fromStdString(rwy->ident()));
483         m_ui->runwayCombo->setCurrentIndex(rwyIndex);
484         m_ui->airportDiagram->setSelectedRunway(rwy);
485     }
486
487     updateDescription();
488 }
489
490 QString LocationWidget::locationDescription() const
491 {
492     if (!m_location)
493         return QString("No location selected");
494
495     bool locIsAirport = FGAirport::isAirportType(m_location.ptr());
496     QString ident = QString::fromStdString(m_location->ident()),
497         name = QString::fromStdString(m_location->name());
498
499     if (locIsAirport) {
500         FGAirport* apt = static_cast<FGAirport*>(m_location.ptr());
501         QString locationOnAirport;
502
503         if (m_ui->runwayRadio->isChecked()) {
504             bool onFinal = m_ui->onFinalCheckbox->isChecked();
505             int comboIndex = m_ui->runwayCombo->currentIndex();
506             QString runwayName = (comboIndex == 0) ?
507                 "active runway" :
508                 QString("runway %1").arg(m_ui->runwayCombo->currentText());
509
510             if (onFinal) {
511                 int finalDistance = m_ui->approachDistanceSpin->value();
512                 locationOnAirport = QString("on %2-mile final to %1").arg(runwayName).arg(finalDistance);
513             } else {
514                 locationOnAirport = QString("on %1").arg(runwayName);
515             }
516         } else if (m_ui->parkingRadio->isChecked()) {
517             locationOnAirport = QString("at parking position %1").arg(m_ui->parkingCombo->currentText());
518         }
519
520         return QString("%2 (%1): %3").arg(ident).arg(name).arg(locationOnAirport);
521     } else {
522         QString navaidType;
523         switch (m_location->type()) {
524         case FGPositioned::VOR:
525             navaidType = QString("VOR"); break;
526         case FGPositioned::NDB:
527             navaidType = QString("NDB"); break;
528         case FGPositioned::FIX:
529             return QString("at waypoint %1").arg(ident);
530         default:
531             // unsupported type
532             break;
533         }
534
535         return QString("at %1 %2 (%3").arg(navaidType).arg(ident).arg(name);
536     }
537
538     return QString("Implement Me");
539 }
540
541
542 void LocationWidget::updateDescription()
543 {
544     bool locIsAirport = FGAirport::isAirportType(m_location.ptr());
545     if (locIsAirport) {
546         FGAirport* apt = static_cast<FGAirport*>(m_location.ptr());
547
548         if (m_ui->runwayRadio->isChecked()) {
549             int comboIndex = m_ui->runwayCombo->currentIndex();
550             int runwayIndex = m_ui->runwayCombo->itemData(comboIndex).toInt();
551             // we can't figure out the active runway in the launcher (yet)
552             FGRunwayRef rwy = (runwayIndex >= 0) ?
553                 apt->getRunwayByIndex(runwayIndex) : FGRunwayRef();
554             m_ui->airportDiagram->setSelectedRunway(rwy);
555         }
556
557         if (m_ui->onFinalCheckbox->isChecked()) {
558             m_ui->airportDiagram->setApproachExtensionDistance(m_ui->approachDistanceSpin->value());
559         } else {
560             m_ui->airportDiagram->setApproachExtensionDistance(0.0);
561         }
562     } else {
563
564     }
565
566 #if 0
567
568     QString locationOnAirport;
569     if (m_ui->runwayRadio->isChecked()) {
570
571
572     } else if (m_ui->parkingRadio->isChecked()) {
573         locationOnAirport =  QString("at parking position %1").arg(m_ui->parkingCombo->currentText());
574     }
575
576     m_ui->airportDescription->setText();
577 #endif
578
579     emit descriptionChanged(locationDescription());
580 }
581
582 void LocationWidget::onSearchResultSelected(const QModelIndex& index)
583 {
584     qDebug() << "selected result:" << index.data();
585     setBaseLocation(m_searchModel->itemAtRow(index.row()));
586 }
587
588 void LocationWidget::onOffsetBearingTrueChanged(bool on)
589 {
590     m_ui->offsetBearingLabel->setText(on ? tr("True bearing:") :
591                                       tr("Magnetic bearing:"));
592 }
593
594
595 void LocationWidget::onPopupHistory()
596 {
597     if (m_recentAirports.isEmpty()) {
598         return;
599     }
600
601 #if 0
602     QMenu m;
603     Q_FOREACH(QString aptCode, m_recentAirports) {
604         FGAirportRef apt = FGAirport::findByIdent(aptCode.toStdString());
605         QString name = QString::fromStdString(apt->name());
606         QAction* act = m.addAction(QString("%1 - %2").arg(aptCode).arg(name));
607         act->setData(aptCode);
608     }
609
610     QPoint popupPos = m_ui->airportHistory->mapToGlobal(m_ui->airportHistory->rect().bottomLeft());
611     QAction* triggered = m.exec(popupPos);
612     if (triggered) {
613         FGAirportRef apt = FGAirport::findByIdent(triggered->data().toString().toStdString());
614         setAirport(apt);
615         m_ui->airportEdit->clear();
616         m_ui->locationStack->setCurrentIndex(0);
617     }
618 #endif
619 }
620
621 void LocationWidget::setBaseLocation(FGPositionedRef ref)
622 {
623     if (m_location == ref)
624         return;
625
626     m_location = ref;
627     onLocationChanged();
628
629 #if 0
630     if (ref.valid()) {
631         // maintain the recent airport list
632         QString icao = QString::fromStdString(ref->ident());
633         if (m_recentAirports.contains(icao)) {
634             // move to front
635             m_recentAirports.removeOne(icao);
636             m_recentAirports.push_front(icao);
637         } else {
638             // insert and trim list if necessary
639             m_recentAirports.push_front(icao);
640             if (m_recentAirports.size() > MAX_RECENT_AIRPORTS) {
641                 m_recentAirports.pop_back();
642             }
643         }
644     }
645 #endif
646     updateDescription();
647 }
648
649 void LocationWidget::onOffsetDataChanged()
650 {
651     qDebug() << "implement me";
652 }
653
654 void LocationWidget::onBackToSearch()
655 {
656     m_ui->stack->setCurrentIndex(2);
657     m_backButton->hide();
658 }
659
660 #include "LocationWidget.moc"