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/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..6344d5b58 100644 --- a/src/LageBuch.App.Shared/Controls/MapCanvasControl.cs +++ b/src/LageBuch.App.Shared/Controls/MapCanvasControl.cs @@ -66,6 +66,14 @@ 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)); + + /// 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)); @@ -87,6 +95,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 +111,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 +119,7 @@ static MapCanvasControl() public MapCanvasControl() { _terrain = new TerrainTileCache(InvalidateVisual); + _rasters = new RasterOverlayCache(InvalidateVisual, OnRasterFailed); GestureRecognizers.Add(new PinchGestureRecognizer()); AddHandler(PinchEvent, OnPinch); AddHandler(PinchEndedEvent, OnPinchEnded); @@ -184,6 +194,37 @@ public IReadOnlyList? Overlays set => SetValue(OverlaysProperty, value); } + public IReadOnlyList? RasterOverlays + { + get => GetValue(RasterOverlaysProperty); + 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; + + /// + /// 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 +272,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 +281,7 @@ protected override void OnDetachedFromVisualTree(VisualTreeAttachmentEventArgs e base.OnDetachedFromVisualTree(e); _tiles.Clear(); _terrain.Clear(); + _rasters.Clear(); } protected override void OnPropertyChanged(AvaloniaPropertyChangedEventArgs change) @@ -483,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/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..5fc6d8842 --- /dev/null +++ b/src/LageBuch.App.Shared/Controls/RasterOverlayCache.cs @@ -0,0 +1,195 @@ +using System.Diagnostics.CodeAnalysis; +using System.Runtime.InteropServices; +using Avalonia.Media.Imaging; +using LageBuch.AppLogic.Services.Map; +using LageBuch.AppLogic.ViewModels; +using SkiaSharp; + +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. +/// +/// +/// +/// 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(); + + // 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; + + // 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 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 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) + { + _wanted.Clear(); + _wanted.UnionWith((rasters ?? []).Select(r => r.FileId)); + foreach (var gone in _decoded.Keys.Where(id => !_wanted.Contains(id)).ToList()) + { + _decoded[gone].Image?.Dispose(); + _decoded.Remove(gone); + } + + _waiting = false; + var ready = new List<(Bitmap, Domain.ValueObjects.GeoBox)>(); + foreach (var raster in rasters ?? []) + { + if (_decoded.TryGetValue(raster.FileId, out var decoded)) + { + if (decoded.Image is { } image) + { + ready.Add((image, raster.Bounds)); + } + } + else if (!_decoding.ContainsKey(raster.FileId)) + { + // 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++; + _wanted.Clear(); + _waiting = false; + foreach (var (image, _) in _decoded.Values) + { + image?.Dispose(); + } + + _decoded.Clear(); + } + + [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)); + } + catch (Exception) + { + bitmap = null; + } + + _decoding.Remove(raster.FileId); + + // Dropped while it was decoding: by a cleared map, or an Ebene hidden or removed meanwhile. + // 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, bitmap is null ? 0 : raster.DecodedBytes); + if (bitmap is null) + { + _failed?.Invoke(raster.FileId); + } + + _ready?.Invoke(); + } + + /// + /// 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) + { + 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; + } + + // 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/Views/LagekarteView.axaml b/src/LageBuch.App.Shared/Views/LagekarteView.axaml index e4a568040..1ba3d6116 100644 --- a/src/LageBuch.App.Shared/Views/LagekarteView.axaml +++ b/src/LageBuch.App.Shared/Views/LagekarteView.axaml @@ -196,6 +196,24 @@ IsEnabled="{Binding !Overlays.IsImporting}" Command="{Binding Overlays.ImportCommand}" /> + + + @@ -372,6 +390,8 @@ FlowPath="{Binding Terrain.FlowPoints}" 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}" @@ -806,11 +826,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.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/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.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/src/LageBuch.AppLogic/LocalIncidentSession.cs b/src/LageBuch.AppLogic/LocalIncidentSession.cs index 88fa8d14b..5c51b4ca4 100644 --- a/src/LageBuch.AppLogic/LocalIncidentSession.cs +++ b/src/LageBuch.AppLogic/LocalIncidentSession.cs @@ -424,21 +424,32 @@ 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); + 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, 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 -- 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); await _store.SaveFileBytesAsync(Path, IncidentFile.StorageFileName(file.Id, file.FileName), bytes, cancellationToken); + return overlay.Id; + } + catch + { + Incident.DiscardFailedMapOverlay(_clock, op, overlay.Id); + Save(); + throw; } finally { diff --git a/src/LageBuch.AppLogic/Services/Map/LdbvImageryClient.cs b/src/LageBuch.AppLogic/Services/Map/LdbvImageryClient.cs new file mode 100644 index 000000000..38986db13 --- /dev/null +++ b/src/LageBuch.AppLogic/Services/Map/LdbvImageryClient.cs @@ -0,0 +1,158 @@ +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 (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. + 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..2f9b003eb --- /dev/null +++ b/src/LageBuch.AppLogic/Services/Map/RasterImage.cs @@ -0,0 +1,52 @@ +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: 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 + /// 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..ebd64e640 --- /dev/null +++ b/src/LageBuch.AppLogic/Services/Map/RasterImageInfo.cs @@ -0,0 +1,108 @@ +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 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) + { + 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 == 0xDA) + { + return frame; + } + + 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 (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)); + if (width == 0 || height == 0) + { + return null; + } + + frame = new RasterImageInfo(RasterFormat.Jpeg, width, height); + } + + 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..ae2ba74fc 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; @@ -884,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. @@ -1139,7 +1148,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); @@ -1756,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); @@ -1801,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/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..3140e7111 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,16 +18,27 @@ 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 { + /// + /// 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; 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 +48,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 +63,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 +77,7 @@ public MapOverlaysViewModel( _clock = clock; _showBounds = showBounds; _timeZone = timeZone ?? TimeZoneInfo.Local; + _luftbild = luftbild; Refresh(); _opened = true; } @@ -90,6 +104,44 @@ 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 = []; + + /// 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 => shown.Contains(i.FileId)) + .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; @@ -114,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)) @@ -131,20 +190,42 @@ 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)); } 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. + // 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 { - foreach (var item in Items) + foreach (var item in Items.Where(i => i.IsRaster && !known.ContainsKey(i.Id))) { - item.IsVisible = ReferenceEquals(item, Items[^1]); + item.IsVisible = true; + } + } + + if (Items.LastOrDefault(i => !i.IsRaster) is { } newest && (first || !known.ContainsKey(newest.Id))) + { + foreach (var item in Items.Where(i => !i.IsRaster)) + { + item.IsVisible = ReferenceEquals(item, newest); } } @@ -156,6 +237,7 @@ private void Rebuild(IReadOnlyList overlays) OnPropertyChanged(nameof(HasItems)); OnPropertyChanged(nameof(Header)); UpdateVisibleShapes(); + UpdateVisibleRasters(); } private void Track(Task load) @@ -165,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() { @@ -187,6 +272,181 @@ internal void UpdateVisibleShapes() } } + // 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 budget = MaxVisibleRasterBytes; + var skipped = false; + var kept = new List(); + foreach (var raster in Items.Where(i => i.IsVisible && !i.DrawFailedOnMap).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; + } + } + + /// + /// 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; + } + + // 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 + { + 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. Leaving waits for this (StopLuftbildAsync). + Error = await StoreBothAsync(photo, parcels, area); + _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; + } + } + + // The Luftbild, then its Flurstücksgrenzen; null when both are in, else what went wrong. A + // 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 + // stored then. + [SuppressMessage( + "Design", + "CA1031", + 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 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); + return null; + } + catch (Exception ex) + { + return await TryRemoveAsync(luftbild) + ? $"Luftbild nicht übernommen: {ex.Message}" + : $"Nur das Luftbild wurde übernommen, die Flurstücksgrenzen nicht: {ex.Message}"; + } + } + + // 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", + 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 _session.Incident.MapOverlays.All(o => o.Id != overlayId); + } + } + + /// + /// 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(); + } + + // 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) => + new(name, 1, null, null, MapOverlayKind.Raster, area.Bounds, LdbvImageryClient.Attribution); + [SuppressMessage( "Design", "CA1031", @@ -307,6 +567,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 +582,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 +598,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 +615,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. @@ -377,12 +655,15 @@ 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; 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 +677,24 @@ 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 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; } + + /// 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 +710,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 +773,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 +795,21 @@ internal void Loaded(OverlayData? data, string? error, bool missing, DateTimeOff NextFrameCommand.NotifyCanExecuteChanged(); } - partial void OnIsVisibleChanged(bool value) => _owner.UpdateVisibleShapes(); + /// 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() + { + DrawFailedOnMap = true; + LoadError = "Ebene konnte nicht gelesen werden: Das Bild lässt sich nicht darstellen."; + } + + 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..229f0b6a4 100644 --- a/src/LageBuch.Domain/Incident.cs +++ b/src/LageBuch.Domain/Incident.cs @@ -25,6 +25,24 @@ 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; + + /// + /// 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. @@ -2007,7 +2025,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 @@ -2032,12 +2050,17 @@ 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)); } - 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); @@ -2071,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/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/IIncidentSession.cs b/src/LageBuch.Sync/IIncidentSession.cs index 751c666f0..3e552a263 100644 --- a/src/LageBuch.Sync/IIncidentSession.cs +++ b/src/LageBuch.Sync/IIncidentSession.cs @@ -325,9 +325,12 @@ 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 + /// 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( + 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/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..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); @@ -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 @@ -922,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/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..3bec97dcb --- /dev/null +++ b/tests/LageBuch.Acceptance.Tests/LagekarteLuftbildRenderTests.cs @@ -0,0 +1,239 @@ +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 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() + { + 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); + 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 }; + window.Show(); + Dispatcher.UIThread.RunJobs(); + + var button = view.GetVisualDescendants().OfType