Debian Codegraph @

src/GUI/FlightPlanController.cxx

raw symbols SCIP
1 #include "FlightPlanController.hxx"
2
3 #include <Main/options.hxx>
4 #include <QAbstractListModel>
5 #include <QDebug>
6 #include <QFileDialog>
7 #include <QQmlComponent>
8 #include <QSettings>
9 #include <QTimer>
10
11 #include <simgear/misc/sg_path.hxx>
12
13 #include <Main/globals.hxx>
14 #include <Navaids/waypoint.hxx>
15 #include <Navaids/airways.hxx>
16 #include <Navaids/navrecord.hxx>
17 #include <Navaids/airways.hxx>
18
19 #include "LaunchConfig.hxx"
20 #include "QmlPositioned.hxx"
21 #include "SettingsWrapper.hxx"
22
23 using namespace flightgear;
24
25 const int LegDistanceRole = Qt::UserRole;
26 const int LegTrackRole = Qt::UserRole + 1;
27 const int LegTerminatorNavRole = Qt::UserRole + 2;
28 const int LegAirwayIdentRole = Qt::UserRole + 3;
29 const int LegTerminatorTypeRole = Qt::UserRole + 4;
30 const int LegTerminatorNavNameRole = Qt::UserRole + 5;
31 const int LegTerminatorNavFrequencyRole = Qt::UserRole + 6;
32 const int LegAltitudeFtRole = Qt::UserRole + 7;
33 const int LegAltitudeTypeRole = Qt::UserRole + 8;
34
35 /////////////////////////////////////////////////////////////////////////////
36
37 void LegsModel::setFlightPlan(flightgear::FlightPlanRef f)
38 {
39 beginResetModel();
40 _fp = f;
41 endResetModel();
42 emit numLegsChanged();
43 }
44
45 int LegsModel::rowCount(const QModelIndex& parent) const
46 {
47 Q_UNUSED(parent)
48 return _fp->numLegs();
49 }
50
51 QVariant LegsModel::data(const QModelIndex& index, int role) const
52 {
53 const auto leg = _fp->legAtIndex(index.row());
54 if (!leg)
55 return {};
56
57 const auto wp = leg->waypoint();
58
59 switch (role) {
60 case Qt::DisplayRole: {
61 if (wp->type() == "via") {
62 // we want the end waypoint name
63 return QString::fromStdString(wp->source()->ident());
64 }
65
66 return QString::fromStdString(leg->waypoint()->ident());
67 }
68
69 case LegDistanceRole:
70 return QVariant::fromValue(QuantityValue{Units::NauticalMiles, leg->distanceNm()});
71 case LegTrackRole:
72 return QVariant::fromValue(QuantityValue{Units::DegreesTrue, leg->courseDeg()});
73
74 case LegAirwayIdentRole: {
75 AirwayRef awy;
76 if (wp->type() == "via") {
77 auto via = static_cast<flightgear::Via*>(leg->waypoint());
78 awy = via->airway();
79 } else if (wp->flag(WPT_VIA)) {
80 awy = static_cast<Airway*>(wp->owner());
81 }
82
83 return awy ? QString::fromStdString(awy->ident()) : QVariant{};
84 }
85
86 case LegTerminatorNavRole: {
87 if (leg->waypoint()->source()) {
88 return QString::fromStdString(leg->waypoint()->source()->ident());
89 }
90 break;
91 }
92
93 case LegTerminatorNavFrequencyRole: {
94 const auto n = fgpositioned_cast<FGNavRecord>(leg->waypoint()->source());
95 if (n) {
96 const double f = n->get_freq() / 100.0;
97 if (n->type() == FGPositioned::NDB) {
98 return QVariant::fromValue(QuantityValue(Units::FreqKHz, f));
99 }
100
101 return QVariant::fromValue(QuantityValue(Units::FreqMHz, f));
102 }
103 return QVariant::fromValue(QuantityValue());
104 }
105
106 case LegTerminatorNavNameRole: {
107 if (leg->waypoint()->source()) {
108 return QString::fromStdString(leg->waypoint()->source()->name());
109 }
110 return QString{}; // avoud undefined-value QML error if we return a null variant
111 }
112
113 case LegTerminatorTypeRole:
114 return QString::fromStdString(leg->waypoint()->type());
115
116 case LegAltitudeFtRole:
117 return leg->altitudeFt();
118
119 case LegAltitudeTypeRole:
120 return leg->altitudeRestriction();
121
122 default:
123 break;
124 }
125
126 return {};
127 }
128
129 void LegsModel::waypointsChanged()
130 {
131 beginResetModel();
132 endResetModel();
133 numLegsChanged();
134 }
135
136 QHash<int, QByteArray> LegsModel::roleNames() const
137 {
138 QHash<int, QByteArray> result = QAbstractListModel::roleNames();
139
140 result[Qt::DisplayRole] = "label";
141 result[LegDistanceRole] = "distance";
142 result[LegTrackRole] = "track";
143 result[LegTerminatorNavRole] = "to";
144 result[LegTerminatorNavFrequencyRole] = "frequency";
145 result[LegAirwayIdentRole] = "via";
146 result[LegTerminatorTypeRole] = "wpType";
147 result[LegTerminatorNavNameRole] = "toName";
148 result[LegAltitudeFtRole] = "altitudeFt";
149 result[LegAltitudeTypeRole] = "altitudeType";
150
151 return result;
152 }
153
154 int LegsModel::numLegs() const
155 {
156 return _fp->numLegs();
157 }
158
159 /////////////////////////////////////////////////////////////////////////////
160
161 class FPDelegate : public FlightPlan::Delegate
162 {
163 public:
164 void arrivalChanged() override
165 {
166 p->infoChanged();
167 }
168
169 void departureChanged() override
170 {
171 p->infoChanged();
172 }
173
174 void cruiseChanged() override
175 {
176 p->infoChanged();
177 }
178
179 void waypointsChanged() override
180 {
181 QTimer::singleShot(0, p->_legs, &LegsModel::waypointsChanged);
182 p->waypointsChanged();
183 p->infoChanged();
184 }
185
186 FlightPlanController* p;
187 };
188
189 /////////////////////////////////////////////////////////////////////////////
190
191 FlightPlanController::FlightPlanController(QObject *parent, LaunchConfig* config)
192 : QObject(parent)
193 {
194 _config = config;
195 connect(_config, &LaunchConfig::collect, this, &FlightPlanController::onCollectConfig);
196 connect(_config, &LaunchConfig::save, this, &FlightPlanController::onSave);
197 connect(_config, &LaunchConfig::restore, this, &FlightPlanController::onRestore);
198
199 _delegate.reset(new FPDelegate);
200 _delegate->p = this; // link back to us
201
202 qmlRegisterUncreatableType<LegsModel>("FlightGear", 1, 0, "LegsModel", "singleton");
203 _fp.reset(flightgear::FlightPlan::createRoute());
204 _fp->addDelegate(_delegate.get());
205 _legs = new LegsModel();
206 _legs->setFlightPlan(_fp);
207
208 // initial restore
209 onRestore();
210 }
211
212 FlightPlanController::~FlightPlanController()
213 {
214 _fp->removeDelegate(_delegate.get());
215 }
216
217 void FlightPlanController::clearPlan()
218 {
219 auto fp = flightgear::FlightPlan::createRoute();
220 _fp->removeDelegate(_delegate.get());
221 _fp = fp;
222 _fp->addDelegate(_delegate.get());
223 _legs->setFlightPlan(fp);
224 emit infoChanged();
225
226 _enabled = false;
227 emit enabledChanged(_enabled);
228 }
229
230 bool FlightPlanController::loadFromPath(QString path)
231 {
232 auto fp = flightgear::FlightPlan::createRoute();
233 bool ok = fp->load(SGPath(path.toUtf8().data()));
234 if (!ok) {
235 qWarning() << "Failed to load flightplan " << path;
236 return false;
237 }
238
239 _fp->removeDelegate(_delegate.get());
240 _fp = fp;
241 _fp->addDelegate(_delegate.get());
242 _legs->setFlightPlan(fp);
243
244 _enabled = true;
245 emit enabledChanged(_enabled);
246
247 // notify that everything changed
248 emit infoChanged();
249 return true;
250 }
251
252 bool FlightPlanController::saveToPath(QString path) const
253 {
254 SGPath p(path.toUtf8().data());
255 return _fp->save(p);
256 }
257
258 void FlightPlanController::onCollectConfig()
259 {
260 if (!_enabled)
261 return;
262
263 SGPath p = globals->get_fg_home() / "launcher.fgfp";
264 _fp->save(p);
265
266 _config->setArg("flight-plan", p.utf8Str());
267 }
268
269 void FlightPlanController::onSave()
270 {
271 std::ostringstream ss;
272 _fp->save(ss);
273 _config->setValueForKey("", "fp", QString::fromStdString(ss.str()));
274 }
275
276 void FlightPlanController::onRestore()
277 {
278 _enabled = _config->getValueForKey("", "fp-enabled", false).toBool();
279 emit enabledChanged(_enabled);
280
281 // if the user specified --flight-plan, load that one
282 auto options = flightgear::Options::sharedInstance();
283 std::string fpArgPath = options->valueForOption("flight-plan");
284 SGPath fp = SGPath::fromUtf8(fpArgPath);
285 if (fp.exists()) {
286 loadFromPath(QString::fromStdString(fpArgPath));
287 } else {
288 std::string planXML = _config->getValueForKey("", "fp", QString()).toString().toStdString();
289 if (!planXML.empty()) {
290 std::istringstream ss(planXML);
291 _fp->load(ss);
292 emit infoChanged();
293 }
294 }
295 }
296
297 QuantityValue FlightPlanController::cruiseAltitude() const
298 {
299 if (_fp->cruiseFlightLevel() > 0) {
300 return {Units::FlightLevel, _fp->cruiseFlightLevel()};
301 }
302
303 if (_fp->cruiseAltitudeM() > 0) {
304 return {Units::MetersMSL, _fp->cruiseAltitudeM()};
305 }
306
307 return {Units::FeetMSL, _fp->cruiseAltitudeFt()};
308 }
309
310 void FlightPlanController::setCruiseAltitude(QuantityValue alt)
311 {
312 const int ival = static_cast<int>(alt.value);
313 switch (alt.unit) {
314 case Units::FlightLevel: {
315 if (_fp->cruiseFlightLevel() == ival) {
316 return;
317 }
318 _fp->setCruiseFlightLevel(ival);
319 break;
320 }
321 case Units::FeetMSL: {
322 if (_fp->cruiseAltitudeFt() == ival) {
323 return;
324 }
325 _fp->setCruiseAltitudeFt(ival);
326 break;
327 }
328 case Units::MetersMSL: {
329 if (_fp->cruiseAltitudeM() == ival) {
330 return;
331 }
332 _fp->setCruiseAltitudeM(ival);
333 break;
334 }
335 default:
336 qWarning() << "Unsupported cruise altitude units" << alt.unit;
337 break;
338 }
339
340 emit infoChanged();
341 }
342
343 QString FlightPlanController::description() const
344 {
345 if (_fp->numLegs() == 0) {
346 return tr("No flight-plan");
347 }
348
349 return tr("From %1 (%2) to %3 (%4)")
350 .arg(departure()->ident())
351 .arg(departure()->name())
352 .arg(destination()->ident())
353 .arg(destination()->name());
354 }
355
356 QmlPositioned *FlightPlanController::departure() const
357 {
358 if (!_fp->departureAirport())
359 return new QmlPositioned;
360
361 return new QmlPositioned(_fp->departureAirport());
362 }
363
364 QmlPositioned *FlightPlanController::destination() const
365 {
366 if (!_fp->destinationAirport())
367 return new QmlPositioned;
368
369 return new QmlPositioned(_fp->destinationAirport());
370 }
371
372 QmlPositioned *FlightPlanController::alternate() const
373 {
374 if (!_fp->alternate())
375 return new QmlPositioned;
376
377 return new QmlPositioned(_fp->alternate());
378 }
379
380 QuantityValue FlightPlanController::cruiseSpeed() const
381 {
382 if (_fp->cruiseSpeedMach() > 0.0) {
383 return {Units::Mach, _fp->cruiseSpeedMach()};
384 }
385
386 if (_fp->cruiseSpeedKPH() > 0) {
387 return {Units::KilometersPerHour, _fp->cruiseSpeedKPH()};
388 }
389
390 return {Units::Knots, _fp->cruiseSpeedKnots()};
391 }
392
393 FlightPlanController::FlightRules FlightPlanController::flightRules() const
394 {
395 return static_cast<FlightRules>(_fp->flightRules());
396 }
397
398 FlightPlanController::FlightType FlightPlanController::flightType() const
399 {
400 return static_cast<FlightType>(_fp->flightType());
401 }
402
403 void FlightPlanController::setFlightRules(FlightRules r)
404 {
405 _fp->setFlightRules(static_cast<flightgear::ICAOFlightRules>(r));
406 }
407
408 void FlightPlanController::setFlightType(FlightType ty)
409 {
410 _fp->setFlightType(static_cast<flightgear::ICAOFlightType>(ty));
411 }
412
413 QString FlightPlanController::callsign() const
414 {
415 return QString::fromStdString(_fp->callsign());
416 }
417
418 QString FlightPlanController::remarks() const
419 {
420 return QString::fromStdString(_fp->remarks());
421 }
422
423 QString FlightPlanController::aircraftType() const
424 {
425 return QString::fromStdString(_fp->icaoAircraftType());
426 }
427
428 void FlightPlanController::setCallsign(QString s)
429 {
430 const auto stdS = s.toStdString();
431 if (_fp->callsign() == stdS)
432 return;
433
434 _fp->setCallsign(stdS);
435 emit infoChanged();
436 }
437
438 void FlightPlanController::setRemarks(QString r)
439 {
440 const auto stdR = r.toStdString();
441 if (_fp->remarks() == stdR)
442 return;
443
444 _fp->setRemarks(stdR);
445 emit infoChanged();
446 }
447
448 void FlightPlanController::setAircraftType(QString ty)
449 {
450 const auto stdT = ty.toStdString();
451 if (_fp->icaoAircraftType() == stdT)
452 return;
453
454 _fp->setIcaoAircraftType(stdT);
455 emit infoChanged();
456 }
457
458 int FlightPlanController::estimatedDurationMinutes() const
459 {
460 return _fp->estimatedDurationMinutes();
461 }
462
463 QuantityValue FlightPlanController::totalDistanceNm() const
464 {
465 return QuantityValue{Units::NauticalMiles, _fp->totalDistanceNm()};
466 }
467
468 bool FlightPlanController::tryParseRoute(QString routeDesc)
469 {
470 bool ok = _fp->parseICAORouteString(routeDesc.toStdString());
471 return ok;
472 }
473
474 bool FlightPlanController::tryGenerateRoute()
475 {
476 if (!_fp->departureAirport() || !_fp->destinationAirport()) {
477 qWarning() << "departure or destination not set";
478
479 return false;
480 }
481
482 auto net = Airway::highLevel();
483 auto fromNode = net->findClosestNode(_fp->departureAirport()->geod());
484 auto toNode = net->findClosestNode(_fp->destinationAirport()->geod());
485 if (!fromNode.first) {
486 qWarning() << "Couldn't find airway network transition for "
487 << QString::fromStdString(_fp->departureAirport()->ident());
488 return false;
489 }
490
491 if (!toNode.first) {
492 qWarning() << "Couldn't find airway network transition for "
493 << QString::fromStdString(_fp->destinationAirport()->ident());
494 return false;
495 }
496
497 WayptRef fromWp = new NavaidWaypoint(fromNode.first, _fp);
498 WayptRef toWp = new NavaidWaypoint(toNode.first, _fp);
499 WayptVec path;
500 bool ok = net->route(fromWp, toWp, path);
501 if (!ok) {
502 qWarning() << "unable to find a route";
503 return false;
504 }
505
506 _fp->clearLegs();
507 _fp->insertWayptAtIndex(fromWp, -1);
508 _fp->insertWayptsAtIndex(path, -1);
509 _fp->insertWayptAtIndex(toWp, -1);
510
511 return true;
512 }
513
514 void FlightPlanController::clearRoute()
515 {
516 _fp->clearAll();
517 }
518
519 QString FlightPlanController::icaoRoute() const
520 {
521 return QString::fromStdString(_fp->asICAORouteString());
522 }
523
524 void FlightPlanController::setEstimatedDurationMinutes(int mins)
525 {
526 if (_fp->estimatedDurationMinutes() == mins)
527 return;
528
529 _fp->setEstimatedDurationMinutes(mins);
530 emit infoChanged();
531 }
532
533 void FlightPlanController::computeDuration()
534 {
535 _fp->computeDurationMinutes();
536 emit infoChanged();
537 }
538
539 bool FlightPlanController::loadPlan()
540 {
541 auto settings = flightgear::getQSettings();
542 QString lastUsedDir = settings.value("flightplan-lastdir", "").toString();
543
544 QString file = QFileDialog::getOpenFileName(nullptr, tr("Load a flight-plan"),
545 lastUsedDir, "*.fgfp *.gpx");
546 if (file.isEmpty())
547 return false;
548
549 QFileInfo fi(file);
550 settings.setValue("flightplan-lastdir", fi.absolutePath());
551
552 return loadFromPath(file);
553 }
554
555 void FlightPlanController::savePlan()
556 {
557 auto settings = flightgear::getQSettings();
558 QString lastUsedDir = settings.value("flightplan-lastdir", "").toString();
559
560 QString file = QFileDialog::getSaveFileName(nullptr, tr("Save flight-plan"),
561 lastUsedDir, "*.fgfp");
562 if (file.isEmpty())
563 return;
564 if (!file.endsWith(".fgfp")) {
565 file += ".fgfp";
566 }
567
568 QFileInfo fi(file);
569 settings.setValue("flightplan-lastdir", fi.absolutePath());
570
571 saveToPath(file);
572 }
573
574 void FlightPlanController::setDeparture(QmlPositioned *apt)
575 {
576 if (!apt) {
577 _fp->clearDeparture();
578 } else {
579 if (apt->inner() == _fp->departureAirport())
580 return;
581
582 _fp->setDeparture(fgpositioned_cast<FGAirport>(apt->inner()));
583 }
584
585 emit infoChanged();
586 }
587
588 void FlightPlanController::setDestination(QmlPositioned *apt)
589 {
590 if (apt) {
591 if (apt->inner() == _fp->destinationAirport())
592 return;
593
594 _fp->setDestination(fgpositioned_cast<FGAirport>(apt->inner()));
595 } else {
596 _fp->clearDestination();
597
598 }
599 emit infoChanged();
600 }
601
602 void FlightPlanController::setAlternate(QmlPositioned *apt)
603 {
604 if (apt) {
605 if (apt->inner() == _fp->alternate())
606 return;
607
608 _fp->setAlternate(fgpositioned_cast<FGAirport>(apt->inner()));
609 } else {
610 _fp->setAlternate(nullptr);
611
612 }
613 emit infoChanged();
614 }
615
616 void FlightPlanController::setCruiseSpeed(QuantityValue speed)
617 {
618 switch (speed.unit) {
619 case Units::Mach: {
620 if (speed == QuantityValue(Units::Mach, _fp->cruiseSpeedMach())) {
621 return;
622 }
623
624 _fp->setCruiseSpeedMach(speed.value);
625 break;
626 }
627 case Units::Knots: {
628 const int knotsVal = static_cast<int>(speed.value);
629 if (_fp->cruiseSpeedKnots() == knotsVal) {
630 return;
631 }
632
633 _fp->setCruiseSpeedKnots(knotsVal);
634 break;
635 }
636 case Units::KilometersPerHour: {
637 const int kmhVal = static_cast<int>(speed.value);
638 if (_fp->cruiseSpeedKPH() == kmhVal) {
639 return;
640 }
641
642 _fp->setCruiseSpeedKPH(kmhVal);
643 break;
644 }
645 default:
646 qWarning() << "Unsupported cruise speed units" << speed.unit;
647 break;
648 }
649
650 emit infoChanged();
651 }