From 586b5aa20e69427d087773d07048b9e239c47c1a Mon Sep 17 00:00:00 2001 From: ricardo404 Date: Mon, 30 Nov 2026 21:21:37 -0300 Subject: [PATCH] feat: add Hybrid Map Editor with Natural Earth regions, manual tile editing and presets --- .../Configuration/CustomMapSources.cs | 308 +++++++ .../Configuration/MountSettings.cs | 37 +- .../Configuration/SettingsOptions.cs | 4 +- src/OrthoStreamXP/Gui/MainWindow.xaml | 1 + src/OrthoStreamXP/Gui/Map/TileMapView.cs | 186 +++- .../Gui/Settings/CustomMapItems.cs | 280 ++++++ .../Gui/Settings/SettingNames.cs | 4 +- .../Gui/ViewModels/ConnectionTestViewModel.cs | 15 +- .../Gui/ViewModels/HybridMapViewModel.cs | 799 ++++++++++++++++++ .../Gui/ViewModels/MainViewModel.cs | 3 + .../Gui/ViewModels/SettingsViewModel.cs | 222 +++-- .../Gui/Views/HybridMapView.xaml | 469 ++++++++++ .../Gui/Views/HybridMapView.xaml.cs | 126 +++ src/OrthoStreamXP/Gui/Views/SettingsView.xaml | 121 ++- .../Textures/Tiles/TileSource.cs | 69 +- .../CustomMapSourcesTests.cs | 181 ++++ 16 files changed, 2711 insertions(+), 114 deletions(-) create mode 100644 src/OrthoStreamXP/Configuration/CustomMapSources.cs create mode 100644 src/OrthoStreamXP/Gui/Settings/CustomMapItems.cs create mode 100644 src/OrthoStreamXP/Gui/ViewModels/HybridMapViewModel.cs create mode 100644 src/OrthoStreamXP/Gui/Views/HybridMapView.xaml create mode 100644 src/OrthoStreamXP/Gui/Views/HybridMapView.xaml.cs create mode 100644 tests/OrthoStreamXP.Tests/CustomMapSourcesTests.cs diff --git a/src/OrthoStreamXP/Configuration/CustomMapSources.cs b/src/OrthoStreamXP/Configuration/CustomMapSources.cs new file mode 100644 index 0000000..49757ce --- /dev/null +++ b/src/OrthoStreamXP/Configuration/CustomMapSources.cs @@ -0,0 +1,308 @@ +using System.Globalization; +using System.Text; +using OrthoGlobalXP.Geo; +using OrthoGlobalXP.Regions; +using OrthoStreamXP.Textures; + +namespace OrthoStreamXP; + +/// A user-defined XYZ or Quadkey tile source stored in orthostreamxp.ini. +internal sealed record CustomMapSource(string Name, string UrlTemplate); + +/// A regional override mapping a Natural Earth region's 1x1 degree tiles to specific providers. +internal sealed record RegionalOverride(Region Region, string Providers, IReadOnlySet Tiles); + +/// +/// A prioritised hybrid map layer: a named set of 1x1 degree tiles (from Natural Earth, manual painting, or both) +/// routed to specific imagery providers, with a display colour and visibility toggle for the Hybrid Map Editor. +/// +internal sealed record HybridLayer( + string Name, + string ColorHex, + bool IsVisible, + string Providers, + IReadOnlySet Tiles, + Region? SourceRegion = null); + +/// Parses, validates and formats custom-sources and regional-providers in orthostreamxp.ini. +internal static class CustomMapSources +{ + public const string SourcesKey = "custom-sources"; + public const string OverridesKey = "regional-providers"; + + public static readonly string[] DefaultPalette = + [ + "#F58231", // Orange + "#00B4D8", // Cyan + "#2FA36B", // Green + "#9D4EDD", // Purple + "#E6399B", // Pink + "#E9C46A", // Gold + "#3D8BFD", // Blue + "#E05252", // Coral Red + ]; + + private static readonly char[] ForbiddenNameChars = ['|', ';', ',']; + private static readonly char[] ForbiddenUrlChars = ['|', ';']; + + /// Returns an error message if the custom source name or URL template is invalid; null when valid. + public static string? ValidateSource(string name, string urlTemplate) + { + string trimmedName = name.Trim(); + if (trimmedName.Length == 0) return "Enter a name for this map source."; + if (trimmedName.Length > 40) return "The source name must be 40 characters or fewer."; + if (trimmedName.IndexOfAny(ForbiddenNameChars) >= 0) return "The source name cannot contain commas, pipes (|) or semicolons (;)."; + if (ImageryProvider.BuiltIn.ContainsKey(trimmedName) || trimmedName.Equals(ImageryProvider.Synthetic, StringComparison.OrdinalIgnoreCase)) + return $"'{trimmedName}' is already a built-in provider name."; + + string trimmedUrl = urlTemplate.Trim(); + if (trimmedUrl.Length == 0) return "Enter a tile URL template."; + if (trimmedUrl.IndexOfAny(ForbiddenUrlChars) >= 0) return "The URL template cannot contain pipes (|) or semicolons (;)."; + if (!trimmedUrl.StartsWith("http://", StringComparison.OrdinalIgnoreCase) && !trimmedUrl.StartsWith("https://", StringComparison.OrdinalIgnoreCase)) + return "The URL template must start with http:// or https://."; + + bool hasQuadkey = trimmedUrl.Contains("{q}", StringComparison.OrdinalIgnoreCase); + bool hasXyz = trimmedUrl.Contains("{z}", StringComparison.OrdinalIgnoreCase) + && trimmedUrl.Contains("{x}", StringComparison.OrdinalIgnoreCase) + && trimmedUrl.Contains("{y}", StringComparison.OrdinalIgnoreCase); + if (!hasQuadkey && !hasXyz) + return "The URL template must include {z}, {x} and {y} placeholders (or {q} for quadkey)."; + + return null; + } + + public static string SanitizeLayerName(string name) + { + string clean = name.Replace('|', ' ').Replace(';', ' ').Trim(); + return clean.Length == 0 ? "Custom Layer" : clean; + } + + public static IReadOnlyList ParseSources(string? raw) + { + if (string.IsNullOrWhiteSpace(raw)) return []; + var list = new List(); + var seen = new HashSet(StringComparer.OrdinalIgnoreCase); + + foreach (string entry in raw.Split(';', StringSplitOptions.RemoveEmptyEntries | StringSplitOptions.TrimEntries)) + { + int sep = entry.IndexOf('|', StringComparison.Ordinal); + if (sep <= 0 || sep == entry.Length - 1) + throw new SettingsException($"Invalid entry in {SourcesKey}: '{entry}'. Expected 'Name|UrlTemplate'."); + + string name = entry[..sep].Trim(); + string url = entry[(sep + 1)..].Trim(); + if (ValidateSource(name, url) is { } error) + throw new SettingsException($"Invalid {SourcesKey} entry '{name}': {error}"); + if (!seen.Add(name)) + throw new SettingsException($"Duplicate custom map source name '{name}' in {SourcesKey}."); + + list.Add(new CustomMapSource(name, url)); + } + return list; + } + + public static string FormatSources(IEnumerable sources) => + string.Join(";", sources.Select(s => $"{s.Name.Trim()}|{s.UrlTemplate.Trim()}")); + + public static IReadOnlyDictionary ToLookup(IEnumerable sources) + { + var map = new Dictionary(StringComparer.OrdinalIgnoreCase); + foreach (CustomMapSource source in sources) + map[source.Name.Trim()] = source.UrlTemplate.Trim(); + return map; + } + + public static IReadOnlyList ParseOverrides(string? raw, IReadOnlyList? catalog = null) + { + if (string.IsNullOrWhiteSpace(raw)) return []; + IReadOnlyList regions = catalog ?? RegionCatalog.All; + var list = new List(); + + foreach (string entry in raw.Split(';', StringSplitOptions.RemoveEmptyEntries | StringSplitOptions.TrimEntries)) + { + string[] parts = entry.Split('|'); + if (parts.Length != 4) + throw new SettingsException($"Invalid entry in {OverridesKey}: '{entry}'. Expected 'Kind|Name|Parent|Providers'."); + + if (!Enum.TryParse(parts[0].Trim(), ignoreCase: true, out RegionKind kind)) + throw new SettingsException($"Unknown region kind '{parts[0]}' in {OverridesKey}."); + + string name = parts[1].Trim(); + string parent = parts[2].Trim(); + string providers = parts[3].Trim(); + if (providers.Length == 0) + throw new SettingsException($"No provider specified for '{name}' in {OverridesKey}."); + + Region? region = regions.FirstOrDefault(r => + r.Kind == kind + && string.Equals(r.Name, name, StringComparison.OrdinalIgnoreCase) + && string.Equals(r.Parent, parent, StringComparison.OrdinalIgnoreCase)); + + if (region is null) + throw new SettingsException($"Region '{name}' ({kind}) was not found in the Natural Earth catalog."); + + list.Add(new RegionalOverride(region, providers, new HashSet(region.Tiles))); + } + return list; + } + + public static string FormatOverrides(IEnumerable overrides) => + string.Join(";", overrides.Select(o => + string.Create(CultureInfo.InvariantCulture, $"{o.Region.Kind}|{o.Region.Name}|{o.Region.Parent}|{o.Providers.Trim()}"))); + + /// + /// Parses both legacy Natural Earth override entries (Kind|Name|Parent|Providers) and full hybrid layers + /// (Layer|Name|ColorHex|Visible|Providers|CompactTiles). + /// + public static IReadOnlyList ParseLayers(string? raw, IReadOnlyList? catalog = null) + { + if (string.IsNullOrWhiteSpace(raw)) return []; + IReadOnlyList regions = catalog ?? RegionCatalog.All; + var list = new List(); + int index = 0; + + foreach (string entry in raw.Split(';', StringSplitOptions.RemoveEmptyEntries | StringSplitOptions.TrimEntries)) + { + string[] parts = entry.Split('|'); + if (parts.Length == 6 && parts[0].Trim().Equals("Layer", StringComparison.OrdinalIgnoreCase)) + { + string name = SanitizeLayerName(parts[1]); + string color = NormalizeHexColor(parts[2], DefaultPalette[index % DefaultPalette.Length]); + bool visible = parts[3].Trim() != "0"; + string providers = parts[4].Trim(); + if (providers.Length == 0) + throw new SettingsException($"No provider specified for layer '{name}' in {OverridesKey}."); + + HashSet tiles = ParseCompactTiles(parts[5]); + list.Add(new HybridLayer(name, color, visible, providers, tiles)); + index++; + continue; + } + + if (parts.Length == 4) + { + if (!Enum.TryParse(parts[0].Trim(), ignoreCase: true, out RegionKind kind)) + throw new SettingsException($"Unknown region kind '{parts[0]}' in {OverridesKey}."); + + string name = parts[1].Trim(); + string parent = parts[2].Trim(); + string providers = parts[3].Trim(); + if (providers.Length == 0) + throw new SettingsException($"No provider specified for '{name}' in {OverridesKey}."); + + Region? region = regions.FirstOrDefault(r => + r.Kind == kind + && string.Equals(r.Name, name, StringComparison.OrdinalIgnoreCase) + && string.Equals(r.Parent, parent, StringComparison.OrdinalIgnoreCase)); + + if (region is null) + throw new SettingsException($"Region '{name}' ({kind}) was not found in the Natural Earth catalog."); + + string color = DefaultPalette[index % DefaultPalette.Length]; + list.Add(new HybridLayer(region.Name, color, true, providers, new HashSet(region.Tiles), region)); + index++; + continue; + } + + throw new SettingsException($"Invalid entry in {OverridesKey}: '{entry}'."); + } + return list; + } + + public static string FormatLayers(IEnumerable layers) + { + var entries = new List(); + foreach (HybridLayer layer in layers) + { + string name = SanitizeLayerName(layer.Name); + string color = NormalizeHexColor(layer.ColorHex, DefaultPalette[0]); + string visible = layer.IsVisible ? "1" : "0"; + string providers = layer.Providers.Trim(); + string tiles = FormatCompactTiles(layer.Tiles); + entries.Add($"Layer|{name}|{color}|{visible}|{providers}|{tiles}"); + } + return string.Join(";", entries); + } + + public static string FormatCompactTiles(IReadOnlySet tiles) + { + if (tiles.Count == 0) return ""; + var byLat = new SortedDictionary>(); + foreach (TileCoordinate t in tiles) + { + if (!byLat.TryGetValue(t.Lat, out List? lons)) + { + lons = []; + byLat[t.Lat] = lons; + } + lons.Add(t.Lon); + } + + var sb = new StringBuilder(); + foreach (var (lat, lons) in byLat) + { + lons.Sort(); + int i = 0; + while (i < lons.Count) + { + int start = lons[i]; + int end = start; + while (i + 1 < lons.Count && lons[i + 1] == end + 1) + { + i++; + end = lons[i]; + } + if (sb.Length > 0) sb.Append(','); + if (start == end) + sb.Append(new TileCoordinate(lat, start).Name); + else + sb.Append(string.Create(CultureInfo.InvariantCulture, $"{lat:+00;-00;+00}{start:+000;-000;+000}..{end:+000;-000;+000}")); + i++; + } + } + return sb.ToString(); + } + + public static HashSet ParseCompactTiles(string raw) + { + var result = new HashSet(); + if (string.IsNullOrWhiteSpace(raw)) return result; + + foreach (string token in raw.Split(',', StringSplitOptions.RemoveEmptyEntries | StringSplitOptions.TrimEntries)) + { + int dots = token.IndexOf("..", StringComparison.Ordinal); + if (dots < 0) + { + if (!TileCoordinate.TryParse(token, out TileCoordinate single)) + throw new SettingsException($"Invalid tile coordinate '{token}' in {OverridesKey}."); + result.Add(single); + continue; + } + + if (dots != 7 || token.Length != 13 + || !int.TryParse(token.AsSpan(0, 3), NumberStyles.Integer, CultureInfo.InvariantCulture, out int lat) + || !int.TryParse(token.AsSpan(3, 4), NumberStyles.Integer, CultureInfo.InvariantCulture, out int lonStart) + || !int.TryParse(token.AsSpan(9, 4), NumberStyles.Integer, CultureInfo.InvariantCulture, out int lonEnd) + || lat is < -90 or > 89 + || lonStart is < -180 or > 179 + || lonEnd is < -180 or > 179 + || lonEnd < lonStart) + { + throw new SettingsException($"Invalid tile range '{token}' in {OverridesKey}."); + } + + for (int lon = lonStart; lon <= lonEnd; lon++) + result.Add(new TileCoordinate(lat, lon)); + } + return result; + } + + private static string NormalizeHexColor(string? raw, string fallback) + { + if (string.IsNullOrWhiteSpace(raw)) return fallback; + string trimmed = raw.Trim(); + if (trimmed.Length == 7 && trimmed[0] == '#' && int.TryParse(trimmed.AsSpan(1), NumberStyles.HexNumber, CultureInfo.InvariantCulture, out _)) + return trimmed.ToUpperInvariant(); + return fallback; + } +} \ No newline at end of file diff --git a/src/OrthoStreamXP/Configuration/MountSettings.cs b/src/OrthoStreamXP/Configuration/MountSettings.cs index 62e7292..808e0c3 100644 --- a/src/OrthoStreamXP/Configuration/MountSettings.cs +++ b/src/OrthoStreamXP/Configuration/MountSettings.cs @@ -156,7 +156,12 @@ public static MountSettings FromValues(SettingValues values, bool console = true if (downloadWorkers < 1) throw new SettingsException("download-workers must be at least 1"); if (downloadTimeout is < 1 or > 120) throw new SettingsException("download-timeout must be between 1 and 120 seconds"); if (downloadAttempts is < 1 or > 10) throw new SettingsException("download-attempts must be between 1 and 10"); - IReadOnlyList? providers = provider is null ? null : ParseProviders(provider, values.String("texture-url")); + IReadOnlyList customSources = CustomMapSources.ParseSources(values.String(CustomMapSources.SourcesKey)); + IReadOnlyDictionary customLookup = CustomMapSources.ToLookup(customSources); + IReadOnlyList regionalOverrides = CustomMapSources.ParseLayers(values.String(CustomMapSources.OverridesKey)); + IReadOnlyList? providers = provider is null + ? null + : BuildProviders(provider, values.String("texture-url"), customLookup, regionalOverrides); if (encoderWorkers is < 1 or > 16) throw new SettingsException("encoder-workers must be between 1 and 16"); if (ddsBuildWorkers < 1) throw new SettingsException("dds-build-workers must be at least 1"); if (fileSystemThreads is < 2 or > 512) throw new SettingsException("filesystem-threads must be between 2 and 512"); @@ -292,11 +297,12 @@ internal static IReadOnlyList PlanPackages(SettingValues values, st } /// The provider list of texture-provider, with its errors as usage errors. - public static IReadOnlyList ParseProviders(string list, string? customTemplate) + public static IReadOnlyList ParseProviders( + string list, string? customTemplate, IReadOnlyDictionary? customSources = null) { try { - return ImageryProvider.ParseList(list, customTemplate); + return ImageryProvider.ParseList(list, customTemplate, customSources); } catch (ArgumentException ex) { @@ -304,6 +310,28 @@ public static IReadOnlyList ParseProviders(string list, string? } } + private static IReadOnlyList BuildProviders( + string globalList, + string? customTemplate, + IReadOnlyDictionary customLookup, + IReadOnlyList overrides) + { + IReadOnlyList globalProviders = ParseProviders(globalList, customTemplate, customLookup); + if (overrides.Count == 0 || globalProviders[0].Name == ImageryProvider.Synthetic) + return globalProviders; + + var combined = new List(); + foreach (HybridLayer rule in overrides) + { + if (!rule.IsVisible || rule.Tiles.Count == 0) continue; + IReadOnlyList ruleProviders = ParseProviders(rule.Providers, null, customLookup); + foreach (ImageryProvider rp in ruleProviders) + combined.Add(rp with { AllowedTiles = rule.Tiles }); + } + combined.AddRange(globalProviders); + return combined; + } + internal static SeasonOptions ParseSeasons(SettingValues values) { string onValue = values.String("seasons") ?? "off"; @@ -316,7 +344,6 @@ internal static SeasonOptions ParseSeasons(SettingValues values) return new SeasonOptions(on, strength / 100, choice); } - /// Dynamic quality's steps, or null when it is off. /// The resolution of the preset the settings are at (resolution-<preset>); Full for a level no preset has. private static TextureResolution ParseResolution(SettingValues values, Setup.QualityPreset? preset) { @@ -352,4 +379,4 @@ private static TextureResolution ParseResolution(SettingValues values, Setup.Qua private static bool SamePath(string a, string b) => string.Equals(Path.TrimEndingDirectorySeparator(a), Path.TrimEndingDirectorySeparator(b), StringComparison.OrdinalIgnoreCase); -} +} \ No newline at end of file diff --git a/src/OrthoStreamXP/Configuration/SettingsOptions.cs b/src/OrthoStreamXP/Configuration/SettingsOptions.cs index 5504976..dbd97a2 100644 --- a/src/OrthoStreamXP/Configuration/SettingsOptions.cs +++ b/src/OrthoStreamXP/Configuration/SettingsOptions.cs @@ -22,6 +22,8 @@ internal static class SettingsOptions .Add("lazy-texture-store", "Optional folder of ready-made DDS files (a textures folder's contents), served when no downloaded version is available") .Add("texture-provider", "Generate missing DDS textures from bing, esri, geoportal (Poland's national orthophoto, asked only for tiles in Poland) or synthetic (or any name with texture-url). Several, comma-separated, are tried in order for each tile: esri,bing") .Add("texture-url", "XYZ URL template for the provider that is not built in; supports {x}, {y}, {z}, {q}, {s}") + .Add(CustomMapSources.SourcesKey, "User-defined custom map sources as 'Name|UrlTemplate' separated by semicolons (;); each URL supports {x}, {y}, {z}, {q}, {s}") + .Add(CustomMapSources.OverridesKey, "Regional provider overrides (hybrid map) as 'Kind|Name|Parent|Providers' separated by semicolons (;); tried before the global texture-provider") .Add("download-workers", "Parallel source-image downloads, shared by all DDS builds (default: 8)") .Add("download-timeout", $"Seconds one tile download attempt may take before it is retried on another server (default: {TileSource.DefaultTimeoutSeconds})") .Add("download-attempts", $"Tries per tile before its texture fails, 1-10 (default: {TileSource.DefaultAttempts})") @@ -76,4 +78,4 @@ private static string ResolutionHelp(string preset) => "the wide ZL16 areas (8192 px: 4096) and keeps the airports' ZL18 ones; low halves them all. From the same downloads, for less graphics memory, RAM and disk " + "(only halving: X-Plane takes no texture whose size is not a power of two). Used while the settings are at that preset; " + "each resolution keeps its textures in its own cache subfolder (default: full)"; -} +} \ No newline at end of file diff --git a/src/OrthoStreamXP/Gui/MainWindow.xaml b/src/OrthoStreamXP/Gui/MainWindow.xaml index 28d1930..985074a 100644 --- a/src/OrthoStreamXP/Gui/MainWindow.xaml +++ b/src/OrthoStreamXP/Gui/MainWindow.xaml @@ -11,6 +11,7 @@ + diff --git a/src/OrthoStreamXP/Gui/Map/TileMapView.cs b/src/OrthoStreamXP/Gui/Map/TileMapView.cs index 01196c1..e4c659b 100644 --- a/src/OrthoStreamXP/Gui/Map/TileMapView.cs +++ b/src/OrthoStreamXP/Gui/Map/TileMapView.cs @@ -9,18 +9,47 @@ namespace OrthoStreamXP.Gui; +/// A coloured 1° tile layer displayed by in the Hybrid Map Editor. +internal sealed record MapColorLayer(IReadOnlySet Tiles, Color Color, bool IsActive); + +/// Mouse tool mode for . +internal enum MapToolMode +{ + /// Click toggles one tile, drag pans, Shift+drag adds a box, Ctrl+drag removes a box. + Navigate, + /// Click or left-drag draws a rectangle to add tiles; right-drag pans. + PaintBox, + /// Click or left-drag draws a rectangle to remove tiles; right-drag pans. + EraseBox, +} + +/// Event args raised when the user interactively edits tiles in Hybrid Map mode. +internal sealed class TileEditEventArgs(IReadOnlyList tiles, bool isAdd, bool isToggleSingle) : EventArgs +{ + public IReadOnlyList Tiles { get; } = tiles; + public bool IsAdd { get; } = isAdd; + public bool IsToggleSingle { get; } = isToggleSingle; +} + /// -/// The Build Scenery map: the world in Web Mercator as a grid of 1° tiles, over OpenStreetMap or plain. Tiles X-Plane's -/// Global Scenery has are shaded (or, over the street map, those it lacks are veiled). Zoomed in, the runways show, with the -/// finer textures the airports get. Cities are named, more as the map zooms in. Click picks or drops a tile, drag pans, -/// Shift+drag picks a rectangle, Ctrl+drag drops one, the wheel zooms. Its colours come from the brushes set on it (the -/// window's theme), so it follows light and dark. +/// The Build Scenery & Hybrid Map control: the world in Web Mercator as a grid of 1° tiles, over OpenStreetMap or plain. +/// Tiles X-Plane's Global Scenery has are shaded (or, over the street map, those it lacks are veiled). Zoomed in, the +/// runways show, with the finer textures the airports get. Cities are named, more as the map zooms in. /// internal sealed class TileMapView : FrameworkElement { public static readonly DependencyProperty ModelProperty = DependencyProperty.Register( nameof(Model), typeof(TileMapModel), typeof(TileMapView), new PropertyMetadata(null, OnModelChanged)); + public static readonly DependencyProperty ColorLayersProperty = DependencyProperty.Register( + nameof(ColorLayers), typeof(IReadOnlyList), typeof(TileMapView), new PropertyMetadata(null, OnColorLayersChanged)); + + public static readonly DependencyProperty ToolModeProperty = DependencyProperty.Register( + nameof(ToolMode), typeof(MapToolMode), typeof(TileMapView), new PropertyMetadata(MapToolMode.Navigate)); + + public static readonly DependencyProperty GlobalTintBrushProperty = DependencyProperty.Register( + nameof(GlobalTintBrush), typeof(Brush), typeof(TileMapView), new PropertyMetadata(null, OnPaletteChanged)); + public static readonly DependencyProperty ShowStreetMapProperty = DependencyProperty.Register( nameof(ShowStreetMap), typeof(bool), typeof(TileMapView), new PropertyMetadata(false, OnLookChanged)); @@ -65,11 +94,16 @@ internal sealed class TileMapView : FrameworkElement private static readonly Brush StreetCityText = Frozen(new SolidColorBrush(StreetInk)); private static readonly Pen StreetCityHalo = Frozen(new Pen(new SolidColorBrush(Color.FromArgb(0xE0, 0xFF, 0xFF, 0xFF)), 3) { LineJoin = PenLineJoin.Round }); + private static readonly Brush DropBoxFill = Frozen(new SolidColorBrush(Color.FromArgb(0x35, 0xE0, 0x52, 0x52))); + private static readonly Pen DropBoxPen = Frozen(new Pen(Solid(Color.FromRgb(0xE0, 0x52, 0x52)), 1.5) { DashStyle = DashStyles.Dash }); + /// The finer textures: one zoom above the package's, two, three and beyond (the legend's colours). private static readonly Brush[] FinerFills = [Solid(Color.FromRgb(0xFF, 0xC8, 0x2E)), Solid(Color.FromRgb(0xE8, 0x4F, 0xD8)), Solid(Color.FromRgb(0xFF, 0x40, 0x40))]; private readonly List[] _rows = [.. Enumerable.Range(0, 180).Select(_ => new List())]; + private readonly List[] _hybridRows = [.. Enumerable.Range(0, 180).Select(_ => new List())]; + private readonly Dictionary<(Color Color, bool IsActive, bool Street), Brush> _hybridBrushes = []; private readonly List _sceneryEdges = []; private readonly Dictionary> _preview = []; private readonly Dictionary> _runwaysByTile = []; @@ -116,12 +150,33 @@ private enum Shade /// The tile under the mouse, or null; for the line under the map. public event EventHandler? HoverChanged; + /// Raised instead of mutating when is active. + public event EventHandler? TilesEdited; + public TileMapModel? Model { get => (TileMapModel?)GetValue(ModelProperty); set => SetValue(ModelProperty, value); } + public IReadOnlyList? ColorLayers + { + get => (IReadOnlyList?)GetValue(ColorLayersProperty); + set => SetValue(ColorLayersProperty, value); + } + + public MapToolMode ToolMode + { + get => (MapToolMode)GetValue(ToolModeProperty); + set => SetValue(ToolModeProperty, value); + } + + public Brush? GlobalTintBrush + { + get => (Brush?)GetValue(GlobalTintBrushProperty); + set => SetValue(GlobalTintBrushProperty, value); + } + public bool ShowStreetMap { get => (bool)GetValue(ShowStreetMapProperty); @@ -194,7 +249,7 @@ public Brush FailedBrush private double PixelsPerDegree => _scale / 360; private Palette Colours => _palette ??= new Palette(ColorOf(Background), ColorOf(Foreground), ColorOf(PickedBrush), ColorOf(BuiltBrush), - ColorOf(BuildingBrush), ColorOf(FailedBrush)); + ColorOf(BuildingBrush), ColorOf(FailedBrush), GlobalTintBrush is SolidColorBrush tint ? tint.Color : (Color?)null); /// Centres the map on a point at the given zoom, or keeps the zoom when it is null. public void CenterOn(double lat, double lon, double? pixelsPerDegree = null) @@ -237,13 +292,18 @@ protected override void OnRender(DrawingContext drawingContext) if (ShowStreetMap) DrawStreetMap(drawingContext, width, height); else drawingContext.DrawRectangle(colours.Ocean, null, world); DrawTiles(drawingContext, width, height); + if (ColorLayers is not null) DrawHybridLayers(drawingContext, width, height); DrawGrid(drawingContext, width, height); DrawSceneryEdges(drawingContext, width, height); if (PixelsPerDegree >= FinerTexturesFrom) DrawAirports(drawingContext, width, height); if (PixelsPerDegree >= LabelsFrom) DrawLabels(drawingContext, width, height); if (ShowCities) DrawCities(drawingContext, width, height); if (_drag is DragMode.Pick or DragMode.Drop && _moved) - drawingContext.DrawRectangle(colours.RectangleFill, colours.RectanglePen, new Rect(_pressedAt, _lastMouse)); + { + Brush fill = _drag == DragMode.Drop ? DropBoxFill : colours.RectangleFill; + Pen pen = _drag == DragMode.Drop ? DropBoxPen : colours.RectanglePen; + drawingContext.DrawRectangle(fill, pen, new Rect(_pressedAt, _lastMouse)); + } } protected override void OnMouseLeftButtonDown(MouseButtonEventArgs e) @@ -252,9 +312,14 @@ protected override void OnMouseLeftButtonDown(MouseButtonEventArgs e) Focus(); _pressedAt = _lastMouse = e.GetPosition(this); _moved = false; - _drag = Keyboard.Modifiers.HasFlag(ModifierKeys.Shift) ? DragMode.Pick - : Keyboard.Modifiers.HasFlag(ModifierKeys.Control) ? DragMode.Drop - : DragMode.Pan; + if (Keyboard.Modifiers.HasFlag(ModifierKeys.Shift)) _drag = DragMode.Pick; + else if (Keyboard.Modifiers.HasFlag(ModifierKeys.Control)) _drag = DragMode.Drop; + else _drag = ToolMode switch + { + MapToolMode.PaintBox => DragMode.Pick, + MapToolMode.EraseBox => DragMode.Drop, + _ => DragMode.Pan, + }; CaptureMouse(); e.Handled = true; } @@ -329,6 +394,22 @@ private void EndDrag(Point at) DragMode drag = _drag; _drag = DragMode.None; ReleaseMouseCapture(); + + if (ColorLayers is not null && TilesEdited is { } edited) + { + if (!_moved && TileAt(at) is { } single) + { + bool isToggle = drag == DragMode.Pan; + edited.Invoke(this, new TileEditEventArgs([single], drag != DragMode.Drop, isToggle)); + } + else if (drag is DragMode.Pick or DragMode.Drop && _moved) + { + edited.Invoke(this, new TileEditEventArgs([.. TilesIn(_pressedAt, at)], drag == DragMode.Pick, false)); + } + InvalidateVisual(); + return; + } + if (Model is { } model) { if (drag == DragMode.Pan && !_moved && TileAt(at) is { } tile) model.Toggle(tile); @@ -356,6 +437,12 @@ private static void OnModelChanged(DependencyObject d, DependencyPropertyChanged view.RebuildRows(); } + private static void OnColorLayersChanged(DependencyObject d, DependencyPropertyChangedEventArgs e) + { + var view = (TileMapView)d; + view.RebuildHybridRows(); + } + private static void OnLookChanged(DependencyObject d, DependencyPropertyChangedEventArgs e) => ((TileMapView)d).InvalidateVisual(); private static void OnRunwaysChanged(DependencyObject d, DependencyPropertyChangedEventArgs e) @@ -420,6 +507,38 @@ private void RebuildRows() InvalidateVisual(); } + /// Precomputes runs of the highest-priority visible hybrid layer colour per row. + private void RebuildHybridRows() + { + for (int i = 0; i < 180; i++) _hybridRows[i].Clear(); + if (ColorLayers is { Count: > 0 } layers) + { + for (int lat = -90; lat < 90; lat++) + { + List row = _hybridRows[lat + 90]; + for (int lon = -180; lon < 180; lon++) + { + var coord = new TileCoordinate(lat, lon); + MapColorLayer? winner = null; + for (int k = 0; k < layers.Count; k++) + { + if (layers[k].Tiles.Contains(coord)) + { + winner = layers[k]; + break; + } + } + if (winner is null) continue; + if (row.Count > 0 && row[^1].Color == winner.Color && row[^1].IsActive == winner.IsActive && row[^1].East == lon - 1) + row[^1] = row[^1] with { East = lon }; + else + row.Add(new HybridRun(lon, lon, winner.Color, winner.IsActive)); + } + } + } + InvalidateVisual(); + } + /// The outline of the tiles X-Plane has: every side between a tile it has and one it lacks (or the world's edge). private void RebuildSceneryEdges(TileMapModel? model) { @@ -512,6 +631,34 @@ private void DrawTiles(DrawingContext dc, double width, double height) } } + private void DrawHybridLayers(DrawingContext dc, double width, double height) + { + var (west, north) = ToGeo(new Point(0, 0)); + var (east, south) = ToGeo(new Point(width, height)); + int firstLat = Math.Max((int)Math.Floor(south), -86), lastLat = Math.Min((int)Math.Floor(north), 85); + bool street = ShowStreetMap; + for (int lat = firstLat; lat <= lastLat; lat++) + { + double top = ToScreen(0, Math.Min(lat + 1, MaxLatitude)).Y, bottom = ToScreen(0, Math.Max(lat, -MaxLatitude)).Y; + foreach (HybridRun run in _hybridRows[lat + 90]) + { + if (run.East + 1 < west || run.West > east) continue; + double left = ToScreen(Math.Max(run.West, west - 1), 0).X, right = ToScreen(Math.Min(run.East + 1, east + 1), 0).X; + dc.DrawRectangle(HybridBrush(run.Color, run.IsActive, street), null, new Rect(left, top, right - left, bottom - top)); + } + } + } + + private Brush HybridBrush(Color color, bool isActive, bool street) + { + var key = (color, isActive, street); + if (_hybridBrushes.TryGetValue(key, out Brush? cached)) return cached; + byte alpha = (byte)(street ? (isActive ? 0xA8 : 0x72) : (isActive ? 0xC8 : 0x88)); + Brush brush = Frozen(new SolidColorBrush(Color.FromArgb(alpha, color.R, color.G, color.B))); + _hybridBrushes[key] = brush; + return brush; + } + private void DrawGrid(DrawingContext dc, double width, double height) { var (west, north) = ToGeo(new Point(0, 0)); @@ -742,25 +889,22 @@ private static T Frozen(T freezable) where T : Freezable /// Tiles to (inclusive) of one row, all of one shade. private readonly record struct Run(int West, int East, Shade Shade); + private readonly record struct HybridRun(int West, int East, Color Color, bool IsActive); + /// One side of a tile, in degrees: west to east along a parallel, or south to north along a meridian. private readonly record struct Edge(int West, int South, int East, int North); - /// - /// The map's brushes and pens, made from the theme's colours: the plain map draws the land in a wash of the text colour - /// over the background, and the picked, built, building and failed tiles in the accent and status colours; over the - /// street map the tiles X-Plane has are left clear, the others greyed out and the states translucent. Either way an - /// outline goes round the tiles X-Plane has. - /// private sealed class Palette { - public Palette(Color background, Color ink, Color picked, Color built, Color building, Color failed) + public Palette(Color background, Color ink, Color picked, Color built, Color building, Color failed, Color? globalTint) { Color pickedBuilt = Mix(picked, built); + Color landPlain = globalTint is { } gt ? WithAlpha(gt, 0x45) : Mix(background, ink, 0.22); Outside = Solid(background); Ocean = Solid(Mix(background, ink, 0.04)); - PlainFill = [null, Solid(Mix(background, ink, 0.22)), Solid(picked), Solid(built), Solid(pickedBuilt), Solid(building), Solid(failed)]; - // The tiles X-Plane lacks are greyed out (a light veil alone vanishes over OpenStreetMap's light colours). - StreetFill = [Solid(WithAlpha(Mix(background, ink, 0.15), 0xB0)), null, Solid(WithAlpha(picked, 0x88)), Solid(WithAlpha(built, 0x80)), + PlainFill = [null, Solid(landPlain), Solid(picked), Solid(built), Solid(pickedBuilt), Solid(building), Solid(failed)]; + StreetFill = [Solid(WithAlpha(Mix(background, ink, 0.15), 0xB0)), globalTint is { } st ? Solid(WithAlpha(st, 0x35)) : null, + Solid(WithAlpha(picked, 0x88)), Solid(WithAlpha(built, 0x80)), Solid(WithAlpha(pickedBuilt, 0x88)), Solid(WithAlpha(building, 0x90)), Solid(WithAlpha(failed, 0x90))]; DegreePen = Frozen(new Pen(Solid(WithAlpha(ink, 0x22)), 1)); TenDegreePen = Frozen(new Pen(Solid(WithAlpha(ink, 0x55)), 1)); @@ -802,4 +946,4 @@ public Palette(Color background, Color ink, Color picked, Color built, Color bui private static Color Mix(Color a, Color b, double share = 0.5) => Color.FromRgb( (byte)Math.Round(a.R + (b.R - a.R) * share), (byte)Math.Round(a.G + (b.G - a.G) * share), (byte)Math.Round(a.B + (b.B - a.B) * share)); } -} +} \ No newline at end of file diff --git a/src/OrthoStreamXP/Gui/Settings/CustomMapItems.cs b/src/OrthoStreamXP/Gui/Settings/CustomMapItems.cs new file mode 100644 index 0000000..22bbd59 --- /dev/null +++ b/src/OrthoStreamXP/Gui/Settings/CustomMapItems.cs @@ -0,0 +1,280 @@ +using System.Diagnostics; +using System.Globalization; +using System.Net; +using System.Net.Http; +using System.Windows.Input; +using System.Windows.Media; +using OrthoGlobalXP.Geo; +using OrthoStreamXP.Textures; + +namespace OrthoStreamXP.Gui; + +/// One user-defined map source row in Settings > Pictures and download. +internal sealed class CustomSourceRow : ObservableObject +{ + private bool _isTesting; + private string? _testStatus; + private bool _testOk; + + public CustomSourceRow(CustomMapSource source, Action remove) + { + Source = source; + TestCommand = new RelayCommand(() => _ = TestAsync(), () => !IsTesting); + RemoveCommand = new RelayCommand(() => remove(this), () => !IsTesting); + } + + public CustomMapSource Source { get; } + public string Name => Source.Name; + public string UrlTemplate => Source.UrlTemplate; + + public ICommand TestCommand { get; } + public ICommand RemoveCommand { get; } + + public bool IsTesting + { + get => _isTesting; + private set + { + if (!Set(ref _isTesting, value)) return; + Raise(nameof(TestButtonText)); + RelayCommand.Refresh(); + } + } + + public string TestButtonText => IsTesting ? "Testing…" : "Test source"; + + public string? TestStatus + { + get => _testStatus; + private set => Set(ref _testStatus, value); + } + + public bool TestOk + { + get => _testOk; + private set => Set(ref _testOk, value); + } + + private async Task TestAsync() + { + IsTesting = true; + TestOk = false; + TestStatus = "Requesting sample tile…"; + try + { + using var http = new HttpClient(new SocketsHttpHandler + { + ConnectTimeout = TimeSpan.FromSeconds(8), + UseProxy = false, + AutomaticDecompression = DecompressionMethods.None, + }) + { Timeout = TimeSpan.FromSeconds(10) }; + http.DefaultRequestHeaders.UserAgent.ParseAdd("orthostreamxp/0.2"); + + // Sample tile in central London at zoom 14 where global satellite providers have coverage. + var (x, y) = Tiles.LatLonToTile(51.50, -0.12, 14); + string url = TileSource.Url(UrlTemplate, x, y, 14, 0); + long started = Stopwatch.GetTimestamp(); + using HttpResponseMessage response = await http.GetAsync(url).ConfigureAwait(true); + response.EnsureSuccessStatusCode(); + byte[] bytes = await response.Content.ReadAsByteArrayAsync().ConfigureAwait(true); + Images.CheckTile(bytes); + double seconds = Stopwatch.GetElapsedTime(started).TotalSeconds; + TestOk = true; + TestStatus = string.Create(CultureInfo.CurrentCulture, $"OK — valid image tile ({bytes.Length / 1024.0:0.0} KB in {seconds:0.00} s)."); + } + catch (Exception ex) when (ex is HttpRequestException or TaskCanceledException or IOException or InvalidDataException or UriFormatException) + { + TestOk = false; + TestStatus = $"Failed: {ex.Message}"; + } + finally + { + IsTesting = false; + } + } +} + +/// One prioritised layer row in the Hybrid Map Editor. +internal sealed class HybridLayerRow : ObservableObject +{ + private readonly Action _onChanged; + private readonly HashSet _tiles; + private string _name; + private string _colorHex; + private bool _isVisible; + private bool _isActive; + private IReadOnlyList _choices = []; + private Choice? _selectedProvider; + + public HybridLayerRow( + HybridLayer layer, + IReadOnlyList choices, + Action onChanged, + Action select, + Action move, + Action frame, + Action clear, + Action remove) + { + _name = layer.Name; + _colorHex = layer.ColorHex; + _isVisible = layer.IsVisible; + _tiles = new HashSet(layer.Tiles); + _onChanged = onChanged; + + SelectCommand = new RelayCommand(() => select(this)); + CycleColorCommand = new RelayCommand(CycleColor); + ToggleVisibleCommand = new RelayCommand(() => IsVisible = !IsVisible); + MoveUpCommand = new RelayCommand(() => move(this, -1)); + MoveDownCommand = new RelayCommand(() => move(this, 1)); + FrameCommand = new RelayCommand(() => frame(this), () => _tiles.Count > 0); + ClearCommand = new RelayCommand(() => clear(this), () => _tiles.Count > 0); + RemoveCommand = new RelayCommand(() => remove(this)); + + UpdateChoices(choices, layer.Providers); + } + + public ICommand SelectCommand { get; } + public ICommand CycleColorCommand { get; } + public ICommand ToggleVisibleCommand { get; } + public ICommand MoveUpCommand { get; } + public ICommand MoveDownCommand { get; } + public ICommand FrameCommand { get; } + public ICommand ClearCommand { get; } + public ICommand RemoveCommand { get; } + + public IReadOnlySet Tiles => _tiles; + + public string Name + { + get => _name; + set + { + string clean = CustomMapSources.SanitizeLayerName(value); + if (!Set(ref _name, clean)) return; + _onChanged(); + } + } + + public string ColorHex + { + get => _colorHex; + private set + { + if (!Set(ref _colorHex, value)) return; + Raise(nameof(SwatchColor)); + Raise(nameof(SwatchBrush)); + _onChanged(); + } + } + + public Color SwatchColor => (Color)ColorConverter.ConvertFromString(_colorHex); + public Brush SwatchBrush => new SolidColorBrush(SwatchColor); + + public bool IsVisible + { + get => _isVisible; + set + { + if (!Set(ref _isVisible, value)) return; + Raise(nameof(EyeGlyph)); + _onChanged(); + } + } + + public string EyeGlyph => IsVisible ? "\uE7B3" : "\uED1A"; + + public bool IsActive + { + get => _isActive; + set => Set(ref _isActive, value); + } + + public int TileCount => _tiles.Count; + + public string TileCountText => _tiles.Count switch + { + 0 => "No tiles yet — pick a region or draw on the map", + 1 => "1 tile (1° × 1°)", + int n => string.Create(CultureInfo.InvariantCulture, $"{n:N0} tiles"), + }; + + public IReadOnlyList Choices + { + get => _choices; + private set => Set(ref _choices, value); + } + + public Choice? SelectedProvider + { + get => _selectedProvider; + set + { + if (value is null || Equals(_selectedProvider, value)) return; + _selectedProvider = value; + Raise(); + _onChanged(); + } + } + + public bool EditTiles(IEnumerable tiles, bool isAdd, bool isToggleSingle) + { + bool changed = false; + if (isToggleSingle) + { + foreach (TileCoordinate t in tiles) + { + if (!_tiles.Remove(t)) _tiles.Add(t); + changed = true; + } + } + else if (isAdd) + { + foreach (TileCoordinate t in tiles) + if (_tiles.Add(t)) changed = true; + } + else + { + foreach (TileCoordinate t in tiles) + if (_tiles.Remove(t)) changed = true; + } + + if (changed) NotifyTilesChanged(); + return changed; + } + + public void ClearTiles() + { + if (_tiles.Count == 0) return; + _tiles.Clear(); + NotifyTilesChanged(); + } + + public HybridLayer ToModel() => + new(Name, ColorHex, IsVisible, SelectedProvider?.Value ?? "bing,esri", new HashSet(_tiles)); + + public void UpdateChoices(IReadOnlyList baseChoices, string? preferredValue = null) + { + string target = preferredValue ?? _selectedProvider?.Value ?? "bing,esri"; + List list = [.. baseChoices]; + if (!list.Any(c => string.Equals(c.Value, target, StringComparison.OrdinalIgnoreCase))) + list.Add(new Choice(target, target)); + Choices = list; + _selectedProvider = Choices.FirstOrDefault(c => string.Equals(c.Value, target, StringComparison.OrdinalIgnoreCase)) ?? Choices[0]; + Raise(nameof(SelectedProvider)); + } + + private void CycleColor() + { + int idx = Array.FindIndex(CustomMapSources.DefaultPalette, c => string.Equals(c, _colorHex, StringComparison.OrdinalIgnoreCase)); + ColorHex = CustomMapSources.DefaultPalette[(idx + 1) % CustomMapSources.DefaultPalette.Length]; + } + + private void NotifyTilesChanged() + { + Raise(nameof(TileCount)); + Raise(nameof(TileCountText)); + RelayCommand.Refresh(); + } +} \ No newline at end of file diff --git a/src/OrthoStreamXP/Gui/Settings/SettingNames.cs b/src/OrthoStreamXP/Gui/Settings/SettingNames.cs index 1ad8685..f09c1d9 100644 --- a/src/OrthoStreamXP/Gui/Settings/SettingNames.cs +++ b/src/OrthoStreamXP/Gui/Settings/SettingNames.cs @@ -16,6 +16,8 @@ internal static class SettingNames [SkippedPackages.Setting] = "Scenery packages switched off", ["cache"] = "Cache folder", ["texture-provider"] = "Where the pictures come from", + [CustomMapSources.SourcesKey] = "Custom map sources", + [CustomMapSources.OverridesKey] = "Hybrid Map", ["download-workers"] = "Downloads at once", ["seasons"] = "Seasons", ["season"] = "Seasons", @@ -46,4 +48,4 @@ public static IReadOnlyList Of(IEnumerable keys) 1 => names[0], _ => $"{string.Join(", ", names.Take(names.Count - 1))} and {names[^1]}", }; -} +} \ No newline at end of file diff --git a/src/OrthoStreamXP/Gui/ViewModels/ConnectionTestViewModel.cs b/src/OrthoStreamXP/Gui/ViewModels/ConnectionTestViewModel.cs index b4e1564..b1e2015 100644 --- a/src/OrthoStreamXP/Gui/ViewModels/ConnectionTestViewModel.cs +++ b/src/OrthoStreamXP/Gui/ViewModels/ConnectionTestViewModel.cs @@ -11,6 +11,7 @@ namespace OrthoStreamXP.Gui; internal sealed class ConnectionTestViewModel : ObservableObject { private readonly Func _providers; + private readonly Func>? _customSources; private readonly Func _canRun; private readonly Action _measured; private readonly Action? _use; @@ -24,9 +25,17 @@ internal sealed class ConnectionTestViewModel : ObservableObject /// Called with each result, after it is saved. /// Sets downloads at once to the suggestion (null: the page sets it itself). /// Downloads at once now, so the suggestion is offered only when it differs. - public ConnectionTestViewModel(Func providers, Func canRun, Action measured, Action? use = null, Func? current = null) + /// Optional custom source URL map for resolving named user providers. + public ConnectionTestViewModel( + Func providers, + Func canRun, + Action measured, + Action? use = null, + Func? current = null, + Func>? customSources = null) { _providers = providers; + _customSources = customSources; _canRun = canRun; _measured = measured; _use = use; @@ -102,7 +111,7 @@ private async Task RunAsync() Status = "Opening the connection…"; try { - ImageryProvider provider = ImageryProvider.ParseList(_providers(), null)[0]; + ImageryProvider provider = ImageryProvider.ParseList(_providers(), null, _customSources?.Invoke())[0]; ConnectionResult result = await ConnectionTest.RunAsync(provider, new Progress(line => Status = line)).ConfigureAwait(true); result.Save(ConnectionResult.PathFor(SettingsDocument.DefaultPath)); _result = result; @@ -128,4 +137,4 @@ private string Describe(ConnectionResult result) string line = $"{result.Summary} (tested {result.WhenUtc.ToLocalTime():d MMM, HH:mm})"; return result.Suggested > 0 && _current?.Invoke() == result.Suggested ? $"{line} Your setting is already {result.Suggested}." : line; } -} +} \ No newline at end of file diff --git a/src/OrthoStreamXP/Gui/ViewModels/HybridMapViewModel.cs b/src/OrthoStreamXP/Gui/ViewModels/HybridMapViewModel.cs new file mode 100644 index 0000000..d6794ee --- /dev/null +++ b/src/OrthoStreamXP/Gui/ViewModels/HybridMapViewModel.cs @@ -0,0 +1,799 @@ +using System.Collections.ObjectModel; +using System.IO.Compression; +using System.Text; +using System.Text.Json; +using System.Windows; +using System.Windows.Input; +using Microsoft.Win32; +using OrthoGlobalXP.Geo; +using OrthoGlobalXP.Regions; +using OrthoGlobalXP.Scenery; +using OrthoStreamXP.Setup; +using GlobalCity = OrthoGlobalXP.Regions.City; + +namespace OrthoStreamXP.Gui; + +/// +/// The dedicated Hybrid Map Editor page: prioritised provider layers painted by Natural Earth regions or +/// manual 1° tile drawing over the world map. +/// +internal sealed class HybridMapViewModel : ObservableObject, IPage +{ + private const string ShareCodePrefix = "OSXP-HYBRID-1:"; + private const int MaxHistory = 50; + + private static readonly IReadOnlyList BuiltInLayerProviders = + [ + new Choice("Bing, then Esri", "bing,esri"), + new Choice("Bing only", "bing"), + new Choice("Esri (ArcGIS)", "esri"), + new Choice("Geoportal (Poland)", "geoportal"), + ]; + + private static readonly JsonSerializerOptions JsonOptions = new() + { + WriteIndented = true, + PropertyNameCaseInsensitive = true, + }; + + private readonly MainViewModel _main; + private readonly List _undoStack = []; + private readonly List _redoStack = []; + private HistorySnapshot? _committedSnapshot; + private string? _lastSavedOverrides; + private bool _initialized; + private bool _restoringHistory; + + private SettingsDocument _document = SettingsDocument.Load(SettingsDocument.DefaultPath); + private string? _loadedXPlane; + private bool _loadingScenery; + + private IReadOnlyList _layerProviders = BuiltInLayerProviders; + private IReadOnlyList _colorLayers = []; + private HybridLayerRow? _activeLayer; + private MapToolMode _toolMode = MapToolMode.Navigate; + private bool _showStreetMap = true; + private bool _showCities = true; + private bool _showGlobalTint = true; + private bool _isImportingCode; + private string _shareCodeInput = ""; + private string _hoverText = ""; + private string _globalFallbackText = "Bing, then Esri"; + private string? _saveError; + private string _toastText = ""; + private bool _showToast; + private readonly System.Windows.Threading.DispatcherTimer _toastTimer = new(); + + public HybridMapViewModel(MainViewModel main) + { + _main = main; + Regions = new RegionSearch(RegionCatalog.All); + + AddLayerCommand = new RelayCommand(AddNewLayer, () => CanEdit); + AddRegionToLayerCommand = new RelayCommand(() => ApplyRegionToActiveLayer(true), () => CanEdit && Regions.Selected is not null); + RemoveRegionFromLayerCommand = new RelayCommand(() => ApplyRegionToActiveLayer(false), () => CanEdit && Regions.Selected is not null && ActiveLayer is { TileCount: > 0 }); + StopStreamingCommand = new RelayCommand(() => _ = _main.Mount.StopAsync(), () => _main.Mount.IsRunning); + OpenSettingsSourcesCommand = new RelayCommand(() => + { + _main.Settings.Tab = SettingsViewModel.PicturesTab; + _main.Show(_main.Settings); + }); + + UndoCommand = new RelayCommand(Undo, () => CanUndo); + RedoCommand = new RelayCommand(Redo, () => CanRedo); + + ExportJsonCommand = new RelayCommand(ExportJson); + ImportJsonCommand = new RelayCommand(ImportJson, () => CanEdit); + CopyShareCodeCommand = new RelayCommand(CopyShareCode); + BeginImportCodeCommand = new RelayCommand(() => + { + ShareCodeInput = ""; + SaveError = null; + IsImportingCode = true; + }, () => CanEdit && !IsImportingCode); + CancelImportCodeCommand = new RelayCommand(() => + { + IsImportingCode = false; + ShareCodeInput = ""; + }); + ConfirmImportCodeCommand = new RelayCommand(ConfirmImportCode, () => CanEdit && !string.IsNullOrWhiteSpace(ShareCodeInput)); + + SetNavigateToolCommand = new RelayCommand(() => ToolMode = MapToolMode.Navigate); + SetPaintToolCommand = new RelayCommand(() => ToolMode = MapToolMode.PaintBox); + SetEraseToolCommand = new RelayCommand(() => ToolMode = MapToolMode.EraseBox); + + _toastTimer.Tick += (_, _) => + { + _toastTimer.Stop(); + ShowToast = false; + }; + _main.Mount.PropertyChanged += (_, e) => + { + if (e.PropertyName != nameof(MountController.State)) return; + Raise(nameof(CanEdit)); + Raise(nameof(IsLocked)); + Raise(nameof(LockedText)); + Raise(nameof(CanUndo)); + Raise(nameof(CanRedo)); + RelayCommand.Refresh(); + }; + } + + public event EventHandler? FrameRequested; + + public TileMapModel Map { get; } = new(); + public RegionSearch Regions { get; } + public IReadOnlyList Cities { get; } = CityCatalog.All; + public ObservableCollection Layers { get; } = []; + + public ICommand AddLayerCommand { get; } + public ICommand AddRegionToLayerCommand { get; } + public ICommand RemoveRegionFromLayerCommand { get; } + public ICommand StopStreamingCommand { get; } + public ICommand OpenSettingsSourcesCommand { get; } + public ICommand UndoCommand { get; } + public ICommand RedoCommand { get; } + public ICommand ExportJsonCommand { get; } + public ICommand ImportJsonCommand { get; } + public ICommand CopyShareCodeCommand { get; } + public ICommand BeginImportCodeCommand { get; } + public ICommand CancelImportCodeCommand { get; } + public ICommand ConfirmImportCodeCommand { get; } + public ICommand SetNavigateToolCommand { get; } + public ICommand SetPaintToolCommand { get; } + public ICommand SetEraseToolCommand { get; } + + public IReadOnlyList ColorLayers + { + get => _colorLayers; + private set => Set(ref _colorLayers, value); + } + + public HybridLayerRow? ActiveLayer + { + get => _activeLayer; + set + { + if (_activeLayer == value) return; + if (_activeLayer is not null) _activeLayer.IsActive = false; + _activeLayer = value; + if (_activeLayer is not null) _activeLayer.IsActive = true; + Raise(); + Raise(nameof(HasActiveLayer)); + Raise(nameof(ActiveLayerStatus)); + RebuildColorLayers(); + RelayCommand.Refresh(); + } + } + + public bool HasActiveLayer => _activeLayer is not null; + + public string ActiveLayerStatus => _activeLayer is { } active + ? $"Editing: {active.Name} ({active.SelectedProvider?.Label ?? "Default"}) · {active.TileCountText}" + : "Select or create a layer on the left to add regions or paint 1° tiles."; + + public MapToolMode ToolMode + { + get => _toolMode; + set + { + if (!Set(ref _toolMode, value)) return; + Raise(nameof(IsNavigateMode)); + Raise(nameof(IsPaintMode)); + Raise(nameof(IsEraseMode)); + } + } + + public bool IsNavigateMode => ToolMode == MapToolMode.Navigate; + public bool IsPaintMode => ToolMode == MapToolMode.PaintBox; + public bool IsEraseMode => ToolMode == MapToolMode.EraseBox; + + public bool ShowStreetMap + { + get => _showStreetMap; + set => Set(ref _showStreetMap, value); + } + + public bool ShowCities + { + get => _showCities; + set => Set(ref _showCities, value); + } + + public bool ShowGlobalTint + { + get => _showGlobalTint; + set + { + if (Set(ref _showGlobalTint, value)) Raise(nameof(EffectiveGlobalTint)); + } + } + + public System.Windows.Media.Brush? EffectiveGlobalTint => ShowGlobalTint + ? new System.Windows.Media.SolidColorBrush(System.Windows.Media.Color.FromRgb(0x3D, 0x8B, 0xFD)) + : null; + + public bool IsImportingCode + { + get => _isImportingCode; + set + { + if (Set(ref _isImportingCode, value)) RelayCommand.Refresh(); + } + } + + public string ShareCodeInput + { + get => _shareCodeInput; + set + { + if (Set(ref _shareCodeInput, value)) RelayCommand.Refresh(); + } + } + + public string HoverText + { + get => _hoverText; + private set => Set(ref _hoverText, value); + } + + public string GlobalFallbackText + { + get => _globalFallbackText; + private set => Set(ref _globalFallbackText, value); + } + + public bool CanEdit => _main.Mount.State == MountState.Stopped; + public bool IsLocked => !CanEdit; + public bool CanUndo => CanEdit && _undoStack.Count > 0; + public bool CanRedo => CanEdit && _redoStack.Count > 0; + + public string LockedText => _main.Mount.State == MountState.Running + ? "Streaming is running. Stop it to edit hybrid map layers." + : "Streaming is starting or stopping. Layers can be edited once it has stopped."; + + public string? SaveError + { + get => _saveError; + private set => Set(ref _saveError, value); + } + + public string ToastText + { + get => _toastText; + private set => Set(ref _toastText, value); + } + + public bool ShowToast + { + get => _showToast; + private set => Set(ref _showToast, value); + } + + public void OnShown() + { + ReloadFromDisk(); + string? xplane = _document.Get("xplane"); + if (!_loadingScenery && xplane != _loadedXPlane) + _ = LoadGlobalSceneryAsync(xplane); + } + + public void SetHover(TileCoordinate? tile) + { + if (tile is not { } t) + { + HoverText = ""; + return; + } + HybridLayerRow? owner = null; + foreach (HybridLayerRow layer in Layers) + { + if (layer.IsVisible && layer.Tiles.Contains(t)) + { + owner = layer; + break; + } + } + string source = owner is not null + ? $"{owner.Name} ({owner.SelectedProvider?.Value ?? "custom"})" + : $"Global fallback ({_document.Get("texture-provider") ?? "bing,esri"})"; + HoverText = $"{t.Name} · {source}"; + } + + public void HandleMapEdit(TileEditEventArgs e) + { + if (!CanEdit) return; + if (ActiveLayer is null) + { + if (!e.IsAdd && !e.IsToggleSingle) return; + HybridLayerRow created = CreateDefaultLayerRow(); + Layers.Insert(0, created); + ActiveLayer = created; + created.EditTiles(e.Tiles, e.IsAdd, e.IsToggleSingle); + CommitLayerChange(); + return; + } + if (ActiveLayer.EditTiles(e.Tiles, e.IsAdd, e.IsToggleSingle)) + CommitLayerChange(); + } + + private void Undo() + { + if (!CanUndo) return; + HistorySnapshot previous = _undoStack[^1]; + _undoStack.RemoveAt(_undoStack.Count - 1); + if (_committedSnapshot is not null) + { + _redoStack.Add(_committedSnapshot); + if (_redoStack.Count > MaxHistory) _redoStack.RemoveAt(0); + } + RestoreSnapshot(previous, "Undone"); + } + + private void Redo() + { + if (!CanRedo) return; + HistorySnapshot next = _redoStack[^1]; + _redoStack.RemoveAt(_redoStack.Count - 1); + if (_committedSnapshot is not null) + { + _undoStack.Add(_committedSnapshot); + if (_undoStack.Count > MaxHistory) _undoStack.RemoveAt(0); + } + RestoreSnapshot(next, "Redone"); + } + + private void RestoreSnapshot(HistorySnapshot snapshot, string toast) + { + _restoringHistory = true; + try + { + Layers.Clear(); + foreach (HybridLayer layer in snapshot.Layers) + Layers.Add(BuildLayerRow(layer)); + + _activeLayer = snapshot.ActiveLayerName is not null + ? Layers.FirstOrDefault(l => string.Equals(l.Name, snapshot.ActiveLayerName, StringComparison.OrdinalIgnoreCase)) ?? (Layers.Count > 0 ? Layers[0] : null) + : (Layers.Count > 0 ? Layers[0] : null); + if (_activeLayer is not null) _activeLayer.IsActive = true; + + Raise(nameof(ActiveLayer)); + Raise(nameof(HasActiveLayer)); + Raise(nameof(ActiveLayerStatus)); + _committedSnapshot = CaptureSnapshot(); + SaveLayers(toast); + } + finally + { + _restoringHistory = false; + Raise(nameof(CanUndo)); + Raise(nameof(CanRedo)); + RelayCommand.Refresh(); + } + } + + private HistorySnapshot CaptureSnapshot() => + new([.. Layers.Select(l => l.ToModel())], ActiveLayer?.Name); + + private void CommitLayerChange(string toast = "Saved") + { + if (!_restoringHistory && _committedSnapshot is not null) + { + _undoStack.Add(_committedSnapshot); + if (_undoStack.Count > MaxHistory) _undoStack.RemoveAt(0); + _redoStack.Clear(); + } + _committedSnapshot = CaptureSnapshot(); + SaveLayers(toast); + Raise(nameof(CanUndo)); + Raise(nameof(CanRedo)); + RelayCommand.Refresh(); + } + + private void ExportJson() + { + try + { + var dialog = new SaveFileDialog + { + Title = "Export Hybrid Map preset", + Filter = "JSON files (*.json)|*.json|All files (*.*)|*.*", + DefaultExt = ".json", + FileName = $"orthostreamxp-hybrid-{DateTime.Now:yyyyMMdd}.json", + }; + if (dialog.ShowDialog() != true) return; + + string json = BuildPresetJson(); + File.WriteAllText(dialog.FileName, json, new UTF8Encoding(false)); + SaveError = null; + NotifyToast("Exported JSON"); + } + catch (Exception ex) when (ex is IOException or UnauthorizedAccessException) + { + SaveError = $"Could not export JSON: {ex.Message}"; + } + } + + private void ImportJson() + { + if (!CanEdit) return; + try + { + var dialog = new OpenFileDialog + { + Title = "Import Hybrid Map preset", + Filter = "JSON files (*.json)|*.json|All files (*.*)|*.*", + DefaultExt = ".json", + }; + if (dialog.ShowDialog() != true) return; + + string raw = File.ReadAllText(dialog.FileName, Encoding.UTF8); + ApplyPresetPayload(raw, "Imported JSON"); + } + catch (Exception ex) when (ex is IOException or UnauthorizedAccessException or JsonException or SettingsException or FormatException) + { + SaveError = $"Could not import JSON: {ex.Message}"; + } + } + + private void CopyShareCode() + { + try + { + string json = BuildPresetJson(); + byte[] utf8 = Encoding.UTF8.GetBytes(json); + using var ms = new MemoryStream(); + using (var gzip = new GZipStream(ms, CompressionLevel.Optimal, leaveOpen: true)) + gzip.Write(utf8, 0, utf8.Length); + string code = ShareCodePrefix + Convert.ToBase64String(ms.ToArray()); + Clipboard.SetText(code); + SaveError = null; + NotifyToast("Share code copied"); + } + catch (Exception ex) + { + SaveError = $"Could not copy share code: {ex.Message}"; + } + } + + private void ConfirmImportCode() + { + if (!CanEdit) return; + try + { + ApplyPresetPayload(ShareCodeInput.Trim(), "Imported from share code"); + IsImportingCode = false; + ShareCodeInput = ""; + } + catch (Exception ex) when (ex is JsonException or SettingsException or FormatException or InvalidDataException) + { + SaveError = $"Invalid share code: {ex.Message}"; + } + } + + private string BuildPresetJson() + { + IReadOnlyList sources = []; + try + { + sources = CustomMapSources.ParseSources(_document.Get(CustomMapSources.SourcesKey)); + } + catch (SettingsException) + { + } + + var dto = new HybridPresetDto( + Version: 1, + GlobalProvider: _document.Get("texture-provider") ?? "bing,esri", + Sources: [.. sources.Select(s => new CustomSourceDto(s.Name, s.UrlTemplate))], + Layers: [.. Layers.Select(l => new HybridLayerDto( + l.Name, + l.ColorHex, + l.IsVisible, + l.SelectedProvider?.Value ?? "bing,esri", + CustomMapSources.FormatCompactTiles(l.Tiles)))]); + + return JsonSerializer.Serialize(dto, JsonOptions); + } + + private void ApplyPresetPayload(string payload, string toast) + { + string json; + if (payload.StartsWith(ShareCodePrefix, StringComparison.OrdinalIgnoreCase)) + { + string base64 = payload[ShareCodePrefix.Length..].Trim(); + byte[] compressed = Convert.FromBase64String(base64); + using var input = new MemoryStream(compressed); + using var gzip = new GZipStream(input, CompressionMode.Decompress); + using var reader = new StreamReader(gzip, Encoding.UTF8); + json = reader.ReadToEnd(); + } + else + { + json = payload; + } + + HybridPresetDto preset = JsonSerializer.Deserialize(json, JsonOptions) + ?? throw new SettingsException("Empty preset data."); + if (preset.Layers is null) + throw new SettingsException("The preset does not contain any layers."); + + var existingSources = new List(); + try + { + existingSources.AddRange(CustomMapSources.ParseSources(_document.Get(CustomMapSources.SourcesKey))); + } + catch (SettingsException) + { + } + + if (preset.Sources is { Count: > 0 }) + { + foreach (CustomSourceDto src in preset.Sources) + { + if (string.IsNullOrWhiteSpace(src.Name) || string.IsNullOrWhiteSpace(src.UrlTemplate)) continue; + if (CustomMapSources.ValidateSource(src.Name, src.UrlTemplate) is not null) continue; + if (existingSources.Any(s => string.Equals(s.Name, src.Name.Trim(), StringComparison.OrdinalIgnoreCase))) continue; + existingSources.Add(new CustomMapSource(src.Name.Trim(), src.UrlTemplate.Trim())); + } + string formattedSources = CustomMapSources.FormatSources(existingSources); + _document.Set(CustomMapSources.SourcesKey, formattedSources.Length == 0 ? null : formattedSources); + } + + RefreshProviderChoices(); + + var importedLayers = new List(); + int idx = 0; + foreach (HybridLayerDto item in preset.Layers) + { + string name = CustomMapSources.SanitizeLayerName(item.Name ?? $"Layer {idx + 1}"); + string color = string.IsNullOrWhiteSpace(item.ColorHex) + ? CustomMapSources.DefaultPalette[idx % CustomMapSources.DefaultPalette.Length] + : item.ColorHex.Trim(); + string providers = string.IsNullOrWhiteSpace(item.Providers) ? "bing,esri" : item.Providers.Trim(); + HashSet tiles = CustomMapSources.ParseCompactTiles(item.Tiles ?? ""); + importedLayers.Add(new HybridLayer(name, color, item.IsVisible, providers, tiles)); + idx++; + } + + _restoringHistory = true; + try + { + Layers.Clear(); + foreach (HybridLayer layer in importedLayers) + Layers.Add(BuildLayerRow(layer)); + _activeLayer = Layers.Count > 0 ? Layers[0] : null; + if (_activeLayer is not null) _activeLayer.IsActive = true; + Raise(nameof(ActiveLayer)); + Raise(nameof(HasActiveLayer)); + Raise(nameof(ActiveLayerStatus)); + } + finally + { + _restoringHistory = false; + } + + CommitLayerChange(toast); + + if (Layers.FirstOrDefault(l => l.TileCount > 0) is { } firstWithTiles) + FrameTiles(firstWithTiles.Tiles); + } + + private void RefreshProviderChoices() + { + var customChoices = new List(); + try + { + foreach (CustomMapSource src in CustomMapSources.ParseSources(_document.Get(CustomMapSources.SourcesKey))) + customChoices.Add(new Choice(src.Name, src.Name)); + } + catch (SettingsException ex) + { + SaveError = ex.Message; + } + _layerProviders = [.. customChoices, .. BuiltInLayerProviders]; + GlobalFallbackText = _document.Get("texture-provider") ?? "bing,esri"; + } + + private void ReloadFromDisk() + { + _document = SettingsDocument.Load(SettingsDocument.DefaultPath); + RefreshProviderChoices(); + + string? diskOverrides = _document.Get(CustomMapSources.OverridesKey); + if (_initialized && string.Equals(diskOverrides, _lastSavedOverrides, StringComparison.Ordinal)) + { + foreach (HybridLayerRow row in Layers) + row.UpdateChoices(_layerProviders); + RelayCommand.Refresh(); + return; + } + + _initialized = true; + _undoStack.Clear(); + _redoStack.Clear(); + string? prevActiveName = ActiveLayer?.Name; + Layers.Clear(); + try + { + foreach (HybridLayer layer in CustomMapSources.ParseLayers(diskOverrides)) + Layers.Add(BuildLayerRow(layer)); + } + catch (SettingsException ex) + { + SaveError = ex.Message; + } + + ActiveLayer = prevActiveName is not null + ? Layers.FirstOrDefault(l => string.Equals(l.Name, prevActiveName, StringComparison.OrdinalIgnoreCase)) ?? (Layers.Count > 0 ? Layers[0] : null) + : (Layers.Count > 0 ? Layers[0] : null); + + _lastSavedOverrides = diskOverrides; + _committedSnapshot = CaptureSnapshot(); + RebuildColorLayers(); + Raise(nameof(CanUndo)); + Raise(nameof(CanRedo)); + RelayCommand.Refresh(); + } + + private HybridLayerRow BuildLayerRow(HybridLayer layer) => new( + layer, + _layerProviders, + OnLayerPropertyChanged, + row => ActiveLayer = row, + MoveLayer, + FrameLayer, + ClearLayer, + RemoveLayer); + + private HybridLayerRow CreateDefaultLayerRow() + { + int index = Layers.Count; + string color = CustomMapSources.DefaultPalette[index % CustomMapSources.DefaultPalette.Length]; + string defaultProvider = _layerProviders.Count > 0 ? _layerProviders[0].Value : "bing,esri"; + return BuildLayerRow(new HybridLayer($"Layer {index + 1}", color, true, defaultProvider, new HashSet())); + } + + private void AddNewLayer() + { + if (!CanEdit) return; + HybridLayerRow row = CreateDefaultLayerRow(); + Layers.Insert(0, row); + ActiveLayer = row; + CommitLayerChange(); + } + + private void ApplyRegionToActiveLayer(bool add) + { + if (!CanEdit || Regions.Selected?.Region is not { } region) return; + if (ActiveLayer is null) + { + if (!add) return; + string color = CustomMapSources.DefaultPalette[Layers.Count % CustomMapSources.DefaultPalette.Length]; + string defaultProvider = _layerProviders.Count > 0 ? _layerProviders[0].Value : "bing,esri"; + HybridLayerRow newRow = BuildLayerRow(new HybridLayer(region.Name, color, true, defaultProvider, new HashSet(region.Tiles), region)); + Layers.Insert(0, newRow); + ActiveLayer = newRow; + CommitLayerChange(); + FrameTiles(region.Tiles); + return; + } + + if (ActiveLayer.EditTiles(region.Tiles, add, false)) + CommitLayerChange(); + if (add) FrameTiles(region.Tiles); + } + + private void MoveLayer(HybridLayerRow row, int delta) + { + if (!CanEdit) return; + int idx = Layers.IndexOf(row); + int target = idx + delta; + if (idx < 0 || target < 0 || target >= Layers.Count) return; + Layers.Move(idx, target); + CommitLayerChange(); + } + + private void FrameLayer(HybridLayerRow row) => FrameTiles(row.Tiles); + + private void ClearLayer(HybridLayerRow row) + { + if (!CanEdit || row.TileCount == 0) return; + row.ClearTiles(); + CommitLayerChange(); + } + + private void RemoveLayer(HybridLayerRow row) + { + if (!CanEdit) return; + int idx = Layers.IndexOf(row); + if (idx < 0) return; + Layers.RemoveAt(idx); + if (ActiveLayer == row) + ActiveLayer = Layers.Count > 0 ? Layers[Math.Min(idx, Layers.Count - 1)] : null; + CommitLayerChange(); + } + + private void OnLayerPropertyChanged() + { + if (_restoringHistory) return; + CommitLayerChange(); + } + + private void SaveLayers(string toast = "Saved") + { + RebuildColorLayers(); + Raise(nameof(ActiveLayerStatus)); + string formatted = CustomMapSources.FormatLayers(Layers.Select(l => l.ToModel())); + string? stored = formatted.Length == 0 ? null : formatted; + _document.Set(CustomMapSources.OverridesKey, stored); + try + { + _document.Save(); + _lastSavedOverrides = stored; + SaveError = null; + NotifyToast(toast); + } + catch (Exception ex) when (ex is IOException or UnauthorizedAccessException) + { + SaveError = $"The hybrid map settings could not be saved: {ex.Message}"; + } + } + + private void NotifyToast(string text) + { + ToastText = text; + ShowToast = true; + _toastTimer.Stop(); + _toastTimer.Interval = TimeSpan.FromSeconds(2); + _toastTimer.Start(); + } + + private void RebuildColorLayers() + { + var list = new List(); + foreach (HybridLayerRow row in Layers) + { + if (!row.IsVisible || row.Tiles.Count == 0) continue; + list.Add(new MapColorLayer(row.Tiles, row.SwatchColor, row == _activeLayer)); + } + ColorLayers = list; + } + + private void FrameTiles(IReadOnlyCollection tiles) + { + if (tiles.Count == 0) return; + int[] lats = [.. tiles.Select(t => t.Lat).Order()], lons = [.. tiles.Select(t => t.Lon).Order()]; + int low = tiles.Count >= 50 ? tiles.Count / 50 : 0, high = tiles.Count - 1 - low; + FrameRequested?.Invoke(this, new MapFrame(lons[low], lats[low], lons[high] + 1, lats[high] + 1)); + } + + private async Task LoadGlobalSceneryAsync(string? folder) + { + _loadedXPlane = folder; + if (string.IsNullOrWhiteSpace(folder)) + { + Map.SetAvailable([]); + return; + } + _loadingScenery = true; + try + { + IReadOnlyList tiles = await Task.Run(() => new GlobalScenery(folder).Tiles()).ConfigureAwait(true); + Map.SetAvailable(tiles); + } + catch (Exception ex) when (ex is IOException or UnauthorizedAccessException) + { + Log.Warning($"Hybrid Map: Global Scenery could not be read: {ex.Message}"); + } + finally + { + _loadingScenery = false; + } + } + + private sealed record HistorySnapshot(IReadOnlyList Layers, string? ActiveLayerName); + private sealed record HybridPresetDto(int Version, string? GlobalProvider, List? Sources, List Layers); + private sealed record CustomSourceDto(string Name, string UrlTemplate); + private sealed record HybridLayerDto(string Name, string ColorHex, bool IsVisible, string Providers, string Tiles); +} \ No newline at end of file diff --git a/src/OrthoStreamXP/Gui/ViewModels/MainViewModel.cs b/src/OrthoStreamXP/Gui/ViewModels/MainViewModel.cs index 3a7cf7c..d22981d 100644 --- a/src/OrthoStreamXP/Gui/ViewModels/MainViewModel.cs +++ b/src/OrthoStreamXP/Gui/ViewModels/MainViewModel.cs @@ -74,6 +74,7 @@ public MainViewModel() BuildScenery = new BuildSceneryViewModel(Mount, () => SettingsDocument.Load(SettingsDocument.DefaultPath).Get("xplane"), PackagesFolder, folder => Settings.PackagesFolder = folder, new SceneryBuildPreferencesStore(SceneryBuildPreferencesStore.DefaultPath)); PackagesPage = new PackagesPageViewModel(Packages, BuildScenery); + HybridMap = new HybridMapViewModel(this); Scenery = new SceneryViewModel(Mount, () => SettingsDocument.Load(SettingsDocument.DefaultPath).Get("xplane")); Airports = new AirportsViewModel(Mount, () => SettingsDocument.Load(SettingsDocument.DefaultPath).Get("xplane")); About = new AboutViewModel(); @@ -83,6 +84,7 @@ public MainViewModel() new NavItem("Settings", "", Settings), new NavItem("Cache", "", Cache), new NavItem("Packages", "", PackagesPage), + new NavItem("Hybrid Map", "\uE826", HybridMap), new NavItem("X-Plane Custom Scenery", "", Scenery), new NavItem("Airports", "", Airports), new NavItem("Log", "", LogPage), @@ -113,6 +115,7 @@ public MainViewModel() public BuildSceneryViewModel BuildScenery { get; } /// The Packages page: its Download and Build tabs. public PackagesPageViewModel PackagesPage { get; } + public HybridMapViewModel HybridMap { get; } /// X-Plane's scenery_packs.ini, to switch packages on or off. public SceneryViewModel Scenery { get; } /// Flattens the terrain under an airport, one at a time, and undoes it. diff --git a/src/OrthoStreamXP/Gui/ViewModels/SettingsViewModel.cs b/src/OrthoStreamXP/Gui/ViewModels/SettingsViewModel.cs index 7044222..47572bd 100644 --- a/src/OrthoStreamXP/Gui/ViewModels/SettingsViewModel.cs +++ b/src/OrthoStreamXP/Gui/ViewModels/SettingsViewModel.cs @@ -1,3 +1,4 @@ +using System.Collections.ObjectModel; using System.Globalization; using System.Windows.Input; using OrthoStreamXP.Setup; @@ -9,6 +10,14 @@ namespace OrthoStreamXP.Gui; /// The Settings page: everything in orthostreamxp.ini, in plain words, saved as soon as it changes. internal sealed class SettingsViewModel : ObservableObject, IPage { + private static readonly IReadOnlyList BuiltInProviders = + [ + new Choice("Bing, then Esri where Bing has no picture (recommended)", "bing,esri"), + new Choice("Esri (ArcGIS), then Bing where Esri has no picture", "esri,bing"), + new Choice("Bing only", "bing"), + new Choice("Geoportal in Poland (national orthophoto), Bing and Esri elsewhere", "geoportal,bing,esri"), + ]; + private readonly MainViewModel _main; private SettingsDocument _document = SettingsDocument.Load(SettingsDocument.DefaultPath); private DateTime _loadedWrite; @@ -21,17 +30,32 @@ internal sealed class SettingsViewModel : ObservableObject, IPage private string? _customLevelNote; private bool _confirmingReset; + private IReadOnlyList _providers = BuiltInProviders; + private bool _isAddingSource; + private string _newSourceName = ""; + private string _newSourceUrl = ""; + private string? _newSourceError; + public SettingsViewModel(MainViewModel main) { _main = main; Presets = [.. QualityPreset.Choices.Select(p => new PresetOption(p, ChoosePreset, SaveResolution, ChooseDynamicBase))]; - Providers = - [ - new Choice("Bing, then Esri where Bing has no picture (recommended)", "bing,esri"), - new Choice("Esri (ArcGIS), then Bing where Esri has no picture", "esri,bing"), - new Choice("Bing only", "bing"), - new Choice("Geoportal in Poland (national orthophoto), Bing and Esri elsewhere", "geoportal,bing,esri"), - ]; + + BeginAddSource = new RelayCommand(() => + { + NewSourceName = $"Custom Source {CustomSources.Count + 1}"; + NewSourceUrl = ""; + NewSourceError = null; + IsAddingSource = true; + }, () => CanEdit && !IsAddingSource); + CancelAddSource = new RelayCommand(() => + { + IsAddingSource = false; + NewSourceError = null; + }); + ConfirmAddSource = new RelayCommand(AddCustomSource); + OpenHybridMap = new RelayCommand(() => _main.Show(_main.HybridMap)); + BrowseXPlane = new RelayCommand(() => { if (Shell.PickFolder("Choose the X-Plane folder", XPlaneFolder) is { } folder) XPlaneFolder = folder; @@ -70,12 +94,12 @@ public SettingsViewModel(MainViewModel main) () => _main.Mount.State == MountState.Stopped, _ => { - // The recommended preset follows the measured speed until a flight says more. PresetMemory.Load(_document.Get("cache")); foreach (PresetOption option in Presets) option.RefreshMemory(); }, workers => DownloadWorkers = workers, - () => (int)DownloadWorkers); + () => (int)DownloadWorkers, + () => CustomMapSources.ToLookup(CustomSources.Select(s => s.Source))); _main.Mount.PropertyChanged += (_, e) => { if (e.PropertyName != nameof(MountController.State)) return; @@ -86,25 +110,60 @@ public SettingsViewModel(MainViewModel main) Reload(); } - /// The connection test beside "Downloads at once". public ConnectionTestViewModel ConnectionTest { get; } - - /// The Colours tab's before and after pictures. public ColourPreviewViewModel ColourPreview { get; } - /// The colour settings as the page shows them, for the preview. private ColourAdjustments ColourSettings => new( new Scenery.SeasonOptions(SeasonsOn, SeasonStrength / 100, SeasonModel.Names.GetValueOrDefault(Season?.Value ?? "auto", SeasonChoice.Auto)), Exposure); public IReadOnlyList Presets { get; } - public IReadOnlyList Providers { get; } + + public IReadOnlyList Providers + { + get => _providers; + private set => Set(ref _providers, value); + } + + public ObservableCollection CustomSources { get; } = []; + + public ICommand BeginAddSource { get; } + public ICommand CancelAddSource { get; } + public ICommand ConfirmAddSource { get; } + public ICommand OpenHybridMap { get; } + + public bool IsAddingSource + { + get => _isAddingSource; + set + { + if (Set(ref _isAddingSource, value)) RelayCommand.Refresh(); + } + } + + public string NewSourceName + { + get => _newSourceName; + set => Set(ref _newSourceName, value); + } + + public string NewSourceUrl + { + get => _newSourceUrl; + set => Set(ref _newSourceUrl, value); + } + + public string? NewSourceError + { + get => _newSourceError; + private set => Set(ref _newSourceError, value); + } + public IReadOnlyList Other { get; } public ICommand BrowseXPlane { get; } public ICommand BrowsePackages { get; } public ICommand BrowseCache { get; } public ICommand OpenFile { get; } public ICommand RunSetup { get; } - /// Stops the streaming, so the settings can be changed. public ICommand StopStreaming { get; } public ICommand AskReset { get; } public ICommand CancelReset { get; } @@ -112,13 +171,10 @@ public SettingsViewModel(MainViewModel main) public string FilePath => _document.Path; - /// The index of the Folders tab (SettingsView.xaml). public const int FoldersTab = 1; - - /// The index of the Colours tab (SettingsView.xaml). + public const int PicturesTab = 2; public const int ColoursTab = 3; - /// The tab shown: kept while the window is open, so coming back to Settings shows the same one. public int Tab { get => _tab; @@ -130,11 +186,9 @@ public int Tab private int _tab; - /// The preset the settings are at, or null for a level set by hand. private QualityPreset? CurrentPreset => QualityPreset.Current(_document.GetInt("level-change") ?? 0, _document.GetBool(QualityPreset.DynamicQualityKey) == true); - /// What the flight tuning changed from the preset's own values. public IReadOnlyList TunedRows => CurrentPreset is { } preset ? [.. TunedSettings.Changed(_document, preset).Select(c => new TunedRow(c.Setting.Label, c.Setting.Show(c.Value), $"{preset.Name}: {c.Setting.Show(c.Default)}"))] : []; @@ -145,7 +199,6 @@ public int Tab ? $"{preset.Name} uses its own settings. After a flight of {Tuner.MinMinutesInFlight:0} minutes or more, Home suggests changes when they would help; nothing changes without your OK." : $"Tuned for this PC and connection from your flights. {preset.Name}'s own values are shown beside them."; - /// Reset would change something: a tuned value, or a setting edited in the file. public bool CanReset => CurrentPreset is { } preset && TunedSettings.DiffersFromDefaults(_document, preset); public string ResetQuestion => $"Put every setting back to the {CurrentPreset?.Name} defaults and forget what was tuned for it? The folders, the picture source, the resolutions and Downloads at once stay as they are."; @@ -156,7 +209,6 @@ public bool ConfirmingReset set => Set(ref _confirmingReset, value); } - /// The level change is not one of the presets (set by hand in the file). public string? CustomLevelNote { get => _customLevelNote; @@ -165,35 +217,37 @@ public string? CustomLevelNote public Choice? Provider { - get => Providers.FirstOrDefault(c => c.Value == _document.Get("texture-provider")?.Replace(" ", "", StringComparison.Ordinal)); + get + { + string current = _document.Get("texture-provider")?.Replace(" ", "", StringComparison.Ordinal) ?? "bing,esri"; + return Providers.FirstOrDefault(c => string.Equals(c.Value.Replace(" ", "", StringComparison.Ordinal), current, StringComparison.OrdinalIgnoreCase)); + } set { if (value is null) return; Save("texture-provider", value.Value); Raise(); + ConnectionTest.Refresh(); } } - /// A double for the slider; saved as a whole number. public double DownloadWorkers { get => _document.GetInt("download-workers") ?? 8; set { int workers = Math.Clamp((int)Math.Round(value), 1, 256); - // Only a real change is a decision: the slider also reports a value it merely snapped (8 shown as 16). bool changed = _document.GetInt("download-workers") is { } before && before != workers; Save("download-workers", workers.ToString(CultureInfo.InvariantCulture)); Raise(); Raise(nameof(DownloadWorkersText)); - if (changed) ConnectionTest?.Decide(); // set by hand or by "Use": the test's suggestion has had its answer + if (changed) ConnectionTest?.Decide(); else ConnectionTest?.Refresh(); } } public string DownloadWorkersText => $"{DownloadWorkers} at once"; - /// The seasons by hand, or automatic. public IReadOnlyList SeasonChoices { get; } = [ new Choice("Automatic: X-Plane's date and the place", "auto"), @@ -233,7 +287,6 @@ public Choice? Season } } - /// The strength in percent, for the slider; saved as a whole number. public double SeasonStrength { get => _document.GetDouble("season-strength") ?? Scenery.SeasonOptions.DefaultStrength; @@ -248,7 +301,6 @@ public double SeasonStrength public string SeasonStrengthText => $"{SeasonStrength:0} %"; - /// The photos' exposure in percent, for the slider; saved as a whole number. public double Exposure { get => _document.GetDouble("exposure") ?? Textures.Exposure.Full; @@ -263,7 +315,6 @@ public double Exposure public string ExposureText => $"{Exposure:0} %"; - /// How strong X-Plane's grass and dirt decals are over the photos, in percent, for the slider. public double GroundDetail { get => Math.Clamp(_document.GetDouble("ground-detail") ?? Scenery.TerrainDecals.Min, Scenery.TerrainDecals.Min, Scenery.TerrainDecals.Full); @@ -277,7 +328,6 @@ public double GroundDetail public string GroundDetailText => $"{GroundDetail:0} %"; - /// Street lamps and lit windows on the photo scenery at night. public bool NightLightsOn { get => _document.GetBool("night-lights") == true; @@ -291,7 +341,6 @@ public bool NightLightsOn public string NightLightsOnText => NightLightsOn ? "On" : "Off"; - /// No detailed photos downloaded at night in X-Plane: the ground under the lights is blurry. public bool SkipPhotosAtNight { get => _document.GetBool("skip-photos-at-night") == true; @@ -314,7 +363,7 @@ public string XPlaneFolder if (!_loading) { Save("xplane", _xplane.Length == 0 ? null : _xplane); - SavePackages(); // a packages folder held back until X-Plane was known + SavePackages(); } Raise(nameof(XPlaneOk)); Raise(nameof(XPlaneStatus)); @@ -341,10 +390,6 @@ public string PackagesFolder } } - /// - /// The packages folder can be saved: X-Plane is known and the folder is not in its Custom Scenery. Otherwise the - /// settings keep the previous folder (an empty one, which clears the setting, is always saved). - /// private bool PackagesAllowed => _packages.Length == 0 || (XPlaneOk && !SystemCheck.IsInCustomScenery(_packages, _xplane)); private void SavePackages() @@ -385,7 +430,6 @@ public string CacheFolder ? $"{CacheInventory.FormatBytes(free)} free on this drive. {CacheEstimate}" : "Choose a folder on a fast drive with plenty of free space."; - /// The disk a newly flown area takes at the chosen texture size (about 3000 textures). public string CacheEstimate { get @@ -401,22 +445,13 @@ public string? SaveError private set => Set(ref _saveError, value); } - // ---------------------------------------------------------------- locked while streaming - - /// - /// The settings can be changed only while the streaming is stopped: what runs is then always what the page shows, - /// and the flight tuning judges the settings a whole session used. While it runs (or starts or stops) they are - /// shown, not editable, and a banner offers to stop it. - /// public bool CanEdit => _main.Mount.State == MountState.Stopped; - public bool IsLocked => !CanEdit; public string LockedText => _main.Mount.State == MountState.Running ? "Streaming is running. Stop it to change settings." : "Streaming is starting or stopping. Settings can be changed once it has stopped."; - /// The note that a change was saved, shown for a moment after each change. public string ToastText { get => _toastText; @@ -429,7 +464,6 @@ public bool ShowToast private set => Set(ref _showToast, value); } - /// A change was saved: a short note says so (the next start uses it). private void Saved() { ToastText = "Saved"; @@ -448,7 +482,6 @@ private void RefreshStatus() public void OnShown() { - // Picks up changes made to the file outside the window. if (File.Exists(_document.Path) && File.GetLastWriteTimeUtc(_document.Path) != _loadedWrite) Reload(); Raise(nameof(PackagesStatus)); Raise(nameof(CacheStatus)); @@ -456,7 +489,6 @@ public void OnShown() if (Tab == ColoursTab) ColourPreview.Show(); } - /// Reads the settings file again and shows its values. public void Reload() { _document = SettingsDocument.Load(SettingsDocument.DefaultPath); @@ -467,6 +499,7 @@ public void Reload() XPlaneFolder = _document.Get("xplane") ?? ""; PackagesFolder = _document.Get("base-packages") ?? _document.Get("source") ?? ""; CacheFolder = _document.Get("cache") ?? ""; + LoadCustomSources(); _loading = false; int level = _document.GetInt("level-change") ?? 0; QualityPreset? current = CurrentPreset; @@ -495,6 +528,85 @@ public void Reload() ColourPreview.Refresh(); } + private void LoadCustomSources() + { + CustomSources.Clear(); + try + { + foreach (CustomMapSource source in CustomMapSources.ParseSources(_document.Get(CustomMapSources.SourcesKey))) + CustomSources.Add(new CustomSourceRow(source, RemoveCustomSource)); + } + catch (SettingsException ex) + { + SaveError = ex.Message; + } + RefreshProviderChoices(); + } + + private void RefreshProviderChoices() + { + List customChoices = [.. CustomSources.Select(s => new Choice(s.Name, s.Name))]; + Providers = [.. BuiltInProviders, .. customChoices]; + Raise(nameof(Provider)); + } + + private void AddCustomSource() + { + string name = NewSourceName.Trim(); + string url = NewSourceUrl.Trim(); + if (CustomMapSources.ValidateSource(name, url) is { } error) + { + NewSourceError = error; + return; + } + if (CustomSources.Any(s => string.Equals(s.Name, name, StringComparison.OrdinalIgnoreCase))) + { + NewSourceError = $"A custom source named '{name}' already exists."; + return; + } + + CustomSources.Add(new CustomSourceRow(new CustomMapSource(name, url), RemoveCustomSource)); + RefreshProviderChoices(); + SaveCustomSources(); + IsAddingSource = false; + NewSourceError = null; + } + + private void RemoveCustomSource(CustomSourceRow row) + { + CustomSources.Remove(row); + RefreshProviderChoices(); + SaveCustomSources(); + + if (string.Equals(_document.Get("texture-provider")?.Trim(), row.Name, StringComparison.OrdinalIgnoreCase)) + { + Save("texture-provider", "bing,esri"); + Raise(nameof(Provider)); + } + + // Remove layers in orthostreamxp.ini that relied solely on the removed custom source. + try + { + IReadOnlyList layers = CustomMapSources.ParseLayers(_document.Get(CustomMapSources.OverridesKey)); + List kept = [.. layers.Where(l => !string.Equals(l.Providers.Trim(), row.Name, StringComparison.OrdinalIgnoreCase))]; + if (kept.Count != layers.Count) + { + string formatted = CustomMapSources.FormatLayers(kept); + Save(CustomMapSources.OverridesKey, formatted.Length == 0 ? null : formatted); + } + } + catch (SettingsException) + { + // Keep existing invalid text untouched. + } + } + + private void SaveCustomSources() + { + string formatted = CustomMapSources.FormatSources(CustomSources.Select(s => s.Source)); + Save(CustomMapSources.SourcesKey, formatted.Length == 0 ? null : formatted); + } + private void ChoosePreset(QualityPreset preset) { TunedSettings.ChoosePreset(_document, preset, TunedStore.Load(_document.Path)); @@ -504,17 +616,12 @@ private void ChoosePreset(QualityPreset preset) Reload(); } - /// - /// Dynamic's base changed on its card: chosen at once while the settings are at Dynamic (its level and that - /// preset's values, with what was tuned for it), otherwise kept for when Dynamic is chosen. - /// private void ChooseDynamicBase(QualityPreset dynamic) { if (CurrentPreset is { IsDynamic: true }) ChoosePreset(dynamic); else Save(QualityPreset.DynamicBaseKey, dynamic.DynamicBase!.Name.ToLowerInvariant()); } - /// A preset card's resolution changed: kept for that preset, used whenever the settings are at it. private void SaveResolution(QualityPreset preset, TextureResolution resolution) { Save(preset.ResolutionKey, resolution.Value); @@ -565,10 +672,9 @@ private SettingField Field(string key, string label, string help, FieldKind kind IReadOnlyList? choices = null, string on = "true", string off = "false", string? placeholder = null) => new(key, label, help, kind, Save, min, max, decimals, choices, on, off, placeholder); - /// What the program uses when the file does not set a value. private static string Default(string key) => key switch { "scenery-packs" => "on", _ => "", }; -} +} \ No newline at end of file diff --git a/src/OrthoStreamXP/Gui/Views/HybridMapView.xaml b/src/OrthoStreamXP/Gui/Views/HybridMapView.xaml new file mode 100644 index 0000000..383e3ee --- /dev/null +++ b/src/OrthoStreamXP/Gui/Views/HybridMapView.xaml @@ -0,0 +1,469 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/src/OrthoStreamXP/Gui/Views/HybridMapView.xaml.cs b/src/OrthoStreamXP/Gui/Views/HybridMapView.xaml.cs new file mode 100644 index 0000000..93dac1a --- /dev/null +++ b/src/OrthoStreamXP/Gui/Views/HybridMapView.xaml.cs @@ -0,0 +1,126 @@ +using System.Windows; +using System.Windows.Controls; +using System.Windows.Input; + +namespace OrthoStreamXP.Gui; + +internal sealed partial class HybridMapView +{ + private HybridMapViewModel? _bound; + private bool _userInteracted; + + public HybridMapView() + { + InitializeComponent(); + DataContextChanged += OnDataContextChanged; + PreviewKeyDown += OnPreviewKeyDown; + MapView.HoverChanged += (_, tile) => _bound?.SetHover(tile); + MapView.TilesEdited += (_, args) => _bound?.HandleMapEdit(args); + MapView.PreviewMouseWheel += (_, _) => _userInteracted = true; + MapView.PreviewMouseLeftButtonDown += (_, _) => _userInteracted = true; + MapView.PreviewMouseRightButtonDown += (_, _) => _userInteracted = true; + MapView.Loaded += (_, _) => ApplyDefaultViewIfReady(); + MapView.SizeChanged += (_, _) => ApplyDefaultViewIfReady(); + } + + private void OnPreviewKeyDown(object sender, KeyEventArgs e) + { + if (Keyboard.FocusedElement is TextBox) return; + if (e.Key == Key.Z && Keyboard.Modifiers == ModifierKeys.Control && _bound?.UndoCommand.CanExecute(null) == true) + { + _bound.UndoCommand.Execute(null); + e.Handled = true; + } + else if (((e.Key == Key.Y && Keyboard.Modifiers == ModifierKeys.Control) + || (e.Key == Key.Z && Keyboard.Modifiers == (ModifierKeys.Control | ModifierKeys.Shift))) + && _bound?.RedoCommand.CanExecute(null) == true) + { + _bound.RedoCommand.Execute(null); + e.Handled = true; + } + } + + private void OnDataContextChanged(object sender, DependencyPropertyChangedEventArgs e) + { + if (_bound is not null) _bound.FrameRequested -= OnFrameRequested; + _bound = e.NewValue as HybridMapViewModel; + if (_bound is not null) _bound.FrameRequested += OnFrameRequested; + } + + private void OnFrameRequested(object? sender, MapFrame frame) + { + _userInteracted = true; + MapView.Frame(frame.West, frame.South, frame.East, frame.North, maxPixelsPerDegree: 18); + } + + private void ApplyDefaultViewIfReady() + { + if (_userInteracted || MapView.ActualWidth <= 0 || MapView.ActualHeight <= 0) return; + ResetWorldView(); + } + + private void ResetWorldView() + { + double scale = Math.Max(MapView.ActualWidth * 1.08, MapView.ActualHeight * 1.15); + double ppd = scale > 0 ? scale / 360.0 : 2.8; + MapView.CenterOn(18, 8, ppd); + } + + private void OnZoomIn(object sender, RoutedEventArgs e) + { + _userInteracted = true; + MapView.ZoomBy(1.5); + } + + private void OnZoomOut(object sender, RoutedEventArgs e) + { + _userInteracted = true; + MapView.ZoomBy(1 / 1.5); + } + + private void OnResetView(object sender, RoutedEventArgs e) + { + _userInteracted = false; + ResetWorldView(); + } + + private void OnRegionBoxFocused(object sender, RoutedEventArgs e) + { + if (RegionBox.Text.Length > 0 && _bound?.Regions.Matches.Count > 0) RegionPopup.IsOpen = true; + } + + private void OnRegionBoxLostFocus(object sender, RoutedEventArgs e) => RegionPopup.IsOpen = false; + + private void OnRegionBoxClicked(object sender, MouseButtonEventArgs e) + { + if (RegionBox.Text.Length > 0 && _bound?.Regions.Matches.Count > 0) RegionPopup.IsOpen = true; + } + + private void OnRegionTextChanged(object sender, TextChangedEventArgs e) => + RegionPopup.IsOpen = RegionBox.IsKeyboardFocusWithin && RegionBox.Text.Length > 0 && _bound?.Regions.Matches.Count > 0; + + private void OnRegionBoxKey(object sender, KeyEventArgs e) + { + if (e.Key == Key.Escape) + { + RegionPopup.IsOpen = false; + e.Handled = true; + return; + } + if (e.Key == Key.Enter && _bound?.AddRegionToLayerCommand.CanExecute(null) == true) + { + _bound.AddRegionToLayerCommand.Execute(null); + RegionPopup.IsOpen = false; + e.Handled = true; + } + } + + private void OnRegionClicked(object sender, MouseButtonEventArgs e) + { + if (ItemsControl.ContainerFromElement(RegionList, e.OriginalSource as DependencyObject) is ListBoxItem item && _bound is not null) + { + RegionList.SelectedItem = item.DataContext; + RegionPopup.IsOpen = false; + } + } +} \ No newline at end of file diff --git a/src/OrthoStreamXP/Gui/Views/SettingsView.xaml b/src/OrthoStreamXP/Gui/Views/SettingsView.xaml index 61b264d..2fbedcf 100644 --- a/src/OrthoStreamXP/Gui/Views/SettingsView.xaml +++ b/src/OrthoStreamXP/Gui/Views/SettingsView.xaml @@ -276,7 +276,7 @@ - + @@ -285,12 +285,127 @@ - + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +