Add mission/drone profile sharing and importing, fix map not fitting to loaded mission

Sharing/Import (Doku 3.5/3.6), analog shareMission()/shareDrone() und den
importMissionInput/importDroneInput-Handlern im HTML-Demonstrator:

- services/sharing/mission_share_codec.dart, drone_share_codec.dart: reine
  Funktionen zum Bauen/Parsen des Export-JSON (appVersion/exportedAt-Umschlag),
  inkl. Erkennung einer abweichenden Hauptversion beim Import - vollstaendig
  unit-getestet ohne Plugin-Abhaengigkeit.
- services/database/waypoint_json_codec.dart: Waypoint-JSON-(De-)Serialisierung
  aus mission_repository.dart herausgezogen, damit Persistenz und Sharing
  exakt dasselbe Dateiformat verwenden statt es zu duplizieren.
- services/sharing/sharing_service.dart: duenne I/O-Schicht - schreibt eine
  temporaere Datei und oeffnet das native Share-Sheet (share_plus), bzw.
  liest eine vom Nutzer per Systemdialog ausgewaehlte JSON-Datei
  (file_picker). Als Klasse mit Instanzmethoden gehalten, damit sie sich in
  Tests durch einen Fake ersetzen laesst.
- ui/widgets/missions_drones_panel.dart: Share-Icon je Zeile, Import-Button
  im Toolbar beider Tabs.

Paket-Versionen bewusst gewaehlt: file_picker 11.0.2/share_plus 11.x wurden
zunaechst wegen einer win32-Konflikt-Aufloesung genutzt, kompilierten auf
diesem Projekt (AGP 9.0.1) aber nicht - file_picker < 12.0.0-beta.1 prueft
nur AGP-Version >= 9 und ueberspringt dann das Anwenden des Kotlin-Android-
Plugins, in der Annahme, AGPs eingebauter Kotlin-Support wuerde das
uebernehmen, was hier zu einem fehlenden compileReleaseKotlin-Task und
"Symbol nicht gefunden" fuehrte. file_picker >=12.0.0-beta.1 respektiert
zusaetzlich die bereits vom Flutter-Template gesetzte Gradle-Property
android.builtInKotlin=false und wendet das Plugin dann korrekt an -
file_picker auf ">=12.0.0-beta.1 <13.0.0" (share_plus zurueck auf ^13.3.0,
beide dann konsistent auf win32 ^6.x) gesetzt, um dies zu nutzen.

Zusaetzlich beim manuellen Durchtesten auf dem Pixel_10a-Emulator einen
zweiten, davon unabhaengigen Bug gefunden und behoben: CurrentMissionMeta-
Notifier.loadMission()/restoreLastSession() aktualisierten zwar Wegpunkte
und Missionsname, bewegten aber nie die Kartenkamera - eine geladene
Mission wurde dadurch mit falscher Kartenausschnitt angezeigt (Name/
Wegpunkte einer Stadt, Karte noch an der zuletzt betrachteten Stelle).
Fix: _fitMapToWaypoints() zentriert nach dem Laden auf die Bounding-Box
der Mission, analog der bereits vorhandenen _onFitPressed()-Logik in
MapSearchControls.

Getestet: 13 neue Unit-Tests fuer die Sharing-Codecs, 4 neue Widget-Tests
mit einem Fake-SharingService (kein echter Platform-Channel-Zugriff in
Tests). Alle 97 Tests sowie flutter analyze bestehen. Manuell auf dem
Pixel_10a-Emulator verifiziert: natives Share-Sheet oeffnet sich mit der
korrekten JSON-Datei, Datei-Import ueber den Systemdialog legt eine neue
Mission bzw. ein neues Drohnenprofil an, Kartensprung beim Laden einer
Mission funktioniert jetzt korrekt fuer sowohl manuelles Laden als auch
den Autosave-Restore beim App-Start.

Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
This commit is contained in:
Constantin Leue
2026-07-28 19:50:19 +02:00
co-authored by Claude Sonnet 5
parent b176ad294e
commit b51c6c16d5
14 changed files with 867 additions and 52 deletions
@@ -4,6 +4,7 @@ import 'package:drift/drift.dart';
import '../../domain/waypoint/flat_waypoint_list.dart';
import 'app_database.dart';
import 'waypoint_json_codec.dart';
/// Kopfzeilen-taugliche Zusammenfassung einer gespeicherten Mission, ohne
/// die komplette Wegpunktliste zu materialisieren (fuer die Missionsliste
@@ -28,11 +29,13 @@ class LoadedMission {
const LoadedMission({
required this.name,
required this.placeName,
required this.createdAt,
required this.waypoints,
});
final String name;
final String? placeName;
final DateTime createdAt;
final List<Waypoint> waypoints;
}
@@ -70,8 +73,9 @@ class MissionRepository {
return LoadedMission(
name: row.name,
placeName: row.location,
createdAt: row.createdAt,
waypoints: [
for (final entry in decoded) _waypointFromJson(entry as Map<String, dynamic>),
for (final entry in decoded) waypointFromJson(entry as Map<String, dynamic>),
],
);
}
@@ -85,7 +89,7 @@ class MissionRepository {
String? placeName,
required List<Waypoint> waypoints,
}) async {
final waypointsJson = jsonEncode([for (final w in waypoints) _waypointToJson(w)]);
final waypointsJson = jsonEncode([for (final w in waypoints) waypointToJson(w)]);
final companion = MissionsCompanion(
name: Value(name),
location: Value(placeName),
@@ -115,35 +119,4 @@ class MissionRepository {
Future<void> delete(int id) async {
await (_db.delete(_db.missions)..where((m) => m.id.equals(id))).go();
}
Map<String, dynamic> _waypointToJson(Waypoint w) => {
'lat': w.lat,
'lon': w.lon,
'altitudeM': w.altitudeM,
'speedMs': w.speedMs,
'catchRadiusM': w.catchRadiusM,
'action': w.action.name,
'jumpTargetIndex': w.jumpTargetIndex,
'jumpRepeatCount': w.jumpRepeatCount,
'windSpeedMs': w.windSpeedMs,
'windDirFromDeg': w.windDirFromDeg,
'windElevationM': w.windElevationM,
};
Waypoint _waypointFromJson(Map<String, dynamic> json) => Waypoint(
lat: (json['lat'] as num).toDouble(),
lon: (json['lon'] as num).toDouble(),
altitudeM: (json['altitudeM'] as num).toDouble(),
speedMs: (json['speedMs'] as num).toDouble(),
catchRadiusM: (json['catchRadiusM'] as num).toDouble(),
action: WaypointAction.values.firstWhere(
(a) => a.name == json['action'],
orElse: () => WaypointAction.none,
),
jumpTargetIndex: json['jumpTargetIndex'] as int?,
jumpRepeatCount: json['jumpRepeatCount'] as int?,
windSpeedMs: (json['windSpeedMs'] as num?)?.toDouble(),
windDirFromDeg: (json['windDirFromDeg'] as num?)?.toDouble(),
windElevationM: (json['windElevationM'] as num?)?.toDouble(),
);
}
@@ -0,0 +1,36 @@
import '../../domain/waypoint/flat_waypoint_list.dart';
/// JSON-(De-)Serialisierung fuer [Waypoint] - gemeinsam genutzt von der
/// Missions-Persistenz ([MissionRepository]) und dem Mission-Sharing
/// ([MissionShareCodec]), damit das Datei-Feldformat an beiden Stellen
/// garantiert identisch bleibt.
Map<String, dynamic> waypointToJson(Waypoint w) => {
'lat': w.lat,
'lon': w.lon,
'altitudeM': w.altitudeM,
'speedMs': w.speedMs,
'catchRadiusM': w.catchRadiusM,
'action': w.action.name,
'jumpTargetIndex': w.jumpTargetIndex,
'jumpRepeatCount': w.jumpRepeatCount,
'windSpeedMs': w.windSpeedMs,
'windDirFromDeg': w.windDirFromDeg,
'windElevationM': w.windElevationM,
};
Waypoint waypointFromJson(Map<String, dynamic> json) => Waypoint(
lat: (json['lat'] as num).toDouble(),
lon: (json['lon'] as num).toDouble(),
altitudeM: (json['altitudeM'] as num).toDouble(),
speedMs: (json['speedMs'] as num).toDouble(),
catchRadiusM: (json['catchRadiusM'] as num).toDouble(),
action: WaypointAction.values.firstWhere(
(a) => a.name == json['action'],
orElse: () => WaypointAction.none,
),
jumpTargetIndex: json['jumpTargetIndex'] as int?,
jumpRepeatCount: json['jumpRepeatCount'] as int?,
windSpeedMs: (json['windSpeedMs'] as num?)?.toDouble(),
windDirFromDeg: (json['windDirFromDeg'] as num?)?.toDouble(),
windElevationM: (json['windElevationM'] as num?)?.toDouble(),
);
@@ -0,0 +1,113 @@
import 'dart:convert';
import '../../app_info.dart';
import '../../domain/mission/drone_profile.dart';
/// Baut die Export-Datei fuer ein Drohnenprofil (Doku 3.5, analog
/// buildDroneExportObject()/shareDrone() im HTML-Demonstrator). Die id wird
/// bewusst nicht mitexportiert - beim Import entsteht immer ein neues,
/// eigenstaendiges Profil (siehe parseDroneImportJson()).
String buildDroneExportJson(DroneProfile profile) {
final map = {
'appVersion': kAppVersion,
'exportedAt': DateTime.now().toUtc().toIso8601String(),
'drone': {
'name': profile.name,
'minSpeed': profile.minSpeed,
'cruiseSpeed': profile.cruiseSpeed,
'maxSpeed': profile.maxSpeed,
'minTurnRadius': profile.minTurnRadius,
'loiterRadius': profile.loiterRadius,
'catchRadius': profile.catchRadius,
'maxClimbRate': profile.maxClimbRate,
'maxDescentRate': profile.maxDescentRate,
'maxRangeM': profile.maxRangeM,
'maxEnduranceMin': profile.maxEnduranceMin,
'maxAltitudeM': profile.maxAltitudeM,
},
};
return const JsonEncoder.withIndent(' ').convert(map);
}
/// Vorschlagsname fuer die geteilte Datei (Doku 3.5, analog
/// `'drone-' + safeName + '.json'` im HTML-Demonstrator).
String droneExportFilename(String name) {
final safeName = name.replaceAll(RegExp(r'[^a-zA-Z0-9]'), '_');
return 'drone-$safeName.json';
}
class ParsedDroneImport {
const ParsedDroneImport({required this.profile, this.versionMismatch});
final DroneProfile profile;
/// Enthaelt die appVersion der Datei, falls sie sich von [kAppVersion] in
/// der Hauptversionsnummer unterscheidet - sonst null.
final String? versionMismatch;
}
const _requiredNumericFields = [
'minSpeed',
'cruiseSpeed',
'maxSpeed',
'minTurnRadius',
'loiterRadius',
'catchRadius',
'maxClimbRate',
'maxDescentRate',
'maxRangeM',
'maxEnduranceMin',
'maxAltitudeM',
];
/// Parst eine importierte Drohnenprofil-Datei - wirft [FormatException] bei
/// ungueltigem JSON oder fehlenden Pflichtfeldern (Doku 3.5, analog dem
/// `change`-Handler von importDroneInput im HTML-Demonstrator).
ParsedDroneImport parseDroneImportJson(String jsonText) {
final Object? decoded;
try {
decoded = jsonDecode(jsonText);
} on FormatException {
throw const FormatException('Invalid drone profile file');
}
if (decoded is! Map<String, dynamic>) {
throw const FormatException('Invalid drone profile file');
}
final droneData = decoded['drone'] ?? decoded;
if (droneData is! Map<String, dynamic>) {
throw const FormatException('Invalid drone profile file');
}
final name = droneData['name'];
if (name is! String || name.isEmpty) {
throw const FormatException('File is not a valid drone profile');
}
for (final field in _requiredNumericFields) {
if (droneData[field] is! num) {
throw const FormatException('File is not a valid drone profile');
}
}
final profile = DroneProfile(
name: name,
minSpeed: (droneData['minSpeed'] as num).toDouble(),
cruiseSpeed: (droneData['cruiseSpeed'] as num).toDouble(),
maxSpeed: (droneData['maxSpeed'] as num).toDouble(),
minTurnRadius: (droneData['minTurnRadius'] as num).toDouble(),
loiterRadius: (droneData['loiterRadius'] as num).toDouble(),
catchRadius: (droneData['catchRadius'] as num).toDouble(),
maxClimbRate: (droneData['maxClimbRate'] as num).toDouble(),
maxDescentRate: (droneData['maxDescentRate'] as num).toDouble(),
maxRangeM: (droneData['maxRangeM'] as num).toDouble(),
maxEnduranceMin: (droneData['maxEnduranceMin'] as num).toDouble(),
maxAltitudeM: (droneData['maxAltitudeM'] as num).toDouble(),
);
final appVersion = decoded['appVersion'] as String?;
final mismatch = appVersion != null &&
appVersion.split('.').first != kAppVersion.split('.').first
? appVersion
: null;
return ParsedDroneImport(profile: profile, versionMismatch: mismatch);
}
@@ -0,0 +1,109 @@
import 'dart:convert';
import '../../app_info.dart';
import '../../domain/waypoint/flat_waypoint_list.dart';
import '../database/waypoint_json_codec.dart';
/// Missionsdaten fuer den Export - unabhaengig von der Drift-Zeilenklasse,
/// damit dieser Codec ohne Datenbankzugriff testbar bleibt.
class MissionExportData {
const MissionExportData({
required this.name,
this.placeName,
required this.createdAt,
required this.waypoints,
});
final String name;
final String? placeName;
final DateTime createdAt;
final List<Waypoint> waypoints;
}
/// Baut die Export-Datei fuer eine Mission (Doku 3.6, analog
/// buildMissionExportObject()/shareMission() im HTML-Demonstrator) - ein
/// mit `appVersion`/`exportedAt` umschlossenes JSON-Dokument, damit ein
/// Import spaeter erkennen kann, aus welcher App-Version die Datei stammt.
String buildMissionExportJson(MissionExportData mission) {
final map = {
'appVersion': kAppVersion,
'exportedAt': DateTime.now().toUtc().toIso8601String(),
'mission': {
'name': mission.name,
'placeName': mission.placeName,
'createdAt': mission.createdAt.toUtc().toIso8601String(),
'waypoints': [for (final w in mission.waypoints) waypointToJson(w)],
},
};
return const JsonEncoder.withIndent(' ').convert(map);
}
/// Vorschlagsname fuer die geteilte Datei (Doku 3.6, analog
/// `'mission-' + safeName + '.json'` im HTML-Demonstrator).
String missionExportFilename(String label) {
final safeName = label.replaceAll(RegExp(r'[^a-zA-Z0-9]'), '_');
return 'mission-$safeName.json';
}
class ParsedMissionImport {
const ParsedMissionImport({
required this.name,
this.placeName,
required this.waypoints,
this.versionMismatch,
});
final String name;
final String? placeName;
final List<Waypoint> waypoints;
/// Enthaelt die appVersion der Datei, falls sie sich von [kAppVersion] in
/// der Hauptversionsnummer unterscheidet - sonst null (analog der
/// "Imported from a different app version"-Warnung im HTML-Demonstrator).
final String? versionMismatch;
}
/// Parst eine importierte Missionsdatei - wirft [FormatException] bei
/// ungueltigem JSON oder fehlenden Wegpunkten (Doku 3.6, analog dem
/// `change`-Handler von importMissionInput im HTML-Demonstrator).
ParsedMissionImport parseMissionImportJson(String jsonText) {
final Object? decoded;
try {
decoded = jsonDecode(jsonText);
} on FormatException {
throw const FormatException('Invalid mission file');
}
if (decoded is! Map<String, dynamic>) {
throw const FormatException('Invalid mission file');
}
final missionData = decoded['mission'] ?? decoded;
if (missionData is! Map<String, dynamic>) {
throw const FormatException('Invalid mission file');
}
final waypointsRaw = missionData['waypoints'];
if (waypointsRaw is! List || waypointsRaw.isEmpty) {
throw const FormatException('File has no waypoints');
}
final waypoints = [
for (final w in waypointsRaw) waypointFromJson(w as Map<String, dynamic>),
];
final name = (missionData['name'] as String?) ??
(missionData['placeName'] as String?) ??
'Imported mission';
final placeName =
(missionData['placeName'] as String?) ?? (missionData['name'] as String?);
final appVersion = decoded['appVersion'] as String?;
final mismatch = appVersion != null &&
appVersion.split('.').first != kAppVersion.split('.').first
? appVersion
: null;
return ParsedMissionImport(
name: name,
placeName: placeName,
waypoints: waypoints,
versionMismatch: mismatch,
);
}
@@ -0,0 +1,49 @@
import 'dart:convert';
import 'dart:io';
import 'package:file_picker/file_picker.dart';
import 'package:path_provider/path_provider.dart';
import 'package:share_plus/share_plus.dart';
/// Kapselt die plattformseitige Ein-/Ausgabe fuer das Teilen/Importieren von
/// Missionen und Drohnenprofilen (Doku 3.5/3.6): schreibt eine JSON-Datei in
/// ein temporaeres Verzeichnis und oeffnet das native Share-Sheet (analog
/// navigator.share() im HTML-Demonstrator), bzw. liest eine vom Nutzer
/// ausgewaehlte JSON-Datei ein (analog dem versteckten `<input type=file>`).
///
/// Bewusst als Klasse mit Instanzmethoden (nicht als statische Aufrufe der
/// Plugins direkt) gehalten, damit sie sich ueber einen Riverpod-Provider
/// durch einen Test-Doppelgaenger ersetzen laesst, ohne echte Platform-
/// Channels anzusprechen.
class SharingService {
const SharingService();
/// Schreibt [json] in eine temporaere Datei namens [filename] und oeffnet
/// das native Share-Sheet dafuer. Es gibt bewusst keinen Blob-/Download-
/// Fallback wie im HTML-Demonstrator - auf Android ist `share_plus`
/// immer verfuegbar.
Future<void> shareJsonFile({
required String json,
required String filename,
required String shareTitle,
}) async {
final dir = await getTemporaryDirectory();
final file = File('${dir.path}/$filename');
await file.writeAsString(json);
await SharePlus.instance.share(
ShareParams(files: [XFile(file.path)], title: shareTitle),
);
}
/// Oeffnet den nativen Dateiauswahl-Dialog fuer eine `.json`-Datei und
/// gibt deren Textinhalt zurueck - null, wenn der Nutzer abgebrochen hat.
Future<String?> pickJsonFileText() async {
final result = await FilePicker.pickFiles(
type: FileType.custom,
allowedExtensions: ['json'],
);
if (result == null || result.files.isEmpty) return null;
final bytes = await result.files.first.readAsBytes();
return utf8.decode(bytes);
}
}