From c182e7690d6d224b71d686e739ac31a042c9c585 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Thomas=20M=C3=BCller?= <1005065+DeepDiver1975@users.noreply.github.com> Date: Fri, 20 Nov 2026 00:04:13 +0100 Subject: [PATCH 1/7] =?UTF-8?q?feat(lagekarte):=20load=20Luftbild=20and=20?= =?UTF-8?q?Flurst=C3=BCcksgrenzen=20from=20the=20LDBV=20as=20Kartenebenen?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit LUFTBILD LADEN in the EBENEN panel asks the Bayerische Vermessungsverwaltung's open WMS services (geoservices.bayern.de, CC BY 4.0, no key) for the DOP40 Luftbild and the Parzellarkarte's Flurstücksgrenzen of the visible map section, capped at 4096 px a side at 0.6 Web-Mercator metres per pixel (about 1.6 km on the ground, scale about 1:2150, under the Parzellarkarte's 1:5000 limit). Both pictures become raster Kartenebenen stored in the Einsatz, so they sync, work offline and keep the licence line they were downloaded under. - Domain: MapOverlay gains Kind (Vector/Raster), Bounds (GeoBox) and Attribution; a raster Ebene takes only JPEG or PNG and needs a box. - Persistence: migration V46 adds kind, west/south/east/north and attribution to map_overlays, declared in SchemaGuard. - Sync: addMapOverlay and the snapshot carry the new fields; protocol and floor rise to 44, because a 43 peer refuses the image type or would read the picture as GeoJSON. - AppLogic: LdbvImageryClient (size-capped, image type and header checked, ServiceException turned into German text), LuftbildArea, and a header check that refuses a picture too large to decode before anything does. - App.Shared: the map draws the pictures between the tiles and the terrain, decoded off the UI thread; the attribution line names the LDBV while one is shown. The PDF leaves the pictures out. Co-Authored-By: Claude Opus 5.5 Signed-off-by: Thomas Müller <1005065+DeepDiver1975@users.noreply.github.com> --- changelog.d/+lagekarte-luftbild.added.md | 1 + docs/datenschutz-und-sicherheit.md | 13 +- src/LageBuch.App.Android/MainActivity.cs | 3 +- src/LageBuch.App.Shared/CompositionRoot.cs | 5 +- .../Controls/MapCanvasControl.cs | 37 ++- .../Controls/MapDrawing.cs | 54 +++- .../Controls/RasterOverlayCache.cs | 114 +++++++ .../Views/LagekarteView.axaml | 24 +- .../Views/LagekarteView.axaml.cs | 9 + src/LageBuch.App/Program.cs | 3 +- .../Services/Map/LdbvImageryClient.cs | 153 +++++++++ .../Services/Map/LuftbildArea.cs | 94 ++++++ .../Services/Map/LuftbildException.cs | 19 ++ .../Services/Map/LuftbildLayer.cs | 11 + .../Services/Map/RasterFormat.cs | 11 + .../Services/Map/RasterImage.cs | 46 +++ .../Services/Map/RasterImageInfo.cs | 95 ++++++ .../Services/Map/WebMercator.cs | 22 ++ .../Services/SessionPdfExport.cs | 6 +- .../ViewModels/HomeViewModel.cs | 8 +- .../ViewModels/IncidentWorkspaceViewModel.cs | 6 +- .../ViewModels/LagekarteViewModel.cs | 24 +- .../ViewModels/MapOverlaysViewModel.cs | 209 ++++++++++-- src/LageBuch.Domain/Files/IncidentFile.cs | 28 +- src/LageBuch.Domain/Incident.cs | 4 +- src/LageBuch.Domain/Map/MapOverlay.cs | 81 ++++- src/LageBuch.Domain/Map/MapOverlayKind.cs | 11 + src/LageBuch.Domain/Map/MapOverlaySummary.cs | 18 +- src/LageBuch.Domain/ValueObjects/GeoBox.cs | 45 +++ .../IncidentRepository.cs | 15 +- src/LageBuch.Persistence/Sqlite/Migrations.cs | 23 +- .../Sqlite/SchemaGuard.cs | 6 + src/LageBuch.Sync/CommandApplier.cs | 9 +- src/LageBuch.Sync/IncidentSnapshot.cs | 11 +- src/LageBuch.Sync/RemoteIncidentSession.cs | 8 +- src/LageBuch.Sync/SnapshotMapper.cs | 27 +- src/LageBuch.Sync/SyncCommand.cs | 13 +- src/LageBuch.Sync/SyncProtocol.cs | 11 +- .../LagekarteLuftbildRenderTests.cs | 238 ++++++++++++++ .../LdbvImageryClientTests.cs | 299 +++++++++++++++++ .../LuftbildAreaTests.cs | 91 ++++++ .../MapOverlaysLuftbildTests.cs | 305 ++++++++++++++++++ .../RasterImageInfoTests.cs | 87 +++++ .../SessionPdfExportTests.cs | 35 ++ tests/LageBuch.AppLogic.Tests/TestImages.cs | 43 +++ tests/LageBuch.Domain.Tests/GeoBoxTests.cs | 53 +++ .../MapOverlayRasterTests.cs | 177 ++++++++++ .../MapOverlayRoundTripTests.cs | 69 ++++ .../MapOverlayHostTests.cs | 35 ++ .../MapOverlaySyncTests.cs | 92 ++++++ .../VersionHandshakeTests.cs | 18 +- 51 files changed, 2734 insertions(+), 85 deletions(-) create mode 100644 changelog.d/+lagekarte-luftbild.added.md create mode 100644 src/LageBuch.App.Shared/Controls/RasterOverlayCache.cs create mode 100644 src/LageBuch.AppLogic/Services/Map/LdbvImageryClient.cs create mode 100644 src/LageBuch.AppLogic/Services/Map/LuftbildArea.cs create mode 100644 src/LageBuch.AppLogic/Services/Map/LuftbildException.cs create mode 100644 src/LageBuch.AppLogic/Services/Map/LuftbildLayer.cs create mode 100644 src/LageBuch.AppLogic/Services/Map/RasterFormat.cs create mode 100644 src/LageBuch.AppLogic/Services/Map/RasterImage.cs create mode 100644 src/LageBuch.AppLogic/Services/Map/RasterImageInfo.cs create mode 100644 src/LageBuch.Domain/Map/MapOverlayKind.cs create mode 100644 src/LageBuch.Domain/ValueObjects/GeoBox.cs create mode 100644 tests/LageBuch.Acceptance.Tests/LagekarteLuftbildRenderTests.cs create mode 100644 tests/LageBuch.AppLogic.Tests/LdbvImageryClientTests.cs create mode 100644 tests/LageBuch.AppLogic.Tests/LuftbildAreaTests.cs create mode 100644 tests/LageBuch.AppLogic.Tests/MapOverlaysLuftbildTests.cs create mode 100644 tests/LageBuch.AppLogic.Tests/RasterImageInfoTests.cs create mode 100644 tests/LageBuch.AppLogic.Tests/TestImages.cs create mode 100644 tests/LageBuch.Domain.Tests/GeoBoxTests.cs create mode 100644 tests/LageBuch.Domain.Tests/MapOverlayRasterTests.cs diff --git a/changelog.d/+lagekarte-luftbild.added.md b/changelog.d/+lagekarte-luftbild.added.md new file mode 100644 index 000000000..5c371b4b3 --- /dev/null +++ b/changelog.d/+lagekarte-luftbild.added.md @@ -0,0 +1 @@ +LUFTBILD LADEN on the Lagekarte downloads the visible section's Luftbild and Flurstücksgrenzen from the Bayerische Vermessungsverwaltung (BayernAtlas data, CC BY 4.0) and keeps them in the Einsatz as two Kartenebenen that sync and work offline. diff --git a/docs/datenschutz-und-sicherheit.md b/docs/datenschutz-und-sicherheit.md index 16a3a4a15..fea9b901e 100644 --- a/docs/datenschutz-und-sicherheit.md +++ b/docs/datenschutz-und-sicherheit.md @@ -199,6 +199,16 @@ dem Bediener ausgelöst: Ohne Antippen wird nichts abgefragt, auch nicht erneut. Die Werte bleiben auf dem Gerät; in den Einsatz gelangen sie nur, wenn sie mit INS ETB als Eintrag übernommen werden. +7. **Luftbild auf der Lagekarte.** Erst wenn unter EBENEN LUFTBILD LADEN + angetippt wird, lädt Lagebuch bei der Bayerischen Vermessungsverwaltung + (`geoservices.bayern.de`) das Luftbild (DOP40) und die Flurstücksgrenzen des + gerade sichtbaren Kartenausschnitts, höchstens etwa 1,6 × 1,6 km. Dafür geht + dieser Ausschnitt an den Dienst; er sieht dabei die IP-Adresse des Geräts und + den Ausschnitt – also ungefähr, wo auf die Karte geschaut wird, aber keine + Adresse, keine Namen und keine weiteren Einsatzdaten. Ohne Antippen wird nichts + abgefragt. Die Bilder werden als zwei Kartenebenen im Einsatz gespeichert, mit + den übrigen Ebenen synchronisiert und danach ohne Netz aus der Einsatzdatei + gezeichnet. In den PDF-Bericht gelangen sie nicht. Nicht vorhanden sind: Nutzungsstatistiken, automatisch versandte Absturzberichte, Updateprüfungen, Werbe- oder Analysebibliotheken sowie Schriftarten oder Kartenkacheln, die während @@ -319,7 +329,8 @@ ein Begleitgerät. Betriebssystem übergibt. - Nachvollziehbare Änderungshistorie: Korrekturen im ETB überschreiben nichts. - Keine Telemetrie, keine Protokolldateien. Fremde Dienste nur auf - ausdrückliches Antippen: Kartenpakete von GitHub, Wetter von Bright Sky. + ausdrückliches Antippen: Kartenpakete von GitHub, Wetter von Bright Sky, + Luftbilder von der Bayerischen Vermessungsverwaltung. - Überprüfbare Installationsdateien: zu jedem Release gehören SHA-256-Prüfsummen und ein Sigstore-Herkunftsnachweis, siehe [Downloads prüfen](../README.md#downloads-prüfen). diff --git a/src/LageBuch.App.Android/MainActivity.cs b/src/LageBuch.App.Android/MainActivity.cs index db857683a..ba3f83cdf 100644 --- a/src/LageBuch.App.Android/MainActivity.cs +++ b/src/LageBuch.App.Android/MainActivity.cs @@ -121,7 +121,8 @@ protected override void OnCreate(global::Android.OS.Bundle? savedInstanceState) alarmMute: new AlarmMute(AndroidAppPaths.AlarmMuteJsonPath(this)), mapPacks: new RegionPackLibrary(MapPackHttp, AndroidAppPaths.RegionPacksDir(this)), mapNightMode: new MapNightMode(AndroidAppPaths.MapNightJsonPath(this)), - weather: new BrightSkyClient(MapPackHttp))); + weather: new BrightSkyClient(MapPackHttp), + luftbild: new LdbvImageryClient(MapPackHttp))); base.OnCreate(savedInstanceState); } diff --git a/src/LageBuch.App.Shared/CompositionRoot.cs b/src/LageBuch.App.Shared/CompositionRoot.cs index 28cdb6dd3..0603ee6de 100644 --- a/src/LageBuch.App.Shared/CompositionRoot.cs +++ b/src/LageBuch.App.Shared/CompositionRoot.cs @@ -42,7 +42,8 @@ public static MainWindowViewModel CreateMainWindowViewModel( IRegionPackLibrary? mapPacks = null, MapNightMode? mapNightMode = null, IWeatherSource? weather = null, - IDispatchInboxStore? dispatchInbox = null) + IDispatchInboxStore? dispatchInbox = null, + LdbvImageryClient? luftbild = null) { // Every cue goes through the device's mute switch (#699); without a file to keep it in, // the switch still works for this run. @@ -51,7 +52,7 @@ public static MainWindowViewModel CreateMainWindowViewModel( var dispatch = dispatchInbox is null ? null : new DispatchInboxViewModel(dispatchInbox, masterData, dialogs, clock, ticker, uiDispatcher, work => _ = Task.Run(work)); - var home = new HomeViewModel(store, masterData, recent, dialogs, clock, ticker, alarm, hostController, appVersion, uiDispatcher, lastSaveFolder, attachmentCacheRoot, trustStore: trustStore, pdfExporter: pdfExporter, lastPdfExport: lastPdfExport, lastConnection: lastConnection, mailComposer: mailComposer, runInBackground: work => _ = Task.Run(work), lastCrashReport: lastCrashReport, alarmMute: alarmMute, mapPacks: mapPacks, mapNightMode: mapNightMode, weather: weather, dispatch: dispatch); + var home = new HomeViewModel(store, masterData, recent, dialogs, clock, ticker, alarm, hostController, appVersion, uiDispatcher, lastSaveFolder, attachmentCacheRoot, trustStore: trustStore, pdfExporter: pdfExporter, lastPdfExport: lastPdfExport, lastConnection: lastConnection, mailComposer: mailComposer, runInBackground: work => _ = Task.Run(work), lastCrashReport: lastCrashReport, alarmMute: alarmMute, mapPacks: mapPacks, mapNightMode: mapNightMode, weather: weather, dispatch: dispatch, luftbild: luftbild); var editor = new MasterDataEditorViewModel(masterData, dialogs, masterDataFileService, mapPacks); return new MainWindowViewModel(home, editor, dialogs, appVersion, alarm, alarmMute, uiDispatcher); } diff --git a/src/LageBuch.App.Shared/Controls/MapCanvasControl.cs b/src/LageBuch.App.Shared/Controls/MapCanvasControl.cs index 44857a792..7dfb218e5 100644 --- a/src/LageBuch.App.Shared/Controls/MapCanvasControl.cs +++ b/src/LageBuch.App.Shared/Controls/MapCanvasControl.cs @@ -66,6 +66,10 @@ public sealed class MapCanvasControl : Control public static readonly StyledProperty?> OverlaysProperty = AvaloniaProperty.Register?>(nameof(Overlays)); + /// The pictures of the visible raster Kartenebenen, drawn on the tiles in this order; null draws none. + public static readonly StyledProperty?> RasterOverlaysProperty = + AvaloniaProperty.Register?>(nameof(RasterOverlays)); + /// The Fließweg from the Einsatzort, start first; null draws none. public static readonly StyledProperty?> FlowPathProperty = AvaloniaProperty.Register?>(nameof(FlowPath)); @@ -87,6 +91,7 @@ public sealed class MapCanvasControl : Control private readonly MapTileCache _tiles = new(); private readonly TerrainTileCache _terrain; + private readonly RasterOverlayCache _rasters; // Where a drag started, on screen and on the map; null while no drag is under way. private Point? _dragStart; @@ -102,7 +107,7 @@ public sealed class MapCanvasControl : Control static MapCanvasControl() { - AffectsRender(TileSourceProperty, CenterProperty, ZoomProperty, RotationProperty, WaterPointsProperty, SelectedWaterPointProperty, ElevationProperty, TerrainStyleProperty, IsNightProperty, OverlaysProperty, FlowPathProperty); + AffectsRender(TileSourceProperty, CenterProperty, ZoomProperty, RotationProperty, WaterPointsProperty, SelectedWaterPointProperty, ElevationProperty, TerrainStyleProperty, IsNightProperty, OverlaysProperty, FlowPathProperty, RasterOverlaysProperty); FocusableProperty.OverrideDefaultValue(true); ClipToBoundsProperty.OverrideDefaultValue(true); } @@ -110,6 +115,7 @@ static MapCanvasControl() public MapCanvasControl() { _terrain = new TerrainTileCache(InvalidateVisual); + _rasters = new RasterOverlayCache(InvalidateVisual); GestureRecognizers.Add(new PinchGestureRecognizer()); AddHandler(PinchEvent, OnPinch); AddHandler(PinchEndedEvent, OnPinchEnded); @@ -184,6 +190,31 @@ public IReadOnlyList? Overlays set => SetValue(OverlaysProperty, value); } + public IReadOnlyList? RasterOverlays + { + get => GetValue(RasterOverlaysProperty); + set => SetValue(RasterOverlaysProperty, value); + } + + /// Whether Luftbild pictures are still being decoded; the map redraws as each is ready. + public bool IsRasterBusy => _rasters.IsBusy; + + /// + /// The box on the map the control shows, its turned corners included; null before the map has + /// a centre or a size. What LUFTBILD LADEN asks the LDBV for. + /// + public GeoBox? VisibleBounds() + { + if (Center is null || Bounds.Width <= 0 || Bounds.Height <= 0) + { + return null; + } + + Point[] corners = [new(0, 0), new(Bounds.Width, 0), new(0, Bounds.Height), new(Bounds.Width, Bounds.Height)]; + var points = corners.Select(ScreenToGeo).OfType().ToList(); + return GeoBox.TryCreate(points.Min(p => p.Longitude), points.Min(p => p.Latitude), points.Max(p => p.Longitude), points.Max(p => p.Latitude)); + } + public bool WheelZoomNeedsControl { get => GetValue(WheelZoomNeedsControlProperty); @@ -231,7 +262,8 @@ public override void Render(DrawingContext context) // Missing tiles are painted too, so the whole control stays hit-testable for a drag. _tiles.Use(TileSource); _terrain.Use(Elevation, TerrainStyle); - MapDrawing.Draw(context, _tiles, center, Zoom, Bounds.Size, Rotation, WaterPoints, SelectedWaterPoint, _terrain, Overlays, FlowPath); + var rasters = _rasters.Use(RasterOverlays); + MapDrawing.Draw(context, _tiles, center, Zoom, Bounds.Size, Rotation, WaterPoints, SelectedWaterPoint, _terrain, Overlays, FlowPath, rasters); } protected override void OnDetachedFromVisualTree(VisualTreeAttachmentEventArgs e) @@ -239,6 +271,7 @@ protected override void OnDetachedFromVisualTree(VisualTreeAttachmentEventArgs e base.OnDetachedFromVisualTree(e); _tiles.Clear(); _terrain.Clear(); + _rasters.Clear(); } protected override void OnPropertyChanged(AvaloniaPropertyChangedEventArgs change) diff --git a/src/LageBuch.App.Shared/Controls/MapDrawing.cs b/src/LageBuch.App.Shared/Controls/MapDrawing.cs index fd0b73c64..826bf23b0 100644 --- a/src/LageBuch.App.Shared/Controls/MapDrawing.cs +++ b/src/LageBuch.App.Shared/Controls/MapDrawing.cs @@ -1,6 +1,7 @@ using System.Globalization; using Avalonia; using Avalonia.Media; +using Avalonia.Media.Imaging; using Avalonia.Media.Immutable; using LageBuch.AppLogic.Services.Map; using LageBuch.Domain.ValueObjects; @@ -30,8 +31,10 @@ public static class MapDrawing /// over the terrain, under the names, and the /// over the Kartenebenen. All of it but the terrain, the /// Kartenebenen and the Fließweg in the colours of the cache's . + /// The , the pictures of the Luftbild Ebenen, lie on the tiles and + /// under the terrain, in their own colours by day and by night. /// - public static void Draw(DrawingContext context, MapTileCache tiles, GeoPoint center, int zoom, Size size, double rotation = 0, IReadOnlyList? waterPoints = null, WaterPoint? selected = null, TerrainTileCache? terrain = null, IReadOnlyList? overlays = null, IReadOnlyList? flowPath = null) + public static void Draw(DrawingContext context, MapTileCache tiles, GeoPoint center, int zoom, Size size, double rotation = 0, IReadOnlyList? waterPoints = null, WaterPoint? selected = null, TerrainTileCache? terrain = null, IReadOnlyList? overlays = null, IReadOnlyList? flowPath = null, IReadOnlyList<(Bitmap Image, GeoBox Bounds)>? rasters = null) { ArgumentNullException.ThrowIfNull(context); ArgumentNullException.ThrowIfNull(tiles); @@ -45,21 +48,29 @@ public static void Draw(DrawingContext context, MapTileCache tiles, GeoPoint cen context.FillRectangle(style.Background, new Rect(size)); var marks = waterPoints is null ? [] : WaterPointMarkers.LayOut(waterPoints, center, zoom, size, selected, rotation); var labels = new List<(MapLabel Label, Point At)>(); - if (tiles.Source is { } source) + var turn = Turn(size, rotation); + IReadOnlyList layers = tiles.Source switch { // Several packs are drawn one over the other. Each pack's tiles are cut to its area when // it is built, so outside it a pack draws nothing that could cover its neighbour's streets. - IReadOnlyList layers = source is CombinedMapTileSource combined ? combined.Layers : [source]; - var turn = Turn(size, rotation); - foreach (var layer in layers) - { - DrawLayer(context, tiles, layer, center, zoom, size, turn, labels); - } + CombinedMapTileSource combined => combined.Layers, + { } single => [single], + _ => [], + }; + foreach (var layer in layers) + { + DrawLayer(context, tiles, layer, center, zoom, size, turn, labels); + } - if (terrain is not null && zoom >= TerrainSampler.MinZoom) - { - DrawTerrain(context, terrain, center, zoom, size, turn, rotation); - } + // A Luftbild covers the streets, but not their names, which are laid over everything below. + if (rasters is { Count: > 0 }) + { + DrawRasters(context, rasters, center, zoom, size, turn); + } + + if (layers.Count > 0 && terrain is not null && zoom >= TerrainSampler.MinZoom) + { + DrawTerrain(context, terrain, center, zoom, size, turn, rotation); } // Kartenebenen lie on the map and its terrain but under its names and the water points, so @@ -202,6 +213,25 @@ private static void DrawLayer(DrawingContext context, MapTileCache tiles, IMapTi } } + // Each picture into the rectangle between its corners on the north-up map, turned with it. A + // WMS picture in EPSG:3857 is linear in Web Mercator, so its corners are all it takes to lay it + // exactly where the tiles are. + private static void DrawRasters(DrawingContext context, IReadOnlyList<(Bitmap Image, GeoBox Bounds)> rasters, GeoPoint center, int zoom, Size size, Matrix turn) + { + var (centerX, centerY) = WebMercator.ToWorldPixel(center, zoom); + var left = centerX - (size.Width / 2); + var top = centerY - (size.Height / 2); + using (context.PushTransform(turn)) + { + foreach (var (image, bounds) in rasters) + { + var (westX, northY) = WebMercator.ToWorldPixel(new GeoPoint(bounds.North, bounds.West), zoom); + var (eastX, southY) = WebMercator.ToWorldPixel(new GeoPoint(bounds.South, bounds.East), zoom); + context.DrawImage(image, new Rect(westX - left, northY - top, eastX - westX, southY - northY)); + } + } + } + // Brown like a topographic map's contours; the relative layer's lines in grey, its Einsatzort line black. private static readonly IPen ContourPen = new ImmutablePen(new ImmutableSolidColorBrush(Color.FromArgb(0xD9, 0x9A, 0x6B, 0x3F)), 0.7); private static readonly IPen ZaehllinienPen = new ImmutablePen(new ImmutableSolidColorBrush(Color.FromRgb(0x7A, 0x4A, 0x1F)), 1.4); diff --git a/src/LageBuch.App.Shared/Controls/RasterOverlayCache.cs b/src/LageBuch.App.Shared/Controls/RasterOverlayCache.cs new file mode 100644 index 000000000..f2bd4d286 --- /dev/null +++ b/src/LageBuch.App.Shared/Controls/RasterOverlayCache.cs @@ -0,0 +1,114 @@ +using System.Diagnostics.CodeAnalysis; +using System.Runtime.InteropServices; +using Avalonia.Media.Imaging; +using LageBuch.AppLogic.Services.Map; + +namespace LageBuch.App.Shared.Controls; + +/// +/// The decoded pictures of the raster Kartenebenen on the map, keyed by their file, so a pan +/// redraws from memory. A picture is decoded off the UI thread -- a 4096 px Luftbild takes a moment +/// -- and the map is told to draw again once it is ready; until then the map shows without it. +/// A picture no longer shown is released at once: each one holds tens of megabytes. +/// +/// Deliberately not , like : its control releases it through . +public sealed class RasterOverlayCache +{ + private readonly Dictionary _decoded = new(); + private readonly HashSet _pending = new(); + private readonly Action? _ready; + + // Bumped by Clear, so a picture decoded for a map that has since let go of it is dropped. + private int _generation; + + /// Called on the UI thread whenever a picture has become ready to draw. + public RasterOverlayCache(Action? ready = null) + { + _ready = ready; + } + + /// Whether pictures are still being decoded. + public bool IsBusy => _pending.Count > 0; + + /// + /// The decoded picture of every one of that is ready, in their + /// order, each with the box it is laid into. Starts decoding the rest, and releases the + /// pictures of Ebenen no longer among them. + /// + public IReadOnlyList<(Bitmap Image, Domain.ValueObjects.GeoBox Bounds)> Use(IReadOnlyList? rasters) + { + var wanted = (rasters ?? []).Select(r => r.FileId).ToHashSet(); + foreach (var gone in _decoded.Keys.Where(id => !wanted.Contains(id)).ToList()) + { + _decoded[gone]?.Dispose(); + _decoded.Remove(gone); + } + + _pending.IntersectWith(wanted); + var ready = new List<(Bitmap, Domain.ValueObjects.GeoBox)>(); + foreach (var raster in rasters ?? []) + { + if (_decoded.TryGetValue(raster.FileId, out var bitmap)) + { + if (bitmap is not null) + { + ready.Add((bitmap, raster.Bounds)); + } + } + else if (_pending.Add(raster.FileId)) + { + // Fire-and-forget on purpose: DecodeAsync never throws, a picture that will not decode is stored as none. + _ = DecodeAsync(raster, _generation); + } + } + + return ready; + } + + public void Clear() + { + _generation++; + _pending.Clear(); + foreach (var bitmap in _decoded.Values) + { + bitmap?.Dispose(); + } + + _decoded.Clear(); + } + + [SuppressMessage("Design", "CA1031", Justification = "A picture that will not decode is drawn as nothing, like a damaged terrain tile; its Ebene stays listed and removable.")] + private async Task DecodeAsync(RasterImage raster, int generation) + { + Bitmap? bitmap; + try + { + bitmap = await Task.Run(() => Decode(raster.Bytes)); + } + catch (Exception) + { + bitmap = null; + } + + // Dropped while it was decoding: by a cleared map, or an Ebene hidden or removed meanwhile. + if (generation != _generation || !_pending.Remove(raster.FileId)) + { + bitmap?.Dispose(); + return; + } + + _decoded[raster.FileId] = bitmap; + if (bitmap is not null) + { + _ready?.Invoke(); + } + } + + private static Bitmap Decode(ReadOnlyMemory bytes) + { + using var stream = MemoryMarshal.TryGetArray(bytes, out var segment) && segment.Array is { } array + ? new MemoryStream(array, segment.Offset, segment.Count, writable: false) + : new MemoryStream(bytes.ToArray(), writable: false); + return new Bitmap(stream); + } +} diff --git a/src/LageBuch.App.Shared/Views/LagekarteView.axaml b/src/LageBuch.App.Shared/Views/LagekarteView.axaml index e4a568040..e49c8b19d 100644 --- a/src/LageBuch.App.Shared/Views/LagekarteView.axaml +++ b/src/LageBuch.App.Shared/Views/LagekarteView.axaml @@ -196,6 +196,21 @@ IsEnabled="{Binding !Overlays.IsImporting}" Command="{Binding Overlays.ImportCommand}" /> + + + @@ -372,6 +387,7 @@ FlowPath="{Binding Terrain.FlowPoints}" SelectedWaterPoint="{Binding SelectedWaterPoint}" Overlays="{Binding MapShapes}" + RasterOverlays="{Binding Overlays.VisibleRasters}" Center="{Binding Map.Center}" Zoom="{Binding Map.Zoom}" Rotation="{Binding Map.Rotation}" @@ -806,11 +822,11 @@ Foreground="{StaticResource TextSecondaryBrush}" /> - + + IsVisible="{Binding MapAttribution, Converter={x:Static ObjectConverters.IsNotNull}}"> - + diff --git a/src/LageBuch.App.Shared/Views/LagekarteView.axaml.cs b/src/LageBuch.App.Shared/Views/LagekarteView.axaml.cs index 86a804b4a..2aac7d660 100644 --- a/src/LageBuch.App.Shared/Views/LagekarteView.axaml.cs +++ b/src/LageBuch.App.Shared/Views/LagekarteView.axaml.cs @@ -20,6 +20,15 @@ public partial class LagekarteView : UserControl private void OnTerrainPicked(object? sender, RoutedEventArgs e) => Dispatcher.UIThread.Post(() => TerrainButton.Flyout?.Hide()); + // LUFTBILD LADEN asks for what the map shows, which only the map control knows. + private void OnLoadLuftbild(object? sender, RoutedEventArgs e) + { + if (ViewModel?.Overlays.LoadLuftbildCommand is { } load && Map.VisibleBounds() is { } visible && load.CanExecute(visible)) + { + load.Execute(visible); + } + } + private void OnMarkerPressed(object? sender, PointerPressedEventArgs e) { if (sender is not Control { DataContext: LagekarteMarker marker } control diff --git a/src/LageBuch.App/Program.cs b/src/LageBuch.App/Program.cs index da66fc00e..10a57ef9c 100644 --- a/src/LageBuch.App/Program.cs +++ b/src/LageBuch.App/Program.cs @@ -110,7 +110,8 @@ private static MainWindowViewModel CreateMainViewModel() mapPacks: new RegionPackLibrary(http, AppPaths.RegionPacksDir), mapNightMode: new MapNightMode(AppPaths.MapNightJsonPath), weather: new BrightSkyClient(http), - dispatchInbox: new JsonDispatchInboxStore(AppPaths.DispatchInboxJsonPath)); + dispatchInbox: new JsonDispatchInboxStore(AppPaths.DispatchInboxJsonPath), + luftbild: new LdbvImageryClient(http)); OpenLaunchedFile(mainViewModel); return mainViewModel; } diff --git a/src/LageBuch.AppLogic/Services/Map/LdbvImageryClient.cs b/src/LageBuch.AppLogic/Services/Map/LdbvImageryClient.cs new file mode 100644 index 000000000..8c2a65a1d --- /dev/null +++ b/src/LageBuch.AppLogic/Services/Map/LdbvImageryClient.cs @@ -0,0 +1,153 @@ +using System.Globalization; +using LageBuch.Domain.Files; + +namespace LageBuch.AppLogic.Services.Map; + +/// +/// Fetches a Luftbild and the Flurstücksgrenzen from the Bayerische Vermessungsverwaltung's open +/// WMS services on geoservices.bayern.de: the data BayernAtlas shows, free and without a +/// key under CC BY 4.0. Asked only when someone presses LUFTBILD LADEN, for the section the +/// Lagekarte shows; the service sees that section and the device's IP address, nothing else. +/// +/// +/// The answer is untrusted input from the network: it is read against +/// , must say it is an image, and must be the format and +/// size that was asked for. Every way a request can fail surfaces as a +/// with a German message, except a cancel the caller asked for. +/// +public sealed class LdbvImageryClient +{ + /// The licence line CC BY 4.0 asks for wherever the pictures are shown. + public const string Attribution = "Luftbild, Flurstücke: © Bayerische Vermessungsverwaltung (CC BY 4.0)"; + + private const string UserAgent = "LageBuch (+https://github.com/CodeForFire/lagebuch)"; + + private const string Service = "Kartendienst der Vermessungsverwaltung"; + + private const string TooLarge = "Das Bild des Kartendienstes ist zu groß."; + + private const string Unreadable = "Das Bild des Kartendienstes ist unlesbar."; + + /// The DOP40 WMS. + public static readonly Uri DopEndpoint = new("https://geoservices.bayern.de/od/wms/dop/v1/dop40"); + + /// The ALKIS-Parzellarkarte WMS. + public static readonly Uri ParzellarkarteEndpoint = new("https://geoservices.bayern.de/od/wms/alkis/v1/parzellarkarte"); + + /// How long one picture may take; a 4096 px JPEG is a few megabytes. + public static readonly TimeSpan RequestTimeout = TimeSpan.FromSeconds(60); + + private readonly HttpClient _http; + private readonly TimeProvider _time; + + public LdbvImageryClient(HttpClient http, TimeProvider? timeProvider = null) + { + ArgumentNullException.ThrowIfNull(http); + _http = http; + _time = timeProvider ?? TimeProvider.System; + } + + /// The picture of over : a JPEG for the Luftbild, a PNG for the Flurstücke. + public async Task GetMapAsync(LuftbildLayer layer, LuftbildArea area, CancellationToken cancellationToken = default) + { + ArgumentNullException.ThrowIfNull(area); + using var request = new HttpRequestMessage(HttpMethod.Get, GetMapUri(layer, area)); + request.Headers.UserAgent.ParseAdd(UserAgent); + using var timer = new CancellationTokenSource(RequestTimeout, _time); + using var timeout = CancellationTokenSource.CreateLinkedTokenSource(cancellationToken, timer.Token); + + byte[] bytes; + try + { + using var response = await _http.SendAsync(request, HttpCompletionOption.ResponseHeadersRead, timeout.Token); + if (!response.IsSuccessStatusCode) + { + throw new LuftbildException($"Der {Service} hat mit HTTP {(int)response.StatusCode} geantwortet."); + } + + // A WMS refuses with status 200 and an XML ServiceExceptionReport in place of the picture. + var mediaType = response.Content.Headers.ContentType?.MediaType ?? string.Empty; + if (mediaType.Contains("xml", StringComparison.OrdinalIgnoreCase)) + { + throw new LuftbildException($"Der {Service} hat die Anfrage abgelehnt."); + } + + if (!mediaType.StartsWith("image/", StringComparison.OrdinalIgnoreCase)) + { + throw new LuftbildException($"Der {Service} hat kein Bild geliefert."); + } + + // Stryker disable once Statement : the capped read below refuses the same body, only later. + if (response.Content.Headers.ContentLength > IncidentFile.MaxSizeBytes) + { + throw new LuftbildException(TooLarge); + } + + await using var body = await response.Content.ReadAsStreamAsync(timeout.Token); + bytes = await ReadCappedAsync(body, timeout.Token); + } + catch (HttpRequestException e) + { + throw new LuftbildException($"{Service} nicht erreichbar. Internetverbindung prüfen.", e); + } + catch (OperationCanceledException e) when (!cancellationToken.IsCancellationRequested) + { + // Our own timeout, or HttpClient's, reported as a cancellation nobody asked for. + throw new LuftbildException($"Der {Service} hat nicht rechtzeitig geantwortet. Später erneut versuchen.", e); + } + + var expected = layer == LuftbildLayer.Luftbild ? RasterFormat.Jpeg : RasterFormat.Png; + if (RasterImageInfo.Read(bytes) != new RasterImageInfo(expected, area.Width, area.Height)) + { + throw new LuftbildException(Unreadable); + } + + return bytes; + } + + /// The WMS 1.3.0 GetMap request for over . + /// + /// EPSG:3857 is easting before northing, so the box is x,y with no axis swap; WMS 1.3.0 swaps + /// only for a CRS whose axis order says so, such as EPSG:4326. + /// + public static Uri GetMapUri(LuftbildLayer layer, LuftbildArea area) + { + ArgumentNullException.ThrowIfNull(area); + var (endpoint, layers, format) = layer == LuftbildLayer.Luftbild + ? (DopEndpoint, "by_dop40c", "image/jpeg") + : (ParzellarkarteEndpoint, "by_alkis_parzellarkarte_umr_gelb", "image/png"); + var box = string.Join(',', new[] { area.MinX, area.MinY, area.MaxX, area.MaxY }.Select(Metres)); + var query = "?SERVICE=WMS&VERSION=1.3.0&REQUEST=GetMap" + + "&LAYERS=" + layers + + "&STYLES=" + + "&CRS=" + Uri.EscapeDataString("EPSG:3857") + + "&BBOX=" + Uri.EscapeDataString(box) + + "&WIDTH=" + area.Width.ToString(CultureInfo.InvariantCulture) + + "&HEIGHT=" + area.Height.ToString(CultureInfo.InvariantCulture) + + "&FORMAT=" + Uri.EscapeDataString(format) + + (layer == LuftbildLayer.Flurstuecke ? "&TRANSPARENT=TRUE" : string.Empty); + return new Uri(endpoint.AbsoluteUri + query); + } + + // To the centimetre: finer than any pixel, and the box stays exactly the area's. + private static string Metres(double value) => value.ToString("0.##", CultureInfo.InvariantCulture); + + // A missing or lying Content-Length must not let the body grow without bound. + private static async Task ReadCappedAsync(Stream body, CancellationToken cancellationToken) + { + using var buffer = new MemoryStream(); + var chunk = new byte[81920]; + int read; + while ((read = await body.ReadAsync(chunk, cancellationToken)) > 0) + { + if (buffer.Length + read > IncidentFile.MaxSizeBytes) + { + throw new LuftbildException(TooLarge); + } + + await buffer.WriteAsync(chunk.AsMemory(0, read), cancellationToken); + } + + return buffer.ToArray(); + } +} diff --git a/src/LageBuch.AppLogic/Services/Map/LuftbildArea.cs b/src/LageBuch.AppLogic/Services/Map/LuftbildArea.cs new file mode 100644 index 000000000..7a22898de --- /dev/null +++ b/src/LageBuch.AppLogic/Services/Map/LuftbildArea.cs @@ -0,0 +1,94 @@ +using LageBuch.Domain.ValueObjects; + +namespace LageBuch.AppLogic.Services.Map; + +/// +/// The part of the map LUFTBILD LADEN asks the LDBV for: a box in EPSG:3857 metres and the size of +/// the picture in pixels. The box is the visible section of the Lagekarte, cut to +/// a side at , so one download never runs past +/// what the services hand out and stays well under . +/// +public sealed record LuftbildArea +{ + /// + /// The DOP40's own resolution in Bavaria: 40 cm on the ground is about 60 cm in Web Mercator at + /// 48° north. It is also a scale of about 1:2150, well under the 1:5000 beyond which the + /// Parzellarkarte draws nothing. + /// + public const double MetresPerPixel = 0.6; + + /// + /// The longest side of one picture: about 2.4 km in Web Mercator, 1.6 km on the ground. Under + /// the services' own 6000 px, and a JPEG of it stays a few megabytes. + /// + public const int MaxPixels = 4096; + + /// The shortest side: a map zoomed onto one house still gets the street around it. + public const int MinPixels = 512; + + /// The German message for a section the LDBV has no pictures of. + public const string OutsideBavaria = "Luftbilder gibt es nur für Bayern."; + + // How the WMS standard turns metres per pixel into a scale: a pixel is 0.28 mm. + private const double MetresPerScreenPixel = 0.00028; + + /// Bavaria's bounding box, a little generous at every edge. + private static readonly GeoBox Bavaria = new(8.95, 47.25, 13.85, 50.6); + + private LuftbildArea(double minX, double minY, double maxX, double maxY, int width, int height) + { + (MinX, MinY, MaxX, MaxY, Width, Height) = (minX, minY, maxX, maxY, width, height); + var southWest = WebMercator.FromMetres(minX, minY); + var northEast = WebMercator.FromMetres(maxX, maxY); + Bounds = new GeoBox(southWest.Longitude, southWest.Latitude, northEast.Longitude, northEast.Latitude); + } + + /// The west edge, in EPSG:3857 metres. + public double MinX { get; } + + /// The south edge, in EPSG:3857 metres. + public double MinY { get; } + + /// The east edge, in EPSG:3857 metres. + public double MaxX { get; } + + /// The north edge, in EPSG:3857 metres. + public double MaxY { get; } + + public int Width { get; } + + public int Height { get; } + + /// The box in WGS84, where the picture is laid on the map. Its corners are the request's exactly. + public GeoBox Bounds { get; } + + /// The scale the services draw the picture at, as the WMS standard computes it. + public double ScaleDenominator => (MaxX - MinX) / Width / MetresPerScreenPixel; + + /// + /// The area to ask for when the Lagekarte shows : centred on it, as large + /// as it within the caps. Null when its middle lies outside Bavaria, where the LDBV has none + /// (). + /// + public static LuftbildArea? For(GeoBox visible) + { + ArgumentNullException.ThrowIfNull(visible); + var (west, south) = WebMercator.ToMetres(new GeoPoint(visible.South, visible.West)); + var (east, north) = WebMercator.ToMetres(new GeoPoint(visible.North, visible.East)); + var (x, y) = ((west + east) / 2, (south + north) / 2); + var middle = WebMercator.FromMetres(x, y); + if (middle.Longitude < Bavaria.West || middle.Longitude > Bavaria.East + || middle.Latitude < Bavaria.South || middle.Latitude > Bavaria.North) + { + return null; + } + + var width = Pixels(east - west); + var height = Pixels(north - south); + var halfWidth = width * MetresPerPixel / 2; + var halfHeight = height * MetresPerPixel / 2; + return new LuftbildArea(x - halfWidth, y - halfHeight, x + halfWidth, y + halfHeight, width, height); + } + + private static int Pixels(double metres) => Math.Clamp((int)Math.Round(metres / MetresPerPixel), MinPixels, MaxPixels); +} diff --git a/src/LageBuch.AppLogic/Services/Map/LuftbildException.cs b/src/LageBuch.AppLogic/Services/Map/LuftbildException.cs new file mode 100644 index 000000000..11b0e1eb1 --- /dev/null +++ b/src/LageBuch.AppLogic/Services/Map/LuftbildException.cs @@ -0,0 +1,19 @@ +namespace LageBuch.AppLogic.Services.Map; + +/// Why a Luftbild could not be loaded, in German. +public sealed class LuftbildException : Exception +{ + public LuftbildException() + { + } + + public LuftbildException(string message) + : base(message) + { + } + + public LuftbildException(string message, Exception innerException) + : base(message, innerException) + { + } +} diff --git a/src/LageBuch.AppLogic/Services/Map/LuftbildLayer.cs b/src/LageBuch.AppLogic/Services/Map/LuftbildLayer.cs new file mode 100644 index 000000000..7aabaab26 --- /dev/null +++ b/src/LageBuch.AppLogic/Services/Map/LuftbildLayer.cs @@ -0,0 +1,11 @@ +namespace LageBuch.AppLogic.Services.Map; + +/// What LUFTBILD LADEN fetches from the LDBV. +public enum LuftbildLayer +{ + /// The DOP40 Digitales Orthophoto, in colour, as a JPEG. + Luftbild, + + /// The Parzellarkarte's Flurstücksgrenzen alone, yellow on transparent, as a PNG. + Flurstuecke, +} diff --git a/src/LageBuch.AppLogic/Services/Map/RasterFormat.cs b/src/LageBuch.AppLogic/Services/Map/RasterFormat.cs new file mode 100644 index 000000000..f61a63257 --- /dev/null +++ b/src/LageBuch.AppLogic/Services/Map/RasterFormat.cs @@ -0,0 +1,11 @@ +namespace LageBuch.AppLogic.Services.Map; + +/// The two image formats a raster Kartenebene may be. +public enum RasterFormat +{ + /// A photo, such as the DOP40 Luftbild: opaque. + Jpeg, + + /// A drawing with a transparent background, such as the Flurstücksgrenzen. + Png, +} diff --git a/src/LageBuch.AppLogic/Services/Map/RasterImage.cs b/src/LageBuch.AppLogic/Services/Map/RasterImage.cs new file mode 100644 index 000000000..152576b21 --- /dev/null +++ b/src/LageBuch.AppLogic/Services/Map/RasterImage.cs @@ -0,0 +1,46 @@ +using System.Diagnostics.CodeAnalysis; +using LageBuch.Domain.ValueObjects; + +namespace LageBuch.AppLogic.Services.Map; + +/// +/// A raster Kartenebene ready for the map: the image's bytes, checked to be a PNG or JPEG of a size +/// the map can draw, and the box it is laid into. Decoding is the map control's job, so this layer +/// stays free of Avalonia; is what it caches the decoded picture by. +/// +public sealed record RasterImage(Guid FileId, ReadOnlyMemory Bytes, GeoBox Bounds, RasterImageInfo Info) +{ + /// The longest side a picture may have to be drawn: past the 4096 LUFTBILD LADEN asks for, far short of a decoding bomb. + public const int MaxPixels = 8192; + + /// + /// The picture in laid into ; false, with the + /// German reason, when it is no PNG or JPEG or too large to decode. + /// + public static bool TryRead( + Guid fileId, + byte[] bytes, + GeoBox bounds, + [NotNullWhen(true)] out RasterImage? image, + [NotNullWhen(false)] out string? error) + { + ArgumentNullException.ThrowIfNull(bytes); + ArgumentNullException.ThrowIfNull(bounds); + image = null; + if (RasterImageInfo.Read(bytes) is not { } info) + { + error = "Die Datei ist kein JPEG- oder PNG-Bild."; + return false; + } + + if (info.Width > MaxPixels || info.Height > MaxPixels) + { + error = "Das Bild ist zu groß für die Karte."; + return false; + } + + error = null; + image = new RasterImage(fileId, bytes, bounds, info); + return true; + } +} diff --git a/src/LageBuch.AppLogic/Services/Map/RasterImageInfo.cs b/src/LageBuch.AppLogic/Services/Map/RasterImageInfo.cs new file mode 100644 index 000000000..4f8b7dcbb --- /dev/null +++ b/src/LageBuch.AppLogic/Services/Map/RasterImageInfo.cs @@ -0,0 +1,95 @@ +using System.Buffers.Binary; + +namespace LageBuch.AppLogic.Services.Map; + +/// +/// What an image's header says it is: its format and its size in pixels. Read before anything +/// decodes the image, because the image may come from a sync peer or a handed-over file, and a +/// small file can claim a picture so large that decoding it would take all the memory there is. +/// +public sealed record RasterImageInfo(RasterFormat Format, int Width, int Height) +{ + private static ReadOnlySpan PngSignature => [0x89, 0x50, 0x4E, 0x47, 0x0D, 0x0A, 0x1A, 0x0A]; + + /// + /// The format and size of , or null when they are neither a PNG nor a + /// JPEG, or their header is cut off or names no size. + /// + public static RasterImageInfo? Read(ReadOnlySpan bytes) + { + if (bytes.StartsWith(PngSignature)) + { + return ReadPng(bytes); + } + + if (bytes.Length >= 3 && bytes[0] == 0xFF && bytes[1] == 0xD8 && bytes[2] == 0xFF) + { + return ReadJpeg(bytes); + } + + return null; + } + + // The IHDR chunk always comes first: length, type, then width and height as big-endian ints. + private static RasterImageInfo? ReadPng(ReadOnlySpan bytes) + { + if (bytes.Length < 24 || !bytes.Slice(12, 4).SequenceEqual("IHDR"u8)) + { + return null; + } + + var width = BinaryPrimitives.ReadInt32BigEndian(bytes.Slice(16, 4)); + var height = BinaryPrimitives.ReadInt32BigEndian(bytes.Slice(20, 4)); + return width > 0 && height > 0 ? new RasterImageInfo(RasterFormat.Png, width, height) : null; + } + + // Walks the segments to the first frame header (SOF0 to SOF15, which are not DHT, JPG or DAC), + // whose payload is precision, then height and width. A scan before any frame header, or a + // segment that runs past the end, makes the file unreadable. + private static RasterImageInfo? ReadJpeg(ReadOnlySpan bytes) + { + var at = 2; + while (at + 1 < bytes.Length) + { + if (bytes[at] != 0xFF) + { + return null; + } + + // Any number of fill bytes may stand before a marker. + var marker = bytes[at + 1]; + if (marker == 0xFF) + { + at++; + continue; + } + + if (marker is 0xDA or 0xD9) + { + return null; + } + + if (at + 4 > bytes.Length) + { + return null; + } + + var length = BinaryPrimitives.ReadUInt16BigEndian(bytes.Slice(at + 2, 2)); + if (marker is >= 0xC0 and <= 0xCF and not 0xC4 and not 0xC8 and not 0xCC) + { + if (length < 7 || at + 9 > bytes.Length) + { + return null; + } + + var height = BinaryPrimitives.ReadUInt16BigEndian(bytes.Slice(at + 5, 2)); + var width = BinaryPrimitives.ReadUInt16BigEndian(bytes.Slice(at + 7, 2)); + return width > 0 && height > 0 ? new RasterImageInfo(RasterFormat.Jpeg, width, height) : null; + } + + at += 2 + length; + } + + return null; + } +} diff --git a/src/LageBuch.AppLogic/Services/Map/WebMercator.cs b/src/LageBuch.AppLogic/Services/Map/WebMercator.cs index b62e67a37..632b9cc3d 100644 --- a/src/LageBuch.AppLogic/Services/Map/WebMercator.cs +++ b/src/LageBuch.AppLogic/Services/Map/WebMercator.cs @@ -48,5 +48,27 @@ public static (int X, int Y) ToTileIndex(double worldX, double worldY) => public static GeoPoint CenterOfTiles(int zoom, int minX, int maxX, int minY, int maxY) => ToGeo((minX + maxX + 1.0) * TileSizePixels / 2.0, (minY + maxY + 1.0) * TileSizePixels / 2.0, zoom); + /// The earth's radius EPSG:3857 projects with, in metres. + public const double EarthRadius = 6378137; + + /// + /// in EPSG:3857 metres, x east and y north of the origin: the + /// coordinates a WMS GetMap request takes its box in. + /// + public static (double X, double Y) ToMetres(GeoPoint point) + { + ArgumentNullException.ThrowIfNull(point); + var latitude = Math.Clamp(point.Latitude, -MaxLatitude, MaxLatitude) * Math.PI / 180.0; + return (EarthRadius * point.Longitude * Math.PI / 180.0, EarthRadius * Math.Log(Math.Tan((Math.PI / 4) + (latitude / 2)))); + } + + /// The inverse of , clamped onto the globe like . + public static GeoPoint FromMetres(double x, double y) + { + var longitude = x / EarthRadius * 180.0 / Math.PI; + var latitude = ((2 * Math.Atan(Math.Exp(y / EarthRadius))) - (Math.PI / 2)) * 180.0 / Math.PI; + return new GeoPoint(Math.Clamp(latitude, -MaxLatitude, MaxLatitude), Math.Clamp(longitude, -180, 180)); + } + private static double WorldSize(int zoom) => TileSizePixels * Math.Pow(2, zoom); } diff --git a/src/LageBuch.AppLogic/Services/SessionPdfExport.cs b/src/LageBuch.AppLogic/Services/SessionPdfExport.cs index a69eb8861..fa3a7360d 100644 --- a/src/LageBuch.AppLogic/Services/SessionPdfExport.cs +++ b/src/LageBuch.AppLogic/Services/SessionPdfExport.cs @@ -1,4 +1,5 @@ using LageBuch.Domain; +using LageBuch.Domain.Map; using LageBuch.Domain.Time; using LageBuch.Sync; @@ -39,7 +40,10 @@ public static class SessionPdfExport string? tempDirectory = null; try { - foreach (var file in incident.Files) + // A Luftbild's pictures are Kartenebenen, not attachments, and too large to print as + // one; the report lists their files by name like every other Ebene's. + var rasters = incident.MapOverlays.Where(o => o.Kind == MapOverlayKind.Raster).Select(o => o.FileId).ToHashSet(); + foreach (var file in incident.Files.Where(f => !rasters.Contains(f.Id))) { var bytes = await session.GetFileBytesAsync(file.Id, cancellationToken); if (bytes is null) diff --git a/src/LageBuch.AppLogic/ViewModels/HomeViewModel.cs b/src/LageBuch.AppLogic/ViewModels/HomeViewModel.cs index c7696ba04..16769fd8d 100644 --- a/src/LageBuch.AppLogic/ViewModels/HomeViewModel.cs +++ b/src/LageBuch.AppLogic/ViewModels/HomeViewModel.cs @@ -29,6 +29,7 @@ public sealed partial class HomeViewModel : ObservableObject private readonly IRegionPackLibrary? _mapPacks; private readonly MapNightMode? _mapNightMode; private readonly IWeatherSource? _weather; + private readonly LdbvImageryClient? _luftbild; private readonly IIncidentHostController _hostController; private readonly IIncidentPdfExporter _pdfExporter; private readonly string _appVersion; @@ -72,11 +73,12 @@ public sealed partial class HomeViewModel : ObservableObject // The report the crash notice is about, or null after a normal start. private readonly string? _crashReportPath; - public HomeViewModel(IIncidentStore store, IMasterDataProvider masterData, IRecentFilesStore recent, IFileDialogService dialogs, IClock clock, ITicker ticker, IAlarmService alarm, IIncidentHostController hostController, string appVersion, IUiDispatcher? uiDispatcher = null, ILastSaveFolderStore? lastSaveFolder = null, string? attachmentCacheRoot = null, ITrustStore? trustStore = null, IIncidentPdfExporter? pdfExporter = null, ILastPdfExportStore? lastPdfExport = null, ILastConnectionStore? lastConnection = null, IMailComposer? mailComposer = null, Action? runInBackground = null, string? lastCrashReport = null, AlarmMute? alarmMute = null, IRegionPackLibrary? mapPacks = null, MapNightMode? mapNightMode = null, IWeatherSource? weather = null, DispatchInboxViewModel? dispatch = null) + public HomeViewModel(IIncidentStore store, IMasterDataProvider masterData, IRecentFilesStore recent, IFileDialogService dialogs, IClock clock, ITicker ticker, IAlarmService alarm, IIncidentHostController hostController, string appVersion, IUiDispatcher? uiDispatcher = null, ILastSaveFolderStore? lastSaveFolder = null, string? attachmentCacheRoot = null, ITrustStore? trustStore = null, IIncidentPdfExporter? pdfExporter = null, ILastPdfExportStore? lastPdfExport = null, ILastConnectionStore? lastConnection = null, IMailComposer? mailComposer = null, Action? runInBackground = null, string? lastCrashReport = null, AlarmMute? alarmMute = null, IRegionPackLibrary? mapPacks = null, MapNightMode? mapNightMode = null, IWeatherSource? weather = null, DispatchInboxViewModel? dispatch = null, LdbvImageryClient? luftbild = null) { _mapPacks = mapPacks; _mapNightMode = mapNightMode; _weather = weather; + _luftbild = luftbild; ArgumentNullException.ThrowIfNull(recent); ArgumentNullException.ThrowIfNull(dialogs); @@ -450,7 +452,7 @@ private void OpenWorkspace(LocalIncidentSession session, string path, Persistenc // The local workspace's own saves flow through this same _store singleton, so wiring it // through here (issue #167 review follow-up) lets it surface a failed background write // that would otherwise leave the operator believing the incident is safely persisted. - var workspace = new IncidentWorkspaceViewModel(session, _clock, _ticker, md, _dialogs, _alarm, _hostController, _pdfExporter, _lastPdfExport, _store, _uiDispatcher, mailComposer: _mailComposer, alarmMute: _alarmMute, mapPacks: _mapPacks, mapNightMode: _mapNightMode, weather: _weather); + var workspace = new IncidentWorkspaceViewModel(session, _clock, _ticker, md, _dialogs, _alarm, _hostController, _pdfExporter, _lastPdfExport, _store, _uiDispatcher, mailComposer: _mailComposer, alarmMute: _alarmMute, mapPacks: _mapPacks, mapNightMode: _mapNightMode, weather: _weather, luftbild: _luftbild); WorkspaceOpened?.Invoke(workspace); } @@ -731,7 +733,7 @@ private static (string Host, int Port) ParseHost(string address) private void OpenRemoteWorkspace(RemoteIncidentSession session, MasterDataSet md, string host) { var workspace = new IncidentWorkspaceViewModel( - session, session.HostClock, _ticker, md, _dialogs, _alarm, new NoopIncidentHostController(), _pdfExporter, _lastPdfExport, remoteHost: host, alarmMute: _alarmMute, mapPacks: _mapPacks, mapNightMode: _mapNightMode, weather: _weather); + session, session.HostClock, _ticker, md, _dialogs, _alarm, new NoopIncidentHostController(), _pdfExporter, _lastPdfExport, remoteHost: host, alarmMute: _alarmMute, mapPacks: _mapPacks, mapNightMode: _mapNightMode, weather: _weather, luftbild: _luftbild); WorkspaceOpened?.Invoke(workspace); } } diff --git a/src/LageBuch.AppLogic/ViewModels/IncidentWorkspaceViewModel.cs b/src/LageBuch.AppLogic/ViewModels/IncidentWorkspaceViewModel.cs index 0451b986d..ec8b86352 100644 --- a/src/LageBuch.AppLogic/ViewModels/IncidentWorkspaceViewModel.cs +++ b/src/LageBuch.AppLogic/ViewModels/IncidentWorkspaceViewModel.cs @@ -37,6 +37,7 @@ public sealed partial class IncidentWorkspaceViewModel : ObservableObject, IDisp private readonly IRegionPackLibrary? _mapPacks; private readonly MapNightMode? _mapNightMode; private readonly IWeatherSource? _weather; + private readonly LdbvImageryClient? _luftbild; private readonly IIncidentHostController _hostController; private readonly IIncidentPdfExporter _pdfExporter; private readonly ILastPdfExportStore? _lastPdfExportStore; @@ -60,12 +61,13 @@ public sealed partial class IncidentWorkspaceViewModel : ObservableObject, IDisp private readonly Dictionary _checklists = new(); private bool _disposed; - public IncidentWorkspaceViewModel(IIncidentSession session, IClock clock, ITicker ticker, MasterDataSet masterData, IFileDialogService dialogs, IAlarmService alarm, IIncidentHostController hostController, IIncidentPdfExporter? pdfExporter = null, ILastPdfExportStore? lastPdfExport = null, IIncidentStore? store = null, IUiDispatcher? uiDispatcher = null, string? remoteHost = null, IMailComposer? mailComposer = null, AlarmMute? alarmMute = null, IRegionPackLibrary? mapPacks = null, MapNightMode? mapNightMode = null, IWeatherSource? weather = null) + public IncidentWorkspaceViewModel(IIncidentSession session, IClock clock, ITicker ticker, MasterDataSet masterData, IFileDialogService dialogs, IAlarmService alarm, IIncidentHostController hostController, IIncidentPdfExporter? pdfExporter = null, ILastPdfExportStore? lastPdfExport = null, IIncidentStore? store = null, IUiDispatcher? uiDispatcher = null, string? remoteHost = null, IMailComposer? mailComposer = null, AlarmMute? alarmMute = null, IRegionPackLibrary? mapPacks = null, MapNightMode? mapNightMode = null, IWeatherSource? weather = null, LdbvImageryClient? luftbild = null) { ArgumentNullException.ThrowIfNull(session); _mapPacks = mapPacks; _mapNightMode = mapNightMode; _weather = weather; + _luftbild = luftbild; _session = session; _local = session as LocalIncidentSession; _clock = clock; @@ -1139,7 +1141,7 @@ private void BuildChildren() OfferUndo, OpenDispatchChannelDialog); - Lagekarte = new LagekarteViewModel(_session, OnChanged, _mapPacks, _mapNightMode, _dialogs, RequestConfirm, _weather, _clock); + Lagekarte = new LagekarteViewModel(_session, OnChanged, _mapPacks, _mapNightMode, _dialogs, RequestConfirm, _weather, _clock, _luftbild); LeadershipTabs = new LeadershipTabsViewModel(Leadership, Roles, Forces, Lagekarte, reopenTab); diff --git a/src/LageBuch.AppLogic/ViewModels/LagekarteViewModel.cs b/src/LageBuch.AppLogic/ViewModels/LagekarteViewModel.cs index bce3264a2..28318e0d6 100644 --- a/src/LageBuch.AppLogic/ViewModels/LagekarteViewModel.cs +++ b/src/LageBuch.AppLogic/ViewModels/LagekarteViewModel.cs @@ -62,7 +62,8 @@ public LagekarteViewModel( IFileDialogService? dialogs = null, Action? requestConfirm = null, IWeatherSource? weather = null, - IClock? clock = null) + IClock? clock = null, + LdbvImageryClient? luftbild = null) { ArgumentNullException.ThrowIfNull(session); ArgumentNullException.ThrowIfNull(onChanged); @@ -87,13 +88,18 @@ public LagekarteViewModel( RefreshProfile(newHeights: true); } }; - Overlays = new MapOverlaysViewModel(session, onChanged, dialogs, requestConfirm, clock ?? new SystemClock(), ShowBounds); + Overlays = new MapOverlaysViewModel(session, onChanged, dialogs, requestConfirm, clock ?? new SystemClock(), ShowBounds, luftbild: luftbild); Overlays.PropertyChanged += (_, e) => { if (e.PropertyName is nameof(MapOverlaysViewModel.VisibleShapes)) { OnPropertyChanged(nameof(MapShapes)); } + + if (e.PropertyName is nameof(MapOverlaysViewModel.RasterAttribution)) + { + OnPropertyChanged(nameof(MapAttribution)); + } }; Weather = new WeatherOverlay( weather, @@ -111,6 +117,11 @@ public LagekarteViewModel( _nightMode.Changed += OnNightModeChanged; Map.PropertyChanged += (_, e) => { + if (e.PropertyName is nameof(MapViewport.Attribution)) + { + OnPropertyChanged(nameof(MapAttribution)); + } + if (e.PropertyName is nameof(MapViewport.Zoom) or nameof(MapViewport.TileSource)) { OnPropertyChanged(nameof(ShowsWaterLegend)); @@ -131,9 +142,16 @@ public void Dispose() /// The GELÄNDE picker: the packs' DGM5 heights laid over the map. public TerrainOverlay Terrain { get; } - /// The Kartenebenen: imported GeoJSON, such as an Ausbreitungsprognose. + /// The Kartenebenen: imported GeoJSON, such as an Ausbreitungsprognose, and Luftbilder. public MapOverlaysViewModel Overlays { get; } + /// + /// The licence lines under the map: the packs' (OSM's ODbL), then those of the shown Luftbilder + /// (the LDBV's CC BY 4.0); null while neither is on screen. + /// + public string? MapAttribution => + string.Join(" ", new[] { Map.Attribution, Overlays.RasterAttribution }.OfType()) is { Length: > 0 } text ? text : null; + /// WETTER: the DWD's reading at the Einsatzort, loaded on request. public WeatherOverlay Weather { get; } diff --git a/src/LageBuch.AppLogic/ViewModels/MapOverlaysViewModel.cs b/src/LageBuch.AppLogic/ViewModels/MapOverlaysViewModel.cs index 51f1e51fa..0321836e6 100644 --- a/src/LageBuch.AppLogic/ViewModels/MapOverlaysViewModel.cs +++ b/src/LageBuch.AppLogic/ViewModels/MapOverlaysViewModel.cs @@ -8,6 +8,7 @@ using LageBuch.Domain.Files; using LageBuch.Domain.Map; using LageBuch.Domain.Time; +using LageBuch.Domain.ValueObjects; using LageBuch.Sync; namespace LageBuch.AppLogic.ViewModels; @@ -17,7 +18,9 @@ namespace LageBuch.AppLogic.ViewModels; /// or off. Which Ebene is shown, and at which time, belongs to this screen and is not stored, like /// the HYDRANTEN switch; the Ebenen themselves are the Einsatz's and sync. A new Ebene is shown /// and the ones before it are hidden, so a newer Ausbreitungsprognose replaces the old one on the -/// map while the old one stays on record. +/// map while the old one stays on record. LUFTBILD LADEN adds the visible section's Luftbild and +/// Flurstücksgrenzen as two raster Ebenen, which lie under every GeoJSON Ebene and so are shown +/// beside them rather than in their place. /// public sealed partial class MapOverlaysViewModel : ObservableObject { @@ -27,6 +30,7 @@ public sealed partial class MapOverlaysViewModel : ObservableObject private readonly Action? _requestConfirm; private readonly IClock _clock; private readonly Action _showBounds; + private readonly LdbvImageryClient? _luftbild; // Where the forecast times are read: a DWD file carries them in UTC, and a forecast reopened // after the clocks changed must still say the hour it said on the day. @@ -36,7 +40,7 @@ public sealed partial class MapOverlaysViewModel : ObservableObject private readonly bool _opened; // Read and parsed once per file and session: the file never changes, only whether it is shown. - private readonly Dictionary> _loads = []; + private readonly Dictionary> _loads = []; // Every row's load since the last settle, for a caller that has to wait on the files being read. private readonly List _pending = []; @@ -51,7 +55,8 @@ public MapOverlaysViewModel( Action? requestConfirm, IClock clock, Action showBounds, - TimeZoneInfo? timeZone = null) + TimeZoneInfo? timeZone = null, + LdbvImageryClient? luftbild = null) { ArgumentNullException.ThrowIfNull(session); ArgumentNullException.ThrowIfNull(onChanged); @@ -64,6 +69,7 @@ public MapOverlaysViewModel( _clock = clock; _showBounds = showBounds; _timeZone = timeZone ?? TimeZoneInfo.Local; + _luftbild = luftbild; Refresh(); _opened = true; } @@ -90,6 +96,39 @@ public MapOverlaysViewModel( [ObservableProperty] private IReadOnlyList _visibleShapes = []; + /// + /// What the map lays under its GeoJSON Ebenen: the image of every shown raster Ebene, every + /// photo below every drawing, so a newer Luftbild never covers an older one's Flurstücksgrenzen. + /// + [ObservableProperty] + [NotifyPropertyChangedFor(nameof(RasterAttribution))] + private IReadOnlyList _visibleRasters = []; + + /// The licence lines of the shown raster Ebenen, each once; null while none is shown. + public string? RasterAttribution + { + get + { + var lines = Items + .Where(i => i.IsVisible && i.Raster is not null) + .Select(i => i.Attribution) + .OfType() + .Distinct(StringComparer.Ordinal) + .ToList(); + return lines.Count == 0 ? null : string.Join(" ", lines); + } + } + + /// LUFTBILD LADEN needs an open Einsatz and, on this device, the way to the LDBV. + public bool CanLoadLuftbild => !_session.IsReadOnly && _luftbild is not null; + + [ObservableProperty] + private bool _isLoadingLuftbild; + + /// How LUFTBILD LADEN is getting on, or how it ended when it was cancelled; null otherwise. + [ObservableProperty] + private string? _luftbildStatus; + [ObservableProperty] private bool _isImporting; @@ -138,13 +177,20 @@ private void Rebuild(IReadOnlyList overlays) Items.Add(item); } - // The newest Ebene is shown when it arrives, here or from another device, and hides the - // ones before it. On opening the Einsatz only the newest is shown. - if (Items.Count > 0 && (first || !known.ContainsKey(Items[^1].Id))) + // The newest GeoJSON Ebene is shown when it arrives, here or from another device, and hides + // the ones before it. On opening the Einsatz only the newest is shown. A raster Ebene lies + // under them all and covers none, so it is shown when it arrives and on opening, and leaves + // the others as they are. + foreach (var item in Items.Where(i => i.IsRaster && (first || !known.ContainsKey(i.Id)))) + { + item.IsVisible = true; + } + + if (Items.LastOrDefault(i => !i.IsRaster) is { } newest && (first || !known.ContainsKey(newest.Id))) { - foreach (var item in Items) + foreach (var item in Items.Where(i => !i.IsRaster)) { - item.IsVisible = ReferenceEquals(item, Items[^1]); + item.IsVisible = ReferenceEquals(item, newest); } } @@ -156,6 +202,7 @@ private void Rebuild(IReadOnlyList overlays) OnPropertyChanged(nameof(HasItems)); OnPropertyChanged(nameof(Header)); UpdateVisibleShapes(); + UpdateVisibleRasters(); } private void Track(Task load) @@ -187,6 +234,86 @@ internal void UpdateVisibleShapes() } } + // Every photo first, then every drawing, each in the order the Einsatz has them. + internal void UpdateVisibleRasters() + { + var rasters = Items + .Where(i => i.IsVisible) + .Select(i => i.Raster) + .OfType() + .OrderBy(r => r.Info.Format == RasterFormat.Png) + .ToList(); + if (!rasters.SequenceEqual(VisibleRasters, ReferenceEqualityComparer.Instance)) + { + VisibleRasters = rasters; + } + } + + /// + /// LUFTBILD LADEN: the Luftbild and the Flurstücksgrenzen of , the + /// section the Lagekarte shows, become two Ebenen. Both pictures are fetched before either is + /// stored, so a failed download leaves the Einsatz as it was. The section goes to the LDBV, and + /// only on this tap (see docs/datenschutz-und-sicherheit.md). + /// + [SuppressMessage( + "Design", + "CA1031", + Justification = "A store or upload failure after both downloads is heterogeneous; it surfaces in Error, as ImportAsync's does.")] + [RelayCommand(CanExecute = nameof(CanLoadLuftbild), IncludeCancelCommand = true)] + private async Task LoadLuftbildAsync(GeoBox? visible, CancellationToken cancellationToken) + { + if (!CanLoadLuftbild || _luftbild is null || visible is null) + { + return; + } + + Error = null; + LuftbildStatus = null; + if (LuftbildArea.For(visible) is not { } area) + { + Error = LuftbildArea.OutsideBavaria; + return; + } + + IsLoadingLuftbild = true; + var step = "Luftbild"; + try + { + LuftbildStatus = "Luftbild wird geladen …"; + var photo = await _luftbild.GetMapAsync(LuftbildLayer.Luftbild, area, cancellationToken); + step = "Flurstücksgrenzen"; + LuftbildStatus = "Flurstücksgrenzen werden geladen …"; + var parcels = await _luftbild.GetMapAsync(LuftbildLayer.Flurstuecke, area, cancellationToken); + LuftbildStatus = null; + + // Not cancellable from here on: both pictures are in, and half an import is worse than a whole one. + await _session.AddMapOverlayAsync("luftbild.jpg", "image/jpeg", photo, Summary("Luftbild (LDBV)", area), CancellationToken.None); + await _session.AddMapOverlayAsync("flurstuecke.png", "image/png", parcels, Summary("Flurstücksgrenzen (LDBV)", area), CancellationToken.None); + _onChanged(); + } + catch (OperationCanceledException) when (cancellationToken.IsCancellationRequested) + { + LuftbildStatus = "Download abgebrochen."; + } + catch (LuftbildException ex) + { + LuftbildStatus = null; + Error = $"{step} nicht geladen: {ex.Message}"; + } + catch (Exception ex) + { + LuftbildStatus = null; + Error = $"Luftbild nicht übernommen: {ex.Message}"; + } + finally + { + IsLoadingLuftbild = false; + } + } + + private static MapOverlaySummary Summary(string name, LuftbildArea area) => + new(name, 1, null, null, MapOverlayKind.Raster, area.Bounds, LdbvImageryClient.Attribution); + [SuppressMessage( "Design", "CA1031", @@ -307,6 +434,10 @@ internal void ShowBounds(MapOverlayItem item) { _showBounds(data.Bounds); } + else if (item.Raster is { Bounds: var box }) + { + _showBounds(new GeoBounds(box.South, box.West, box.North, box.East)); + } } [SuppressMessage( @@ -318,13 +449,13 @@ private async Task LoadAsync(MapOverlayItem item) var fileId = item.FileId; bool missing; bool again; - (OverlayData? Data, string? Error, bool Parsed) result; + LoadResult result; do { var changesAtStart = _changes; if (!_loads.TryGetValue(fileId, out var load)) { - load = Fetch(fileId); + load = Fetch(fileId, item.RasterBounds); _loads[fileId] = load; } @@ -334,11 +465,11 @@ private async Task LoadAsync(MapOverlayItem item) } catch (Exception ex) { - result = (null, ex.Message, false); + result = new LoadResult(null, null, ex.Message, false); } // A file that could not be fetched is tried again; one that was read, or will never parse, stays. - missing = result.Data is null && !result.Parsed; + missing = !result.Parsed; if (missing && _loads.TryGetValue(fileId, out var cached) && ReferenceEquals(cached, load)) { _loads.Remove(fileId); @@ -351,24 +482,38 @@ private async Task LoadAsync(MapOverlayItem item) } while (again); - item.Loaded(result.Data, result.Error, missing, _clock.Now); + item.Loaded(result.Data, result.Raster, result.Error, missing, _clock.Now); UpdateVisibleShapes(); + UpdateVisibleRasters(); } - private async Task<(OverlayData? Data, string? Error, bool Parsed)> Fetch(Guid fileId) + // A raster Ebene's file is only checked here, never decoded: that is the map's job, and the + // header check is what keeps a hostile file from asking it for more than it can hold. + private async Task Fetch(Guid fileId, GeoBox? rasterBounds) { var bytes = await _session.GetFileBytesAsync(fileId); if (bytes is null) { - return (null, "Datei ist noch nicht verfügbar.", false); + return new LoadResult(null, null, "Datei ist noch nicht verfügbar.", false); + } + + if (rasterBounds is not null) + { + return RasterImage.TryRead(fileId, bytes, rasterBounds, out var raster, out var rasterError) + ? new LoadResult(null, raster, null, true) + : new LoadResult(null, null, rasterError, true); } var (data, error) = await Task.Run(() => Parse(bytes)); - return (data, error, true); + return new LoadResult(data, null, error, true); } private static (OverlayData? Data, string? Error) Parse(byte[] bytes) => OverlayGeoJson.TryParse(bytes, out var data, out var error) ? (data, null) : (null, error); + + // What reading an Ebene's file came to: shapes or a picture, or why neither, and whether the + // file was there to read at all. + private sealed record LoadResult(OverlayData? Data, RasterImage? Raster, string? Error, bool Parsed); } /// One Ebene in the EBENEN list. @@ -383,6 +528,8 @@ internal MapOverlayItem(MapOverlay overlay, MapOverlaysViewModel owner, TimeZone Id = overlay.Id; FileId = overlay.FileId; Name = overlay.Name; + RasterBounds = overlay.Kind == MapOverlayKind.Raster ? overlay.Bounds : null; + Attribution = overlay.Attribution; Detail = $"{Formatting.Timestamp(overlay.ImportedAt)} · {overlay.ImportedBy}"; _owner = owner; } @@ -396,6 +543,21 @@ internal MapOverlayItem(MapOverlay overlay, MapOverlaysViewModel owner, TimeZone /// When and by whom it was imported. public string Detail { get; } + /// Where a raster Ebene's picture lies; null for a GeoJSON Ebene. + public GeoBox? RasterBounds { get; } + + /// A raster Ebene: a Luftbild or Flurstücksgrenzen. + public bool IsRaster => RasterBounds is not null; + + /// The licence line the Ebene's source asks for, as recorded at its download. + public string? Attribution { get; } + + /// A raster Ebene's checked picture; null until its file is read, for a GeoJSON Ebene, and when it could not be. + public RasterImage? Raster { get; private set; } + + /// The Ebene can be centred on: its file has been read. + public bool CanShow => Data is not null || Raster is not null; + public string VisibilityAutomationName => $"{Name}: auf der Karte zeigen"; public string RemoveAutomationName => $"{Name}: entfernen"; @@ -411,7 +573,7 @@ internal MapOverlayItem(MapOverlay overlay, MapOverlaysViewModel owner, TimeZone /// Null while the file is still being read, and when it could not be. public OverlayData? Data { get; private set; } - public bool IsLoading => Data is null && LoadError is null; + public bool IsLoading => !CanShow && LoadError is null; /// Why the Ebene cannot be drawn, in German. [ObservableProperty] @@ -474,13 +636,16 @@ public double FramePosition private bool CanStepForward => FrameIndex < MaxFrameIndex; - internal void Loaded(OverlayData? data, string? error, bool missing, DateTimeOffset now) + internal void Loaded(OverlayData? data, RasterImage? raster, string? error, bool missing, DateTimeOffset now) { IsMissing = missing; Data = data; + Raster = raster; FrameIndex = data?.FrameIndexAt(now) ?? 0; - LoadError = data is null ? $"Ebene konnte nicht gelesen werden: {error}" : null; + LoadError = data is null && raster is null ? $"Ebene konnte nicht gelesen werden: {error}" : null; OnPropertyChanged(nameof(Data)); + OnPropertyChanged(nameof(Raster)); + OnPropertyChanged(nameof(CanShow)); OnPropertyChanged(nameof(IsLoading)); OnPropertyChanged(nameof(IsTimeSeries)); OnPropertyChanged(nameof(ShowsTimeline)); @@ -493,7 +658,11 @@ internal void Loaded(OverlayData? data, string? error, bool missing, DateTimeOff NextFrameCommand.NotifyCanExecuteChanged(); } - partial void OnIsVisibleChanged(bool value) => _owner.UpdateVisibleShapes(); + partial void OnIsVisibleChanged(bool value) + { + _owner.UpdateVisibleShapes(); + _owner.UpdateVisibleRasters(); + } partial void OnFrameIndexChanged(int value) { diff --git a/src/LageBuch.Domain/Files/IncidentFile.cs b/src/LageBuch.Domain/Files/IncidentFile.cs index 86f7f4f34..2fb5e8484 100644 --- a/src/LageBuch.Domain/Files/IncidentFile.cs +++ b/src/LageBuch.Domain/Files/IncidentFile.cs @@ -1,3 +1,5 @@ +using LageBuch.Domain.Map; + namespace LageBuch.Domain.Files; public sealed record IncidentFile @@ -52,6 +54,18 @@ public sealed record IncidentFile [".zip"] = "application/zip", }; + /// + /// The file types a raster Kartenebene, a Luftbild or Flurstücksgrenzen, may be stored as. Its + /// own table, so a GeoJSON Ebene can never be handed an image and an image never a GeoJSON. + /// + public static readonly IReadOnlyDictionary MapOverlayRasterMimeTypesByExtension = + new Dictionary(StringComparer.OrdinalIgnoreCase) + { + [".jpg"] = "image/jpeg", + [".jpeg"] = "image/jpeg", + [".png"] = "image/png", + }; + /// The generic fallback used where "unknown" should still mean a concrete, valid MIME /// type rather than Android's wildcard intent type — see . public const string DefaultMimeType = "application/octet-stream"; @@ -98,11 +112,19 @@ public static IncidentFile Create( /// /// The file behind a Kartenebene: the same rules as , - /// checked against instead. + /// checked against instead, or for a raster Ebene + /// against . /// public static IncidentFile CreateMapOverlay( - Guid id, string fileName, string contentType, long sizeBytes, DateTimeOffset addedAt, string addedBy) => - Create(id, fileName, contentType, sizeBytes, addedAt, addedBy, MapOverlayMimeTypesByExtension); + Guid id, string fileName, string contentType, long sizeBytes, DateTimeOffset addedAt, string addedBy, MapOverlayKind kind = MapOverlayKind.Vector) => + Create( + id, + fileName, + contentType, + sizeBytes, + addedAt, + addedBy, + kind == MapOverlayKind.Raster ? MapOverlayRasterMimeTypesByExtension : MapOverlayMimeTypesByExtension); private static IncidentFile Create( Guid id, diff --git a/src/LageBuch.Domain/Incident.cs b/src/LageBuch.Domain/Incident.cs index 377d72670..f3350d674 100644 --- a/src/LageBuch.Domain/Incident.cs +++ b/src/LageBuch.Domain/Incident.cs @@ -2007,7 +2007,7 @@ public IncidentFile RemoveFile(IClock clock, SessionOperator op, Guid fileId) } /// - /// Imports a Kartenebene: its file (the GeoJSON or zip, unchanged) joins the Einsatz's files, + /// Imports a Kartenebene: its file (the GeoJSON or zip, or a Luftbild's image, unchanged) joins the Einsatz's files, /// and the Ebene points at it. The ETB records the import as a professional record, not /// bookkeeping — an Ausbreitungsprognose is what the Einsatzleitung decided on — so it stays /// visible with Systemmeldungen hidden. The importing device generates both ids, the way @@ -2037,7 +2037,7 @@ public MapOverlay AddMapOverlay( throw new ArgumentException("Diese Kartenebene ist schon im Einsatz.", nameof(overlayId)); } - var file = IncidentFile.CreateMapOverlay(fileId, fileName, contentType, sizeBytes, clock.Now, op.Display); + var file = IncidentFile.CreateMapOverlay(fileId, fileName, contentType, sizeBytes, clock.Now, op.Display, summary.Kind); var overlay = MapOverlay.Create(overlayId, file.Id, summary, clock.Now, op.Display); _files.Add(file); _mapOverlays.Add(overlay); diff --git a/src/LageBuch.Domain/Map/MapOverlay.cs b/src/LageBuch.Domain/Map/MapOverlay.cs index 9fac7158b..bc9a08909 100644 --- a/src/LageBuch.Domain/Map/MapOverlay.cs +++ b/src/LageBuch.Domain/Map/MapOverlay.cs @@ -1,8 +1,12 @@ +using LageBuch.Domain.ValueObjects; + namespace LageBuch.Domain.Map; /// /// An Ebene on the Lagekarte: a GeoJSON file imported into the Einsatz, such as a DWD -/// Ausbreitungsprognose or a Sperrgebiet drawn elsewhere. The geometry stays in the file +/// Ausbreitungsprognose or a Sperrgebiet drawn elsewhere, or an image laid on the map at its +/// , such as a Luftbild (). The geometry +/// or the picture stays in the file /// (, one of the Einsatz's own s); this record /// carries only what the Lagebuch says about the import, so the snapshot every sync pushes stays /// small however large the plume is. @@ -15,6 +19,9 @@ public sealed record MapOverlay /// The most forecast times one Ebene may carry. public const int MaxFrames = 500; + /// The longest licence line kept; a longer one is cut. + public const int MaxAttributionLength = 200; + private MapOverlay( Guid id, Guid fileId, @@ -23,7 +30,10 @@ private MapOverlay( string importedBy, int frameCount, DateTimeOffset? firstTime, - DateTimeOffset? lastTime) + DateTimeOffset? lastTime, + MapOverlayKind kind, + GeoBox? bounds, + string? attribution) { Id = id; FileId = fileId; @@ -33,6 +43,9 @@ private MapOverlay( FrameCount = frameCount; FirstTime = firstTime; LastTime = lastTime; + Kind = kind; + Bounds = bounds; + Attribution = attribution; } public Guid Id { get; } @@ -55,6 +68,21 @@ private MapOverlay( /// The last forecast time, or null when the file carries none. public DateTimeOffset? LastTime { get; } + /// Whether the file holds GeoJSON shapes or one image. + public MapOverlayKind Kind { get; } + + /// + /// Where an image lies on the map; always set for a Ebene and + /// never for a vector one, whose shapes carry their own positions. + /// + public GeoBox? Bounds { get; } + + /// + /// The licence line the source asks for wherever its data is shown, copied at the moment of the + /// download (see AGENTS.md, Stammdaten in an incident); null when the file needs none. + /// + public string? Attribution { get; } + /// True when the Ebene steps through several points in time. public bool IsTimeSeries => FrameCount > 1; @@ -81,13 +109,41 @@ public static MapOverlay Create( throw new ArgumentException("Die Zeitpunkte der Kartenebene passen nicht zusammen.", nameof(summary)); } - return new MapOverlay(id, fileId, name, importedAt, importedBy, summary.FrameCount, summary.FirstTime, summary.LastTime); + if (!Enum.IsDefined(summary.Kind)) + { + throw new ArgumentException("Unbekannte Art von Kartenebene.", nameof(summary)); + } + + if (summary.Kind == MapOverlayKind.Raster && summary.Bounds is null) + { + throw new ArgumentException("Ein Luftbild braucht seine Lage auf der Karte.", nameof(summary)); + } + + if (summary.Kind == MapOverlayKind.Vector && summary.Bounds is not null) + { + throw new ArgumentException("Eine GeoJSON-Ebene trägt ihre Lage selbst.", nameof(summary)); + } + + return new MapOverlay( + id, + fileId, + name, + importedAt, + importedBy, + summary.FrameCount, + summary.FirstTime, + summary.LastTime, + summary.Kind, + summary.Bounds, + Capped(summary.Attribution, MaxAttributionLength)); } /// /// The load path (SQLite and a host's snapshot). Never throws: a row a foreign build or a hostile /// file wrote reads back as the nearest valid Ebene, because an Einsatz that opens with a - /// slightly wrong layer list beats one that does not open. + /// slightly wrong layer list beats one that does not open. An image without a box, or of a kind + /// this build does not know, reads back as a vector Ebene: the map then reports its file as + /// unreadable rather than placing it anywhere, and it can still be removed. /// public static MapOverlay Rehydrate( Guid id, @@ -97,9 +153,13 @@ public static MapOverlay Rehydrate( string? importedBy, int frameCount, DateTimeOffset? firstTime, - DateTimeOffset? lastTime) + DateTimeOffset? lastTime, + MapOverlayKind kind = MapOverlayKind.Vector, + GeoBox? bounds = null, + string? attribution = null) { var timesValid = firstTime is { } first && lastTime is { } last && first <= last; + var raster = kind == MapOverlayKind.Raster && bounds is not null; return new MapOverlay( id, fileId, @@ -108,10 +168,15 @@ public static MapOverlay Rehydrate( importedBy ?? string.Empty, Math.Clamp(frameCount, 1, MaxFrames), timesValid ? firstTime : null, - timesValid ? lastTime : null); + timesValid ? lastTime : null, + raster ? MapOverlayKind.Raster : MapOverlayKind.Vector, + raster ? bounds : null, + Capped(attribution, MaxAttributionLength)); } - private static string? Trimmed(string? value) + private static string? Trimmed(string? value) => Capped(value, MaxNameLength); + + private static string? Capped(string? value, int maxLength) { var trimmed = value?.Trim(); if (string.IsNullOrEmpty(trimmed)) @@ -119,6 +184,6 @@ public static MapOverlay Rehydrate( return null; } - return trimmed[..Math.Min(trimmed.Length, MaxNameLength)].TrimEnd(); + return trimmed[..Math.Min(trimmed.Length, maxLength)].TrimEnd(); } } diff --git a/src/LageBuch.Domain/Map/MapOverlayKind.cs b/src/LageBuch.Domain/Map/MapOverlayKind.cs new file mode 100644 index 000000000..832176c73 --- /dev/null +++ b/src/LageBuch.Domain/Map/MapOverlayKind.cs @@ -0,0 +1,11 @@ +namespace LageBuch.Domain.Map; + +/// What a Kartenebene's file holds, and so how the Lagekarte draws it. +public enum MapOverlayKind +{ + /// GeoJSON shapes, such as a DWD Ausbreitungsprognose. What every Ebene was before the Luftbild. + Vector = 0, + + /// One image, a JPEG or PNG, laid on the map at its : a Luftbild or Flurstücksgrenzen. + Raster = 1, +} diff --git a/src/LageBuch.Domain/Map/MapOverlaySummary.cs b/src/LageBuch.Domain/Map/MapOverlaySummary.cs index a1ca24d77..d720212ca 100644 --- a/src/LageBuch.Domain/Map/MapOverlaySummary.cs +++ b/src/LageBuch.Domain/Map/MapOverlaySummary.cs @@ -1,8 +1,18 @@ +using LageBuch.Domain.ValueObjects; + namespace LageBuch.Domain.Map; /// -/// What the importing device read from a GeoJSON file before it became an Ebene: the name to show -/// and the span of forecast times. The device that parsed the file sends it along, so the host can -/// write the Lagebuch entry without reading the geometry itself. +/// What the importing device read from a file before it became an Ebene: the name to show and the +/// span of forecast times, and for an image its , the box it covers and the +/// licence line it has to carry. The device that read the file sends it along, so the host can +/// write the Lagebuch entry without reading the file itself. /// -public sealed record MapOverlaySummary(string Name, int FrameCount, DateTimeOffset? FirstTime, DateTimeOffset? LastTime); +public sealed record MapOverlaySummary( + string Name, + int FrameCount, + DateTimeOffset? FirstTime, + DateTimeOffset? LastTime, + MapOverlayKind Kind = MapOverlayKind.Vector, + GeoBox? Bounds = null, + string? Attribution = null); diff --git a/src/LageBuch.Domain/ValueObjects/GeoBox.cs b/src/LageBuch.Domain/ValueObjects/GeoBox.cs new file mode 100644 index 000000000..84b203099 --- /dev/null +++ b/src/LageBuch.Domain/ValueObjects/GeoBox.cs @@ -0,0 +1,45 @@ +namespace LageBuch.Domain.ValueObjects; + +/// A box on the Lagekarte, in WGS84 degrees: its west, south, east and north edges. +/// +/// Like , refuses NaN, infinity, anything off the globe and edges out of +/// order, so a box read from a hostile file or a sync peer never reaches the map as one it cannot +/// draw. A box with no width or no height is refused too: nothing could be laid into it. +/// +public sealed record GeoBox +{ + public GeoBox(double west, double south, double east, double north) + { + if (!IsValid(west, south, east, north)) + { + throw new ArgumentOutOfRangeException(nameof(west), "A box needs finite edges on the globe, west of east and south of north."); + } + + West = west; + South = south; + East = east; + North = north; + } + + public double West { get; } + + public double South { get; } + + public double East { get; } + + public double North { get; } + + /// + /// The box, or null when an edge is missing, off the globe or out of order. For edges read from + /// a file or a sync peer, where a bad value must cost the box, not the Einsatz. + /// + public static GeoBox? TryCreate(double? west, double? south, double? east, double? north) => + west is { } w && south is { } s && east is { } e && north is { } n && IsValid(w, s, e, n) + ? new GeoBox(w, s, e, n) + : null; + + private static bool IsValid(double west, double south, double east, double north) => + double.IsFinite(west) && double.IsFinite(east) && double.IsFinite(south) && double.IsFinite(north) + && west >= -180 && east <= 180 && south >= -90 && north <= 90 + && west < east && south < north; +} diff --git a/src/LageBuch.Persistence/IncidentRepository.cs b/src/LageBuch.Persistence/IncidentRepository.cs index 975868a14..9f16e8451 100644 --- a/src/LageBuch.Persistence/IncidentRepository.cs +++ b/src/LageBuch.Persistence/IncidentRepository.cs @@ -371,7 +371,7 @@ private static void WriteMapOverlays(InsertCommands inserts, Incident incident) var o = incident.MapOverlays[i]; Run( inserts, - "INSERT INTO map_overlays (id, ordinal, file_id, name, imported_at, imported_by, frame_count, first_time, last_time) VALUES ($id,$o,$file,$name,$at,$by,$frames,$first,$last);", + "INSERT INTO map_overlays (id, ordinal, file_id, name, imported_at, imported_by, frame_count, first_time, last_time, kind, west, south, east, north, attribution) VALUES ($id,$o,$file,$name,$at,$by,$frames,$first,$last,$kind,$west,$south,$east,$north,$attr);", p => { p("$id", o.Id.ToString()); @@ -383,6 +383,12 @@ private static void WriteMapOverlays(InsertCommands inserts, Incident incident) p("$frames", o.FrameCount); p("$first", (object?)o.FirstTime?.ToString(Iso) ?? DBNull.Value); p("$last", (object?)o.LastTime?.ToString(Iso) ?? DBNull.Value); + p("$kind", (int)o.Kind); + p("$west", (object?)o.Bounds?.West ?? DBNull.Value); + p("$south", (object?)o.Bounds?.South ?? DBNull.Value); + p("$east", (object?)o.Bounds?.East ?? DBNull.Value); + p("$north", (object?)o.Bounds?.North ?? DBNull.Value); + p("$attr", (object?)o.Attribution ?? DBNull.Value); }); } } @@ -1056,7 +1062,7 @@ public static Incident Load(string path) // Einsatz that will not open. var mapOverlays = ReadAll( cn, - "SELECT id, file_id, name, imported_at, imported_by, frame_count, first_time, last_time FROM map_overlays ORDER BY ordinal;", + "SELECT id, file_id, name, imported_at, imported_by, frame_count, first_time, last_time, kind, west, south, east, north, attribution FROM map_overlays ORDER BY ordinal;", r => Guid.TryParse(Str(r, 0), out var id) && Guid.TryParse(Str(r, 1), out var fileId) ? Domain.Map.MapOverlay.Rehydrate( id, @@ -1066,7 +1072,10 @@ public static Incident Load(string path) Str(r, 4), NullableInt(r, 5) ?? 1, NullableDate(r, 6), - NullableDate(r, 7)) + NullableDate(r, 7), + (Domain.Map.MapOverlayKind)(NullableInt(r, 8) ?? 0), + Domain.ValueObjects.GeoBox.TryCreate(NullableDouble(r, 9), NullableDouble(r, 10), NullableDouble(r, 11), NullableDouble(r, 12)), + Str(r, 13)) : null) .OfType() .ToList(); diff --git a/src/LageBuch.Persistence/Sqlite/Migrations.cs b/src/LageBuch.Persistence/Sqlite/Migrations.cs index b7e4000be..b67e66d3e 100644 --- a/src/LageBuch.Persistence/Sqlite/Migrations.cs +++ b/src/LageBuch.Persistence/Sqlite/Migrations.cs @@ -8,7 +8,7 @@ namespace LageBuch.Persistence.Sqlite; public static class Migrations { - public const int CurrentVersion = 45; + public const int CurrentVersion = 46; public static int GetVersion(SqliteConnection cn) { @@ -310,6 +310,11 @@ public static void Migrate(SqliteConnection cn) ApplyV45(cn, tx); } + if (version < 46) + { + ApplyV46(cn, tx); + } + // The version gate above is not proof that the steps it skipped ever ran: a build from a // parallel branch numbers its own migrations too, so a file can carry a marker this lineage // never put there and be missing a column no `version < N` will ever add back. Reconcile the @@ -1364,6 +1369,22 @@ private static void ApplyV45(SqliteConnection cn, SqliteTransaction tx) // Stryker restore all } + // Raster Kartenebenen, the Luftbild and the Flurstücksgrenzen: what kind of file an Ebene is, + // the box an image lies in, and the licence line copied at the download. Additive: an older + // file's Ebenen read back as GeoJSON without a box, which is all they ever were. + // Stryker disable all : SchemaGuard.Reconcile adds these same columns on every open (see V26). + private static void ApplyV46(SqliteConnection cn, SqliteTransaction tx) + { + SchemaHelpers.AddColumnIfMissing(cn, tx, "map_overlays", "kind", "INTEGER NOT NULL DEFAULT 0"); + SchemaHelpers.AddColumnIfMissing(cn, tx, "map_overlays", "west", "REAL"); + SchemaHelpers.AddColumnIfMissing(cn, tx, "map_overlays", "south", "REAL"); + SchemaHelpers.AddColumnIfMissing(cn, tx, "map_overlays", "east", "REAL"); + SchemaHelpers.AddColumnIfMissing(cn, tx, "map_overlays", "north", "REAL"); + SchemaHelpers.AddColumnIfMissing(cn, tx, "map_overlays", "attribution", "TEXT"); + + // Stryker restore all + } + [SuppressMessage( "Security", "CA2100", diff --git a/src/LageBuch.Persistence/Sqlite/SchemaGuard.cs b/src/LageBuch.Persistence/Sqlite/SchemaGuard.cs index d86164622..f5d0c1558 100644 --- a/src/LageBuch.Persistence/Sqlite/SchemaGuard.cs +++ b/src/LageBuch.Persistence/Sqlite/SchemaGuard.cs @@ -116,6 +116,12 @@ internal static class SchemaGuard new("map_overlays", "frame_count", "INTEGER", true, "1"), new("map_overlays", "first_time", "TEXT", false, null), new("map_overlays", "last_time", "TEXT", false, null), + new("map_overlays", "kind", "INTEGER", true, "0"), + new("map_overlays", "west", "REAL", false, null), + new("map_overlays", "south", "REAL", false, null), + new("map_overlays", "east", "REAL", false, null), + new("map_overlays", "north", "REAL", false, null), + new("map_overlays", "attribution", "TEXT", false, null), new("incident_meta", "incident_number", "TEXT", false, null), new("incident_meta", "ils_number", "TEXT", false, null), new("incident_meta", "keyword", "TEXT", false, null), diff --git a/src/LageBuch.Sync/CommandApplier.cs b/src/LageBuch.Sync/CommandApplier.cs index 017a19e38..51053761a 100644 --- a/src/LageBuch.Sync/CommandApplier.cs +++ b/src/LageBuch.Sync/CommandApplier.cs @@ -239,7 +239,14 @@ public static class CommandApplier c.FileName, c.ContentType, c.SizeBytes, - new MapOverlaySummary(c.Name, c.FrameCount, c.FirstTime, c.LastTime)); + new MapOverlaySummary( + c.Name, + c.FrameCount, + c.FirstTime, + c.LastTime, + c.Kind, + GeoBox.TryCreate(c.West, c.South, c.East, c.North), + c.Attribution)); return incident.Files.First(f => f.Id == c.FileId); case RemoveMapOverlayCommand c: return incident.RemoveMapOverlay(clock, Operator(c.Operator), c.OverlayId); diff --git a/src/LageBuch.Sync/IncidentSnapshot.cs b/src/LageBuch.Sync/IncidentSnapshot.cs index 53cb41df5..ad798bcbd 100644 --- a/src/LageBuch.Sync/IncidentSnapshot.cs +++ b/src/LageBuch.Sync/IncidentSnapshot.cs @@ -3,6 +3,7 @@ using LageBuch.Domain.CoMeasurement; using LageBuch.Domain.Etb; using LageBuch.Domain.Leadership; +using LageBuch.Domain.Map; using LageBuch.Domain.Tasks; namespace LageBuch.Sync; @@ -106,7 +107,15 @@ public sealed record MapOverlayDto( string? ImportedBy, int FrameCount, DateTimeOffset? FirstTime, - DateTimeOffset? LastTime); + DateTimeOffset? LastTime, + + // Protocol 44: a raster Ebene's kind, box and licence line; absent, the Ebene is GeoJSON. + MapOverlayKind Kind = MapOverlayKind.Vector, + double? West = null, + double? South = null, + double? East = null, + double? North = null, + string? Attribution = null); public sealed record TimerDto( string Key, diff --git a/src/LageBuch.Sync/RemoteIncidentSession.cs b/src/LageBuch.Sync/RemoteIncidentSession.cs index 77b278c2a..4553097d8 100644 --- a/src/LageBuch.Sync/RemoteIncidentSession.cs +++ b/src/LageBuch.Sync/RemoteIncidentSession.cs @@ -905,7 +905,13 @@ await SendAsync( summary.Name, summary.FrameCount, summary.FirstTime, - summary.LastTime), + summary.LastTime, + summary.Kind, + summary.Bounds?.West, + summary.Bounds?.South, + summary.Bounds?.East, + summary.Bounds?.North, + summary.Attribution), cancellationToken); try diff --git a/src/LageBuch.Sync/SnapshotMapper.cs b/src/LageBuch.Sync/SnapshotMapper.cs index d8fc2506c..09a1d9dc4 100644 --- a/src/LageBuch.Sync/SnapshotMapper.cs +++ b/src/LageBuch.Sync/SnapshotMapper.cs @@ -158,7 +158,20 @@ public static IncidentSnapshot ToSnapshot(Incident incident) NavOverrides: incident.NavOverrides.ToDictionary(kv => kv.Key, kv => kv.Value, StringComparer.Ordinal), ElFuehrungsfahrzeug: incident.LeadershipPost.Fuehrungsfahrzeug, MapOverlays: incident.MapOverlays.Select(o => new MapOverlayDto( - o.Id, o.FileId, o.Name, o.ImportedAt, o.ImportedBy, o.FrameCount, o.FirstTime, o.LastTime)).ToList(), + o.Id, + o.FileId, + o.Name, + o.ImportedAt, + o.ImportedBy, + o.FrameCount, + o.FirstTime, + o.LastTime, + o.Kind, + o.Bounds?.West, + o.Bounds?.South, + o.Bounds?.East, + o.Bounds?.North, + o.Attribution)).ToList(), Gases: incident.Gases.Select(g => new IncidentGasDto(g.Id, GasDefinitionDto.From(g.Definition))).ToList(), DispatchChannel: incident.DispatchChannel, LagefuehrungNodeId: incident.LagefuehrungNodeId); @@ -295,7 +308,17 @@ public static Incident FromSnapshot(IncidentSnapshot snapshot) GeoPoint.TryCreate(snapshot.LocationLatitude, snapshot.LocationLongitude), snapshot.NavOverrides, (snapshot.MapOverlays ?? []).Select(o => MapOverlay.Rehydrate( - o.Id, o.FileId, o.Name, o.ImportedAt, o.ImportedBy, o.FrameCount, o.FirstTime, o.LastTime)), + o.Id, + o.FileId, + o.Name, + o.ImportedAt, + o.ImportedBy, + o.FrameCount, + o.FirstTime, + o.LastTime, + o.Kind, + GeoBox.TryCreate(o.West, o.South, o.East, o.North), + o.Attribution)), snapshot.Gases?.Where(g => g?.Definition is not null).Select(g => new IncidentGas(g.Id, g.Definition.ToDefinition())), snapshot.DispatchChannel, snapshot.LagefuehrungNodeId); diff --git a/src/LageBuch.Sync/SyncCommand.cs b/src/LageBuch.Sync/SyncCommand.cs index e03ff4cf8..dac67b1da 100644 --- a/src/LageBuch.Sync/SyncCommand.cs +++ b/src/LageBuch.Sync/SyncCommand.cs @@ -2,6 +2,7 @@ using LageBuch.Domain.CoMeasurement; using LageBuch.Domain.Etb; using LageBuch.Domain.Leadership; +using LageBuch.Domain.Map; using LageBuch.Domain.Tasks; namespace LageBuch.Sync; @@ -181,7 +182,17 @@ public sealed record AddMapOverlayCommand( string Name, int FrameCount, DateTimeOffset? FirstTime, - DateTimeOffset? LastTime) : SyncCommand; + DateTimeOffset? LastTime, + + // Protocol 44: a raster Ebene, a Luftbild or Flurstücksgrenzen. Its file is a JPEG or PNG laid + // on the map at West/South/East/North (WGS84); the host checks the box (GeoBox) and the kind. + // Defaulted, so a GeoJSON Ebene reads exactly as it did at 38. + MapOverlayKind Kind = MapOverlayKind.Vector, + double? West = null, + double? South = null, + double? East = null, + double? North = null, + string? Attribution = null) : SyncCommand; public sealed record RemoveMapOverlayCommand(OperatorDto Operator, Guid OverlayId) : SyncCommand; diff --git a/src/LageBuch.Sync/SyncProtocol.cs b/src/LageBuch.Sync/SyncProtocol.cs index 5535bfb72..b55d4abdb 100644 --- a/src/LageBuch.Sync/SyncProtocol.cs +++ b/src/LageBuch.Sync/SyncProtocol.cs @@ -249,15 +249,22 @@ public static class SyncProtocol /// Fahrzeugtyp is filled from. A peer at 42 drops the key and reads none, which only leaves its /// new vehicles to be typed by hand, so the floor stays at 40. /// + /// + /// 44: raster Kartenebenen, the Luftbild and the Flurstücksgrenzen. addMapOverlay and the + /// snapshot's mapOverlays carry an optional kind, the box west, + /// south, east, north and an attribution, and the Ebene's file may + /// be a JPEG or PNG. A host at 43 refuses that file type, and a peer at 43 would drop the kind + /// and try to read the image as GeoJSON, so the floor rises to 44. + /// /// - public const int ProtocolVersion = 43; + public const int ProtocolVersion = 44; /// /// The oldest contract this build still speaks. A peer below it is refused with a message naming /// which end to update; a peer at or above it is served. See for /// when to raise this. /// - public const int MinimumProtocolVersion = 40; + public const int MinimumProtocolVersion = 44; /// /// What an absent or zero protocol number on the wire means: the contract as it stood at v0.6.1, diff --git a/tests/LageBuch.Acceptance.Tests/LagekarteLuftbildRenderTests.cs b/tests/LageBuch.Acceptance.Tests/LagekarteLuftbildRenderTests.cs new file mode 100644 index 000000000..e60eefcd4 --- /dev/null +++ b/tests/LageBuch.Acceptance.Tests/LagekarteLuftbildRenderTests.cs @@ -0,0 +1,238 @@ +using System.Buffers.Binary; +using System.Net; +using System.Runtime.InteropServices; +using System.Web; +using Avalonia; +using Avalonia.Controls; +using Avalonia.Headless; +using Avalonia.Headless.XUnit; +using Avalonia.Interactivity; +using Avalonia.Media; +using Avalonia.Media.Imaging; +using Avalonia.Platform; +using Avalonia.Threading; +using Avalonia.VisualTree; +using LageBuch.App.Shared.Controls; +using LageBuch.App.Shared.Views; +using LageBuch.AppLogic.Services.Map; +using LageBuch.AppLogic.ViewModels; +using LageBuch.Domain; +using LageBuch.Domain.ValueObjects; +using LageBuch.Persistence.MasterData; + +namespace LageBuch.Acceptance.Tests; + +/// A Luftbild Ebene on the Lagekarte: where its picture lands, and how LUFTBILD LADEN fills the EBENEN list. +public sealed class LagekarteLuftbildRenderTests : IDisposable +{ + private static readonly GeoPoint Fuerstenfeldbruck = new(48.1785, 11.2555); + + private static readonly Color Red = Color.FromRgb(0xE5, 0x39, 0x35); + + private readonly List _clients = []; + + public void Dispose() + { + foreach (var client in _clients) + { + client.Dispose(); + } + } + + [AvaloniaFact] + public void A_picture_is_drawn_exactly_into_the_rectangle_of_its_box() + { + var (window, control) = ShowMap(rotation: 0); + control.RasterOverlays = [Picture(BoxOnScreen(control, new Rect(100, 50, 200, 200)))]; + + using var frame = Settled(window, control); + + Assert.Equal(Red, PixelAt(frame, 200, 150)); + Assert.Equal(Red, PixelAt(frame, 103, 53)); + Assert.Equal(Red, PixelAt(frame, 296, 246)); + Assert.NotEqual(Red, PixelAt(frame, 96, 150)); + Assert.NotEqual(Red, PixelAt(frame, 304, 150)); + Assert.NotEqual(Red, PixelAt(frame, 200, 46)); + Assert.NotEqual(Red, PixelAt(frame, 200, 254)); + } + + [AvaloniaFact] + public void On_a_turned_map_the_picture_turns_with_the_streets() + { + // A box east of the centre, 100 to 180 px right of it on the north-up map. + var (window, control) = ShowMap(rotation: 0); + var box = BoxOnScreen(control, new Rect(300, 130, 80, 40)); + control.RasterOverlays = [Picture(box)]; + control.Rotation = 90; + + using var frame = Settled(window, control); + + // A quarter turn clockwise puts east at the bottom: the box now lies below the centre. + Assert.Equal(Red, PixelAt(frame, 200, 290)); + Assert.NotEqual(Red, PixelAt(frame, 340, 150)); + } + + [AvaloniaFact] + public void A_hidden_picture_leaves_the_map_as_it_was() + { + var (window, control) = ShowMap(rotation: 0); + control.RasterOverlays = [Picture(BoxOnScreen(control, new Rect(100, 50, 200, 200)))]; + using (var shown = Settled(window, control)) + { + Assert.Equal(Red, PixelAt(shown, 200, 150)); + } + + control.RasterOverlays = []; + using var hidden = Settled(window, control); + + Assert.NotEqual(Red, PixelAt(hidden, 200, 150)); + } + + [AvaloniaFact] + public void LUFTBILD_LADEN_adds_two_Ebenen_and_their_licence_line() + { + var session = TestSession.StartNew( + new FakeStore(), + new FixedClock(), + new SessionOperator(AnonymizedExampleData.OperatorSurname, "FFB 12/1"), + "/x.lagebuch", + Array.Empty<(string, bool)>(), + Array.Empty<(string, bool)>()); + var http = new HttpClient(new LdbvHandler()); + _clients.Add(http); + var vm = new LagekarteViewModel(session, () => { }, luftbild: new LdbvImageryClient(http)); + vm.Map.ChangeViewCommand.Execute(new MapViewChange(Fuerstenfeldbruck, 16)); + var view = new LagekarteView { DataContext = vm }; + var window = new Window { Content = view, Width = 1280, Height = 800 }; + window.Show(); + Dispatcher.UIThread.RunJobs(); + + var button = view.GetVisualDescendants().OfType public sealed record RasterImage(Guid FileId, ReadOnlyMemory Bytes, GeoBox Bounds, RasterImageInfo Info) { - /// The longest side a picture may have to be drawn: past the 4096 LUFTBILD LADEN asks for, far short of a decoding bomb. - public const int MaxPixels = 8192; + /// + /// The longest side a picture may have to be drawn: what LUFTBILD LADEN asks for at most. A + /// picture from a file or a sync peer that claims more is refused before anything decodes it. + /// + public const int MaxPixels = LuftbildArea.MaxPixels; + + /// What the picture takes in memory once decoded, four bytes a pixel. + public long DecodedBytes => 4L * Info.Width * Info.Height; /// /// The picture in laid into ; false, with the diff --git a/src/LageBuch.AppLogic/Services/Map/RasterImageInfo.cs b/src/LageBuch.AppLogic/Services/Map/RasterImageInfo.cs index 4f8b7dcbb..ebd64e640 100644 --- a/src/LageBuch.AppLogic/Services/Map/RasterImageInfo.cs +++ b/src/LageBuch.AppLogic/Services/Map/RasterImageInfo.cs @@ -43,11 +43,14 @@ public sealed record RasterImageInfo(RasterFormat Format, int Width, int Height) return width > 0 && height > 0 ? new RasterImageInfo(RasterFormat.Png, width, height) : null; } - // Walks the segments to the first frame header (SOF0 to SOF15, which are not DHT, JPG or DAC), - // whose payload is precision, then height and width. A scan before any frame header, or a - // segment that runs past the end, makes the file unreadable. + // Walks the segments up to the scan (SOS) the way a decoder does, and takes the size from the + // one frame header (SOF0 to SOF15, which are not DHT, JPG or DAC) before it. Anything a decoder + // could read differently makes the file unreadable rather than guessed at: a length-less marker + // (TEM, RSTn, a second SOI, a stuffed FF00) where only segments belong, a second frame header, + // a scan without one, the end of the image before any scan, or a segment running past the end. private static RasterImageInfo? ReadJpeg(ReadOnlySpan bytes) { + RasterImageInfo? frame = null; var at = 2; while (at + 1 < bytes.Length) { @@ -64,27 +67,37 @@ public sealed record RasterImageInfo(RasterFormat Format, int Width, int Height) continue; } - if (marker is 0xDA or 0xD9) + if (marker == 0xDA) { - return null; + return frame; } - if (at + 4 > bytes.Length) + if (marker is 0x00 or 0x01 or 0xD8 or 0xD9 or (>= 0xD0 and <= 0xD7) || at + 4 > bytes.Length) { return null; } var length = BinaryPrimitives.ReadUInt16BigEndian(bytes.Slice(at + 2, 2)); + if (length < 2) + { + return null; + } + if (marker is >= 0xC0 and <= 0xCF and not 0xC4 and not 0xC8 and not 0xCC) { - if (length < 7 || at + 9 > bytes.Length) + if (frame is not null || length < 8 || at + 9 > bytes.Length) { return null; } var height = BinaryPrimitives.ReadUInt16BigEndian(bytes.Slice(at + 5, 2)); var width = BinaryPrimitives.ReadUInt16BigEndian(bytes.Slice(at + 7, 2)); - return width > 0 && height > 0 ? new RasterImageInfo(RasterFormat.Jpeg, width, height) : null; + if (width == 0 || height == 0) + { + return null; + } + + frame = new RasterImageInfo(RasterFormat.Jpeg, width, height); } at += 2 + length; diff --git a/src/LageBuch.AppLogic/ViewModels/MapOverlaysViewModel.cs b/src/LageBuch.AppLogic/ViewModels/MapOverlaysViewModel.cs index 0321836e6..99afb7477 100644 --- a/src/LageBuch.AppLogic/ViewModels/MapOverlaysViewModel.cs +++ b/src/LageBuch.AppLogic/ViewModels/MapOverlaysViewModel.cs @@ -24,6 +24,14 @@ namespace LageBuch.AppLogic.ViewModels; /// public sealed partial class MapOverlaysViewModel : ObservableObject { + /// + /// How much memory the shown pictures may take once decoded, together: one Luftbild and its + /// Flurstücksgrenzen at the largest LUFTBILD LADEN fetches (2 × 4096² × 4 bytes, 128 MiB), which + /// an Android tablet still holds beside the map. A picture past it stays off the map, newest + /// first kept, so a file or a peer with many pictures cannot exhaust a device's memory. + /// + public const long MaxVisibleRasterBytes = 2L * RasterImage.MaxPixels * RasterImage.MaxPixels * 4; + private readonly IIncidentSession _session; private readonly Action _onChanged; private readonly IFileDialogService? _dialogs; @@ -104,13 +112,18 @@ public MapOverlaysViewModel( [NotifyPropertyChangedFor(nameof(RasterAttribution))] private IReadOnlyList _visibleRasters = []; - /// The licence lines of the shown raster Ebenen, each once; null while none is shown. + /// Why a switched-on picture is not on the map: the shown ones would take too much memory. Null otherwise. + [ObservableProperty] + private string? _rasterBudgetHint; + + /// The licence lines of the pictures on the map, each once; null while none is. public string? RasterAttribution { get { + var shown = VisibleRasters.Select(r => r.FileId).ToHashSet(); var lines = Items - .Where(i => i.IsVisible && i.Raster is not null) + .Where(i => shown.Contains(i.FileId)) .Select(i => i.Attribution) .OfType() .Distinct(StringComparer.Ordinal) @@ -170,7 +183,8 @@ private void Rebuild(IReadOnlyList overlays) { if (!known.TryGetValue(overlay.Id, out var item)) { - item = new MapOverlayItem(overlay, this, _timeZone); + var contentType = _session.Incident.Files.FirstOrDefault(f => f.Id == overlay.FileId)?.ContentType; + item = new MapOverlayItem(overlay, this, _timeZone, string.Equals(contentType, "image/jpeg", StringComparison.OrdinalIgnoreCase)); Track(LoadAsync(item)); } @@ -181,9 +195,23 @@ private void Rebuild(IReadOnlyList overlays) // the ones before it. On opening the Einsatz only the newest is shown. A raster Ebene lies // under them all and covers none, so it is shown when it arrives and on opening, and leaves // the others as they are. - foreach (var item in Items.Where(i => i.IsRaster && (first || !known.ContainsKey(i.Id)))) + // On opening, only the newest Luftbild and the newest Flurstücksgrenzen: an Einsatz may hold + // many sections, and every picture shown takes its memory. + if (first) + { + var newestPhoto = Items.LastOrDefault(i => i.IsRaster && i.IsPhoto); + var newestDrawing = Items.LastOrDefault(i => i.IsRaster && !i.IsPhoto); + foreach (var item in Items.Where(i => i.IsRaster)) + { + item.IsVisible = ReferenceEquals(item, newestPhoto) || ReferenceEquals(item, newestDrawing); + } + } + else { - item.IsVisible = true; + foreach (var item in Items.Where(i => i.IsRaster && !known.ContainsKey(i.Id))) + { + item.IsVisible = true; + } } if (Items.LastOrDefault(i => !i.IsRaster) is { } newest && (first || !known.ContainsKey(newest.Id))) @@ -234,15 +262,28 @@ internal void UpdateVisibleShapes() } } - // Every photo first, then every drawing, each in the order the Einsatz has them. + // Every photo first, then every drawing, each in the order the Einsatz has them; within + // MaxVisibleRasterBytes, filled from the newest down. internal void UpdateVisibleRasters() { - var rasters = Items - .Where(i => i.IsVisible) - .Select(i => i.Raster) - .OfType() - .OrderBy(r => r.Info.Format == RasterFormat.Png) - .ToList(); + var budget = MaxVisibleRasterBytes; + var skipped = false; + var kept = new List(); + foreach (var raster in Items.Where(i => i.IsVisible).Select(i => i.Raster).OfType().Reverse()) + { + if (raster.DecodedBytes > budget) + { + skipped = true; + continue; + } + + budget -= raster.DecodedBytes; + kept.Add(raster); + } + + kept.Reverse(); + var rasters = kept.OrderBy(r => r.Info.Format == RasterFormat.Png).ToList(); + RasterBudgetHint = skipped ? "Nicht alle eingeblendeten Luftbilder passen in den Speicher. Ältere ausblenden." : null; if (!rasters.SequenceEqual(VisibleRasters, ReferenceEqualityComparer.Instance)) { VisibleRasters = rasters; @@ -522,8 +563,9 @@ public sealed partial class MapOverlayItem : ObservableObject private readonly MapOverlaysViewModel _owner; private readonly TimeZoneInfo _timeZone; - internal MapOverlayItem(MapOverlay overlay, MapOverlaysViewModel owner, TimeZoneInfo timeZone) + internal MapOverlayItem(MapOverlay overlay, MapOverlaysViewModel owner, TimeZoneInfo timeZone, bool isPhoto) { + IsPhoto = isPhoto; _timeZone = timeZone; Id = overlay.Id; FileId = overlay.FileId; @@ -549,6 +591,9 @@ internal MapOverlayItem(MapOverlay overlay, MapOverlaysViewModel owner, TimeZone /// A raster Ebene: a Luftbild or Flurstücksgrenzen. public bool IsRaster => RasterBounds is not null; + /// The Ebene's file is a JPEG: for a raster Ebene, a Luftbild rather than Flurstücksgrenzen. + public bool IsPhoto { get; } + /// The licence line the Ebene's source asks for, as recorded at its download. public string? Attribution { get; } diff --git a/src/LageBuch.Domain/Incident.cs b/src/LageBuch.Domain/Incident.cs index f3350d674..8ab1f7049 100644 --- a/src/LageBuch.Domain/Incident.cs +++ b/src/LageBuch.Domain/Incident.cs @@ -25,6 +25,13 @@ public sealed class Incident /// Ausbreitungsprognose every hour or so; this leaves room for days of them. public const int MaxMapOverlays = 100; + /// + /// The most Luftbild and Flurstücksgrenzen Ebenen one Einsatz holds: ten sections of both. Each + /// is a picture of up to tens of megabytes in the file and in every device's memory, so a long + /// list of them is a burden on a tablet long before it is useful. + /// + public const int MaxRasterMapOverlays = 20; + /// /// Why refuses a partner's Einsatzleitung, in German. The Führung /// board says the same while a unit is held over one. @@ -2032,6 +2039,11 @@ public MapOverlay AddMapOverlay( throw new InvalidOperationException($"Ein Einsatz hat höchstens {MaxMapOverlays} Kartenebenen."); } + if (summary.Kind == MapOverlayKind.Raster && _mapOverlays.Count(o => o.Kind == MapOverlayKind.Raster) >= MaxRasterMapOverlays) + { + throw new InvalidOperationException($"Ein Einsatz hat höchstens {MaxRasterMapOverlays} Luftbild-Ebenen. Ältere entfernen."); + } + if (_mapOverlays.Any(o => o.Id == overlayId) || _files.Any(f => f.Id == fileId)) { throw new ArgumentException("Diese Kartenebene ist schon im Einsatz.", nameof(overlayId)); diff --git a/tests/LageBuch.Acceptance.Tests/LagekarteLuftbildRenderTests.cs b/tests/LageBuch.Acceptance.Tests/LagekarteLuftbildRenderTests.cs index e60eefcd4..9bcc5534a 100644 --- a/tests/LageBuch.Acceptance.Tests/LagekarteLuftbildRenderTests.cs +++ b/tests/LageBuch.Acceptance.Tests/LagekarteLuftbildRenderTests.cs @@ -88,6 +88,18 @@ public void A_hidden_picture_leaves_the_map_as_it_was() Assert.NotEqual(Red, PixelAt(hidden, 200, 150)); } + [AvaloniaFact] + public void A_picture_that_decodes_to_another_shape_than_its_header_claimed_is_not_drawn() + { + var (window, control) = ShowMap(rotation: 0); + var box = BoxOnScreen(control, new Rect(100, 50, 200, 200)); + control.RasterOverlays = [new RasterImage(Guid.NewGuid(), RedPng(64, 64), box, new RasterImageInfo(RasterFormat.Png, 32, 16))]; + + using var frame = Settled(window, control); + + Assert.NotEqual(Red, PixelAt(frame, 200, 150)); + } + [AvaloniaFact] public void LUFTBILD_LADEN_adds_two_Ebenen_and_their_licence_line() { @@ -229,7 +241,7 @@ private static byte[] PngHeader(int width, int height) private static byte[] JpegHeader(int width, int height) { - var bytes = new byte[] { 0xFF, 0xD8, 0xFF, 0xC0, 0x00, 0x11, 0x08, 0, 0, 0, 0, 3, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0xFF, 0xD9 }; + var bytes = new byte[] { 0xFF, 0xD8, 0xFF, 0xC0, 0x00, 0x11, 0x08, 0, 0, 0, 0, 3, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0xFF, 0xDA, 0x00, 0x08, 0x01, 0x01, 0x00, 0x00, 0x3F, 0x00, 0xFF, 0xD9 }; BinaryPrimitives.WriteUInt16BigEndian(bytes.AsSpan(7), (ushort)height); BinaryPrimitives.WriteUInt16BigEndian(bytes.AsSpan(9), (ushort)width); return bytes; diff --git a/tests/LageBuch.AppLogic.Tests/MapOverlaysLuftbildTests.cs b/tests/LageBuch.AppLogic.Tests/MapOverlaysLuftbildTests.cs index 3437c7cff..6974a7af6 100644 --- a/tests/LageBuch.AppLogic.Tests/MapOverlaysLuftbildTests.cs +++ b/tests/LageBuch.AppLogic.Tests/MapOverlaysLuftbildTests.cs @@ -293,6 +293,81 @@ await session.AddMapOverlayAsync( Assert.Empty(vm.VisibleRasters); } + [Fact] + public async Task On_opening_an_Einsatz_only_its_newest_Luftbild_and_Flurstuecksgrenzen_are_shown() + { + var session = NewSession(); + await AddPair(session, 1000, 1000); + await AddPair(session, 1000, 1000); + + var (vm, _) = Open(session, null); + await vm.SettledAsync(); + + Assert.Equal([false, false, true, true], vm.Items.Select(i => i.IsVisible)); + Assert.Equal(2, vm.VisibleRasters.Count); + } + + [Fact] + public async Task Pictures_past_the_memory_budget_stay_off_the_map_and_say_so() + { + var session = NewSession(); + await AddPair(session, 4096, 4096); + await AddPair(session, 4096, 4096); + var (vm, _) = Open(session, null); + await vm.SettledAsync(); + Assert.Null(vm.RasterBudgetHint); + + // The older pair switched on as well: the newer pair fills the budget, so the older stays off. + vm.Items[0].IsVisible = true; + vm.Items[1].IsVisible = true; + + Assert.Equal(2, vm.VisibleRasters.Count); + Assert.All(vm.VisibleRasters, r => Assert.Contains(r.FileId, vm.Items.Skip(2).Select(i => i.FileId))); + Assert.Equal("Nicht alle eingeblendeten Luftbilder passen in den Speicher. Ältere ausblenden.", vm.RasterBudgetHint); + Assert.True(MapOverlaysViewModel.MaxVisibleRasterBytes >= 2L * 4096 * 4096 * 4); + + vm.Items[0].IsVisible = false; + vm.Items[1].IsVisible = false; + Assert.Null(vm.RasterBudgetHint); + } + + [Fact] + public async Task A_hostile_file_of_many_pictures_never_lays_more_than_the_budget_on_the_map() + { + var session = NewSession(); + for (var i = 0; i < 5; i++) + { + await AddPair(session, 4096, 4096); + } + + var (vm, _) = Open(session, null); + await vm.SettledAsync(); + foreach (var item in vm.Items) + { + item.IsVisible = true; + } + + var bytes = vm.VisibleRasters.Sum(r => 4L * r.Info.Width * r.Info.Height); + Assert.InRange(bytes, 1, MapOverlaysViewModel.MaxVisibleRasterBytes); + Assert.NotNull(vm.RasterBudgetHint); + } + + [Fact] + public void A_picture_is_drawn_up_to_what_LUFTBILD_LADEN_asks_for_and_no_larger() + { + Assert.True(RasterImage.TryRead(Guid.NewGuid(), TestImages.Png(LuftbildArea.MaxPixels, LuftbildArea.MaxPixels), Visible, out _, out _)); + Assert.False(RasterImage.TryRead(Guid.NewGuid(), TestImages.Png(LuftbildArea.MaxPixels + 1, 10), Visible, out _, out var error)); + Assert.Equal("Das Bild ist zu groß für die Karte.", error); + } + + private static async Task AddPair(LocalIncidentSession session, int width, int height) + { + await session.AddMapOverlayAsync( + "luftbild.jpg", "image/jpeg", TestImages.Jpeg(width, height), new MapOverlaySummary("Luftbild (LDBV)", 1, null, null, MapOverlayKind.Raster, Visible, LdbvImageryClient.Attribution)); + await session.AddMapOverlayAsync( + "flurstuecke.png", "image/png", TestImages.Png(width, height), new MapOverlaySummary("Flurstücksgrenzen (LDBV)", 1, null, null, MapOverlayKind.Raster, Visible, LdbvImageryClient.Attribution)); + } + private static HttpResponseMessage Jpeg(HttpRequestMessage request) { var query = HttpUtility.ParseQueryString(Assert.IsType(request.RequestUri).Query); diff --git a/tests/LageBuch.AppLogic.Tests/RasterImageInfoTests.cs b/tests/LageBuch.AppLogic.Tests/RasterImageInfoTests.cs index 1483bbdb5..1c28328ea 100644 --- a/tests/LageBuch.AppLogic.Tests/RasterImageInfoTests.cs +++ b/tests/LageBuch.AppLogic.Tests/RasterImageInfoTests.cs @@ -52,6 +52,56 @@ public void A_segment_running_past_the_end_is_unreadable() Assert.Null(RasterImageInfo.Read(bytes.AsSpan(0, 10))); } + // A restart marker has no length. A walk that added one would step over the real frame header + // and could land on a decoy one, while the decoder reads the real size. + [Theory] + [InlineData(0xD0)] + [InlineData(0xD7)] + [InlineData(0x01)] + [InlineData(0xD8)] + [InlineData(0x00)] + public void A_length_less_marker_before_the_frame_header_makes_the_JPEG_unreadable(byte marker) + { + byte[] bytes = [.. TestImages.Jfif, 0xFF, marker, .. TestImages.Frame(640, 480), .. TestImages.Scan, 0xFF, 0xD9]; + + Assert.Null(RasterImageInfo.Read(bytes)); + } + + [Fact] + public void A_restart_marker_hiding_a_huge_frame_behind_a_small_decoy_is_unreadable() + { + // FF D0 followed by two bytes a length-adding walk would read as 0x0013, skipping the + // 60000 px frame and finding the 64 px one; a decoder reads the first. + byte[] bytes = [.. TestImages.Jfif, 0xFF, 0xD0, .. TestImages.Frame(60_000, 60_000), .. TestImages.Frame(64, 64), .. TestImages.Scan, 0xFF, 0xD9]; + + Assert.Null(RasterImageInfo.Read(bytes)); + } + + [Fact] + public void Two_frame_headers_before_the_scan_make_the_JPEG_unreadable() + { + byte[] bytes = [.. TestImages.Jfif, .. TestImages.Frame(64, 64), .. TestImages.Frame(60_000, 60_000), .. TestImages.Scan, 0xFF, 0xD9]; + + Assert.Null(RasterImageInfo.Read(bytes)); + } + + [Fact] + public void A_JPEG_that_ends_before_its_scan_is_unreadable() + { + byte[] bytes = [.. TestImages.Jfif, .. TestImages.Frame(64, 64), 0xFF, 0xD9]; + + Assert.Null(RasterImageInfo.Read(bytes)); + } + + [Fact] + public void A_frame_header_after_another_segment_is_still_found() + { + byte[] comment = [0xFF, 0xFE, 0x00, 0x05, (byte)'L', (byte)'D', (byte)'B']; + byte[] bytes = [.. TestImages.Jfif, .. comment, .. TestImages.Frame(640, 480), .. TestImages.Scan, 0xFF, 0xD9]; + + Assert.Equal(new RasterImageInfo(RasterFormat.Jpeg, 640, 480), RasterImageInfo.Read(bytes)); + } + [Theory] [InlineData(0, 10)] [InlineData(10, 0)] diff --git a/tests/LageBuch.AppLogic.Tests/TestImages.cs b/tests/LageBuch.AppLogic.Tests/TestImages.cs index d23692cb9..26489597b 100644 --- a/tests/LageBuch.AppLogic.Tests/TestImages.cs +++ b/tests/LageBuch.AppLogic.Tests/TestImages.cs @@ -8,6 +8,9 @@ namespace LageBuch.AppLogic.Tests; /// internal static class TestImages { + /// Where the JPEG's frame header (FF C0) starts, right after the JFIF segment. + public const int JpegFrameAt = 20; + public static byte[] Png(int width, int height) { var bytes = new byte[33]; @@ -22,22 +25,25 @@ public static byte[] Png(int width, int height) return bytes; } - /// A JFIF header, then the baseline frame header that names the size. - public static byte[] Jpeg(int width, int height) + /// A JFIF header, the baseline frame header that names the size, a scan header and the end. + public static byte[] Jpeg(int width, int height) => [.. Jfif, .. Frame(width, height), .. Scan, 0xFF, 0xD9]; + + /// The JFIF APP0 segment after the start-of-image marker: 20 bytes. + public static byte[] Jfif => + [ + 0xFF, 0xD8, + 0xFF, 0xE0, 0x00, 0x10, (byte)'J', (byte)'F', (byte)'I', (byte)'F', 0x00, 0x01, 0x01, 0x00, 0x00, 0x01, 0x00, 0x01, 0x00, 0x00, + ]; + + /// A baseline frame header (SOF0) of three components: 19 bytes. + public static byte[] Frame(int width, int height) { - byte[] start = - [ - 0xFF, 0xD8, - 0xFF, 0xE0, 0x00, 0x10, (byte)'J', (byte)'F', (byte)'I', (byte)'F', 0x00, 0x01, 0x01, 0x00, 0x00, 0x01, 0x00, 0x01, 0x00, 0x00, - 0xFF, 0xC0, 0x00, 0x11, 0x08, - ]; - var bytes = new byte[start.Length + 4 + 12 + 2]; - start.CopyTo(bytes, 0); - BinaryPrimitives.WriteUInt16BigEndian(bytes.AsSpan(start.Length), (ushort)height); - BinaryPrimitives.WriteUInt16BigEndian(bytes.AsSpan(start.Length + 2), (ushort)width); - bytes[start.Length + 4] = 3; - bytes[^2] = 0xFF; - bytes[^1] = 0xD9; - return bytes; + byte[] frame = [0xFF, 0xC0, 0x00, 0x11, 0x08, 0, 0, 0, 0, 3, 1, 0x22, 0, 2, 0x11, 1, 3, 0x11, 1]; + BinaryPrimitives.WriteUInt16BigEndian(frame.AsSpan(5), (ushort)height); + BinaryPrimitives.WriteUInt16BigEndian(frame.AsSpan(7), (ushort)width); + return frame; } + + /// A scan header (SOS) of one component, then a byte of entropy-coded data. + public static byte[] Scan => [0xFF, 0xDA, 0x00, 0x08, 0x01, 0x01, 0x00, 0x00, 0x3F, 0x00, 0x12]; } diff --git a/tests/LageBuch.Domain.Tests/MapOverlayRasterTests.cs b/tests/LageBuch.Domain.Tests/MapOverlayRasterTests.cs index 9e402dff1..64277d524 100644 --- a/tests/LageBuch.Domain.Tests/MapOverlayRasterTests.cs +++ b/tests/LageBuch.Domain.Tests/MapOverlayRasterTests.cs @@ -142,6 +142,25 @@ public void An_attribution_is_trimmed_capped_and_blank_means_none() Assert.Null(blank.Attribution); } + [Fact] + public void An_Einsatz_takes_only_so_many_raster_Ebenen_but_still_GeoJSON_ones() + { + var (incident, clock, op) = NewIncident(); + for (var i = 0; i < Incident.MaxRasterMapOverlays; i++) + { + incident.AddMapOverlay(clock, op, Guid.NewGuid(), Guid.NewGuid(), "a.png", "image/png", 10, Raster()); + } + + var refused = Assert.Throws(() => + incident.AddMapOverlay(clock, op, Guid.NewGuid(), Guid.NewGuid(), "b.png", "image/png", 10, Raster())); + Assert.Equal($"Ein Einsatz hat höchstens {Incident.MaxRasterMapOverlays} Luftbild-Ebenen. Ältere entfernen.", refused.Message); + Assert.Equal(Incident.MaxRasterMapOverlays, incident.MapOverlays.Count); + Assert.Equal(Incident.MaxRasterMapOverlays, incident.Files.Count); + + incident.AddMapOverlay(clock, op, Guid.NewGuid(), Guid.NewGuid(), "lage.geojson", "application/geo+json", 10, new MapOverlaySummary("lage", 1, null, null)); + Assert.Equal(Incident.MaxRasterMapOverlays + 1, incident.MapOverlays.Count); + } + [Fact] public void A_loaded_raster_row_without_a_box_reads_back_as_a_vector_Ebene() { From 295b477a1c4e0ea45892c96c705162f7a6adebd2 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Thomas=20M=C3=BCller?= <1005065+DeepDiver1975@users.noreply.github.com> Date: Fri, 20 Nov 2026 00:43:20 +0100 Subject: [PATCH 3/7] fix(lagekarte): ask the codec for a Luftbild's size before decoding it MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit RasterOverlayCache now opens every picture with SkiaSharp's SKCodec and reads the size the decoder itself reports before a single pixel is allocated. A picture the codec cannot open, whose size differs from what RasterImageInfo read from its header, or that is over 4096 px a side is drawn as nothing. This replaces the DecodeToWidth guard, which only checked after decoding. SkiaSharp 3.119.4 already ships through Avalonia.Skia; App.Shared now references it directly, with the version pinned centrally to the one Avalonia resolves. The lock files change only from Transitive to CentralTransitive with the same version and hash. Co-Authored-By: Claude Opus 5.5 Signed-off-by: Thomas Müller <1005065+DeepDiver1975@users.noreply.github.com> --- Directory.Packages.props | 2 + .../Controls/RasterOverlayCache.cs | 42 ++++++--- .../LageBuch.App.Shared.csproj | 1 + src/LageBuch.App.Shared/packages.lock.json | 20 ++++ src/LageBuch.App/packages.lock.json | 22 +++-- .../RasterOverlayCacheTests.cs | 91 +++++++++++++++++++ .../packages.lock.json | 22 +++-- tests/LageBuch.App.Tests/packages.lock.json | 22 +++-- 8 files changed, 179 insertions(+), 43 deletions(-) create mode 100644 tests/LageBuch.Acceptance.Tests/RasterOverlayCacheTests.cs diff --git a/Directory.Packages.props b/Directory.Packages.props index e181df09b..07a3a6ec5 100644 --- a/Directory.Packages.props +++ b/Directory.Packages.props @@ -28,6 +28,8 @@ + + diff --git a/src/LageBuch.App.Shared/Controls/RasterOverlayCache.cs b/src/LageBuch.App.Shared/Controls/RasterOverlayCache.cs index 7669c8744..128180466 100644 --- a/src/LageBuch.App.Shared/Controls/RasterOverlayCache.cs +++ b/src/LageBuch.App.Shared/Controls/RasterOverlayCache.cs @@ -2,6 +2,7 @@ using System.Runtime.InteropServices; using Avalonia.Media.Imaging; using LageBuch.AppLogic.Services.Map; +using SkiaSharp; namespace LageBuch.App.Shared.Controls; @@ -104,23 +105,38 @@ private async Task DecodeAsync(RasterImage raster, int generation) } } - // Decoded to the width its checked header names, so a picture whose real frame claims more than - // RasterImageInfo read is scaled down rather than held at full size; and a picture that does not - // come out at exactly the checked size is dropped, never drawn into a box made for another. - private static Bitmap? Decode(RasterImage raster) + /// + /// Whether the decoder itself, asked before a single pixel is allocated, opens the picture and + /// reports exactly the size read from its header, within + /// a side. The header check in AppLogic is ours; this is the + /// codec's own reading, so a file crafted to read one way to us and another to Skia never decodes. + /// + public static bool CodecConfirms(RasterImage raster) { - using var stream = MemoryMarshal.TryGetArray(raster.Bytes, out var segment) && segment.Array is { } array - ? new MemoryStream(array, segment.Offset, segment.Count, writable: false) - : new MemoryStream(raster.Bytes.ToArray(), writable: false); - var bitmap = Bitmap.DecodeToWidth(stream, raster.Info.Width); - if (bitmap.PixelSize.Width == raster.Info.Width && bitmap.PixelSize.Height == raster.Info.Height) - { - return bitmap; - } + ArgumentNullException.ThrowIfNull(raster); + using var stream = Open(raster.Bytes); + using var codec = SKCodec.Create(stream); + return codec is { Info: var info } + && info.Width == raster.Info.Width + && info.Height == raster.Info.Height + && info.Width <= RasterImage.MaxPixels + && info.Height <= RasterImage.MaxPixels; + } - using (bitmap) + // Only a picture the codec vouches for is decoded; any other is drawn as nothing. + private static Bitmap? Decode(RasterImage raster) + { + if (!CodecConfirms(raster)) { return null; } + + using var stream = Open(raster.Bytes); + return new Bitmap(stream); } + + private static MemoryStream Open(ReadOnlyMemory bytes) => + MemoryMarshal.TryGetArray(bytes, out var segment) && segment.Array is { } array + ? new MemoryStream(array, segment.Offset, segment.Count, writable: false) + : new MemoryStream(bytes.ToArray(), writable: false); } diff --git a/src/LageBuch.App.Shared/LageBuch.App.Shared.csproj b/src/LageBuch.App.Shared/LageBuch.App.Shared.csproj index a637ea73d..bc867d45a 100644 --- a/src/LageBuch.App.Shared/LageBuch.App.Shared.csproj +++ b/src/LageBuch.App.Shared/LageBuch.App.Shared.csproj @@ -9,6 +9,7 @@ + diff --git a/src/LageBuch.App.Shared/packages.lock.json b/src/LageBuch.App.Shared/packages.lock.json index 2c74e2452..15333434f 100644 --- a/src/LageBuch.App.Shared/packages.lock.json +++ b/src/LageBuch.App.Shared/packages.lock.json @@ -31,6 +31,16 @@ "Avalonia": "12.1.6" } }, + "SkiaSharp": { + "type": "Direct", + "requested": "[3.119.4, )", + "resolved": "3.119.4", + "contentHash": "53NOSUZ1Us+91Sm0uCkIivh/k7jOowRErZT2sIWwPFN9mLUvdxnE6rS4sWo4255+Rd2MWUSF+j0NMZHD6Cke+Q==", + "dependencies": { + "SkiaSharp.NativeAssets.Win32": "3.119.4", + "SkiaSharp.NativeAssets.macOS": "3.119.4" + } + }, "StyleCop.Analyzers": { "type": "Direct", "requested": "[1.2.0-beta.556, )", @@ -185,6 +195,16 @@ "resolved": "11.0.0", "contentHash": "HH2akbW2HeY/xeZJA5UceuQQX+1Pv/Kxrz/x4XPoH6wYDtgPIlBeOTZlQXlT+b50b1Ym/xfP+WJCX9FW4uLBXQ==" }, + "SkiaSharp.NativeAssets.macOS": { + "type": "Transitive", + "resolved": "3.119.4", + "contentHash": "fgBOWEqbY012x7gMfJU4ezgz6dfhJb30Z6YdW35h85Zoe39+a8YNbAAwL29ihPfWoppg5AjvyKNzD1oCvlqWwA==" + }, + "SkiaSharp.NativeAssets.Win32": { + "type": "Transitive", + "resolved": "3.119.4", + "contentHash": "XOpbx/4CReO2wYsq2s6rbvdauc6dntG4Zv499sHGTJ87bwZaFXszFkwql3+FIZMc8kUPeaj3Mx2ezIJmo8a1Kg==" + }, "SQLite": { "type": "Transitive", "resolved": "3.53.4", diff --git a/src/LageBuch.App/packages.lock.json b/src/LageBuch.App/packages.lock.json index e72f2ef3b..22eccbe1b 100644 --- a/src/LageBuch.App/packages.lock.json +++ b/src/LageBuch.App/packages.lock.json @@ -280,15 +280,6 @@ "resolved": "11.0.0", "contentHash": "HH2akbW2HeY/xeZJA5UceuQQX+1Pv/Kxrz/x4XPoH6wYDtgPIlBeOTZlQXlT+b50b1Ym/xfP+WJCX9FW4uLBXQ==" }, - "SkiaSharp": { - "type": "Transitive", - "resolved": "3.119.4", - "contentHash": "53NOSUZ1Us+91Sm0uCkIivh/k7jOowRErZT2sIWwPFN9mLUvdxnE6rS4sWo4255+Rd2MWUSF+j0NMZHD6Cke+Q==", - "dependencies": { - "SkiaSharp.NativeAssets.Win32": "3.119.4", - "SkiaSharp.NativeAssets.macOS": "3.119.4" - } - }, "SkiaSharp.NativeAssets.Linux": { "type": "Transitive", "resolved": "3.119.4", @@ -394,7 +385,8 @@ "Avalonia": "[12.1.6, )", "Avalonia.Controls.DataGrid": "[12.1.2, )", "Avalonia.Themes.Fluent": "[12.1.6, )", - "LageBuch.AppLogic": "[1.0.0, )" + "LageBuch.AppLogic": "[1.0.0, )", + "SkiaSharp": "[3.119.4, )" } }, "lagebuch.applogic": { @@ -511,6 +503,16 @@ "requested": "[2026.9.1, )", "resolved": "2026.9.1", "contentHash": "i2BT/v+Ui6Hg9+BZbOci/VfsyvmtY8nlQqAOmFt8iOZ4Hm9aKZZRgZZ+LfrKWYXAHRb3l1EjDcMVfjRaZTt+Cw==" + }, + "SkiaSharp": { + "type": "CentralTransitive", + "requested": "[3.119.4, )", + "resolved": "3.119.4", + "contentHash": "53NOSUZ1Us+91Sm0uCkIivh/k7jOowRErZT2sIWwPFN9mLUvdxnE6rS4sWo4255+Rd2MWUSF+j0NMZHD6Cke+Q==", + "dependencies": { + "SkiaSharp.NativeAssets.Win32": "3.119.4", + "SkiaSharp.NativeAssets.macOS": "3.119.4" + } } } } diff --git a/tests/LageBuch.Acceptance.Tests/RasterOverlayCacheTests.cs b/tests/LageBuch.Acceptance.Tests/RasterOverlayCacheTests.cs new file mode 100644 index 000000000..8f46f3d9f --- /dev/null +++ b/tests/LageBuch.Acceptance.Tests/RasterOverlayCacheTests.cs @@ -0,0 +1,91 @@ +using System.Buffers.Binary; +using Avalonia; +using Avalonia.Headless.XUnit; +using Avalonia.Media.Imaging; +using Avalonia.Platform; +using LageBuch.App.Shared.Controls; +using LageBuch.AppLogic.Services.Map; +using LageBuch.Domain.ValueObjects; + +namespace LageBuch.Acceptance.Tests; + +/// +/// The decoder's own word on a picture's size, asked before a pixel is allocated: what +/// read from the header is only trusted as far as the codec agrees. +/// +public class RasterOverlayCacheTests +{ + private static readonly GeoBox Box = new(11.24, 48.17, 11.26, 48.18); + + [AvaloniaFact] + public void A_real_picture_whose_header_the_codec_confirms_is_taken() + { + var png = Png(64, 48); + + Assert.True(RasterOverlayCache.CodecConfirms(Read(png))); + } + + [AvaloniaFact] + public void A_header_the_codec_reads_as_another_size_is_refused_before_decoding() + { + // The bytes are a 64 × 48 picture; the checked header claims 32 × 48. + var png = Png(64, 48); + var claimed = new RasterImage(Guid.NewGuid(), png, Box, new RasterImageInfo(RasterFormat.Png, 32, 48)); + + Assert.False(RasterOverlayCache.CodecConfirms(claimed)); + } + + [AvaloniaFact] + public void A_PNG_whose_header_was_rewritten_to_a_small_size_is_refused() + { + // RasterImageInfo reads the forged IHDR as 16 × 16; the codec refuses the chunk whose CRC no longer matches. + var png = Png(64, 48); + BinaryPrimitives.WriteInt32BigEndian(png.AsSpan(16), 16); + BinaryPrimitives.WriteInt32BigEndian(png.AsSpan(20), 16); + var raster = Read(png); + Assert.Equal(16, raster.Info.Width); + + Assert.False(RasterOverlayCache.CodecConfirms(raster)); + } + + [AvaloniaFact] + public void A_header_without_a_picture_behind_it_is_refused() + { + // A PNG signature and IHDR that RasterImageInfo accepts, and nothing a codec can open. + var header = Png(64, 48)[..33]; + var raster = Read(header); + + Assert.False(RasterOverlayCache.CodecConfirms(raster)); + } + + [AvaloniaFact] + public void A_crafted_JPEG_frame_the_codec_cannot_open_is_refused() + { + // A frame header of 64 × 48 with no colour components: RasterImageInfo reads its size, a + // real decoder refuses the frame outright. + byte[] jpeg = + [ + 0xFF, 0xD8, + 0xFF, 0xC0, 0x00, 0x08, 0x08, 0x00, 0x30, 0x00, 0x40, 0x00, + 0xFF, 0xDA, 0x00, 0x08, 0x01, 0x01, 0x00, 0x00, 0x3F, 0x00, 0xFF, 0xD9, + ]; + var raster = Read(jpeg); + Assert.Equal(64, raster.Info.Width); + + Assert.False(RasterOverlayCache.CodecConfirms(raster)); + } + + private static RasterImage Read(byte[] bytes) + { + Assert.True(RasterImage.TryRead(Guid.NewGuid(), bytes, Box, out var raster, out var error), error); + return raster; + } + + private static byte[] Png(int width, int height) + { + using var bitmap = new WriteableBitmap(new PixelSize(width, height), new Vector(96, 96), PixelFormat.Bgra8888, AlphaFormat.Premul); + using var stream = new MemoryStream(); + bitmap.Save(stream, PngBitmapEncoderOptions.Default); + return stream.ToArray(); + } +} diff --git a/tests/LageBuch.Acceptance.Tests/packages.lock.json b/tests/LageBuch.Acceptance.Tests/packages.lock.json index 59a27627a..cb64414ec 100644 --- a/tests/LageBuch.Acceptance.Tests/packages.lock.json +++ b/tests/LageBuch.Acceptance.Tests/packages.lock.json @@ -314,15 +314,6 @@ "resolved": "5.0.0", "contentHash": "dDoKi0PnDz31yAyETfRntsLArTlVAVzUzCIvvEDsDsucrl33Dl8pIJG06ePTJTI3tGpeyHS9Cq7Foc/s4EeKcg==" }, - "SkiaSharp": { - "type": "Transitive", - "resolved": "3.119.4", - "contentHash": "53NOSUZ1Us+91Sm0uCkIivh/k7jOowRErZT2sIWwPFN9mLUvdxnE6rS4sWo4255+Rd2MWUSF+j0NMZHD6Cke+Q==", - "dependencies": { - "SkiaSharp.NativeAssets.Win32": "3.119.4", - "SkiaSharp.NativeAssets.macOS": "3.119.4" - } - }, "SkiaSharp.NativeAssets.Linux": { "type": "Transitive", "resolved": "3.119.4", @@ -490,7 +481,8 @@ "Avalonia": "[12.1.6, )", "Avalonia.Controls.DataGrid": "[12.1.2, )", "Avalonia.Themes.Fluent": "[12.1.6, )", - "LageBuch.AppLogic": "[1.0.0, )" + "LageBuch.AppLogic": "[1.0.0, )", + "SkiaSharp": "[3.119.4, )" } }, "lagebuch.applogic": { @@ -592,6 +584,16 @@ "SQLitePCLRaw.bundle_e_sqlite3": "3.0.5", "SQLitePCLRaw.core": "3.0.5" } + }, + "SkiaSharp": { + "type": "CentralTransitive", + "requested": "[3.119.4, )", + "resolved": "3.119.4", + "contentHash": "53NOSUZ1Us+91Sm0uCkIivh/k7jOowRErZT2sIWwPFN9mLUvdxnE6rS4sWo4255+Rd2MWUSF+j0NMZHD6Cke+Q==", + "dependencies": { + "SkiaSharp.NativeAssets.Win32": "3.119.4", + "SkiaSharp.NativeAssets.macOS": "3.119.4" + } } } } diff --git a/tests/LageBuch.App.Tests/packages.lock.json b/tests/LageBuch.App.Tests/packages.lock.json index 4acd6ef61..9c05329f6 100644 --- a/tests/LageBuch.App.Tests/packages.lock.json +++ b/tests/LageBuch.App.Tests/packages.lock.json @@ -291,15 +291,6 @@ "Microsoft.TestPlatform.ObjectModel": "18.12.0" } }, - "SkiaSharp": { - "type": "Transitive", - "resolved": "3.119.4", - "contentHash": "53NOSUZ1Us+91Sm0uCkIivh/k7jOowRErZT2sIWwPFN9mLUvdxnE6rS4sWo4255+Rd2MWUSF+j0NMZHD6Cke+Q==", - "dependencies": { - "SkiaSharp.NativeAssets.Win32": "3.119.4", - "SkiaSharp.NativeAssets.macOS": "3.119.4" - } - }, "SkiaSharp.NativeAssets.Linux": { "type": "Transitive", "resolved": "3.119.4", @@ -457,7 +448,8 @@ "Avalonia": "[12.1.6, )", "Avalonia.Controls.DataGrid": "[12.1.2, )", "Avalonia.Themes.Fluent": "[12.1.6, )", - "LageBuch.AppLogic": "[1.0.0, )" + "LageBuch.AppLogic": "[1.0.0, )", + "SkiaSharp": "[3.119.4, )" } }, "lagebuch.applogic": { @@ -608,6 +600,16 @@ "requested": "[2026.9.1, )", "resolved": "2026.9.1", "contentHash": "i2BT/v+Ui6Hg9+BZbOci/VfsyvmtY8nlQqAOmFt8iOZ4Hm9aKZZRgZZ+LfrKWYXAHRb3l1EjDcMVfjRaZTt+Cw==" + }, + "SkiaSharp": { + "type": "CentralTransitive", + "requested": "[3.119.4, )", + "resolved": "3.119.4", + "contentHash": "53NOSUZ1Us+91Sm0uCkIivh/k7jOowRErZT2sIWwPFN9mLUvdxnE6rS4sWo4255+Rd2MWUSF+j0NMZHD6Cke+Q==", + "dependencies": { + "SkiaSharp.NativeAssets.Win32": "3.119.4", + "SkiaSharp.NativeAssets.macOS": "3.119.4" + } } } } From 5c830c19c948643af642537ba099e77a4de7f8fb Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Thomas=20M=C3=BCller?= <1005065+DeepDiver1975@users.noreply.github.com> Date: Fri, 20 Nov 2026 10:19:02 +0100 Subject: [PATCH 4/7] fix(lagekarte): address review of the Luftbild download and its map cache MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit - RasterOverlayCache counts running decodes against the 128 MiB budget until they end, also after their Ebene is hidden or the cache cleared, so a pair replaced mid-decode makes the new pair wait. A picture hidden and shown again reuses the decode already under way. - A picture that fails to decode is reported through the map's RasterFailedCommand; its Ebene's row says so and stays removable. - LdbvImageryClient wraps a connection dropped inside the body (IOException, HttpIOException) in a German LuftbildException. - MapOverlaysViewModel lets go of the contents of removed Ebenen. - Leaving the Einsatz cancels a LUFTBILD LADEN still downloading and waits for it; one already storing is let finish. - LUFTBILD LADEN checks for two free raster slots before it downloads, and takes the Luftbild back out should its Flurstücksgrenzen be refused, with a message that names what the Einsatz holds afterwards. Co-Authored-By: Claude Opus 5.5 Signed-off-by: Thomas Müller <1005065+DeepDiver1975@users.noreply.github.com> --- .../Controls/MapCanvasControl.cs | 20 ++- .../Controls/RasterOverlayCache.cs | 109 ++++++++++++---- .../Views/LagekarteView.axaml | 1 + .../Services/Map/LdbvImageryClient.cs | 5 + .../ViewModels/IncidentWorkspaceViewModel.cs | 7 + .../ViewModels/MapOverlaysViewModel.cs | 94 +++++++++++++- src/LageBuch.Domain/Incident.cs | 11 ++ .../RasterOverlayCacheTests.cs | 120 ++++++++++++++++++ .../LdbvImageryClientTests.cs | 55 ++++++++ .../MapOverlaysLuftbildTests.cs | 77 +++++++++++ .../MapOverlayRasterTests.cs | 18 +++ 11 files changed, 485 insertions(+), 32 deletions(-) diff --git a/src/LageBuch.App.Shared/Controls/MapCanvasControl.cs b/src/LageBuch.App.Shared/Controls/MapCanvasControl.cs index 7dfb218e5..6344d5b58 100644 --- a/src/LageBuch.App.Shared/Controls/MapCanvasControl.cs +++ b/src/LageBuch.App.Shared/Controls/MapCanvasControl.cs @@ -70,6 +70,10 @@ public sealed class MapCanvasControl : Control public static readonly StyledProperty?> RasterOverlaysProperty = AvaloniaProperty.Register?>(nameof(RasterOverlays)); + /// Invoked with the file of a raster picture that would not decode, so its Ebene can say so. + public static readonly StyledProperty RasterFailedCommandProperty = + AvaloniaProperty.Register(nameof(RasterFailedCommand)); + /// The Fließweg from the Einsatzort, start first; null draws none. public static readonly StyledProperty?> FlowPathProperty = AvaloniaProperty.Register?>(nameof(FlowPath)); @@ -115,7 +119,7 @@ static MapCanvasControl() public MapCanvasControl() { _terrain = new TerrainTileCache(InvalidateVisual); - _rasters = new RasterOverlayCache(InvalidateVisual); + _rasters = new RasterOverlayCache(InvalidateVisual, OnRasterFailed); GestureRecognizers.Add(new PinchGestureRecognizer()); AddHandler(PinchEvent, OnPinch); AddHandler(PinchEndedEvent, OnPinchEnded); @@ -196,6 +200,12 @@ public IReadOnlyList? RasterOverlays set => SetValue(RasterOverlaysProperty, value); } + public ICommand? RasterFailedCommand + { + get => GetValue(RasterFailedCommandProperty); + set => SetValue(RasterFailedCommandProperty, value); + } + /// Whether Luftbild pictures are still being decoded; the map redraws as each is ready. public bool IsRasterBusy => _rasters.IsBusy; @@ -516,6 +526,14 @@ private void ZoomAt(Point screen, int zoom) Report(WebMercator.ToGeo(anchorX - dx, anchorY - dy, zoom), zoom); } + private void OnRasterFailed(Guid fileId) + { + if (RasterFailedCommand?.CanExecute(fileId) == true) + { + RasterFailedCommand.Execute(fileId); + } + } + // A pan or zoom leaves the turn as it is: the rotation is null unless the hand turned the map. private void Report(GeoPoint center, int zoom, double? rotation = null) { diff --git a/src/LageBuch.App.Shared/Controls/RasterOverlayCache.cs b/src/LageBuch.App.Shared/Controls/RasterOverlayCache.cs index 128180466..5fc6d8842 100644 --- a/src/LageBuch.App.Shared/Controls/RasterOverlayCache.cs +++ b/src/LageBuch.App.Shared/Controls/RasterOverlayCache.cs @@ -2,6 +2,7 @@ using System.Runtime.InteropServices; using Avalonia.Media.Imaging; using LageBuch.AppLogic.Services.Map; +using LageBuch.AppLogic.ViewModels; using SkiaSharp; namespace LageBuch.App.Shared.Controls; @@ -12,97 +13,149 @@ namespace LageBuch.App.Shared.Controls; /// -- and the map is told to draw again once it is ready; until then the map shows without it. /// A picture no longer shown is released at once: each one holds tens of megabytes. /// -/// Deliberately not , like : its control releases it through . +/// +/// +/// The memory the pictures hold and the memory the decodes under way are about to take share one +/// budget, . A decode is never forgotten +/// while it runs -- not when its Ebene is hidden, not by -- so a pair replaced +/// mid-decode keeps its share until it is done, and the new pair waits for it. A picture hidden and +/// shown again while it decodes takes the decode already under way. +/// +/// Deliberately not , like : its control releases it through . +/// public sealed class RasterOverlayCache { - private readonly Dictionary _decoded = new(); - private readonly HashSet _pending = new(); + private readonly Dictionary _decoded = new(); + + // Every decode still running, with the memory its picture will take, whoever still wants it. + private readonly Dictionary _decoding = new(); + + // What the map shows now: a decode that ends for a file no longer here is thrown away. + private readonly HashSet _wanted = new(); private readonly Action? _ready; + private readonly Action? _failed; + private readonly Func _decode; // Bumped by Clear, so a picture decoded for a map that has since let go of it is dropped. private int _generation; - /// Called on the UI thread whenever a picture has become ready to draw. - public RasterOverlayCache(Action? ready = null) + // A wanted picture is waiting for the budget to free up. + private bool _waiting; + + /// Called on the UI thread whenever a picture has become ready to draw, or a decode ended and freed its share of the budget. + /// Called on the UI thread with the file of a picture that would not decode. + /// Decodes one picture off the UI thread; null means . Tests hand in their own. + public RasterOverlayCache(Action? ready = null, Action? failed = null, Func? decode = null) { _ready = ready; + _failed = failed; + _decode = decode ?? Decode; } - /// Whether pictures are still being decoded. - public bool IsBusy => _pending.Count > 0; + /// Whether a decode is running, or a picture to be shown waits for one. + public bool IsBusy => _decoding.Count > 0 || _waiting; + + /// Whether a decode is running, wanted or not. + public bool IsDecoding => _decoding.Count > 0; + + // What the shown pictures hold and the running decodes are about to. + private long Committed => _decoded.Values.Sum(d => d.Bytes) + _decoding.Values.Sum(); /// /// The decoded picture of every one of that is ready, in their - /// order, each with the box it is laid into. Starts decoding the rest, and releases the - /// pictures of Ebenen no longer among them. + /// order, each with the box it is laid into. Starts decoding the rest as far as the budget + /// allows, and releases the pictures of Ebenen no longer among them. /// public IReadOnlyList<(Bitmap Image, Domain.ValueObjects.GeoBox Bounds)> Use(IReadOnlyList? rasters) { - var wanted = (rasters ?? []).Select(r => r.FileId).ToHashSet(); - foreach (var gone in _decoded.Keys.Where(id => !wanted.Contains(id)).ToList()) + _wanted.Clear(); + _wanted.UnionWith((rasters ?? []).Select(r => r.FileId)); + foreach (var gone in _decoded.Keys.Where(id => !_wanted.Contains(id)).ToList()) { - _decoded[gone]?.Dispose(); + _decoded[gone].Image?.Dispose(); _decoded.Remove(gone); } - _pending.IntersectWith(wanted); + _waiting = false; var ready = new List<(Bitmap, Domain.ValueObjects.GeoBox)>(); foreach (var raster in rasters ?? []) { - if (_decoded.TryGetValue(raster.FileId, out var bitmap)) + if (_decoded.TryGetValue(raster.FileId, out var decoded)) { - if (bitmap is not null) + if (decoded.Image is { } image) { - ready.Add((bitmap, raster.Bounds)); + ready.Add((image, raster.Bounds)); } } - else if (_pending.Add(raster.FileId)) + else if (!_decoding.ContainsKey(raster.FileId)) { - // Fire-and-forget on purpose: DecodeAsync never throws, a picture that will not decode is stored as none. - _ = DecodeAsync(raster, _generation); + // A decode already under way, perhaps from before the Ebene was hidden, is reused. + StartOrWait(raster); } } return ready; } + private void StartOrWait(RasterImage raster) + { + if (Committed + raster.DecodedBytes > MapOverlaysViewModel.MaxVisibleRasterBytes) + { + _waiting = true; + return; + } + + _decoding[raster.FileId] = raster.DecodedBytes; + + // Fire-and-forget on purpose: DecodeAsync never throws, a picture that will not decode is stored as none. + _ = DecodeAsync(raster, _generation); + } + + /// Releases every picture. Decodes still running keep their share of the budget until they end, and their results are dropped. public void Clear() { _generation++; - _pending.Clear(); - foreach (var bitmap in _decoded.Values) + _wanted.Clear(); + _waiting = false; + foreach (var (image, _) in _decoded.Values) { - bitmap?.Dispose(); + image?.Dispose(); } _decoded.Clear(); } - [SuppressMessage("Design", "CA1031", Justification = "A picture that will not decode is drawn as nothing, like a damaged terrain tile; its Ebene stays listed and removable.")] + [SuppressMessage("Design", "CA1031", Justification = "A picture that will not decode is drawn as nothing and reported through the failed callback, which the map forwards to its Ebene's row.")] private async Task DecodeAsync(RasterImage raster, int generation) { Bitmap? bitmap; try { - bitmap = await Task.Run(() => Decode(raster)); + bitmap = await Task.Run(() => _decode(raster)); } catch (Exception) { bitmap = null; } + _decoding.Remove(raster.FileId); + // Dropped while it was decoding: by a cleared map, or an Ebene hidden or removed meanwhile. - if (generation != _generation || !_pending.Remove(raster.FileId)) + // Its share of the budget is free again either way, which may let a waiting picture start. + if (generation != _generation || !_wanted.Contains(raster.FileId)) { bitmap?.Dispose(); + _ready?.Invoke(); return; } - _decoded[raster.FileId] = bitmap; - if (bitmap is not null) + _decoded[raster.FileId] = (bitmap, bitmap is null ? 0 : raster.DecodedBytes); + if (bitmap is null) { - _ready?.Invoke(); + _failed?.Invoke(raster.FileId); } + + _ready?.Invoke(); } /// diff --git a/src/LageBuch.App.Shared/Views/LagekarteView.axaml b/src/LageBuch.App.Shared/Views/LagekarteView.axaml index 882aec5e9..1ba3d6116 100644 --- a/src/LageBuch.App.Shared/Views/LagekarteView.axaml +++ b/src/LageBuch.App.Shared/Views/LagekarteView.axaml @@ -391,6 +391,7 @@ SelectedWaterPoint="{Binding SelectedWaterPoint}" Overlays="{Binding MapShapes}" RasterOverlays="{Binding Overlays.VisibleRasters}" + RasterFailedCommand="{Binding Overlays.RasterFailedCommand}" Center="{Binding Map.Center}" Zoom="{Binding Map.Zoom}" Rotation="{Binding Map.Rotation}" diff --git a/src/LageBuch.AppLogic/Services/Map/LdbvImageryClient.cs b/src/LageBuch.AppLogic/Services/Map/LdbvImageryClient.cs index 8c2a65a1d..38986db13 100644 --- a/src/LageBuch.AppLogic/Services/Map/LdbvImageryClient.cs +++ b/src/LageBuch.AppLogic/Services/Map/LdbvImageryClient.cs @@ -90,6 +90,11 @@ public async Task GetMapAsync(LuftbildLayer layer, LuftbildArea area, Ca { throw new LuftbildException($"{Service} nicht erreichbar. Internetverbindung prüfen.", e); } + catch (IOException e) + { + // The connection dropped after the headers, inside the picture (HttpIOException and kin). + throw new LuftbildException($"Die Verbindung zum {Service} ist abgebrochen. Erneut versuchen.", e); + } catch (OperationCanceledException e) when (!cancellationToken.IsCancellationRequested) { // Our own timeout, or HttpClient's, reported as a cancellation nobody asked for. diff --git a/src/LageBuch.AppLogic/ViewModels/IncidentWorkspaceViewModel.cs b/src/LageBuch.AppLogic/ViewModels/IncidentWorkspaceViewModel.cs index ec8b86352..3e9290a49 100644 --- a/src/LageBuch.AppLogic/ViewModels/IncidentWorkspaceViewModel.cs +++ b/src/LageBuch.AppLogic/ViewModels/IncidentWorkspaceViewModel.cs @@ -886,6 +886,13 @@ public void ConfirmLeaveThen(Action leave) /// public async ValueTask LeaveAsync() { + // A LUFTBILD LADEN under way would otherwise store into this session after it is gone, + // or surface its failure in the next workspace: cancel the download and wait for it. + if (Lagekarte is { } lagekarte) + { + await lagekarte.Overlays.StopLuftbildAsync(); + } + // The host controller is app-lifetime too (#463): left running, it would keep serving this // incident to its clients after the operator moved on, and a later share would come back // with the old PIN and the Stammdaten it serialized at the start. diff --git a/src/LageBuch.AppLogic/ViewModels/MapOverlaysViewModel.cs b/src/LageBuch.AppLogic/ViewModels/MapOverlaysViewModel.cs index 99afb7477..0a54eef9a 100644 --- a/src/LageBuch.AppLogic/ViewModels/MapOverlaysViewModel.cs +++ b/src/LageBuch.AppLogic/ViewModels/MapOverlaysViewModel.cs @@ -166,6 +166,13 @@ public void Refresh() Rebuild(overlays); } + // A removed Ebene's file is let go: a Luftbild holds megabytes. A hidden one's stays read. + var files = overlays.Select(o => o.FileId).ToHashSet(); + foreach (var gone in _loads.Keys.Where(id => !files.Contains(id)).ToList()) + { + _loads.Remove(gone); + } + // A file not there yet -- a peer's upload still under way -- is looked for again on every // change, the upload's own announcement included. foreach (var item in Items.Where(i => i.IsMissing)) @@ -240,6 +247,9 @@ private void Track(Task load) _pending.Add(load); } + /// How many files' contents are held; the files of removed Ebenen are let go. + internal int LoadedFileCount => _loads.Count; + /// Completes when every Ebene's file has been looked for. Tests wait on it; the view never needs to. internal async Task SettledAsync() { @@ -316,6 +326,13 @@ private async Task LoadLuftbildAsync(GeoBox? visible, CancellationToken cancella return; } + // Both Ebenen or neither: without room for two, nothing is fetched. + if (_session.Incident.FreeRasterMapOverlaySlots < 2) + { + Error = $"Kein Platz für ein weiteres Luftbild: Ein Einsatz hat höchstens {Incident.MaxRasterMapOverlays} Luftbild-Ebenen. Ältere entfernen."; + return; + } + IsLoadingLuftbild = true; var step = "Luftbild"; try @@ -327,9 +344,9 @@ private async Task LoadLuftbildAsync(GeoBox? visible, CancellationToken cancella var parcels = await _luftbild.GetMapAsync(LuftbildLayer.Flurstuecke, area, cancellationToken); LuftbildStatus = null; - // Not cancellable from here on: both pictures are in, and half an import is worse than a whole one. - await _session.AddMapOverlayAsync("luftbild.jpg", "image/jpeg", photo, Summary("Luftbild (LDBV)", area), CancellationToken.None); - await _session.AddMapOverlayAsync("flurstuecke.png", "image/png", parcels, Summary("Flurstücksgrenzen (LDBV)", area), CancellationToken.None); + // Not cancellable from here on: both pictures are in, and half an import is worse than a + // whole one. Leaving waits for this (StopLuftbildAsync). + Error = await StoreBothAsync(photo, parcels, area); _onChanged(); } catch (OperationCanceledException) when (cancellationToken.IsCancellationRequested) @@ -352,6 +369,74 @@ private async Task LoadLuftbildAsync(GeoBox? visible, CancellationToken cancella } } + // The Luftbild, then its Flurstücksgrenzen; null when both are in, else what went wrong. Should + // the second be refused -- a peer took the last slot meanwhile, the host went away -- the first + // is taken back out, so the Einsatz holds both or neither; if even that fails, the message says + // which one stayed. A failure of the first add is thrown: nothing was stored then. + [SuppressMessage( + "Design", + "CA1031", + Justification = "A refused second add is heterogeneous (domain cap, network, host); it is returned as the German error the caller shows.")] + private async Task StoreBothAsync(byte[] photo, byte[] parcels, LuftbildArea area) + { + var before = _session.Incident.MapOverlays.Select(o => o.Id).ToHashSet(); + await _session.AddMapOverlayAsync("luftbild.jpg", "image/jpeg", photo, Summary("Luftbild (LDBV)", area), CancellationToken.None); + try + { + await _session.AddMapOverlayAsync("flurstuecke.png", "image/png", parcels, Summary("Flurstücksgrenzen (LDBV)", area), CancellationToken.None); + return null; + } + catch (Exception ex) + { + var added = _session.Incident.MapOverlays.FirstOrDefault(o => !before.Contains(o.Id)); + return added is null || await TryRemoveAsync(added.Id) + ? $"Luftbild nicht übernommen: {ex.Message}" + : $"Nur das Luftbild wurde übernommen, die Flurstücksgrenzen nicht: {ex.Message}"; + } + } + + [SuppressMessage( + "Design", + "CA1031", + Justification = "The take-back is best effort: its failure is reported by the caller's error, which then names the Ebene that stayed.")] + private async Task TryRemoveAsync(Guid overlayId) + { + try + { + await _session.RemoveMapOverlayAsync(overlayId, CancellationToken.None); + return true; + } + catch (Exception) + { + return false; + } + } + + /// + /// Cancels a LUFTBILD LADEN still downloading and waits until it has ended. One already storing + /// its two Ebenen is let finish, so the Einsatz is left with both or neither. + /// + public async Task StopLuftbildAsync() + { + if (LoadLuftbildCommand.ExecutionTask is not { IsCompleted: false } running) + { + return; + } + + LoadLuftbildCommand.Cancel(); + await running; + } + + /// The map could not draw the picture of the Ebene whose file this is: its row says so. + [RelayCommand] + private void RasterFailed(Guid fileId) + { + foreach (var item in Items.Where(i => i.FileId == fileId)) + { + item.DrawFailed(); + } + } + private static MapOverlaySummary Summary(string name, LuftbildArea area) => new(name, 1, null, null, MapOverlayKind.Raster, area.Bounds, LdbvImageryClient.Attribution); @@ -703,6 +788,9 @@ internal void Loaded(OverlayData? data, RasterImage? raster, string? error, bool NextFrameCommand.NotifyCanExecuteChanged(); } + // The picture passed every check but the map could not decode it: it stays listed and removable. + internal void DrawFailed() => LoadError = "Ebene konnte nicht gelesen werden: Das Bild lässt sich nicht darstellen."; + partial void OnIsVisibleChanged(bool value) { _owner.UpdateVisibleShapes(); diff --git a/src/LageBuch.Domain/Incident.cs b/src/LageBuch.Domain/Incident.cs index 8ab1f7049..848db6bc7 100644 --- a/src/LageBuch.Domain/Incident.cs +++ b/src/LageBuch.Domain/Incident.cs @@ -32,6 +32,17 @@ public sealed class Incident /// public const int MaxRasterMapOverlays = 20; + /// + /// How many more raster Ebenen this Einsatz takes: within + /// and within overall. LUFTBILD LADEN needs two, and checks for + /// both before it adds either. + /// + public int FreeRasterMapOverlaySlots => Math.Max( + 0, + Math.Min( + MaxRasterMapOverlays - _mapOverlays.Count(o => o.Kind == MapOverlayKind.Raster), + MaxMapOverlays - _mapOverlays.Count)); + /// /// Why refuses a partner's Einsatzleitung, in German. The Führung /// board says the same while a unit is held over one. diff --git a/tests/LageBuch.Acceptance.Tests/RasterOverlayCacheTests.cs b/tests/LageBuch.Acceptance.Tests/RasterOverlayCacheTests.cs index 8f46f3d9f..eb454f682 100644 --- a/tests/LageBuch.Acceptance.Tests/RasterOverlayCacheTests.cs +++ b/tests/LageBuch.Acceptance.Tests/RasterOverlayCacheTests.cs @@ -75,6 +75,126 @@ public void A_crafted_JPEG_frame_the_codec_cannot_open_is_refused() Assert.False(RasterOverlayCache.CodecConfirms(raster)); } + [AvaloniaFact] + public void Hiding_and_showing_a_picture_while_it_decodes_reuses_the_decode_under_way() + { + using var decoder = new GatedDecoder(); + var cache = new RasterOverlayCache(decode: decoder.Decode); + var photo = Full(); + + cache.Use([photo]); + cache.Use([]); + cache.Use([photo]); + decoder.ReleaseAll(); + Pump(() => !cache.IsBusy); + + Assert.Equal(1, decoder.Started); + Assert.Single(cache.Use([photo])); + } + + [AvaloniaFact] + public void A_new_pair_waits_until_the_pair_it_replaces_has_finished_decoding() + { + using var decoder = new GatedDecoder(); + var cache = new RasterOverlayCache(decode: decoder.Decode); + RasterImage[] old = [Full(), Full()]; + RasterImage[] replacement = [Full(), Full()]; + + cache.Use(old); + Pump(() => decoder.Started == 2); + cache.Use(replacement); + + // Two full-size pictures still decoding fill the budget: the new ones may not start yet. + Assert.Equal(2, decoder.Started); + decoder.ReleaseAll(); + Pump(() => decoder.Running == 0 && !cache.IsDecoding); + cache.Use(replacement); + Pump(() => decoder.Started == 4); + decoder.ReleaseAll(); + Pump(() => !cache.IsBusy); + + Assert.Equal(2, cache.Use(replacement).Count); + } + + [AvaloniaFact] + public void A_cleared_cache_still_counts_the_decodes_it_left_running() + { + using var decoder = new GatedDecoder(); + var cache = new RasterOverlayCache(decode: decoder.Decode); + cache.Use([Full(), Full()]); + Pump(() => decoder.Started == 2); + + cache.Clear(); + RasterImage[] next = [Full()]; + cache.Use(next); + + Assert.Equal(2, decoder.Started); + decoder.ReleaseAll(); + Pump(() => !cache.IsDecoding); + cache.Use(next); + Pump(() => decoder.Started == 3); + decoder.ReleaseAll(); + Pump(() => !cache.IsBusy); + Assert.Single(cache.Use(next)); + } + + [AvaloniaFact] + public void A_picture_that_fails_to_decode_is_reported_once_and_drawn_as_nothing() + { + var failed = new List(); + var cache = new RasterOverlayCache(failed: failed.Add, decode: _ => throw new InvalidOperationException("kaputt")); + var photo = Full(); + + cache.Use([photo]); + Pump(() => !cache.IsBusy); + + Assert.Empty(cache.Use([photo])); + Assert.Equal([photo.FileId], failed); + } + + private static RasterImage Full() => + new(Guid.NewGuid(), new byte[] { 1 }, Box, new RasterImageInfo(RasterFormat.Jpeg, RasterImage.MaxPixels, RasterImage.MaxPixels)); + + private static void Pump(Func until) => + Assert.True(SpinWait.SpinUntil( + () => + { + Avalonia.Threading.Dispatcher.UIThread.RunJobs(); + return until(); + }, + TimeSpan.FromSeconds(10))); + + /// Decodes to a 1 × 1 bitmap, but only once the test lets it. + private sealed class GatedDecoder : IDisposable + { + private readonly SemaphoreSlim _gate = new(0); + private int _started; + private int _running; + + public int Started => Volatile.Read(ref _started); + + public int Running => Volatile.Read(ref _running); + + public WriteableBitmap? Decode(RasterImage raster) + { + Interlocked.Increment(ref _started); + Interlocked.Increment(ref _running); + try + { + _gate.Wait(TimeSpan.FromSeconds(10)); + return new WriteableBitmap(new PixelSize(1, 1), new Vector(96, 96), PixelFormat.Bgra8888, AlphaFormat.Premul); + } + finally + { + Interlocked.Decrement(ref _running); + } + } + + public void ReleaseAll() => _gate.Release(16); + + public void Dispose() => _gate.Dispose(); + } + private static RasterImage Read(byte[] bytes) { Assert.True(RasterImage.TryRead(Guid.NewGuid(), bytes, Box, out var raster, out var error), error); diff --git a/tests/LageBuch.AppLogic.Tests/LdbvImageryClientTests.cs b/tests/LageBuch.AppLogic.Tests/LdbvImageryClientTests.cs index e17c49716..6dbfc8b45 100644 --- a/tests/LageBuch.AppLogic.Tests/LdbvImageryClientTests.cs +++ b/tests/LageBuch.AppLogic.Tests/LdbvImageryClientTests.cs @@ -96,6 +96,45 @@ public override void Flush() public override void Write(byte[] buffer, int offset, int count) => throw new NotSupportedException(); } + /// Hands out , then fails the way a dropped connection does. + private sealed class BreakingStream(byte[] start) : Stream + { + private int _position; + + public override bool CanRead => true; + + public override bool CanSeek => false; + + public override bool CanWrite => false; + + public override long Length => throw new NotSupportedException(); + + public override long Position { get => throw new NotSupportedException(); set => throw new NotSupportedException(); } + + public override int Read(byte[] buffer, int offset, int count) + { + if (_position >= start.Length) + { + throw new HttpIOException(HttpRequestError.ResponseEnded, "The response ended prematurely."); + } + + var n = Math.Min(count, start.Length - _position); + Array.Copy(start, _position, buffer, offset, n); + _position += n; + return n; + } + + public override void Flush() + { + } + + public override long Seek(long offset, SeekOrigin origin) => throw new NotSupportedException(); + + public override void SetLength(long value) => throw new NotSupportedException(); + + public override void Write(byte[] buffer, int offset, int count) => throw new NotSupportedException(); + } + private static HttpResponseMessage Image(byte[] bytes, string contentType) { var content = new ByteArrayContent(bytes); @@ -236,6 +275,22 @@ public async Task An_oversized_body_is_refused_by_its_content_length() Assert.Equal("Das Bild des Kartendienstes ist zu groß.", e.Message); } + [Fact] + public async Task A_connection_that_breaks_off_inside_the_picture_becomes_a_German_error() + { + var (client, _) = Create(_ => + { + var content = new StreamContent(new BreakingStream(TestImages.Jpeg(Area.Width, Area.Height)[..8])); + content.Headers.ContentType = new System.Net.Http.Headers.MediaTypeHeaderValue("image/jpeg"); + return new HttpResponseMessage(HttpStatusCode.OK) { Content = content }; + }); + + var e = await Assert.ThrowsAsync(() => client.GetMapAsync(LuftbildLayer.Luftbild, Area)); + + Assert.Equal("Die Verbindung zum Kartendienst der Vermessungsverwaltung ist abgebrochen. Erneut versuchen.", e.Message); + Assert.IsAssignableFrom(e.InnerException); + } + [Fact] public async Task An_endless_body_without_a_length_is_cut_off_at_the_cap() { diff --git a/tests/LageBuch.AppLogic.Tests/MapOverlaysLuftbildTests.cs b/tests/LageBuch.AppLogic.Tests/MapOverlaysLuftbildTests.cs index 6974a7af6..d230125b0 100644 --- a/tests/LageBuch.AppLogic.Tests/MapOverlaysLuftbildTests.cs +++ b/tests/LageBuch.AppLogic.Tests/MapOverlaysLuftbildTests.cs @@ -245,6 +245,83 @@ public async Task A_newer_Luftbild_s_photo_lies_under_an_older_one_s_Flurstuecks Assert.Equal(LdbvImageryClient.Attribution, vm.RasterAttribution); } + [Fact] + public async Task Leaving_cancels_a_download_under_way_and_waits_for_it_to_end() + { + var session = NewSession(); + var handler = new HangingHandler(); + var (vm, _) = Open(session, Client(handler)); + var load = vm.LoadLuftbildCommand.ExecuteAsync(Visible); + await handler.Started.Task; + + await vm.StopLuftbildAsync(); + + Assert.True(load.IsCompleted); + Assert.False(vm.IsLoadingLuftbild); + Assert.Empty(session.Incident.MapOverlays); + } + + [Fact] + public async Task Stopping_with_no_download_under_way_does_nothing() + { + var (vm, _) = Open(NewSession(), Client(new LdbvHandler())); + + await vm.StopLuftbildAsync(); + + Assert.False(vm.IsLoadingLuftbild); + Assert.Null(vm.LuftbildStatus); + } + + [Fact] + public async Task Without_room_for_both_Ebenen_nothing_is_downloaded_or_stored() + { + var session = NewSession(); + for (var i = 0; i < Incident.MaxRasterMapOverlays - 1; i++) + { + await session.AddMapOverlayAsync( + "luftbild.png", "image/png", TestImages.Png(10, 10), new MapOverlaySummary("alt", 1, null, null, MapOverlayKind.Raster, Visible)); + } + + var handler = new LdbvHandler(); + var (vm, _) = Open(session, Client(handler)); + + await vm.LoadLuftbildCommand.ExecuteAsync(Visible); + + Assert.Equal($"Kein Platz für ein weiteres Luftbild: Ein Einsatz hat höchstens {Incident.MaxRasterMapOverlays} Luftbild-Ebenen. Ältere entfernen.", vm.Error); + Assert.Empty(handler.Layers); + Assert.Equal(Incident.MaxRasterMapOverlays - 1, session.Incident.MapOverlays.Count); + } + + [Fact] + public async Task A_removed_Ebene_s_picture_is_not_kept_in_memory() + { + var session = NewSession(); + var (vm, _) = Open(session, Client(new LdbvHandler())); + await vm.LoadLuftbildCommand.ExecuteAsync(Visible); + await vm.SettledAsync(); + Assert.Equal(2, vm.LoadedFileCount); + + await session.RemoveMapOverlayAsync(session.Incident.MapOverlays[0].Id); + await vm.SettledAsync(); + + Assert.Equal(1, vm.LoadedFileCount); + } + + [Fact] + public async Task A_picture_the_map_could_not_draw_says_so_on_its_row() + { + var session = NewSession(); + var (vm, _) = Open(session, Client(new LdbvHandler())); + await vm.LoadLuftbildCommand.ExecuteAsync(Visible); + await vm.SettledAsync(); + + vm.RasterFailedCommand.Execute(vm.Items[0].FileId); + + Assert.Equal("Ebene konnte nicht gelesen werden: Das Bild lässt sich nicht darstellen.", vm.Items[0].LoadError); + Assert.Null(vm.Items[1].LoadError); + Assert.Null(vm.Error); + } + [Fact] public async Task Reopening_an_Einsatz_shows_its_Luftbilder_and_can_centre_on_one() { diff --git a/tests/LageBuch.Domain.Tests/MapOverlayRasterTests.cs b/tests/LageBuch.Domain.Tests/MapOverlayRasterTests.cs index 64277d524..709991c82 100644 --- a/tests/LageBuch.Domain.Tests/MapOverlayRasterTests.cs +++ b/tests/LageBuch.Domain.Tests/MapOverlayRasterTests.cs @@ -161,6 +161,24 @@ public void An_Einsatz_takes_only_so_many_raster_Ebenen_but_still_GeoJSON_ones() Assert.Equal(Incident.MaxRasterMapOverlays + 1, incident.MapOverlays.Count); } + [Fact] + public void The_free_raster_slots_count_down_with_each_Luftbild_and_the_overall_cap() + { + var (incident, clock, op) = NewIncident(); + Assert.Equal(Incident.MaxRasterMapOverlays, incident.FreeRasterMapOverlaySlots); + + incident.AddMapOverlay(clock, op, Guid.NewGuid(), Guid.NewGuid(), "a.png", "image/png", 10, Raster()); + Assert.Equal(Incident.MaxRasterMapOverlays - 1, incident.FreeRasterMapOverlaySlots); + + // GeoJSON Ebenen take no raster slot until the Einsatz runs out of Ebenen altogether. + for (var i = 1; i < Incident.MaxMapOverlays - 1; i++) + { + incident.AddMapOverlay(clock, op, Guid.NewGuid(), Guid.NewGuid(), "lage.geojson", "application/geo+json", 10, new MapOverlaySummary("lage", 1, null, null)); + } + + Assert.Equal(1, incident.FreeRasterMapOverlaySlots); + } + [Fact] public void A_loaded_raster_row_without_a_box_reads_back_as_a_vector_Ebene() { From a333c5a9b8c0f1485689b7af2d10970025c508a2 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Thomas=20M=C3=BCller?= <1005065+DeepDiver1975@users.noreply.github.com> Date: Fri, 20 Nov 2026 11:30:26 +0100 Subject: [PATCH 5/7] fix(lagekarte): roll a half-stored Luftbild back by its own id MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit - IIncidentSession.AddMapOverlayAsync returns the id of the Ebene it created. LocalIncidentSession takes the Ebene back out when its bytes cannot be stored, so a failed add leaves nothing behind; the remote session already did, and now returns the id it generated. - LUFTBILD LADEN rolls the Luftbild back by that id when its Flurstücksgrenzen fail, instead of diffing the Ebenen, which could hit another device's. The rollback is now covered by a test whose store fails the second byte write. - RasterOverlayCacheTests release their decoded bitmaps in finally. Co-Authored-By: Claude Opus 5.5 Signed-off-by: Thomas Müller <1005065+DeepDiver1975@users.noreply.github.com> --- src/LageBuch.AppLogic/LocalIncidentSession.cs | 15 ++- .../ViewModels/MapOverlaysViewModel.cs | 18 +-- src/LageBuch.Sync/IIncidentSession.cs | 5 +- src/LageBuch.Sync/RemoteIncidentSession.cs | 4 +- .../RasterOverlayCacheTests.cs | 122 +++++++++++------- .../CoMessprotokollViewModelTests.cs | 2 +- .../IncidentSessionTests.cs | 11 ++ .../MapOverlaysLuftbildTests.cs | 44 ++++++- 8 files changed, 158 insertions(+), 63 deletions(-) diff --git a/src/LageBuch.AppLogic/LocalIncidentSession.cs b/src/LageBuch.AppLogic/LocalIncidentSession.cs index 88fa8d14b..64eff4130 100644 --- a/src/LageBuch.AppLogic/LocalIncidentSession.cs +++ b/src/LageBuch.AppLogic/LocalIncidentSession.cs @@ -424,7 +424,7 @@ public async Task RemoveFileAsync(Guid fileId, CancellationToken cancellationTok } } - public async Task AddMapOverlayAsync( + public async Task AddMapOverlayAsync( string fileName, string contentType, byte[] bytes, MapOverlaySummary summary, CancellationToken cancellationToken = default) { ArgumentNullException.ThrowIfNull(bytes); @@ -433,12 +433,21 @@ public async Task AddMapOverlayAsync( var file = Incident.Files.First(f => f.Id == overlay.FileId); Save(); - // As AddFileAsync: the incident file must exist before the bytes go in, and Changed is - // raised even when that write fails, because the domain already holds the Ebene. + // As AddFileAsync: the incident file must exist before the bytes go in, so the Ebene is + // recorded first. Should the bytes not go in, the Ebene is taken back out -- an Ebene without + // its file is drawn from nothing -- and the failure still reaches the caller. Changed is + // raised either way, because the domain changed. try { await _store.FlushAsync(cancellationToken); await _store.SaveFileBytesAsync(Path, IncidentFile.StorageFileName(file.Id, file.FileName), bytes, cancellationToken); + return overlay.Id; + } + catch + { + Incident.RemoveMapOverlay(_clock, RequireOperator(), overlay.Id); + Save(); + throw; } finally { diff --git a/src/LageBuch.AppLogic/ViewModels/MapOverlaysViewModel.cs b/src/LageBuch.AppLogic/ViewModels/MapOverlaysViewModel.cs index 0a54eef9a..7243f72ee 100644 --- a/src/LageBuch.AppLogic/ViewModels/MapOverlaysViewModel.cs +++ b/src/LageBuch.AppLogic/ViewModels/MapOverlaysViewModel.cs @@ -369,18 +369,19 @@ private async Task LoadLuftbildAsync(GeoBox? visible, CancellationToken cancella } } - // The Luftbild, then its Flurstücksgrenzen; null when both are in, else what went wrong. Should - // the second be refused -- a peer took the last slot meanwhile, the host went away -- the first - // is taken back out, so the Einsatz holds both or neither; if even that fails, the message says - // which one stayed. A failure of the first add is thrown: nothing was stored then. + // The Luftbild, then its Flurstücksgrenzen; null when both are in, else what went wrong. A + // failed add leaves nothing of itself behind (IIncidentSession.AddMapOverlayAsync), so should + // the second fail -- a peer took the last slot, the disk is full, the host went away -- the + // first is taken back out by the id it was given, never another device's Ebene; if even that + // fails, the message says which one stayed. A failure of the first add is thrown: nothing was + // stored then. [SuppressMessage( "Design", "CA1031", - Justification = "A refused second add is heterogeneous (domain cap, network, host); it is returned as the German error the caller shows.")] + Justification = "A refused second add is heterogeneous (domain cap, disk, network, host); it is returned as the German error the caller shows.")] private async Task StoreBothAsync(byte[] photo, byte[] parcels, LuftbildArea area) { - var before = _session.Incident.MapOverlays.Select(o => o.Id).ToHashSet(); - await _session.AddMapOverlayAsync("luftbild.jpg", "image/jpeg", photo, Summary("Luftbild (LDBV)", area), CancellationToken.None); + var luftbild = await _session.AddMapOverlayAsync("luftbild.jpg", "image/jpeg", photo, Summary("Luftbild (LDBV)", area), CancellationToken.None); try { await _session.AddMapOverlayAsync("flurstuecke.png", "image/png", parcels, Summary("Flurstücksgrenzen (LDBV)", area), CancellationToken.None); @@ -388,8 +389,7 @@ private async Task LoadLuftbildAsync(GeoBox? visible, CancellationToken cancella } catch (Exception ex) { - var added = _session.Incident.MapOverlays.FirstOrDefault(o => !before.Contains(o.Id)); - return added is null || await TryRemoveAsync(added.Id) + return await TryRemoveAsync(luftbild) ? $"Luftbild nicht übernommen: {ex.Message}" : $"Nur das Luftbild wurde übernommen, die Flurstücksgrenzen nicht: {ex.Message}"; } diff --git a/src/LageBuch.Sync/IIncidentSession.cs b/src/LageBuch.Sync/IIncidentSession.cs index 751c666f0..9ec5bd4ad 100644 --- a/src/LageBuch.Sync/IIncidentSession.cs +++ b/src/LageBuch.Sync/IIncidentSession.cs @@ -325,9 +325,10 @@ void AddScbaTrupp( /// /// Imports a Kartenebene: the file's bytes go in as an attachment and the Ebene points at it. /// Awaited like , for the same reasons. The caller has parsed the file - /// already; is what it read. + /// already; is what it read. Returns the new Ebene's id. A failed add + /// leaves no Ebene behind: one whose bytes could not be stored is taken back out. /// - Task AddMapOverlayAsync( + Task AddMapOverlayAsync( string fileName, string contentType, byte[] bytes, MapOverlaySummary summary, CancellationToken cancellationToken = default); /// Takes a Kartenebene off the Lagekarte and its file out of the Einsatz, bytes included. diff --git a/src/LageBuch.Sync/RemoteIncidentSession.cs b/src/LageBuch.Sync/RemoteIncidentSession.cs index 4553097d8..b3726d47c 100644 --- a/src/LageBuch.Sync/RemoteIncidentSession.cs +++ b/src/LageBuch.Sync/RemoteIncidentSession.cs @@ -882,7 +882,7 @@ public Task RemoveFileAsync(Guid fileId, CancellationToken cancellationToken = d // The AddFileAsync split: metadata as a command, then the bytes as a PUT to the file id the // command registered. - public async Task AddMapOverlayAsync( + public async Task AddMapOverlayAsync( string fileName, string contentType, byte[] bytes, MapOverlaySummary summary, CancellationToken cancellationToken = default) { ArgumentNullException.ThrowIfNull(bytes); @@ -928,6 +928,8 @@ await SendAsync( await TakeBackMapOverlayAsync(overlayId); throw; } + + return overlayId; } // Best effort, and deliberately not cancellable: the import's own token may be what failed. If diff --git a/tests/LageBuch.Acceptance.Tests/RasterOverlayCacheTests.cs b/tests/LageBuch.Acceptance.Tests/RasterOverlayCacheTests.cs index eb454f682..23fe56fe4 100644 --- a/tests/LageBuch.Acceptance.Tests/RasterOverlayCacheTests.cs +++ b/tests/LageBuch.Acceptance.Tests/RasterOverlayCacheTests.cs @@ -80,16 +80,24 @@ public void Hiding_and_showing_a_picture_while_it_decodes_reuses_the_decode_unde { using var decoder = new GatedDecoder(); var cache = new RasterOverlayCache(decode: decoder.Decode); - var photo = Full(); + try + { + var photo = Full(); - cache.Use([photo]); - cache.Use([]); - cache.Use([photo]); - decoder.ReleaseAll(); - Pump(() => !cache.IsBusy); + cache.Use([photo]); + cache.Use([]); + cache.Use([photo]); + decoder.ReleaseAll(); + Pump(() => !cache.IsBusy); - Assert.Equal(1, decoder.Started); - Assert.Single(cache.Use([photo])); + Assert.Equal(1, decoder.Started); + Assert.Single(cache.Use([photo])); + } + finally + { + // Releases the decoded bitmaps the test leaves behind. + cache.Clear(); + } } [AvaloniaFact] @@ -97,23 +105,31 @@ public void A_new_pair_waits_until_the_pair_it_replaces_has_finished_decoding() { using var decoder = new GatedDecoder(); var cache = new RasterOverlayCache(decode: decoder.Decode); - RasterImage[] old = [Full(), Full()]; - RasterImage[] replacement = [Full(), Full()]; - - cache.Use(old); - Pump(() => decoder.Started == 2); - cache.Use(replacement); - - // Two full-size pictures still decoding fill the budget: the new ones may not start yet. - Assert.Equal(2, decoder.Started); - decoder.ReleaseAll(); - Pump(() => decoder.Running == 0 && !cache.IsDecoding); - cache.Use(replacement); - Pump(() => decoder.Started == 4); - decoder.ReleaseAll(); - Pump(() => !cache.IsBusy); - - Assert.Equal(2, cache.Use(replacement).Count); + try + { + RasterImage[] old = [Full(), Full()]; + RasterImage[] replacement = [Full(), Full()]; + + cache.Use(old); + Pump(() => decoder.Started == 2); + cache.Use(replacement); + + // Two full-size pictures still decoding fill the budget: the new ones may not start yet. + Assert.Equal(2, decoder.Started); + decoder.ReleaseAll(); + Pump(() => decoder.Running == 0 && !cache.IsDecoding); + cache.Use(replacement); + Pump(() => decoder.Started == 4); + decoder.ReleaseAll(); + Pump(() => !cache.IsBusy); + + Assert.Equal(2, cache.Use(replacement).Count); + } + finally + { + // Releases the decoded bitmaps the test leaves behind. + cache.Clear(); + } } [AvaloniaFact] @@ -121,21 +137,29 @@ public void A_cleared_cache_still_counts_the_decodes_it_left_running() { using var decoder = new GatedDecoder(); var cache = new RasterOverlayCache(decode: decoder.Decode); - cache.Use([Full(), Full()]); - Pump(() => decoder.Started == 2); - - cache.Clear(); - RasterImage[] next = [Full()]; - cache.Use(next); - - Assert.Equal(2, decoder.Started); - decoder.ReleaseAll(); - Pump(() => !cache.IsDecoding); - cache.Use(next); - Pump(() => decoder.Started == 3); - decoder.ReleaseAll(); - Pump(() => !cache.IsBusy); - Assert.Single(cache.Use(next)); + try + { + cache.Use([Full(), Full()]); + Pump(() => decoder.Started == 2); + + cache.Clear(); + RasterImage[] next = [Full()]; + cache.Use(next); + + Assert.Equal(2, decoder.Started); + decoder.ReleaseAll(); + Pump(() => !cache.IsDecoding); + cache.Use(next); + Pump(() => decoder.Started == 3); + decoder.ReleaseAll(); + Pump(() => !cache.IsBusy); + Assert.Single(cache.Use(next)); + } + finally + { + // Releases the decoded bitmaps the test leaves behind. + cache.Clear(); + } } [AvaloniaFact] @@ -143,13 +167,21 @@ public void A_picture_that_fails_to_decode_is_reported_once_and_drawn_as_nothing { var failed = new List(); var cache = new RasterOverlayCache(failed: failed.Add, decode: _ => throw new InvalidOperationException("kaputt")); - var photo = Full(); + try + { + var photo = Full(); - cache.Use([photo]); - Pump(() => !cache.IsBusy); + cache.Use([photo]); + Pump(() => !cache.IsBusy); - Assert.Empty(cache.Use([photo])); - Assert.Equal([photo.FileId], failed); + Assert.Empty(cache.Use([photo])); + Assert.Equal([photo.FileId], failed); + } + finally + { + // Releases the decoded bitmaps the test leaves behind. + cache.Clear(); + } } private static RasterImage Full() => diff --git a/tests/LageBuch.AppLogic.Tests/CoMessprotokollViewModelTests.cs b/tests/LageBuch.AppLogic.Tests/CoMessprotokollViewModelTests.cs index d693ecdb5..a489eb51a 100644 --- a/tests/LageBuch.AppLogic.Tests/CoMessprotokollViewModelTests.cs +++ b/tests/LageBuch.AppLogic.Tests/CoMessprotokollViewModelTests.cs @@ -1480,7 +1480,7 @@ public Task AddFileAsync(string fileName, string contentType, byte[] bytes, Canc public Task RemoveFileAsync(Guid fileId, CancellationToken cancellationToken = default) => _inner.RemoveFileAsync(fileId, cancellationToken); - public Task AddMapOverlayAsync( + public Task AddMapOverlayAsync( string fileName, string contentType, byte[] bytes, LageBuch.Domain.Map.MapOverlaySummary summary, CancellationToken cancellationToken = default) => _inner.AddMapOverlayAsync(fileName, contentType, bytes, summary, cancellationToken); diff --git a/tests/LageBuch.AppLogic.Tests/IncidentSessionTests.cs b/tests/LageBuch.AppLogic.Tests/IncidentSessionTests.cs index eb2758f5d..f41112b75 100644 --- a/tests/LageBuch.AppLogic.Tests/IncidentSessionTests.cs +++ b/tests/LageBuch.AppLogic.Tests/IncidentSessionTests.cs @@ -581,8 +581,19 @@ public Task FlushAsync(CancellationToken cancellationToken = default) private readonly Dictionary _files = new(); + /// When set, throws it for a file whose storage name contains . + public Exception? WriteFailure { get; set; } + + /// Which files hits; empty hits every one. + public string WriteFailureFor { get; set; } = string.Empty; + public Task SaveFileBytesAsync(string path, string storageFileName, byte[] bytes, CancellationToken cancellationToken = default) { + if (WriteFailure is not null && storageFileName.Contains(WriteFailureFor, StringComparison.Ordinal)) + { + throw WriteFailure; + } + _files[$"{path}/{storageFileName}"] = bytes; return Task.CompletedTask; } diff --git a/tests/LageBuch.AppLogic.Tests/MapOverlaysLuftbildTests.cs b/tests/LageBuch.AppLogic.Tests/MapOverlaysLuftbildTests.cs index d230125b0..64aebfc9c 100644 --- a/tests/LageBuch.AppLogic.Tests/MapOverlaysLuftbildTests.cs +++ b/tests/LageBuch.AppLogic.Tests/MapOverlaysLuftbildTests.cs @@ -76,8 +76,8 @@ private LdbvImageryClient Client(HttpMessageHandler handler) return new LdbvImageryClient(http); } - private static LocalIncidentSession NewSession() => TestSession.StartNew( - new FakeStore(), + private static LocalIncidentSession NewSession(FakeStore? store = null) => TestSession.StartNew( + store ?? new FakeStore(), new FixedClock(T0), new SessionOperator("Müller", "FFB 12/1"), "/x.lagebuch", @@ -322,6 +322,46 @@ public async Task A_picture_the_map_could_not_draw_says_so_on_its_row() Assert.Null(vm.Error); } + [Fact] + public async Task A_session_s_failed_byte_write_leaves_no_Ebene_behind() + { + var store = new FakeStore { WriteFailure = new IOException("Datenträger voll") }; + var session = NewSession(store); + + await Assert.ThrowsAsync(() => session.AddMapOverlayAsync( + "luftbild.png", "image/png", TestImages.Png(10, 10), new MapOverlaySummary("Luftbild", 1, null, null, MapOverlayKind.Raster, Visible))); + + Assert.Empty(session.Incident.MapOverlays); + Assert.Empty(session.Incident.Files); + } + + [Fact] + public async Task A_session_names_the_Ebene_it_added() + { + var session = NewSession(); + + var id = await session.AddMapOverlayAsync( + "luftbild.png", "image/png", TestImages.Png(10, 10), new MapOverlaySummary("Luftbild", 1, null, null, MapOverlayKind.Raster, Visible)); + + Assert.Equal(id, Assert.Single(session.Incident.MapOverlays).Id); + } + + [Fact] + public async Task When_the_Flurstuecksgrenzen_cannot_be_stored_the_Luftbild_is_taken_back_out() + { + var store = new FakeStore { WriteFailure = new IOException("Datenträger voll"), WriteFailureFor = ".png" }; + var session = NewSession(store); + var other = await session.AddMapOverlayAsync( + "lage.geojson", "application/geo+json", Encoding.UTF8.GetBytes(Sperrgebiet), new MapOverlaySummary("Lage", 1, null, null)); + var (vm, _) = Open(session, Client(new LdbvHandler())); + + await vm.LoadLuftbildCommand.ExecuteAsync(Visible); + + Assert.Equal("Luftbild nicht übernommen: Datenträger voll", vm.Error); + Assert.Equal(other, Assert.Single(session.Incident.MapOverlays).Id); + Assert.Single(session.Incident.Files); + } + [Fact] public async Task Reopening_an_Einsatz_shows_its_Luftbilder_and_can_centre_on_one() { From c836c55417b64c75f93ec300baf7e0f6f4ef29c0 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Thomas=20M=C3=BCller?= <1005065+DeepDiver1975@users.noreply.github.com> Date: Fri, 20 Nov 2026 12:32:48 +0100 Subject: [PATCH 6/7] docs(lagekarte): say a remote take-back can leave a fileless Ebene MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit The AddMapOverlayAsync contract claimed a failed add always leaves nothing behind. On a joined client the take-back after a failed upload is best effort: if the host cannot be reached for it either, the Ebene stays without its file. The documentation now says so. Co-Authored-By: Claude Opus 5.5 Signed-off-by: Thomas Müller <1005065+DeepDiver1975@users.noreply.github.com> --- src/LageBuch.AppLogic/ViewModels/MapOverlaysViewModel.cs | 3 ++- src/LageBuch.Sync/IIncidentSession.cs | 4 +++- 2 files changed, 5 insertions(+), 2 deletions(-) diff --git a/src/LageBuch.AppLogic/ViewModels/MapOverlaysViewModel.cs b/src/LageBuch.AppLogic/ViewModels/MapOverlaysViewModel.cs index 7243f72ee..b1057ead5 100644 --- a/src/LageBuch.AppLogic/ViewModels/MapOverlaysViewModel.cs +++ b/src/LageBuch.AppLogic/ViewModels/MapOverlaysViewModel.cs @@ -370,7 +370,8 @@ private async Task LoadLuftbildAsync(GeoBox? visible, CancellationToken cancella } // The Luftbild, then its Flurstücksgrenzen; null when both are in, else what went wrong. A - // failed add leaves nothing of itself behind (IIncidentSession.AddMapOverlayAsync), so should + // failed add normally leaves nothing of itself behind (IIncidentSession.AddMapOverlayAsync; on a + // joined client whose host is gone, its take-back can fail too, which this cannot see), so should // the second fail -- a peer took the last slot, the disk is full, the host went away -- the // first is taken back out by the id it was given, never another device's Ebene; if even that // fails, the message says which one stayed. A failure of the first add is thrown: nothing was diff --git a/src/LageBuch.Sync/IIncidentSession.cs b/src/LageBuch.Sync/IIncidentSession.cs index 9ec5bd4ad..3e552a263 100644 --- a/src/LageBuch.Sync/IIncidentSession.cs +++ b/src/LageBuch.Sync/IIncidentSession.cs @@ -326,7 +326,9 @@ void AddScbaTrupp( /// Imports a Kartenebene: the file's bytes go in as an attachment and the Ebene points at it. /// Awaited like , for the same reasons. The caller has parsed the file /// already; is what it read. Returns the new Ebene's id. A failed add - /// leaves no Ebene behind: one whose bytes could not be stored is taken back out. + /// normally leaves no Ebene behind: one whose bytes could not be stored is taken back out. On a + /// joined client that take-back is best effort; if the host cannot be reached for it either, + /// the Ebene stays in the Einsatz without its file, shown as not yet available and removable. /// Task AddMapOverlayAsync( string fileName, string contentType, byte[] bytes, MapOverlaySummary summary, CancellationToken cancellationToken = default); From c4e2cc1f1a339210a7c676a75f201d8f4d38a215 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Thomas=20M=C3=BCller?= <1005065+DeepDiver1975@users.noreply.github.com> Date: Fri, 20 Nov 2026 16:41:00 +0100 Subject: [PATCH 7/7] fix(lagekarte): settle LUFTBILD LADEN before closing and keep failed pictures out MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit - Closing the Einsatz now cancels a LUFTBILD LADEN still downloading and waits for one already storing, so the closed Einsatz holds both Ebenen or neither. - A byte write that fails after the Einsatz was closed meanwhile still takes its Ebene back out (Incident.DiscardFailedMapOverlay) and surfaces the storage error, not the closed-incident one. - The pair rollback counts the Luftbild as taken back when it is out of the Einsatz, even if wiping its bytes failed, so the message no longer claims it stayed. - A picture the map could not decode leaves the display selection and the memory budget; the shown pictures are recomputed. - The Lagekarte render test disposes its view model and serves decodable pictures. Co-Authored-By: Claude Opus 5.5 Signed-off-by: Thomas Müller <1005065+DeepDiver1975@users.noreply.github.com> --- src/LageBuch.AppLogic/LocalIncidentSession.cs | 10 +-- .../ViewModels/IncidentWorkspaceViewModel.cs | 41 +++++++----- .../ViewModels/MapOverlaysViewModel.cs | 19 +++++- src/LageBuch.Domain/Incident.cs | 22 +++++++ .../LagekarteLuftbildRenderTests.cs | 27 +++----- .../IncidentSessionTests.cs | 4 ++ .../IncidentWorkspaceLuftbildTests.cs | 66 +++++++++++++++++++ .../MapOverlaysLuftbildTests.cs | 53 +++++++++++++++ 8 files changed, 199 insertions(+), 43 deletions(-) create mode 100644 tests/LageBuch.AppLogic.Tests/IncidentWorkspaceLuftbildTests.cs diff --git a/src/LageBuch.AppLogic/LocalIncidentSession.cs b/src/LageBuch.AppLogic/LocalIncidentSession.cs index 64eff4130..5c51b4ca4 100644 --- a/src/LageBuch.AppLogic/LocalIncidentSession.cs +++ b/src/LageBuch.AppLogic/LocalIncidentSession.cs @@ -428,15 +428,17 @@ public async Task AddMapOverlayAsync( string fileName, string contentType, byte[] bytes, MapOverlaySummary summary, CancellationToken cancellationToken = default) { ArgumentNullException.ThrowIfNull(bytes); + var op = RequireOperator(); var overlay = Incident.AddMapOverlay( - _clock, RequireOperator(), Guid.NewGuid(), Guid.NewGuid(), fileName, contentType, bytes.LongLength, summary); + _clock, op, Guid.NewGuid(), Guid.NewGuid(), fileName, contentType, bytes.LongLength, summary); var file = Incident.Files.First(f => f.Id == overlay.FileId); Save(); // As AddFileAsync: the incident file must exist before the bytes go in, so the Ebene is // recorded first. Should the bytes not go in, the Ebene is taken back out -- an Ebene without - // its file is drawn from nothing -- and the failure still reaches the caller. Changed is - // raised either way, because the domain changed. + // its file is drawn from nothing -- even if the Einsatz was closed while they were being + // written, and the storage failure is what reaches the caller. Changed is raised either way, + // because the domain changed. try { await _store.FlushAsync(cancellationToken); @@ -445,7 +447,7 @@ public async Task AddMapOverlayAsync( } catch { - Incident.RemoveMapOverlay(_clock, RequireOperator(), overlay.Id); + Incident.DiscardFailedMapOverlay(_clock, op, overlay.Id); Save(); throw; } diff --git a/src/LageBuch.AppLogic/ViewModels/IncidentWorkspaceViewModel.cs b/src/LageBuch.AppLogic/ViewModels/IncidentWorkspaceViewModel.cs index 3e9290a49..ae2ba74fc 100644 --- a/src/LageBuch.AppLogic/ViewModels/IncidentWorkspaceViewModel.cs +++ b/src/LageBuch.AppLogic/ViewModels/IncidentWorkspaceViewModel.cs @@ -1765,23 +1765,7 @@ private void CloseIncident() "Einsatz abschließen?", message, "ABSCHLIESSEN", - () => - { - PerformClose(); - if (dialog?.IsOptionChecked != true) - { - return; - } - - if (dialog.IsSubOptionChecked) - { - OpenPdfExportOptions(RunExportAndMailAsync, "PDF ERSTELLEN & MAILEN"); - } - else - { - OpenPdfExportOptions(RunExportAsync); - } - }, + () => _ = CloseThenOfferPdfAsync(dialog), CanExport ? "PDF exportieren" : null, CanMailPdf ? "und per E-Mail senden" : null); @@ -1810,6 +1794,29 @@ private void OpenSpellingHelper() PendingSpellingHelper = dialog; } + // A LUFTBILD LADEN under way is cancelled and waited for first -- one already storing its two + // Ebenen finishes them -- so the closed Einsatz holds both or neither. Idle, the wait is no wait + // and the close happens at once, as it always did. The stop never throws: the command surfaces + // its own failures. + private async Task CloseThenOfferPdfAsync(ConfirmDialogViewModel? dialog) + { + await Lagekarte.Overlays.StopLuftbildAsync(); + PerformClose(); + if (dialog?.IsOptionChecked != true) + { + return; + } + + if (dialog.IsSubOptionChecked) + { + OpenPdfExportOptions(RunExportAndMailAsync, "PDF ERSTELLEN & MAILEN"); + } + else + { + OpenPdfExportOptions(RunExportAsync); + } + } + private void PerformClose() { _session.Close(); diff --git a/src/LageBuch.AppLogic/ViewModels/MapOverlaysViewModel.cs b/src/LageBuch.AppLogic/ViewModels/MapOverlaysViewModel.cs index b1057ead5..3140e7111 100644 --- a/src/LageBuch.AppLogic/ViewModels/MapOverlaysViewModel.cs +++ b/src/LageBuch.AppLogic/ViewModels/MapOverlaysViewModel.cs @@ -279,7 +279,7 @@ internal void UpdateVisibleRasters() var budget = MaxVisibleRasterBytes; var skipped = false; var kept = new List(); - foreach (var raster in Items.Where(i => i.IsVisible).Select(i => i.Raster).OfType().Reverse()) + foreach (var raster in Items.Where(i => i.IsVisible && !i.DrawFailedOnMap).Select(i => i.Raster).OfType().Reverse()) { if (raster.DecodedBytes > budget) { @@ -396,6 +396,9 @@ private async Task LoadLuftbildAsync(GeoBox? visible, CancellationToken cancella } } + // True when the Ebene is out of the Einsatz. A removal that took the Ebene out and then failed + // to wipe its bytes still took it out: what counts is whether the Einsatz holds it, not whether + // the call threw. [SuppressMessage( "Design", "CA1031", @@ -409,7 +412,7 @@ private async Task TryRemoveAsync(Guid overlayId) } catch (Exception) { - return false; + return _session.Incident.MapOverlays.All(o => o.Id != overlayId); } } @@ -436,6 +439,9 @@ private void RasterFailed(Guid fileId) { item.DrawFailed(); } + + // A picture the map cannot draw takes no share of the budget: the next one may have it. + UpdateVisibleRasters(); } private static MapOverlaySummary Summary(string name, LuftbildArea area) => @@ -789,8 +795,15 @@ internal void Loaded(OverlayData? data, RasterImage? raster, string? error, bool NextFrameCommand.NotifyCanExecuteChanged(); } + /// The map could not decode the picture; it is left out of what the map is handed. + public bool DrawFailedOnMap { get; private set; } + // The picture passed every check but the map could not decode it: it stays listed and removable. - internal void DrawFailed() => LoadError = "Ebene konnte nicht gelesen werden: Das Bild lässt sich nicht darstellen."; + internal void DrawFailed() + { + DrawFailedOnMap = true; + LoadError = "Ebene konnte nicht gelesen werden: Das Bild lässt sich nicht darstellen."; + } partial void OnIsVisibleChanged(bool value) { diff --git a/src/LageBuch.Domain/Incident.cs b/src/LageBuch.Domain/Incident.cs index 848db6bc7..229f0b6a4 100644 --- a/src/LageBuch.Domain/Incident.cs +++ b/src/LageBuch.Domain/Incident.cs @@ -2094,6 +2094,28 @@ public MapOverlay AddMapOverlay( return file; } + /// + /// Takes back a Kartenebene whose file never arrived, open Einsatz or closed: the import failed + /// as a whole, so nothing of it may stay. On an open Einsatz the ETB says so, as + /// does; a closed one's journal is not written to any more. + /// + public void DiscardFailedMapOverlay(IClock clock, SessionOperator op, Guid overlayId) + { + ArgumentNullException.ThrowIfNull(clock); + ArgumentNullException.ThrowIfNull(op); + if (State != IncidentState.Closed) + { + RemoveMapOverlay(clock, op, overlayId); + return; + } + + if (_mapOverlays.Find(o => o.Id == overlayId) is { } overlay) + { + _mapOverlays.Remove(overlay); + _files.RemoveAll(f => f.Id == overlay.FileId); + } + } + // The forecast times as the Lagebuchführer reads them: in the Einsatz's own time zone, which is // the clock's, not the UTC a DWD file carries. private static string TimeSpanText(MapOverlay overlay, IClock clock) diff --git a/tests/LageBuch.Acceptance.Tests/LagekarteLuftbildRenderTests.cs b/tests/LageBuch.Acceptance.Tests/LagekarteLuftbildRenderTests.cs index 9bcc5534a..3bec97dcb 100644 --- a/tests/LageBuch.Acceptance.Tests/LagekarteLuftbildRenderTests.cs +++ b/tests/LageBuch.Acceptance.Tests/LagekarteLuftbildRenderTests.cs @@ -1,4 +1,3 @@ -using System.Buffers.Binary; using System.Net; using System.Runtime.InteropServices; using System.Web; @@ -112,7 +111,7 @@ public void LUFTBILD_LADEN_adds_two_Ebenen_and_their_licence_line() Array.Empty<(string, bool)>()); var http = new HttpClient(new LdbvHandler()); _clients.Add(http); - var vm = new LagekarteViewModel(session, () => { }, luftbild: new LdbvImageryClient(http)); + using var vm = new LagekarteViewModel(session, () => { }, luftbild: new LdbvImageryClient(http)); vm.Map.ChangeViewCommand.Execute(new MapViewChange(Fuerstenfeldbruck, 16)); var view = new LagekarteView { DataContext = vm }; var window = new Window { Content = view, Width = 1280, Height = 800 }; @@ -223,28 +222,18 @@ protected override Task SendAsync(HttpRequestMessage reques var width = int.Parse(query["WIDTH"] ?? "0", System.Globalization.CultureInfo.InvariantCulture); var height = int.Parse(query["HEIGHT"] ?? "0", System.Globalization.CultureInfo.InvariantCulture); var photo = query["LAYERS"] == "by_dop40c"; - var content = new ByteArrayContent(photo ? JpegHeader(width, height) : PngHeader(width, height)); + var content = new ByteArrayContent(Encoded(width, height, photo)); content.Headers.ContentType = new System.Net.Http.Headers.MediaTypeHeaderValue(photo ? "image/jpeg" : "image/png"); return Task.FromResult(new HttpResponseMessage(HttpStatusCode.OK) { Content = content }); } - private static byte[] PngHeader(int width, int height) + // A real, decodable picture of the size asked for: the map draws only what decodes. + private static byte[] Encoded(int width, int height, bool photo) { - var bytes = new byte[33]; - new byte[] { 0x89, 0x50, 0x4E, 0x47, 0x0D, 0x0A, 0x1A, 0x0A }.CopyTo(bytes, 0); - BinaryPrimitives.WriteInt32BigEndian(bytes.AsSpan(8), 13); - "IHDR"u8.CopyTo(bytes.AsSpan(12)); - BinaryPrimitives.WriteInt32BigEndian(bytes.AsSpan(16), width); - BinaryPrimitives.WriteInt32BigEndian(bytes.AsSpan(20), height); - return bytes; - } - - private static byte[] JpegHeader(int width, int height) - { - var bytes = new byte[] { 0xFF, 0xD8, 0xFF, 0xC0, 0x00, 0x11, 0x08, 0, 0, 0, 0, 3, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0xFF, 0xDA, 0x00, 0x08, 0x01, 0x01, 0x00, 0x00, 0x3F, 0x00, 0xFF, 0xD9 }; - BinaryPrimitives.WriteUInt16BigEndian(bytes.AsSpan(7), (ushort)height); - BinaryPrimitives.WriteUInt16BigEndian(bytes.AsSpan(9), (ushort)width); - return bytes; + using var bitmap = new WriteableBitmap(new PixelSize(width, height), new Vector(96, 96), PixelFormat.Bgra8888, AlphaFormat.Premul); + using var stream = new MemoryStream(); + bitmap.Save(stream, photo ? JpegBitmapEncoderOptions.Default : PngBitmapEncoderOptions.Default); + return stream.ToArray(); } } } diff --git a/tests/LageBuch.AppLogic.Tests/IncidentSessionTests.cs b/tests/LageBuch.AppLogic.Tests/IncidentSessionTests.cs index f41112b75..d6a2f4477 100644 --- a/tests/LageBuch.AppLogic.Tests/IncidentSessionTests.cs +++ b/tests/LageBuch.AppLogic.Tests/IncidentSessionTests.cs @@ -587,8 +587,12 @@ public Task FlushAsync(CancellationToken cancellationToken = default) /// Which files hits; empty hits every one. public string WriteFailureFor { get; set; } = string.Empty; + /// Runs just before every byte write, like a user acting while the write is under way. + public Action? BeforeWrite { get; set; } + public Task SaveFileBytesAsync(string path, string storageFileName, byte[] bytes, CancellationToken cancellationToken = default) { + BeforeWrite?.Invoke(); if (WriteFailure is not null && storageFileName.Contains(WriteFailureFor, StringComparison.Ordinal)) { throw WriteFailure; diff --git a/tests/LageBuch.AppLogic.Tests/IncidentWorkspaceLuftbildTests.cs b/tests/LageBuch.AppLogic.Tests/IncidentWorkspaceLuftbildTests.cs new file mode 100644 index 000000000..0f6c303fc --- /dev/null +++ b/tests/LageBuch.AppLogic.Tests/IncidentWorkspaceLuftbildTests.cs @@ -0,0 +1,66 @@ +using System.Net; +using LageBuch.AppLogic.Services; +using LageBuch.AppLogic.Services.Map; +using LageBuch.AppLogic.ViewModels; +using LageBuch.Domain; +using LageBuch.Domain.ValueObjects; +using LageBuch.Persistence.MasterData; + +namespace LageBuch.AppLogic.Tests; + +/// Closing the Einsatz while LUFTBILD LADEN is under way. +public sealed class IncidentWorkspaceLuftbildTests : IDisposable +{ + private static readonly DateTimeOffset T0 = new(2026, 3, 14, 10, 20, 0, TimeSpan.FromHours(1)); + + private readonly HttpClient _http = new(new HangingHandler()); + + public void Dispose() => _http.Dispose(); + + /// Waits for the caller to give up. + private sealed class HangingHandler : HttpMessageHandler + { + public TaskCompletionSource Started { get; } = new(TaskCreationOptions.RunContinuationsAsynchronously); + + protected override async Task SendAsync(HttpRequestMessage request, CancellationToken cancellationToken) + { + Started.TrySetResult(); + await Task.Delay(Timeout.Infinite, cancellationToken); + return new HttpResponseMessage(HttpStatusCode.OK); + } + } + + [Fact] + public async Task Closing_cancels_a_download_under_way_and_waits_for_it_before_the_Einsatz_closes() + { + var clock = new FixedClock(T0); + var session = TestSession.StartNew( + new FakeStore(), + clock, + new SessionOperator("Müller"), + "/x.lagebuch", + Array.Empty<(string, bool)>(), + Array.Empty<(string, bool)>()); + var vm = new IncidentWorkspaceViewModel( + session, + clock, + new FakeTicker(), + MasterDataSet.Empty, + new FakeDialogs(), + new FakeAlarmService(), + new NoopIncidentHostController(), + new TestPdfExporter(), + luftbild: new LdbvImageryClient(_http)); + var load = vm.Lagekarte.Overlays.LoadLuftbildCommand.ExecuteAsync(new GeoBox(11.2475, 48.1765, 11.2635, 48.1805)); + + vm.CloseIncidentCommand.Execute(null); + var confirm = vm.PendingConfirm; + Assert.NotNull(confirm); + confirm.IsOptionChecked = false; + confirm.ConfirmCommand.Execute(null); + + await load.WaitAsync(TimeSpan.FromSeconds(5)); + Assert.True(SpinWait.SpinUntil(() => session.Incident.State == IncidentState.Closed, TimeSpan.FromSeconds(5))); + Assert.Empty(session.Incident.MapOverlays); + } +} diff --git a/tests/LageBuch.AppLogic.Tests/MapOverlaysLuftbildTests.cs b/tests/LageBuch.AppLogic.Tests/MapOverlaysLuftbildTests.cs index 64aebfc9c..e57adfd81 100644 --- a/tests/LageBuch.AppLogic.Tests/MapOverlaysLuftbildTests.cs +++ b/tests/LageBuch.AppLogic.Tests/MapOverlaysLuftbildTests.cs @@ -362,6 +362,59 @@ public async Task When_the_Flurstuecksgrenzen_cannot_be_stored_the_Luftbild_is_t Assert.Single(session.Incident.Files); } + [Fact] + public async Task A_failed_byte_write_on_an_Einsatz_closed_meanwhile_keeps_its_error_and_leaves_no_Ebene() + { + var store = new FakeStore { WriteFailure = new IOException("Datenträger voll") }; + var session = NewSession(store); + store.BeforeWrite = session.Close; + + var e = await Assert.ThrowsAsync(() => session.AddMapOverlayAsync( + "luftbild.png", "image/png", TestImages.Png(10, 10), new MapOverlaySummary("Luftbild", 1, null, null, MapOverlayKind.Raster, Visible))); + + Assert.Equal("Datenträger voll", e.Message); + Assert.Equal(IncidentState.Closed, session.Incident.State); + Assert.Empty(session.Incident.MapOverlays); + Assert.Empty(session.Incident.Files); + } + + [Fact] + public async Task A_Luftbild_taken_back_whose_bytes_will_not_go_away_is_still_not_reported_as_kept() + { + var store = new FakeStore + { + WriteFailure = new IOException("Datenträger voll"), + WriteFailureFor = ".png", + DeleteFailure = new IOException("Datei gesperrt"), + }; + var session = NewSession(store); + var (vm, _) = Open(session, Client(new LdbvHandler())); + + await vm.LoadLuftbildCommand.ExecuteAsync(Visible); + + Assert.Equal("Luftbild nicht übernommen: Datenträger voll", vm.Error); + Assert.Empty(session.Incident.MapOverlays); + } + + [Fact] + public async Task A_pair_the_map_could_not_draw_gives_its_memory_to_the_next_pair() + { + var session = NewSession(); + await AddPair(session, 4096, 4096); + await AddPair(session, 4096, 4096); + var (vm, _) = Open(session, null); + await vm.SettledAsync(); + vm.Items[0].IsVisible = true; + vm.Items[1].IsVisible = true; + Assert.NotNull(vm.RasterBudgetHint); + + vm.RasterFailedCommand.Execute(vm.Items[2].FileId); + vm.RasterFailedCommand.Execute(vm.Items[3].FileId); + + Assert.Equal([vm.Items[0].FileId, vm.Items[1].FileId], vm.VisibleRasters.Select(r => r.FileId)); + Assert.Null(vm.RasterBudgetHint); + } + [Fact] public async Task Reopening_an_Einsatz_shows_its_Luftbilder_and_can_centre_on_one() {