PlanMasterController.cc 25.2 KB
Newer Older
1 2
/****************************************************************************
 *
3
 * (c) 2009-2020 QGROUNDCONTROL PROJECT <http://www.qgroundcontrol.org>
4 5 6 7 8 9 10 11
 *
 * QGroundControl is licensed according to the terms in the file
 * COPYING.md in the root of the source code directory.
 *
 ****************************************************************************/

#include "PlanMasterController.h"
#include "AppSettings.h"
12 13
#include "BlankPlanCreator.h"
#include "CorridorScanPlanCreator.h"
14
#include "JsonHelper.h"
15
#include "KMLPlanDomDocument.h"
16 17 18 19 20 21
#include "MeasurementPlanCreator.h"
#include "MissionManager.h"
#include "MultiVehicleManager.h"
#include "QGCApplication.h"
#include "QGCCorePlugin.h"
#include "SettingsManager.h"
22
#include "StructureScanPlanCreator.h"
23
#include "SurveyPlanCreator.h"
24 25 26
#if defined(QGC_AIRMAP_ENABLED)
#include "AirspaceFlightPlanProvider.h"
#endif
27

28
#include <QDomDocument>
Don Gagne's avatar
Don Gagne committed
29
#include <QFileInfo>
30
#include <QJsonDocument>
31

DonLakeFlyer's avatar
DonLakeFlyer committed
32 33
QGC_LOGGING_CATEGORY(PlanMasterControllerLog, "PlanMasterControllerLog")

34 35 36 37 38
const int PlanMasterController::kPlanFileVersion = 1;
const char *PlanMasterController::kPlanFileType = "Plan";
const char *PlanMasterController::kJsonMissionObjectKey = "mission";
const char *PlanMasterController::kJsonGeoFenceObjectKey = "geoFence";
const char *PlanMasterController::kJsonRallyPointsObjectKey = "rallyPoints";
39

40 41 42 43 44 45 46 47 48
PlanMasterController::PlanMasterController(QObject *parent)
    : QObject(parent),
      _multiVehicleMgr(qgcApp()->toolbox()->multiVehicleManager()),
      _controllerVehicle(
          new Vehicle(Vehicle::MAV_AUTOPILOT_TRACK, Vehicle::MAV_TYPE_TRACK,
                      qgcApp()->toolbox()->firmwarePluginManager(), this)),
      _managerVehicle(_controllerVehicle), _missionController(this),
      _geoFenceController(this), _rallyPointController(this) {
  _commonInit();
49 50 51
}

#ifdef QT_DEBUG
52 53 54 55 56 57 58 59 60 61 62
PlanMasterController::PlanMasterController(MAV_AUTOPILOT firmwareType,
                                           MAV_TYPE vehicleType,
                                           QObject *parent)
    : QObject(parent),
      _multiVehicleMgr(qgcApp()->toolbox()->multiVehicleManager()),
      _controllerVehicle(
          new Vehicle(firmwareType, vehicleType,
                      qgcApp()->toolbox()->firmwarePluginManager())),
      _managerVehicle(_controllerVehicle), _missionController(this),
      _geoFenceController(this), _rallyPointController(this) {
  _commonInit();
63 64 65
}
#endif

66 67 68 69 70 71 72
void PlanMasterController::_commonInit(void) {
  connect(&_missionController, &MissionController::dirtyChanged, this,
          &PlanMasterController::dirtyChanged);
  connect(&_geoFenceController, &GeoFenceController::dirtyChanged, this,
          &PlanMasterController::dirtyChanged);
  connect(&_rallyPointController, &RallyPointController::dirtyChanged, this,
          &PlanMasterController::dirtyChanged);
73

74 75 76 77 78 79
  connect(&_missionController, &MissionController::containsItemsChanged, this,
          &PlanMasterController::containsItemsChanged);
  connect(&_geoFenceController, &GeoFenceController::containsItemsChanged, this,
          &PlanMasterController::containsItemsChanged);
  connect(&_rallyPointController, &RallyPointController::containsItemsChanged,
          this, &PlanMasterController::containsItemsChanged);
80

81 82 83 84 85 86
  connect(&_missionController, &MissionController::syncInProgressChanged, this,
          &PlanMasterController::syncInProgressChanged);
  connect(&_geoFenceController, &GeoFenceController::syncInProgressChanged,
          this, &PlanMasterController::syncInProgressChanged);
  connect(&_rallyPointController, &RallyPointController::syncInProgressChanged,
          this, &PlanMasterController::syncInProgressChanged);
87

88 89 90
  // Offline vehicle can change firmware/vehicle type
  connect(_controllerVehicle, &Vehicle::vehicleTypeChanged, this,
          &PlanMasterController::_updatePlanCreatorsList);
91 92
}

93
PlanMasterController::~PlanMasterController() {}
94

95 96 97 98
void PlanMasterController::start(void) {
  _missionController.start(_flyView);
  _geoFenceController.start(_flyView);
  _rallyPointController.start(_flyView);
99

100 101 102
  _activeVehicleChanged(_multiVehicleMgr->activeVehicle());
  connect(_multiVehicleMgr, &MultiVehicleManager::activeVehicleChanged, this,
          &PlanMasterController::_activeVehicleChanged);
103

104
  _updatePlanCreatorsList();
105 106

#if defined(QGC_AIRMAP_ENABLED)
107 108 109 110 111 112 113 114 115
  //-- This assumes there is one single instance of PlanMasterController in edit
  //mode.
  if (!flyView) {
    // Wait for signal confirming AirMap client connection before starting
    // flight planning
    connect(qgcApp()->toolbox()->airspaceManager(),
            &AirspaceManager::connectStatusChanged, this,
            &PlanMasterController::_startFlightPlanning);
  }
116
#endif
117 118
}

119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193
void PlanMasterController::startStaticActiveVehicle(
    Vehicle *vehicle, bool deleteWhenSendCompleted) {
  _flyView = true;
  _deleteWhenSendCompleted = deleteWhenSendCompleted;
  _missionController.start(_flyView);
  _geoFenceController.start(_flyView);
  _rallyPointController.start(_flyView);
  _activeVehicleChanged(vehicle);
}

void PlanMasterController::_activeVehicleChanged(Vehicle *activeVehicle) {
  if (_managerVehicle == activeVehicle) {
    // We are already setup for this vehicle
    return;
  }

  qCDebug(PlanMasterControllerLog) << "_activeVehicleChanged" << activeVehicle;

  if (_managerVehicle) {
    // Disconnect old vehicle. Be careful of wildcarding disconnect too much
    // since _managerVehicle may equal _controllerVehicle
    disconnect(_managerVehicle->missionManager(), nullptr, nullptr, nullptr);
    disconnect(_managerVehicle->geoFenceManager(), nullptr, nullptr, nullptr);
    disconnect(_managerVehicle->rallyPointManager(), nullptr, nullptr, nullptr);
  }

  bool newOffline = false;
  if (activeVehicle == nullptr) {
    // Since there is no longer an active vehicle we use the offline controller
    // vehicle as the manager vehicle
    _managerVehicle = _controllerVehicle;
    newOffline = true;
  } else {
    newOffline = false;
    _managerVehicle = activeVehicle;

    // Update controllerVehicle to the currently connected vehicle
    AppSettings *appSettings =
        qgcApp()->toolbox()->settingsManager()->appSettings();
    appSettings->offlineEditingFirmwareClass()->setRawValue(
        QGCMAVLink::firmwareClass(_managerVehicle->firmwareType()));
    appSettings->offlineEditingVehicleClass()->setRawValue(
        QGCMAVLink::vehicleClass(_managerVehicle->vehicleType()));

    // We use these signals to sequence upload and download to the multiple
    // controller/managers
    connect(_managerVehicle->missionManager(),
            &MissionManager::newMissionItemsAvailable, this,
            &PlanMasterController::_loadMissionComplete);
    connect(_managerVehicle->geoFenceManager(), &GeoFenceManager::loadComplete,
            this, &PlanMasterController::_loadGeoFenceComplete);
    connect(_managerVehicle->rallyPointManager(),
            &RallyPointManager::loadComplete, this,
            &PlanMasterController::_loadRallyPointsComplete);
    connect(_managerVehicle->missionManager(), &MissionManager::sendComplete,
            this, &PlanMasterController::_sendMissionComplete);
    connect(_managerVehicle->geoFenceManager(), &GeoFenceManager::sendComplete,
            this, &PlanMasterController::_sendGeoFenceComplete);
    connect(_managerVehicle->rallyPointManager(),
            &RallyPointManager::sendComplete, this,
            &PlanMasterController::_sendRallyPointsComplete);
  }

  _offline = newOffline;
  emit offlineChanged(offline());
  emit managerVehicleChanged(_managerVehicle);

  if (_flyView) {
    // We are in the Fly View
    if (newOffline) {
      // No active vehicle, clear mission
      qCDebug(PlanMasterControllerLog)
          << "_activeVehicleChanged: Fly View - No active vehicle, clearing "
             "stale plan";
      removeAll();
194
    } else {
195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214
      // Fly view has changed to a new active vehicle, update to show correct
      // mission
      qCDebug(PlanMasterControllerLog)
          << "_activeVehicleChanged: Fly View - New active vehicle, loading "
             "new plan from manager vehicle";
      _showPlanFromManagerVehicle();
    }
  } else {
    // We are in the Plan view.
    if (containsItems()) {
      // The plan view has a stale plan in it
      if (dirty()) {
        // Plan is dirty, the user must decide what to do in all cases
        qCDebug(PlanMasterControllerLog)
            << "_activeVehicleChanged: Plan View - Previous dirty plan exists, "
               "no new active vehicle, sending "
               "promptForPlanUsageOnVehicleChange signal";
        emit promptForPlanUsageOnVehicleChange();
      } else {
        // Plan is not dirty
215
        if (newOffline) {
216 217 218 219 220
          // The active vehicle went away with no new active vehicle
          qCDebug(PlanMasterControllerLog)
              << "_activeVehicleChanged: Plan View - Previous clean plan "
                 "exists, no new active vehicle, clear stale plan";
          removeAll();
DonLakeFlyer's avatar
DonLakeFlyer committed
221
        } else {
222 223 224 225 226 227
          // We are transitioning from one active vehicle to another. Show the
          // plan from the new vehicle.
          qCDebug(PlanMasterControllerLog)
              << "_activeVehicleChanged: Plan View - Previous clean plan "
                 "exists, new active vehicle, loading from new manager vehicle";
          _showPlanFromManagerVehicle();
DonLakeFlyer's avatar
DonLakeFlyer committed
228
        }
229
      }
230
    } else {
231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292
      // There is no previous Plan in the view
      if (newOffline) {
        // Nothing special to do in this case
        qCDebug(PlanMasterControllerLog)
            << "_activeVehicleChanged: Plan View - No previous plan, no longer "
               "connected to vehicle, nothing to do";
      } else {
        // Just show the plan from the new vehicle
        qCDebug(PlanMasterControllerLog)
            << "_activeVehicleChanged: Plan View - No previous plan, new "
               "active vehicle, loading from new manager vehicle";
        _showPlanFromManagerVehicle();
      }
    }
  }

  // Vehicle changed so we need to signal everything
  emit containsItemsChanged(containsItems());
  emit syncInProgressChanged();
  emit dirtyChanged(dirty());

  _updatePlanCreatorsList();
}

void PlanMasterController::loadFromVehicle(void) {
  if (_managerVehicle->vehicleLinkManager()
          ->primaryLink()
          ->linkConfiguration()
          ->isHighLatency()) {
    qgcApp()->showAppMessage(
        tr("Download not supported on high latency links."));
    return;
  }

  if (offline()) {
    qCWarning(PlanMasterControllerLog)
        << "PlanMasterController::loadFromVehicle called while offline";
  } else if (_flyView) {
    qCWarning(PlanMasterControllerLog)
        << "PlanMasterController::loadFromVehicle called from Fly view";
  } else if (syncInProgress()) {
    qCWarning(PlanMasterControllerLog)
        << "PlanMasterController::loadFromVehicle called while syncInProgress";
  } else {
    _loadGeoFence = true;
    qCDebug(PlanMasterControllerLog)
        << "PlanMasterController::loadFromVehicle calling "
           "_missionController.loadFromVehicle";
    _missionController.loadFromVehicle();
    setDirty(false);
  }
}

void PlanMasterController::_loadMissionComplete(void) {
  if (!_flyView && _loadGeoFence) {
    _loadGeoFence = false;
    _loadRallyPoints = true;
    if (_geoFenceController.supported()) {
      qCDebug(PlanMasterControllerLog)
          << "PlanMasterController::_loadMissionComplete calling "
             "_geoFenceController.loadFromVehicle";
      _geoFenceController.loadFromVehicle();
DonLakeFlyer's avatar
DonLakeFlyer committed
293
    } else {
294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317
      qCDebug(PlanMasterControllerLog)
          << "PlanMasterController::_loadMissionComplete GeoFence not "
             "supported skipping";
      _geoFenceController.removeAll();
      _loadGeoFenceComplete();
    }
    setDirty(false);
  }
}

void PlanMasterController::_loadGeoFenceComplete(void) {
  if (!_flyView && _loadRallyPoints) {
    _loadRallyPoints = false;
    if (_rallyPointController.supported()) {
      qCDebug(PlanMasterControllerLog)
          << "PlanMasterController::_loadGeoFenceComplete calling "
             "_rallyPointController.loadFromVehicle";
      _rallyPointController.loadFromVehicle();
    } else {
      qCDebug(PlanMasterControllerLog)
          << "PlanMasterController::_loadMissionComplete Rally Points not "
             "supported skipping";
      _rallyPointController.removeAll();
      _loadRallyPointsComplete();
DonLakeFlyer's avatar
DonLakeFlyer committed
318
    }
319 320
    setDirty(false);
  }
DonLakeFlyer's avatar
DonLakeFlyer committed
321 322
}

323 324 325
void PlanMasterController::_loadRallyPointsComplete(void) {
  qCDebug(PlanMasterControllerLog)
      << "PlanMasterController::_loadRallyPointsComplete";
DonLakeFlyer's avatar
DonLakeFlyer committed
326 327
}

328 329 330 331 332 333 334 335 336 337 338 339
void PlanMasterController::_sendMissionComplete(void) {
  if (_sendGeoFence) {
    _sendGeoFence = false;
    _sendRallyPoints = true;
    if (_geoFenceController.supported()) {
      qCDebug(PlanMasterControllerLog)
          << "PlanMasterController::sendToVehicle start GeoFence sendToVehicle";
      _geoFenceController.sendToVehicle();
    } else {
      qCDebug(PlanMasterControllerLog) << "PlanMasterController::sendToVehicle "
                                          "GeoFence not supported skipping";
      _sendGeoFenceComplete();
340
    }
341 342
    setDirty(false);
  }
343 344
}

345 346 347 348 349 350 351 352 353 354 355
void PlanMasterController::_sendGeoFenceComplete(void) {
  if (_sendRallyPoints) {
    _sendRallyPoints = false;
    if (_rallyPointController.supported()) {
      qCDebug(PlanMasterControllerLog)
          << "PlanMasterController::sendToVehicle start rally sendToVehicle";
      _rallyPointController.sendToVehicle();
    } else {
      qCDebug(PlanMasterControllerLog) << "PlanMasterController::sendToVehicle "
                                          "Rally Points not support skipping";
      _sendRallyPointsComplete();
356
    }
357
  }
358 359
}

360 361 362 363 364 365
void PlanMasterController::_sendRallyPointsComplete(void) {
  qCDebug(PlanMasterControllerLog)
      << "PlanMasterController::sendToVehicle Rally Point send complete";
  if (_deleteWhenSendCompleted) {
    this->deleteLater();
  }
DonLakeFlyer's avatar
DonLakeFlyer committed
366 367
}

368 369
#if defined(QGC_AIRMAP_ENABLED)
void PlanMasterController::_startFlightPlanning(void) {
370 371 372 373 374 375 376
  if (qgcApp()->toolbox()->airspaceManager()->connected()) {
    qCDebug(PlanMasterControllerLog)
        << "PlanMasterController::_startFlightPlanning client connected, start "
           "flight planning";
    qgcApp()->toolbox()->airspaceManager()->flightPlan()->startFlightPlanning(
        this);
  }
377 378 379
}
#endif

380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460
void PlanMasterController::sendToVehicle(void) {
  if (_managerVehicle->vehicleLinkManager()
          ->primaryLink()
          ->linkConfiguration()
          ->isHighLatency()) {
    qgcApp()->showAppMessage(tr("Upload not supported on high latency links."));
    return;
  }

  if (offline()) {
    qCWarning(PlanMasterControllerLog)
        << "PlanMasterController::sendToVehicle called while offline";
  } else if (syncInProgress()) {
    qCWarning(PlanMasterControllerLog)
        << "PlanMasterController::sendToVehicle called while syncInProgress";
  } else {
    qCDebug(PlanMasterControllerLog)
        << "PlanMasterController::sendToVehicle start mission sendToVehicle";
    _sendGeoFence = true;
    _missionController.sendToVehicle();
    setDirty(false);
  }
}

void PlanMasterController::loadFromFile(const QString &filename) {
  QString errorString;
  QString errorMessage =
      tr("Error loading Plan file (%1). %2").arg(filename).arg("%1");

  if (filename.isEmpty()) {
    return;
  }

  QFileInfo fileInfo(filename);
  QFile file(filename);

  if (!file.open(QIODevice::ReadOnly | QIODevice::Text)) {
    errorString = file.errorString() + QStringLiteral(" ") + filename;
    qgcApp()->showAppMessage(errorMessage.arg(errorString));
    return;
  }

  bool success = false;
  if (fileInfo.suffix() == AppSettings::planFileExtension) {
    QJsonDocument jsonDoc;
    QByteArray bytes = file.readAll();

    if (!JsonHelper::isJsonFile(bytes, jsonDoc, errorString)) {
      qgcApp()->showAppMessage(errorMessage.arg(errorString));
      return;
    }

    QJsonObject json = jsonDoc.object();
    //-- Allow plugins to pre process the load
    qgcApp()->toolbox()->corePlugin()->preLoadFromJson(this, json);

    int version;
    if (!JsonHelper::validateExternalQGCJsonFile(
            json, kPlanFileType, kPlanFileVersion, kPlanFileVersion, version,
            errorString)) {
      qgcApp()->showAppMessage(errorMessage.arg(errorString));
      return;
    }

    QList<JsonHelper::KeyValidateInfo> rgKeyInfo = {
        {kJsonMissionObjectKey, QJsonValue::Object, true},
        {kJsonGeoFenceObjectKey, QJsonValue::Object, true},
        {kJsonRallyPointsObjectKey, QJsonValue::Object, true},
    };
    if (!JsonHelper::validateKeys(json, rgKeyInfo, errorString)) {
      qgcApp()->showAppMessage(errorMessage.arg(errorString));
      return;
    }

    if (!_missionController.load(json[kJsonMissionObjectKey].toObject(),
                                 errorString) ||
        !_geoFenceController.load(json[kJsonGeoFenceObjectKey].toObject(),
                                  errorString) ||
        !_rallyPointController.load(json[kJsonRallyPointsObjectKey].toObject(),
                                    errorString)) {
      qgcApp()->showAppMessage(errorMessage.arg(errorString));
DonLakeFlyer's avatar
DonLakeFlyer committed
461
    } else {
462 463 464
      //-- Allow plugins to post process the load
      qgcApp()->toolbox()->corePlugin()->postLoadFromJson(this, json);
      success = true;
465
    }
466 467 468
  } else if (fileInfo.suffix() == AppSettings::missionFileExtension) {
    if (!_missionController.loadJsonFile(file, errorString)) {
      qgcApp()->showAppMessage(errorMessage.arg(errorString));
469
    } else {
470
      success = true;
471
    }
472 473 474 475
  } else if (fileInfo.suffix() == AppSettings::waypointsFileExtension ||
             fileInfo.suffix() == QStringLiteral("txt")) {
    if (!_missionController.loadTextFile(file, errorString)) {
      qgcApp()->showAppMessage(errorMessage.arg(errorString));
476
    } else {
477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540
      success = true;
    }
  } else {
    //-- TODO: What then?
  }

  if (success) {
    _currentPlanFile =
        QString::asprintf("%s/%s.%s", fileInfo.path().toLocal8Bit().data(),
                          fileInfo.completeBaseName().toLocal8Bit().data(),
                          AppSettings::planFileExtension);
  } else {
    _currentPlanFile.clear();
  }
  emit currentPlanFileChanged();

  if (!offline()) {
    setDirty(true);
  }
}

QJsonDocument PlanMasterController::saveToJson() {
  QJsonObject planJson;
  qgcApp()->toolbox()->corePlugin()->preSaveToJson(this, planJson);
  QJsonObject missionJson;
  QJsonObject fenceJson;
  QJsonObject rallyJson;
  JsonHelper::saveQGCJsonFileHeader(planJson, kPlanFileType, kPlanFileVersion);
  //-- Allow plugin to preemptly add its own keys to mission
  qgcApp()->toolbox()->corePlugin()->preSaveToMissionJson(this, missionJson);
  _missionController.save(missionJson);
  //-- Allow plugin to add its own keys to mission
  qgcApp()->toolbox()->corePlugin()->postSaveToMissionJson(this, missionJson);
  _geoFenceController.save(fenceJson);
  _rallyPointController.save(rallyJson);
  planJson[kJsonMissionObjectKey] = missionJson;
  planJson[kJsonGeoFenceObjectKey] = fenceJson;
  planJson[kJsonRallyPointsObjectKey] = rallyJson;
  qgcApp()->toolbox()->corePlugin()->postSaveToJson(this, planJson);
  return QJsonDocument(planJson);
}

void PlanMasterController::saveToCurrent() {
  if (!_currentPlanFile.isEmpty()) {
    saveToFile(_currentPlanFile);
  }
}

void PlanMasterController::saveToFile(const QString &filename) {
  if (filename.isEmpty()) {
    return;
  }

  QString planFilename = filename;
  if (!QFileInfo(filename).fileName().contains(".")) {
    planFilename += QString(".%1").arg(fileExtension());
  }

  QFile file(planFilename);

  if (!file.open(QIODevice::WriteOnly | QIODevice::Text)) {
    qgcApp()->showAppMessage(
        tr("Plan save error %1 : %2").arg(filename).arg(file.errorString()));
    _currentPlanFile.clear();
541
    emit currentPlanFileChanged();
542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591
  } else {
    QJsonDocument saveDoc = saveToJson();
    file.write(saveDoc.toJson());
    if (_currentPlanFile != planFilename) {
      _currentPlanFile = planFilename;
      emit currentPlanFileChanged();
    }
  }

  // Only clear dirty bit if we are offline
  if (offline()) {
    setDirty(false);
  }
}

void PlanMasterController::saveToKml(const QString &filename) {
  if (filename.isEmpty()) {
    return;
  }

  QString kmlFilename = filename;
  if (!QFileInfo(filename).fileName().contains(".")) {
    kmlFilename += QString(".%1").arg(kmlFileExtension());
  }

  QFile file(kmlFilename);

  if (!file.open(QIODevice::WriteOnly | QIODevice::Text)) {
    qgcApp()->showAppMessage(
        tr("KML save error %1 : %2").arg(filename).arg(file.errorString()));
  } else {
    KMLPlanDomDocument planKML;
    _missionController.addMissionToKML(planKML);
    QTextStream stream(&file);
    stream << planKML.toString();
    file.close();
  }
}

void PlanMasterController::removeAll(void) {
  _missionController.removeAll();
  _geoFenceController.removeAll();
  _rallyPointController.removeAll();
  if (_offline) {
    _missionController.setDirty(false);
    _geoFenceController.setDirty(false);
    _rallyPointController.setDirty(false);
    _currentPlanFile.clear();
    emit currentPlanFileChanged();
  }
592 593
}

594 595 596 597 598
void PlanMasterController::removeAllFromVehicle(void) {
  if (!offline()) {
    _missionController.removeAllFromVehicle();
    if (_geoFenceController.supported()) {
      _geoFenceController.removeAllFromVehicle();
599
    }
600 601
    if (_rallyPointController.supported()) {
      _rallyPointController.removeAllFromVehicle();
602
    }
603 604 605 606 607
    setDirty(false);
  } else {
    qWarning()
        << "PlanMasterController::removeAllFromVehicle called while offline";
  }
608 609
}

610 611 612 613
bool PlanMasterController::containsItems(void) const {
  return _missionController.containsItems() ||
         _geoFenceController.containsItems() ||
         _rallyPointController.containsItems();
614 615
}

616 617 618
bool PlanMasterController::dirty(void) const {
  return _missionController.dirty() || _geoFenceController.dirty() ||
         _rallyPointController.dirty();
619 620
}

621 622 623 624
void PlanMasterController::setDirty(bool dirty) {
  _missionController.setDirty(dirty);
  _geoFenceController.setDirty(dirty);
  _rallyPointController.setDirty(dirty);
625 626
}

627 628
QString PlanMasterController::fileExtension(void) const {
  return AppSettings::planFileExtension;
629 630
}

631 632
QString PlanMasterController::kmlFileExtension(void) const {
  return AppSettings::kmlFileExtension;
633 634
}

635 636
QStringList PlanMasterController::loadNameFilters(void) const {
  QStringList filters;
637

638 639 640 641 642 643 644
  filters << tr("Supported types (*.%1 *.%2 *.%3 *.%4)")
                 .arg(AppSettings::planFileExtension)
                 .arg(AppSettings::missionFileExtension)
                 .arg(AppSettings::waypointsFileExtension)
                 .arg("txt")
          << tr("All Files (*.*)");
  return filters;
645 646
}

647 648
QStringList PlanMasterController::saveNameFilters(void) const {
  QStringList filters;
649

650 651 652
  filters << tr("Plan Files (*.%1)").arg(fileExtension())
          << tr("All Files (*.*)");
  return filters;
653 654
}

655 656 657 658 659 660 661 662
void PlanMasterController::sendPlanToVehicle(Vehicle *vehicle,
                                             const QString &filename) {
  // Use a transient PlanMasterController to accomplish this
  PlanMasterController *controller = new PlanMasterController();
  controller->startStaticActiveVehicle(vehicle,
                                       true /* deleteWhenSendCompleted */);
  controller->loadFromFile(filename);
  controller->sendToVehicle();
663
}
DonLakeFlyer's avatar
DonLakeFlyer committed
664

665 666 667 668 669 670
void PlanMasterController::_showPlanFromManagerVehicle(void) {
  if (!_managerVehicle->initialPlanRequestComplete() && !syncInProgress()) {
    // Something went wrong with initial load. All controllers are idle, so just
    // force it off
    _managerVehicle->forceInitialPlanRequestComplete();
  }
671

672 673 674 675 676
  // The crazy if structure is to handle the load propagating by itself through
  // the system
  if (!_missionController.showPlanFromManagerVehicle()) {
    if (!_geoFenceController.showPlanFromManagerVehicle()) {
      _rallyPointController.showPlanFromManagerVehicle();
DonLakeFlyer's avatar
DonLakeFlyer committed
677
    }
678
  }
DonLakeFlyer's avatar
DonLakeFlyer committed
679
}
680

681 682 683 684
bool PlanMasterController::syncInProgress(void) const {
  return _missionController.syncInProgress() ||
         _geoFenceController.syncInProgress() ||
         _rallyPointController.syncInProgress();
685
}
686

687 688 689
bool PlanMasterController::isEmpty(void) const {
  return _missionController.isEmpty() && _geoFenceController.isEmpty() &&
         _rallyPointController.isEmpty();
690 691
}

692 693 694 695 696 697 698 699 700
void PlanMasterController::_updatePlanCreatorsList(void) {
  if (!_flyView) {
    if (!_planCreators) {
      _planCreators = new QmlObjectListModel(this);
      _planCreators->append(new BlankPlanCreator(this, this));
      _planCreators->append(new SurveyPlanCreator(this, this));
      _planCreators->append(new CorridorScanPlanCreator(this, this));
      _planCreators->append(new MeasurementPlanCreator(this, this));
      emit planCreatorsChanged(_planCreators);
701 702
    }

703 704 705 706
    if (_managerVehicle->fixedWing()) {
      if (_planCreators->count() == 5) {
        _planCreators->removeAt(_planCreators->count() - 1);
      }
707
    } else {
708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728
      if (_planCreators->count() != 5) {
        _planCreators->append(new StructureScanPlanCreator(this, this));
      }
    }
  }
}

void PlanMasterController::showPlanFromManagerVehicle(void) {
  if (offline()) {
    // There is no new vehicle so clear any previous plan
    qCDebug(PlanMasterControllerLog)
        << "showPlanFromManagerVehicle: Plan View - No new vehicle, clear any "
           "previous plan";
    removeAll();
  } else {
    // We have a new active vehicle, show the plan from that
    qCDebug(PlanMasterControllerLog)
        << "showPlanFromManagerVehicle: Plan View - New vehicle available, "
           "show plan from new manager vehicle";
    _showPlanFromManagerVehicle();
  }
729
}