diff --git a/CLAUDE.md b/CLAUDE.md index bcc870a..5f4429f 100644 --- a/CLAUDE.md +++ b/CLAUDE.md @@ -35,7 +35,7 @@ Source layout under `src/OrthoStreamXP/`. Sub-folders are for navigation only: * - `Configuration/` — `SettingsOptions`/`SettingsSchema` (the known settings and the ini reader), `SettingValues` (typed access), `SettingsException`; `MountSettings` turns the values into a mount's settings. - `Mounting/` — `MountSession`: each scenery package gets its own `PackageMount` (overlay + build scheduler + load-ahead), sharing one downloader/encoder and the aircraft-position listener. `MountStatus` is the live snapshot for the UI. - `Infrastructure/` — `Log`, `AtomicFile`. -- `Gui/` — `App`, `MainWindow`, `GuiHost`, `MountController` (drives a `MountSession` from the window) at the root; `Views/` (XAML + code-behind: Home, Setup, Settings, Cache, Log, About), `ViewModels/`, `Settings/` and `Home/` (the types those pages show), `Mvvm/` (`ObservableObject`, `RelayCommand`, converters), `Map/` (cities, flight charts). +- `Gui/` — `App`, `MainWindow`, `GuiHost`, `MountController` (drives a `MountSession` from the window) at the root; `Views/` (XAML + code-behind: Home, Setup, Settings, Cache, Airports, Log, About), `ViewModels/`, `Settings/`, `Home/` and `Airports/` (the types those pages show), `Mvvm/` (`ObservableObject`, `RelayCommand`, converters), `Map/` (cities, flight charts). - `Scenery/` — the runtime streaming pipeline: - `FileSystem/`: `SceneryFileSystem` (WinFsp `FileSystemBase`) → `SceneryOverlay` (resolves a path to a backing file, a streamed photo texture, or an in-memory terrain definition); `SceneryPacks`, `TerrainDefinitions`. - `Streaming/`: `TextureStreamer` and its read/stand-in/build types, `TextureScheduler`, `TextureCatalog`, `ReadLog`. @@ -44,7 +44,7 @@ Source layout under `src/OrthoStreamXP/`. Sub-folders are for navigation only: * - `Aircraft/`: `AircraftPositionListener` (X-Plane UDP), `ViewTracker`, `SceneryLoads`. - `Colour/`: `SeasonClock` (seasonal tint by simulated date/location), `ObservedSeasons` (loads the satellite record per ~500 km tile for `season = satellite`). - `Textures/` — imagery to DDS: `TextureBuilder` (fetch → stitch → resize → sharpen → mipmaps → BC1 encode → atomic write; SkiaSharp is decode-only), `TextureQuality`, `Images`, `Sharpening` (unsharp mask on brightness, not a setting: 100 % for the areas' textures below ZL18, 60 % for the airports' ZL18 and finer) at the root; `Tiles/` (`TileSource`/`TileStore`: download + cache; the low-zoom base is zoom 13 and coarser because Bing's zoom 12 is other, lighter imagery; a tile every provider definitively lacks throws `TileNotAvailableException`, and `TextureBuilder` then makes it from a parent at hand, never coarser than 13), `Dds/` (`Dds` layout/encode/decode; mip levels by `MipFilter` = 2x2 averages in linear light; BC1 by `IspcBc1` = Intel's ISPC `ispc_texcomp.dll` from `native/ispc_texcomp/` (checked in, rebuilt by its `build.ps1`), loaded from the exe's folder, with one-colour blocks and four-colour mode fixed after it and every other block's colours refined by least squares (`Bc1Refinement`); `Dds.EncodeRangeFit` is the fallback without the DLL), `Scheduling/` (priority gates), `Seasons/` (`SeasonModel` calendar, `ObservedSeason` + `GreennessYear`: grass and fields by a place's yearly NDVI against its greenest month, trees by the calendar), `Vegetation/` (`VegetationSource`: NASA GIBS monthly VIIRS NDVI, downloaded and kept under the low-zoom base; `VegetationTile`, `NdviPalette`), `Colour/` (`Exposure`, `Contrast` (fixed 60 % S-curve, always on, not a setting), `ColourTable` = the shared BC1 lookup-table recolouring, `PhotoColours` = season → contrast → exposure as one table (rounded to 565 once) applied as X-Plane reads, also used by the Settings preview). -- `Setup/` — `Settings/` (`SettingsDocument`, ini under `%LOCALAPPDATA%\OrthoStreamXP`, `QualityPreset`, `ConnectionTest`), `Cache/` (inventory, areas, eviction), `Packages/` (downloads AutoOrtho's mesh regions from GitHub into the packages folder as `OrthoStream_*` packages: `MeshCatalog`, `AssetDownload`, `ZipUnpacker`, `OverlayPackage`, `RegionInstaller`; the tiles AutoOrtho lacks come from `flysimdev/orthostreamxp-scenery`'s latest-release `supplements.json` (`SupplementCatalog`, `RegionSupplement`) and are merged into their region without replacing any file, at install or, for regions installed before, by `Gui/Packages/SupplementUpdater` at each window start), `Installation/` (`AppPaths`, `AppUpdates`, `LegacyNames` migrating older settings/cache locations, `SystemCheck`, Velopack hooks). +- `Setup/` — `Settings/` (`SettingsDocument`, ini under `%LOCALAPPDATA%\OrthoStreamXP`, `QualityPreset`, `ConnectionTest`), `Cache/` (inventory, areas, eviction), `Packages/` (downloads AutoOrtho's mesh regions from GitHub into the packages folder as `OrthoStream_*` packages: `MeshCatalog`, `AssetDownload`, `ZipUnpacker`, `OverlayPackage`, `RegionInstaller`; the tiles AutoOrtho lacks come from `flysimdev/orthostreamxp-scenery`'s latest-release `supplements.json` (`SupplementCatalog`, `RegionSupplement`) and are merged into their region without replacing any file, at install or, for regions installed before, by `Gui/Packages/SupplementUpdater` at each window start), `Airports/` (the Airports page's flattening, one airport at a time: `AptDatReader` lists the airports of an apt.dat, `AirportSources` + `AirportCatalog` pick each ident from the highest enabled package in scenery_packs.ini (`*GLOBAL_AIRPORTS*` = Global Scenery\Global Airports), `FlattenedAirports` keeps a copy of each flattened airport with `1302 flatten 1` in its own `Custom Scenery\OrthoStreamXP Flattened Airports` package listed above the airport's source; the source files are never changed, Undo removes the copy and the last one removes the package), `Installation/` (`AppPaths`, `AppUpdates`, `LegacyNames` migrating older settings/cache locations, `SystemCheck`, Velopack hooks). - `Tuning/` — flight reports, facts and the preset/setting recommendations. - Logs go to `%LOCALAPPDATA%\OrthoStreamXP\logs`. diff --git a/README.md b/README.md index 2887e2e..497c90a 100644 --- a/README.md +++ b/README.md @@ -34,6 +34,7 @@ Traditional photo scenery often requires downloading and building large areas be - **Exposure and a live preview** — tone down photos that look too bright next to X-Plane's own scenery, and see any colour change on a photo from your cache before you fly. - **See what happened during your flight** — review download performance, scenery loading, and your flight route. - **Your scenery list, without Notepad** — switch X-Plane's scenery packages on or off and drag them into order on the X-Plane Custom Scenery page, and leave any of your photo scenery packages out of a flight with one switch on the Home page. +- **Level airports** — an airport that sits on a bump or in a hollow of the photo scenery's ground can be flattened on the Airports page, one at a time, without changing the airport's own files. Undo puts it back. ### Designed for everyday flying diff --git a/build-user-guide.ps1 b/build-user-guide.ps1 index 1db8e73..3b1f125 100644 --- a/build-user-guide.ps1 +++ b/build-user-guide.ps1 @@ -24,7 +24,7 @@ if (-not $browser) { throw 'Google Chrome or Microsoft Edge is needed to print t # The order of the guide's contents (docs\README.md). The pages keep their names so that pandoc's --file-scope # turns the links between them (settings.md#quality) into links inside the PDF. -$pages = 'README', 'installation', 'first-setup', 'flying', 'settings', 'cache', 'packages', 'custom-scenery', 'troubleshooting', 'faq' +$pages = 'README', 'installation', 'first-setup', 'flying', 'settings', 'cache', 'packages', 'custom-scenery', 'airports', 'troubleshooting', 'faq' $work = 'artifacts\user-guide' if (Test-Path $work) { Remove-Item $work -Recurse -Force } New-Item -ItemType Directory $work | Out-Null diff --git a/docs/OrthoStreamXP-UserGuide.pdf b/docs/OrthoStreamXP-UserGuide.pdf index a06080a..2ce13a8 100644 Binary files a/docs/OrthoStreamXP-UserGuide.pdf and b/docs/OrthoStreamXP-UserGuide.pdf differ diff --git a/docs/README.md b/docs/README.md index 0eef53d..828b68a 100644 --- a/docs/README.md +++ b/docs/README.md @@ -13,8 +13,9 @@ OrthoStreamXP adds real-world aerial photos to your X-Plane 12 scenery while you 5. [Cache](cache.md): how much disk space the scenery uses and how to free it. 6. [Packages](packages.md): downloading the ground mesh of a whole region, the quickest way to get scenery packages. 7. [X-Plane Custom Scenery](custom-scenery.md): switching X-Plane's scenery packages on or off and changing their order. -8. [Troubleshooting](troubleshooting.md): common problems, the log, updates, uninstalling and reporting a bug. -9. [Questions and answers](faq.md): what OrthoStreamXP does and does not do, choosing the packages folder, switching from AutoOrtho. +8. [Airports](airports.md): levelling the ground under an airport that sits on a bump or in a hollow, and undoing it. +9. [Troubleshooting](troubleshooting.md): common problems, the log, updates, uninstalling and reporting a bug. +10. [Questions and answers](faq.md): what OrthoStreamXP does and does not do, choosing the packages folder, switching from AutoOrtho. ## The short version diff --git a/docs/airports.md b/docs/airports.md new file mode 100644 index 0000000..e1d7be0 --- /dev/null +++ b/docs/airports.md @@ -0,0 +1,42 @@ +# Airports + +[User guide](README.md) › Airports + +Photo scenery packages bring their own, more detailed ground. Some airports then sit on a bump or in a hollow of it: the runway slopes, the terminal stands on a hill, parked aircraft lean. The **Airports** page in the sidebar fixes that one airport at a time: **Flatten** asks X-Plane to level the ground under the airport. + +## Finding an airport + +- Type in the search box: an **ICAO code** (or its start), or part of the airport's **name or city**. An exact code comes first, then codes that start with it, then names and cities. The page shows the first 50 matches; type more to narrow them. +- With the search box empty, the page lists **the airports you flattened**. +- Under each airport's name is its place and where X-Plane takes the airport from, for example *from Global Airports* (X-Plane's own airports) or the name of a custom scenery package. +- The page needs the **X-Plane folder** to be set in [Settings › Folders](settings.md#folders); until then it says *Choose your X-Plane folder first*. It reads the airports of the scenery packages switched on in X-Plane's scenery list each time you open it. **Refresh** reads them again, for example after you installed an airport while the page was open. + +## Flattening and undoing + +- **Flatten** levels the ground under the airport. The row then says **Flattened by OrthoStreamXP**. +- **Undo** takes the flattening out: X-Plane uses the airport as its scenery has it again. +- One airport is changed at a time. While it is being changed, the row says *Working…*. +- **Already flattened by its own scenery** means the airport's scenery levels the ground already: there is nothing to do, and the row has no button. + +> **Custom airports:** use **Flatten** for X-Plane's own airports, not for custom airport scenery. A custom airport loses its buildings and other scenery when the flattened copy is above it. The page reminds you of this at the top: in X-Plane's scenery list, keep **OrthoStreamXP Flattened Airports** below your custom airports (see [X-Plane Custom Scenery](custom-scenery.md)). + +## When changes apply + +- X-Plane reads the airports when it starts, so a change shows from **X-Plane's next start**. +- You can flatten or undo while OrthoStreamXP is stopped or while it runs, but not while it is starting or stopping. OrthoStreamXP does not need to be restarted. + +## How it works + +OrthoStreamXP never changes an airport's own files. It puts a copy of the airport, marked to be flattened, in a scenery package of its own: **OrthoStreamXP Flattened Airports** in X-Plane's `Custom Scenery` folder. It lists that package in X-Plane's scenery list just above the scenery the airport comes from, because X-Plane uses an airport from the highest package in the list that has it. **Open the folder** opens the package in Explorer. + +**Undo** takes the airport's copy out of the package. Undoing the last one removes the package and its line in the scenery list. + +## When a row shows a warning + +| The row says | What to do | +|---|---| +| **Flattened, but its scenery changed since** | The airport's layout changed after you flattened it, for example after an X-Plane update, and the copy still has the old one. Click **Flatten again** to take the new layout. | +| **Flattened, but X-Plane uses** *(package)***'s copy** | **OrthoStreamXP Flattened Airports** is below that package in the scenery list, or switched off. Click **Flatten again** to switch it on and move it just above. | +| *Its scenery package is no longer in the scenery list* | The package the airport came from is gone or switched off, and only the flattened copy is left. Click **Undo** if you no longer want it. | + +Next: [Troubleshooting](troubleshooting.md) diff --git a/docs/custom-scenery.md b/docs/custom-scenery.md index 44ec0ff..d3b8c57 100644 --- a/docs/custom-scenery.md +++ b/docs/custom-scenery.md @@ -35,6 +35,8 @@ Leave the photo scenery near the end, below airports and overlays. With **Keep t When you click **Start**, OrthoStreamXP adds its packages to the end of the list. When you click **Stop**, it takes out again the ones it added, because their folders are gone from `Custom Scenery` until the next start. A package that was already in the list before the start (for example from an earlier version of OrthoStreamXP) stays where it is. +**OrthoStreamXP Flattened Airports** is different: the [Airports](airports.md) page adds it when you flatten an airport, and it stays in the list whether OrthoStreamXP runs or not, until you undo the last flattened airport. Keep it below your custom airports. + To leave one of your own scenery packages out of OrthoStreamXP's photo scenery, use its switch under **Scenery packages** on the Home page instead (see [Flying › Leaving a package out](flying.md#leaving-a-package-out)). -Next: [Troubleshooting](troubleshooting.md) +Next: [Airports](airports.md) diff --git a/docs/faq.md b/docs/faq.md index e923a9b..e38a5cb 100644 --- a/docs/faq.md +++ b/docs/faq.md @@ -46,6 +46,10 @@ It does not change it. The water, the coastlines and the sea and inland water co Yes. Install SimHeaven the way its instructions say, and OrthoStreamXP as this guide describes. OrthoStreamXP puts its packages at the end of `scenery_packs.ini`, below SimHeaven, airports and other overlays, so they stay on top of the photos. +### An airport sits on a hill or in a dip. Can I fix it? + +Yes, for X-Plane's own airports. The ground comes from your scenery packages, and it is more detailed than X-Plane's, so a few airports no longer sit level on it. Find the airport on the [Airports](airports.md) page and click **Flatten**: X-Plane levels the ground under it from its next start. **Undo** puts it back. Custom airport scenery should not be flattened this way: it loses its buildings. + ### Is there a Mac or Linux version? No, OrthoStreamXP runs on Windows 10 and 11 only. There are no plans for a Mac version at the moment; that may change if enough people ask for it. diff --git a/mkdocs.yml b/mkdocs.yml index 57ac94e..399e00b 100644 --- a/mkdocs.yml +++ b/mkdocs.yml @@ -23,6 +23,7 @@ nav: - cache.md - packages.md - custom-scenery.md + - airports.md - troubleshooting.md - Questions and answers: faq.md - User guide (PDF): OrthoStreamXP-UserGuide.pdf diff --git a/release-notes/v1.6.0.md b/release-notes/v1.6.0.md new file mode 100644 index 0000000..2f9888e --- /dev/null +++ b/release-notes/v1.6.0.md @@ -0,0 +1,19 @@ +## What's new + +- **Airports page: flatten an airport.** Photo scenery comes with its own, more detailed ground, and some airports end up on a bump or in a hollow of it: a sloping runway, a terminal on a hill, aircraft parked in a dip. A new **Airports** page in the sidebar fixes that one airport at a time. Search by ICAO code, name or city, and click **Flatten**: X-Plane then levels the ground under that airport. **Undo** puts it back as it was. +- Without a search, the page lists the airports you have flattened. Each one says where its layout comes from, for example *from Global Airports*, and whether the flattening is in effect. + +## How flattening works + +OrthoStreamXP does not change any airport's own files. It puts a copy of the airport, marked to be flattened, in a scenery package of its own, **OrthoStreamXP Flattened Airports** in X-Plane's `Custom Scenery` folder, and lists it just above the airport's own scenery so X-Plane uses the copy. **Undo** takes the copy out again, and undoing the last airport removes the package. **Open the folder** shows the package in Explorer. + +## Good to know + +- **X-Plane reads the airports when it starts**, so a flattened airport shows level from X-Plane's next start. +- You can flatten an airport while OrthoStreamXP is stopped or while it runs, but not while it is starting or stopping. You do not need to restart OrthoStreamXP. +- **Use it for X-Plane's own airports, not for custom airport scenery.** A custom airport loses its buildings and other scenery when the flattened copy is above it. In X-Plane's scenery list, keep **OrthoStreamXP Flattened Airports** below your custom airports. You can check its place on the **X-Plane Custom Scenery** page. +- **Already flattened by its own scenery** means the airport is level already: there is nothing to do. +- If an airport's layout changes later, for example after an X-Plane update, the page says **Flattened, but its scenery changed since**. Click **Flatten again** to take the new layout. +- If the page says X-Plane uses another package's copy, the flattened package is lower in the scenery list or switched off. **Flatten again** puts it back in place. +- Nothing is downloaded, and none of your settings change with the update. +- **Reporting a problem?** The GitHub issue page now has forms: **Bug report**, **Scenery looks wrong** and **Feature request**. They ask for what helps most, such as the log and the exact place. diff --git a/src/OrthoStreamXP/Gui/Airports/AirportRow.cs b/src/OrthoStreamXP/Gui/Airports/AirportRow.cs new file mode 100644 index 0000000..748acde --- /dev/null +++ b/src/OrthoStreamXP/Gui/Airports/AirportRow.cs @@ -0,0 +1,84 @@ +using System.Windows.Input; +using OrthoStreamXP.Setup; + +namespace OrthoStreamXP.Gui; + +/// An airport on the Airports page, with its own Flatten or Undo button (one airport at a time: there is no batch). +internal sealed class AirportRow : ObservableObject +{ + private FlattenableAirport _airport; + private bool _busy; + private string? _error; + + public AirportRow(FlattenableAirport airport, AirportsViewModel page) + { + _airport = airport; + Flatten = new RelayCommand(() => _ = page.FlattenAsync(this), () => page.CanChange && CanFlatten); + Undo = new RelayCommand(() => _ = page.UndoAsync(this), () => page.CanChange && CanUndo); + } + + public FlattenableAirport Airport + { + get => _airport; + set + { + _airport = value; + Raise(null); // every property follows from it + } + } + + public string Ident => Airport.Ident; + public string Name => Airport.Name; + + /// "Brussels, BEL · from Global Airports". + public string Details + { + get + { + string from = Airport.Source is { } source ? $"from {source.Source.Name}" : "its scenery package is no longer in the scenery list"; + return Airport.Place is { } place ? $"{place} · {from}" : char.ToUpperInvariant(from[0]) + from[1..]; + } + } + + /// The airport's flattening in words; null while it is not flattened. + public string? StateText => Airport.State switch + { + FlattenState.FlattenedByScenery => "Already flattened by its own scenery", + FlattenState.Outdated => "Flattened, but the copy is out of date (its scenery changed, or it was made without the buildings): flatten it again", + FlattenState.Flattened when !Airport.InEffect => + $"Flattened, but X-Plane uses {Airport.Source?.Source.Name}'s copy: it is higher in the scenery list, or {FlattenedAirports.PackageName} is switched off. Flatten it again to fix that", + FlattenState.Flattened => "Flattened by OrthoStreamXP", + _ => null, + }; + + /// A problem to point out (an outdated or overridden copy) rather than a plain state. + public bool StateIsWarning => Airport.State == FlattenState.Outdated || (Airport.IsFlattenedHere && !Airport.InEffect); + + public bool CanFlatten => !Busy && Airport.Source is not null + && (Airport.State is FlattenState.NotFlattened or FlattenState.Outdated || (Airport.IsFlattenedHere && !Airport.InEffect)); + + public bool CanUndo => !Busy && Airport.IsFlattenedHere; + + public bool ShowFlatten => Airport.Source is not null && Airport.State != FlattenState.FlattenedByScenery && (!Airport.IsFlattenedHere || StateIsWarning); + public bool ShowUndo => Airport.IsFlattenedHere; + public string FlattenLabel => Airport.IsFlattenedHere ? "Flatten again" : "Flatten"; + + public ICommand Flatten { get; } + public ICommand Undo { get; } + + public bool Busy + { + get => _busy; + set + { + Set(ref _busy, value); + RelayCommand.Refresh(); + } + } + + public string? Error + { + get => _error; + set => Set(ref _error, value); + } +} diff --git a/src/OrthoStreamXP/Gui/MainWindow.xaml b/src/OrthoStreamXP/Gui/MainWindow.xaml index 6b7b49a..4ad8ee4 100644 --- a/src/OrthoStreamXP/Gui/MainWindow.xaml +++ b/src/OrthoStreamXP/Gui/MainWindow.xaml @@ -12,6 +12,7 @@ + diff --git a/src/OrthoStreamXP/Gui/ViewModels/AirportsViewModel.cs b/src/OrthoStreamXP/Gui/ViewModels/AirportsViewModel.cs new file mode 100644 index 0000000..d95698c --- /dev/null +++ b/src/OrthoStreamXP/Gui/ViewModels/AirportsViewModel.cs @@ -0,0 +1,197 @@ +using System.Collections.ObjectModel; +using System.Windows.Input; +using OrthoStreamXP.Setup; + +namespace OrthoStreamXP.Gui; + +/// +/// The Airports page: find an airport or airfield and flatten the terrain under it (for an airport that sits on a bump or in a +/// hollow of the mesh), or undo that. One airport at a time. The airports are read from the apt.dat files of the packages in +/// X-Plane's scenery_packs.ini when the page is shown (only the files that changed are read again). +/// +internal sealed class AirportsViewModel : ObservableObject, IPage +{ + /// How many matches the list shows: enough to pick from, few enough to stay quick. + private const int MaxRows = 50; + + private readonly MountController _mount; + private readonly Func _xplane; + private readonly AirportCatalog _catalog = new(); + private readonly Dictionary _airports = new(StringComparer.OrdinalIgnoreCase); + private AirportFlattening? _flattening; + private string _search = ""; + private bool _loading, _changing, _moreRows; + private string? _message; + + /// The X-Plane folder of the settings; null while there is none. + public AirportsViewModel(MountController mount, Func xplane) + { + _mount = mount; + _xplane = xplane; + Refresh = new RelayCommand(() => _ = LoadAsync(), () => !Loading && !_changing); + OpenFolder = new RelayCommand(() => Shell.Open(_flattening!.PackageFolder), () => _flattening is { } f && Directory.Exists(f.PackageFolder)); + // Starting and stopping rewrite scenery_packs.ini: no change of it meanwhile. + _mount.PropertyChanged += (_, e) => + { + if (e.PropertyName != nameof(MountController.State)) return; + Raise(nameof(CanChange)); + RelayCommand.Refresh(); + }; + } + + public ObservableCollection Rows { get; } = []; + public ICommand Refresh { get; } + public ICommand OpenFolder { get; } + + /// An ICAO code (or the start of one), or part of a name or city. + public string Search + { + get => _search; + set + { + if (Set(ref _search, value ?? "")) Filter(); + } + } + + public bool Loading + { + get => _loading; + private set + { + Set(ref _loading, value); + Raise(nameof(ListText)); + RelayCommand.Refresh(); + } + } + + /// One airport is changed at a time, and none while OrthoStreamXP starts or stops. + public bool CanChange => !_changing && !Loading && (_mount.IsRunning || _mount.IsStopped); + + /// What the list below shows. + public string ListText + { + get + { + if (Loading) return "Reading the airports of your scenery…"; + if (_xplane() is null) return "Choose your X-Plane folder first (in Settings): its airports are listed here."; + if (Search.Trim().Length == 0) + return Rows.Count == 0 ? "Search for an airport by its ICAO code, name or city." : "The airports you flattened:"; + if (Rows.Count == 0) return $"No airport matches \"{Search.Trim()}\"."; + return _moreRows ? $"The first {MaxRows} matches: type more to narrow them." : ""; + } + } + + public string? Message + { + get => _message; + private set + { + Set(ref _message, value); + Raise(nameof(HasMessage)); + } + } + + public bool HasMessage => Message is not null; + + public void OnShown() => _ = LoadAsync(); + + private async Task LoadAsync() + { + if (Loading || _changing) return; // the change in progress refreshes its own row + Message = null; + if (_xplane() is not { } xplane) + { + _flattening = null; + _airports.Clear(); + Filter(); + return; + } + Loading = true; + try + { + var flattening = new AirportFlattening(xplane, _catalog); + IReadOnlyList airports = await Task.Run(() => flattening.Load(CancellationToken.None)).ConfigureAwait(true); + _flattening = flattening; + _airports.Clear(); + foreach (FlattenableAirport airport in airports) _airports[airport.Ident] = airport; + if (_airports.Count == 0) Message = $"No airports found: X-Plane's Global Airports and the packages in {Path.Join(xplane, "Custom Scenery")} list none."; + } + catch (Exception ex) when (ex is IOException or UnauthorizedAccessException) + { + Message = $"Could not read the airports: {ex.Message}"; + Log.Warning(Message); + } + catch (Exception ex) + { + // Runs unawaited from the page: nothing that goes wrong may vanish. + Message = $"Could not read the airports: {ex.Message}"; + Log.Error("The airports could not be read", ex); + } + finally + { + Loading = false; + Filter(); + } + } + + public Task FlattenAsync(AirportRow row) => ChangeAsync(row, f => f.Flatten(row.Airport), "flattened"); + + public Task UndoAsync(AirportRow row) => ChangeAsync(row, f => f.Undo(row.Airport), "put back"); + + private async Task ChangeAsync(AirportRow row, Func change, string done) + { + if (!CanChange || _flattening is not { } flattening) return; + _changing = true; + row.Busy = true; + row.Error = null; + Raise(nameof(CanChange)); + try + { + FlattenableAirport changed = await Task.Run(() => change(flattening)).ConfigureAwait(true); + _airports[changed.Ident] = changed; + row.Airport = changed; + } + catch (Exception ex) when (ex is IOException or UnauthorizedAccessException or InvalidOperationException or FormatException) + { + row.Error = $"{row.Ident} could not be {done}: {ex.Message}"; + Log.Warning(row.Error); + } + catch (Exception ex) + { + // Runs unawaited from a button: nothing that goes wrong may vanish. + row.Error = $"{row.Ident} could not be {done}: {ex.Message}"; + Log.Error(row.Error, ex); + } + finally + { + _changing = false; + row.Busy = false; + Raise(nameof(CanChange)); + RelayCommand.Refresh(); + } + } + + /// The airports matching the search (an exact code first, then codes starting with it, then names and cities); the flattened ones without a search. + private void Filter() + { + string query = Search.Trim(); + IEnumerable matches = query.Length == 0 + ? _airports.Values.Where(a => a.IsFlattenedHere).OrderBy(a => a.Ident, StringComparer.OrdinalIgnoreCase) + : _airports.Values.Select(a => (Airport: a, Rank: Rank(a, query))).Where(m => m.Rank >= 0) + .OrderBy(m => m.Rank).ThenBy(m => m.Airport.Ident, StringComparer.OrdinalIgnoreCase).Select(m => m.Airport); + FlattenableAirport[] shown = [.. matches.Take(MaxRows + 1)]; + _moreRows = shown.Length > MaxRows; + Rows.Clear(); + foreach (FlattenableAirport airport in shown.Take(MaxRows)) Rows.Add(new AirportRow(airport, this)); + Raise(nameof(ListText)); + RelayCommand.Refresh(); + } + + private static int Rank(FlattenableAirport airport, string query) + { + if (airport.Ident.Equals(query, StringComparison.OrdinalIgnoreCase)) return 0; + if (airport.Ident.StartsWith(query, StringComparison.OrdinalIgnoreCase)) return 1; + if (airport.Name.Contains(query, StringComparison.OrdinalIgnoreCase)) return 2; + return airport.Place?.Contains(query, StringComparison.OrdinalIgnoreCase) == true ? 3 : -1; + } +} diff --git a/src/OrthoStreamXP/Gui/ViewModels/MainViewModel.cs b/src/OrthoStreamXP/Gui/ViewModels/MainViewModel.cs index 79170ea..f626f72 100644 --- a/src/OrthoStreamXP/Gui/ViewModels/MainViewModel.cs +++ b/src/OrthoStreamXP/Gui/ViewModels/MainViewModel.cs @@ -71,6 +71,7 @@ public MainViewModel() Cache = new CacheViewModel(this); Packages = new PackagesViewModel(Mount, Preferences, MeshHttp, MeshInstalls, PackagesFolder); Scenery = new SceneryViewModel(Mount, () => SettingsDocument.Load(SettingsDocument.DefaultPath).Get("xplane")); + Airports = new AirportsViewModel(Mount, () => SettingsDocument.Load(SettingsDocument.DefaultPath).Get("xplane")); About = new AboutViewModel(); Navigation = [ @@ -79,6 +80,7 @@ public MainViewModel() new NavItem("Cache", "", Cache), new NavItem("Packages", "", Packages), new NavItem("X-Plane Custom Scenery", "", Scenery), + new NavItem("Airports", "", Airports), new NavItem("Log", "", LogPage), new NavItem("About", "", About), ]; @@ -105,6 +107,8 @@ public MainViewModel() public InstallSlot MeshInstalls { get; } = new(); /// 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. + public AirportsViewModel Airports { get; } public LogViewModel LogPage { get; } public AboutViewModel About { get; } public IReadOnlyList Navigation { get; } diff --git a/src/OrthoStreamXP/Gui/Views/AirportsView.xaml b/src/OrthoStreamXP/Gui/Views/AirportsView.xaml new file mode 100644 index 0000000..e445870 --- /dev/null +++ b/src/OrthoStreamXP/Gui/Views/AirportsView.xaml @@ -0,0 +1,97 @@ + + + + + + + + + + +