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..daa061c
--- /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 its scenery changed since: flatten it again to take the new layout",
+ 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 @@
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
diff --git a/src/OrthoStreamXP/Gui/Views/AirportsView.xaml.cs b/src/OrthoStreamXP/Gui/Views/AirportsView.xaml.cs
new file mode 100644
index 0000000..f7c6b6c
--- /dev/null
+++ b/src/OrthoStreamXP/Gui/Views/AirportsView.xaml.cs
@@ -0,0 +1,7 @@
+namespace OrthoStreamXP.Gui;
+
+/// The Airports page: search, then flatten or undo one airport at a time.
+internal sealed partial class AirportsView
+{
+ public AirportsView() => InitializeComponent();
+}
diff --git a/src/OrthoStreamXP/Scenery/FileSystem/SceneryPackList.cs b/src/OrthoStreamXP/Scenery/FileSystem/SceneryPackList.cs
index 0bc4c2d..1bea7ba 100644
--- a/src/OrthoStreamXP/Scenery/FileSystem/SceneryPackList.cs
+++ b/src/OrthoStreamXP/Scenery/FileSystem/SceneryPackList.cs
@@ -22,7 +22,7 @@ public IReadOnlyList Read() =>
public bool SetEnabled(string path, bool enabled) => Change(lines =>
{
bool changed = false;
- for (int i = 0; i < lines.Length; i++)
+ for (int i = 0; i < lines.Count; i++)
{
if (SceneryPackEntry.Parse(lines[i]) is not { } entry || entry.Enabled == enabled || !entry.IsAt(path)) continue;
lines[i] = (entry with { Enabled = enabled }).ToLine();
@@ -38,7 +38,7 @@ public bool SetEnabled(string path, bool enabled) => Change(lines =>
///
public bool MoveTo(string path, int to) => Change(lines =>
{
- int[] entries = [.. Enumerable.Range(0, lines.Length).Where(i => SceneryPackEntry.Parse(lines[i]) is not null)];
+ int[] entries = [.. Enumerable.Range(0, lines.Count).Where(i => SceneryPackEntry.Parse(lines[i]) is not null)];
int from = Array.FindIndex(entries, i => SceneryPackEntry.Parse(lines[i])!.IsAt(path));
if (from < 0 || to < 0 || to >= entries.Length || from == to) return false;
string moved = lines[entries[from]];
@@ -48,13 +48,28 @@ public bool MoveTo(string path, int to) => Change(lines =>
return true;
});
+ ///
+ /// Adds an enabled entry for just before the entry at , so X-Plane gives it
+ /// priority over that one and no other; before the first entry when is not listed (after the file's
+ /// other lines when it has no entry yet). Returns whether the file changed (not when it already lists the path, or there is no
+ /// file: X-Plane lists a new package first itself when it writes the file).
+ ///
+ public bool AddAbove(string path, string above) => Change(lines =>
+ {
+ if (lines.Exists(line => SceneryPackEntry.Parse(line)?.IsAt(path) == true)) return false;
+ int at = lines.FindIndex(line => SceneryPackEntry.Parse(line)?.IsAt(above) == true);
+ if (at < 0) at = lines.FindIndex(line => SceneryPackEntry.Parse(line) is not null);
+ lines.Insert(at < 0 ? lines.Count : at, new SceneryPackEntry(path, Enabled: true).ToLine());
+ return true;
+ });
+
/// Reads the file's lines, lets change them in place, and writes them back if it did.
- private bool Change(Func edit)
+ private bool Change(Func, bool> edit)
{
if (!File.Exists(FilePath)) return false;
string text = File.ReadAllText(FilePath);
string newline = text.Contains("\r\n", StringComparison.Ordinal) ? "\r\n" : "\n";
- string[] lines = text.ReplaceLineEndings("\n").TrimEnd('\n').Split('\n');
+ List lines = [.. text.ReplaceLineEndings("\n").TrimEnd('\n').Split('\n')];
if (!edit(lines)) return false;
AtomicFile.Write(FilePath, Encoding.UTF8.GetBytes(string.Join(newline, lines) + newline));
return true;
diff --git a/src/OrthoStreamXP/Setup/Airports/AirportBlock.cs b/src/OrthoStreamXP/Setup/Airports/AirportBlock.cs
new file mode 100644
index 0000000..6c3368d
--- /dev/null
+++ b/src/OrthoStreamXP/Setup/Airports/AirportBlock.cs
@@ -0,0 +1,100 @@
+namespace OrthoStreamXP.Setup;
+
+///
+/// One airport's lines of an apt.dat: its header (row 1, 16 or 17), its 1302 metadata, and its runways, taxiways and the rest.
+/// The lines are kept as they are, without the blank lines around them.
+///
+internal sealed class AirportBlock
+{
+ public const int LandAirport = 1, SeaplaneBase = 16, Heliport = 17, Metadata1302 = 1302, EndOfFile = 99;
+ private const string FlattenLine = "1302 flatten 1";
+
+ private readonly string[] _lines;
+
+ public AirportBlock(string text)
+ {
+ _lines = text.ReplaceLineEndings("\n").Trim('\n').Split('\n').Select(l => l.TrimEnd()).ToArray();
+ if (Header(_lines[0]) is not var (ident, name)) throw new FormatException($"Not an airport header: {_lines[0]}");
+ (Ident, Name) = (ident, name);
+ }
+
+ private AirportBlock(string[] lines, string ident, string name) => (_lines, Ident, Name) = (lines, ident, name);
+
+ public string Ident { get; }
+ public string Name { get; }
+
+ /// The lines, ending with a line break.
+ public string Text => string.Join("\r\n", _lines) + "\r\n";
+
+ /// Whether the airport asks X-Plane to flatten the terrain under it (1302 flatten 1).
+ public bool IsFlattened => _lines.Any(line => Metadata(line) is ("flatten", "1"));
+
+ ///
+ /// The same airport asking X-Plane to flatten it: an existing flatten line is set to 1, or one is added after the header's
+ /// metadata lines.
+ ///
+ public AirportBlock Flattened()
+ {
+ var lines = new List(_lines);
+ int existing = lines.FindIndex(line => Metadata(line) is ("flatten", _));
+ if (existing >= 0)
+ {
+ lines[existing] = FlattenLine;
+ }
+ else
+ {
+ int at = 1;
+ while (at < lines.Count && Metadata(lines[at]) is not null) at++;
+ lines.Insert(at, FlattenLine);
+ }
+ return new AirportBlock([.. lines], Ident, Name);
+ }
+
+ /// Whether both hold the same lines.
+ public bool SameAs(AirportBlock other) => _lines.SequenceEqual(other._lines, StringComparer.Ordinal);
+
+ /// The airports of an apt.dat's text, in order; the file's own header and end line are left out.
+ public static IReadOnlyList Split(string text)
+ {
+ var blocks = new List();
+ List? current = null;
+ foreach (string line in text.ReplaceLineEndings("\n").Split('\n'))
+ {
+ int code = RowCode(line);
+ if (code is LandAirport or SeaplaneBase or Heliport or EndOfFile)
+ {
+ Add(current, blocks);
+ current = code == EndOfFile ? null : [];
+ }
+ current?.Add(line);
+ }
+ Add(current, blocks);
+ return blocks;
+
+ static void Add(List? lines, List blocks)
+ {
+ if (lines is not null && Header(lines[0]) is not null) blocks.Add(new AirportBlock(string.Join('\n', lines)));
+ }
+ }
+
+ /// The ident and name of an airport header line ("1 145 0 0 EBBR Brussels National"), or null.
+ public static (string Ident, string Name)? Header(string line)
+ {
+ string[] parts = line.Split((char[]?)null, 6, StringSplitOptions.RemoveEmptyEntries | StringSplitOptions.TrimEntries);
+ if (parts.Length < 5 || RowCode(line) is not (LandAirport or SeaplaneBase or Heliport)) return null;
+ return (parts[4], parts.Length > 5 ? parts[5] : "");
+ }
+
+ /// The key and value of a 1302 line ("1302 city Brussels"), or null for any other line.
+ public static (string Key, string Value)? Metadata(string line)
+ {
+ string[] parts = line.Split((char[]?)null, 3, StringSplitOptions.RemoveEmptyEntries | StringSplitOptions.TrimEntries);
+ return parts.Length >= 2 && parts[0] == "1302" ? (parts[1], parts.Length > 2 ? parts[2] : "") : null;
+ }
+
+ private static int RowCode(string line)
+ {
+ int blank = line.IndexOfAny([' ', '\t']);
+ return int.TryParse(blank < 0 ? line : line[..blank], System.Globalization.NumberStyles.None, System.Globalization.CultureInfo.InvariantCulture, out int code) ? code : -1;
+ }
+}
diff --git a/src/OrthoStreamXP/Setup/Airports/AirportCatalog.cs b/src/OrthoStreamXP/Setup/Airports/AirportCatalog.cs
new file mode 100644
index 0000000..f804ad9
--- /dev/null
+++ b/src/OrthoStreamXP/Setup/Airports/AirportCatalog.cs
@@ -0,0 +1,37 @@
+namespace OrthoStreamXP.Setup;
+
+/// An airport and the package X-Plane takes it from.
+internal sealed record SourcedAirport(AirportRecord Record, AirportSource Source);
+
+///
+/// The airports X-Plane uses: each ident from the first source that lists it. A file is read again only when its size or time
+/// changed, so a refresh after flattening does not read Global Airports' 400 MB again.
+///
+internal sealed class AirportCatalog
+{
+ private readonly Dictionary Airports)> _files =
+ new(StringComparer.OrdinalIgnoreCase);
+ private readonly Lock _lock = new();
+
+ public IReadOnlyDictionary Load(IReadOnlyList sources, CancellationToken cancel)
+ {
+ var airports = new Dictionary(StringComparer.OrdinalIgnoreCase);
+ foreach (AirportSource source in sources)
+ foreach (AirportRecord airport in Airports(source.AptDat, cancel))
+ airports.TryAdd(airport.Ident, new SourcedAirport(airport, source));
+ return airports;
+ }
+
+ private IReadOnlyList Airports(string aptDat, CancellationToken cancel)
+ {
+ var file = new FileInfo(aptDat);
+ lock (_lock)
+ {
+ if (_files.TryGetValue(aptDat, out var known) && known.Length == file.Length && known.Written == file.LastWriteTimeUtc)
+ return known.Airports;
+ }
+ IReadOnlyList airports = AptDatReader.Read(aptDat, cancel);
+ lock (_lock) _files[aptDat] = (file.Length, file.LastWriteTimeUtc, airports);
+ return airports;
+ }
+}
diff --git a/src/OrthoStreamXP/Setup/Airports/AirportFlattening.cs b/src/OrthoStreamXP/Setup/Airports/AirportFlattening.cs
new file mode 100644
index 0000000..e000fc8
--- /dev/null
+++ b/src/OrthoStreamXP/Setup/Airports/AirportFlattening.cs
@@ -0,0 +1,88 @@
+namespace OrthoStreamXP.Setup;
+
+/// Where an airport stands on flattening.
+internal enum FlattenState
+{
+ /// X-Plane follows the terrain under it.
+ NotFlattened,
+ /// Its own scenery already asks X-Plane to flatten it: nothing to do.
+ FlattenedByScenery,
+ /// Flattened by OrthoStreamXP; can be undone.
+ Flattened,
+ /// Flattened by OrthoStreamXP, but its scenery changed since: the copy holds the old layout.
+ Outdated,
+}
+
+///
+/// An airport on the Airports page. is where X-Plane takes it from without OrthoStreamXP (null when that
+/// package is gone and only the flattened copy is left); is false when the flattened copy is listed
+/// below that package or switched off in scenery_packs.ini, so X-Plane does not use it.
+///
+internal sealed record FlattenableAirport(string Ident, string Name, string? Place, SourcedAirport? Source, FlattenState State, bool InEffect)
+{
+ public bool IsFlattenedHere => State is FlattenState.Flattened or FlattenState.Outdated;
+}
+
+///
+/// Flattens one airport at a time, and undoes it: see for how. The airports come from the
+/// apt.dat files of the enabled packages in X-Plane's scenery_packs.ini (see ).
+///
+internal sealed class AirportFlattening(string xplane, AirportCatalog catalog)
+{
+ private readonly FlattenedAirports _package = new(xplane);
+
+ /// The package flattened airports are kept in.
+ public string PackageFolder => _package.Folder;
+
+ /// Every airport X-Plane knows, with its state; reads the apt.dat files that changed since the last call.
+ public IReadOnlyList Load(CancellationToken cancel)
+ {
+ IReadOnlyDictionary sourced = catalog.Load(new AirportSources(xplane).Find(), cancel);
+ var flattened = new Dictionary(StringComparer.OrdinalIgnoreCase);
+ foreach (AirportBlock block in _package.Read()) flattened[block.Ident] = block;
+
+ var airports = new List(sourced.Count + flattened.Count);
+ foreach (SourcedAirport airport in sourced.Values)
+ airports.Add(Describe(airport, flattened.GetValueOrDefault(airport.Record.Ident)));
+ foreach (AirportBlock orphan in flattened.Values.Where(b => !sourced.ContainsKey(b.Ident)))
+ airports.Add(new FlattenableAirport(orphan.Ident, orphan.Name, null, null, FlattenState.Flattened, InEffect: true));
+ return airports;
+ }
+
+ /// Flattens (again, for an outdated copy: the copy is taken from its scenery as it is now).
+ public FlattenableAirport Flatten(FlattenableAirport airport)
+ {
+ if (airport.Source is not { } source) throw new InvalidOperationException($"{airport.Ident} has no scenery to take it from.");
+ AirportBlock block = AptDatReader.ReadBlock(source.Source.AptDat, source.Record);
+ _package.Add(block.Flattened(), source.Source.EntryPath);
+ Log.Info($"Flattened {airport.Ident} ({airport.Name}), from {source.Source.Name}, in {FlattenedAirports.PackageName}");
+ return airport with { State = FlattenState.Flattened, InEffect = _package.IsAbove(source.Source.EntryPath) };
+ }
+
+ /// Takes 's flattened copy out: X-Plane uses its own scenery's again.
+ public FlattenableAirport Undo(FlattenableAirport airport)
+ {
+ _package.Remove(airport.Ident);
+ Log.Info($"Undid the flattening of {airport.Ident} ({airport.Name})");
+ bool byScenery = airport.Source?.Record.Flattened == true;
+ return airport with { State = byScenery ? FlattenState.FlattenedByScenery : FlattenState.NotFlattened, InEffect = true };
+ }
+
+ private FlattenableAirport Describe(SourcedAirport airport, AirportBlock? copy)
+ {
+ AirportRecord record = airport.Record;
+ if (copy is null)
+ return new(record.Ident, record.Name, record.Place, airport, record.Flattened ? FlattenState.FlattenedByScenery : FlattenState.NotFlattened, true);
+ FlattenState state;
+ try
+ {
+ state = AptDatReader.ReadBlock(airport.Source.AptDat, record).Flattened().SameAs(copy) ? FlattenState.Flattened : FlattenState.Outdated;
+ }
+ catch (Exception ex) when (ex is IOException or UnauthorizedAccessException or FormatException)
+ {
+ Log.Warning($"Could not compare the flattened {record.Ident} with {airport.Source.AptDat}: {ex.Message}");
+ state = FlattenState.Flattened;
+ }
+ return new(record.Ident, record.Name, record.Place, airport, state, _package.IsAbove(airport.Source.EntryPath));
+ }
+}
diff --git a/src/OrthoStreamXP/Setup/Airports/AirportRecord.cs b/src/OrthoStreamXP/Setup/Airports/AirportRecord.cs
new file mode 100644
index 0000000..1f6d18a
--- /dev/null
+++ b/src/OrthoStreamXP/Setup/Airports/AirportRecord.cs
@@ -0,0 +1,17 @@
+namespace OrthoStreamXP.Setup;
+
+///
+/// An airport as an apt.dat lists it: its identifier, name and place, whether its own definition already asks X-Plane to flatten
+/// it, and where its lines are in the file (from its header line to the next airport's).
+///
+internal sealed record AirportRecord(string Ident, string Name, string? City, string? Country, bool Flattened, long Offset, int Length)
+{
+ /// "Brussels, BEL"; null when the file names neither.
+ public string? Place => (City, Country) switch
+ {
+ (null, null) => null,
+ ({ } city, null) => city,
+ (null, { } country) => country,
+ var (city, country) => $"{city}, {country}",
+ };
+}
diff --git a/src/OrthoStreamXP/Setup/Airports/AirportSources.cs b/src/OrthoStreamXP/Setup/Airports/AirportSources.cs
new file mode 100644
index 0000000..18a1c51
--- /dev/null
+++ b/src/OrthoStreamXP/Setup/Airports/AirportSources.cs
@@ -0,0 +1,41 @@
+using OrthoStreamXP.Scenery;
+
+namespace OrthoStreamXP.Setup;
+
+/// A scenery package with airports: its scenery_packs.ini entry (as written there) and its apt.dat.
+internal sealed record AirportSource(string Name, string EntryPath, string AptDat);
+
+///
+/// The apt.dat files X-Plane takes its airports from, highest priority first: the enabled entries of Custom Scenery\scenery_packs.ini
+/// that have one, with *GLOBAL_AIRPORTS* standing for Global Scenery\Global Airports. X-Plane uses an airport's definition from the
+/// first of them that lists it. The package of the flattened airports is left out: it is what this is compared with.
+///
+internal sealed class AirportSources(string xplane)
+{
+ public const string GlobalAirportsEntry = "*GLOBAL_AIRPORTS*";
+
+ public IReadOnlyList Find()
+ {
+ var sources = new List();
+ bool globalListed = false;
+ foreach (SceneryPackEntry entry in new SceneryPackList(Path.Join(xplane, "Custom Scenery")).Read())
+ {
+ bool global = entry.IsAt(GlobalAirportsEntry);
+ globalListed |= global;
+ if (!entry.Enabled || entry.IsAt(FlattenedAirports.EntryPath)) continue;
+ string folder = global ? GlobalAirportsFolder : Path.IsPathRooted(entry.Path) ? entry.Path : Path.Join(xplane, entry.Path);
+ Add(sources, global ? "Global Airports" : entry.Name, entry.Path, folder);
+ }
+ // X-Plane loads its own airports below the custom scenery when the list does not place them.
+ if (!globalListed) Add(sources, "Global Airports", GlobalAirportsEntry, GlobalAirportsFolder);
+ return sources;
+ }
+
+ private string GlobalAirportsFolder => Path.Join(xplane, "Global Scenery", "Global Airports");
+
+ private static void Add(List sources, string name, string entryPath, string folder)
+ {
+ string aptDat = Path.Join(folder, "Earth nav data", "apt.dat");
+ if (File.Exists(aptDat)) sources.Add(new AirportSource(name, entryPath, aptDat));
+ }
+}
diff --git a/src/OrthoStreamXP/Setup/Airports/AptDatReader.cs b/src/OrthoStreamXP/Setup/Airports/AptDatReader.cs
new file mode 100644
index 0000000..392661f
--- /dev/null
+++ b/src/OrthoStreamXP/Setup/Airports/AptDatReader.cs
@@ -0,0 +1,133 @@
+using System.Text;
+
+namespace OrthoStreamXP.Setup;
+
+///
+/// Lists the airports of an apt.dat (X-Plane's Global Airports one is close to 400 MB) and reads one airport's lines back. Only
+/// the header and 1302 metadata lines are decoded; the rest is passed over as bytes.
+///
+internal static class AptDatReader
+{
+ private const int BufferSize = 1 << 20;
+
+ /// The airports in the file's order. A file that lists one airport twice lists both.
+ public static IReadOnlyList Read(string file, CancellationToken cancel)
+ {
+ var airports = new List();
+ using var stream = new FileStream(file, FileMode.Open, FileAccess.Read, FileShare.ReadWrite, 1, FileOptions.SequentialScan);
+ var current = new PendingAirport();
+ byte[] buffer = new byte[BufferSize];
+ int filled = 0;
+ long bufferOffset = 0; // the file offset of buffer[0]
+ while (true)
+ {
+ cancel.ThrowIfCancellationRequested();
+ int read = stream.Read(buffer, filled, buffer.Length - filled);
+ filled += read;
+ int start = 0;
+ while (start < filled)
+ {
+ int newline = Array.IndexOf(buffer, (byte)'\n', start, filled - start);
+ if (newline < 0 && read > 0) break; // the rest of this line is still to be read
+ int end = newline < 0 ? filled : newline;
+ OnLine(buffer.AsSpan(start, end - start), bufferOffset + start, current, airports);
+ start = end + 1;
+ }
+ if (read == 0) break;
+ Buffer.BlockCopy(buffer, start, buffer, 0, filled - start);
+ bufferOffset += start;
+ filled -= start;
+ if (filled == buffer.Length) Array.Resize(ref buffer, buffer.Length * 2); // one line longer than the buffer
+ }
+ current.Finish(bufferOffset + filled, airports);
+ return airports;
+ }
+
+ ///
+ /// The lines of , read from where found them. Throws an
+ /// when another airport is there now: the file changed since.
+ ///
+ public static AirportBlock ReadBlock(string file, AirportRecord airport)
+ {
+ byte[] bytes = new byte[airport.Length];
+ using (var stream = new FileStream(file, FileMode.Open, FileAccess.Read, FileShare.ReadWrite))
+ {
+ stream.Position = airport.Offset;
+ stream.ReadExactly(bytes);
+ }
+ var block = new AirportBlock(Encoding.UTF8.GetString(bytes));
+ if (!block.Ident.Equals(airport.Ident, StringComparison.OrdinalIgnoreCase))
+ throw new IOException($"{file} changed since it was read: press Refresh and try again.");
+ return block;
+ }
+
+ private static void OnLine(ReadOnlySpan line, long offset, PendingAirport current, List airports)
+ {
+ if (line.EndsWith("\r"u8)) line = line[..^1];
+ int code = RowCode(line);
+ switch (code)
+ {
+ case AirportBlock.LandAirport or AirportBlock.SeaplaneBase or AirportBlock.Heliport:
+ current.Finish(offset, airports);
+ current.Start(Encoding.UTF8.GetString(line), offset);
+ break;
+ case AirportBlock.EndOfFile:
+ current.Finish(offset, airports);
+ break;
+ case AirportBlock.Metadata1302 when current.IsOpen:
+ current.Add(AirportBlock.Metadata(Encoding.UTF8.GetString(line)));
+ break;
+ }
+ }
+
+ /// The row code a line starts with (the number before the first blank), or -1.
+ private static int RowCode(ReadOnlySpan line)
+ {
+ int code = 0, i = 0;
+ for (; i < line.Length && line[i] is >= (byte)'0' and <= (byte)'9'; i++)
+ {
+ code = code * 10 + (line[i] - '0');
+ if (code > 99_999) return -1;
+ }
+ return i > 0 && (i == line.Length || line[i] is (byte)' ' or (byte)'\t') ? code : -1;
+ }
+
+ /// The airport whose lines are being read: started at its header, written out at the next one.
+ private sealed class PendingAirport
+ {
+ private string? _ident, _name, _city, _country;
+ private bool _flattened;
+ private long _offset;
+
+ public bool IsOpen => _ident is not null;
+
+ public void Start(string header, long offset)
+ {
+ (_ident, _name, _city, _country, _flattened, _offset) = (null, null, null, null, false, offset);
+ if (AirportBlock.Header(header) is var (ident, name)) (_ident, _name) = (ident, name); // a header without an ident is skipped
+ }
+
+ public void Add((string Key, string Value)? metadata)
+ {
+ switch (metadata)
+ {
+ case ("city", var city):
+ _city = city;
+ break;
+ case ("country", var country):
+ _country = country;
+ break;
+ case ("flatten", var flatten):
+ _flattened = flatten == "1";
+ break;
+ }
+ }
+
+ public void Finish(long end, List airports)
+ {
+ if (_ident is null) return;
+ airports.Add(new AirportRecord(_ident, _name ?? "", _city, _country, _flattened, _offset, checked((int)(end - _offset))));
+ _ident = null;
+ }
+ }
+}
diff --git a/src/OrthoStreamXP/Setup/Airports/FlattenedAirports.cs b/src/OrthoStreamXP/Setup/Airports/FlattenedAirports.cs
new file mode 100644
index 0000000..f7071eb
--- /dev/null
+++ b/src/OrthoStreamXP/Setup/Airports/FlattenedAirports.cs
@@ -0,0 +1,97 @@
+using System.Text;
+using OrthoStreamXP.Scenery;
+
+namespace OrthoStreamXP.Setup;
+
+///
+/// The scenery package OrthoStreamXP keeps its flattened airports in: Custom Scenery\OrthoStreamXP Flattened Airports, with an
+/// apt.dat holding a copy of each airport plus "1302 flatten 1". X-Plane uses an airport's definition from the highest package
+/// that lists it, so the package is kept above the airports' own ones in scenery_packs.ini (a new entry goes just above the first
+/// airport's package, not above unrelated ones); their files are never changed.
+/// Undoing takes the airport out again, and the package goes when its last airport does.
+///
+internal sealed class FlattenedAirports(string xplane)
+{
+ public const string PackageName = "OrthoStreamXP Flattened Airports";
+ public const string EntryPath = $"Custom Scenery/{PackageName}/";
+
+ private string CustomScenery => Path.Join(xplane, "Custom Scenery");
+ public string Folder => Path.Join(CustomScenery, PackageName);
+ private string NavData => Path.Join(Folder, "Earth nav data");
+ private string AptDat => Path.Join(NavData, "apt.dat");
+ private SceneryPackList List => new(CustomScenery);
+
+ /// The airports flattened so far.
+ public IReadOnlyList Read() => File.Exists(AptDat) ? AirportBlock.Split(File.ReadAllText(AptDat)) : [];
+
+ ///
+ /// Adds (or replaces) , and makes sure the package is listed, enabled, above
+ /// (the scenery_packs.ini entry of the package the airport comes from).
+ ///
+ public void Add(AirportBlock airport, string sourceEntry)
+ {
+ Write([.. Read().Where(b => !b.Ident.Equals(airport.Ident, StringComparison.OrdinalIgnoreCase)), airport]);
+ PlaceAbove(sourceEntry);
+ }
+
+ /// Takes the airport out; the last one takes the package and its scenery_packs.ini entry with it. False when it was not there.
+ public bool Remove(string ident)
+ {
+ IReadOnlyList airports = Read();
+ AirportBlock[] kept = [.. airports.Where(b => !b.Ident.Equals(ident, StringComparison.OrdinalIgnoreCase))];
+ if (kept.Length == airports.Count) return false;
+ if (kept.Length > 0) Write(kept);
+ else Delete();
+ return true;
+ }
+
+ ///
+ /// Whether X-Plane takes this package's airports over those of : it is enabled and listed above
+ /// it, or not listed yet (X-Plane lists a new package first).
+ ///
+ public bool IsAbove(string sourceEntry)
+ {
+ IReadOnlyList entries = List.Read();
+ int ours = IndexOf(entries, EntryPath);
+ if (ours < 0) return true;
+ if (!entries[ours].Enabled) return false;
+ int source = IndexOf(entries, sourceEntry);
+ return source < 0 || ours < source;
+ }
+
+ private void PlaceAbove(string sourceEntry)
+ {
+ SceneryPackList list = List;
+ if (list.AddAbove(EntryPath, sourceEntry)) return;
+ list.SetEnabled(EntryPath, enabled: true);
+ IReadOnlyList entries = list.Read();
+ int ours = IndexOf(entries, EntryPath), source = IndexOf(entries, sourceEntry);
+ if (ours >= 0 && source >= 0 && ours > source) list.MoveTo(EntryPath, source);
+ }
+
+ private void Write(IEnumerable airports)
+ {
+ var text = new StringBuilder("I\r\n1200 Version - airports flattened by OrthoStreamXP\r\n\r\n");
+ foreach (AirportBlock airport in airports.OrderBy(a => a.Ident, StringComparer.OrdinalIgnoreCase))
+ text.Append(airport.Text).Append("\r\n");
+ text.Append("99\r\n");
+ Directory.CreateDirectory(NavData);
+ AtomicFile.Write(AptDat, new UTF8Encoding(false).GetBytes(text.ToString()));
+ }
+
+ /// Removes the package's own file and folders (anything else put there is left, with its folder) and its list entry.
+ private void Delete()
+ {
+ File.Delete(AptDat);
+ foreach (string folder in new[] { NavData, Folder })
+ if (Directory.Exists(folder) && !Directory.EnumerateFileSystemEntries(folder).Any()) Directory.Delete(folder);
+ SceneryPacks.RemoveEntries(CustomScenery, [PackageName]);
+ }
+
+ private static int IndexOf(IReadOnlyList entries, string path)
+ {
+ for (int i = 0; i < entries.Count; i++)
+ if (entries[i].IsAt(path)) return i;
+ return -1;
+ }
+}
diff --git a/tests/OrthoStreamXP.Tests/AirportFlatteningTests.cs b/tests/OrthoStreamXP.Tests/AirportFlatteningTests.cs
new file mode 100644
index 0000000..860f728
--- /dev/null
+++ b/tests/OrthoStreamXP.Tests/AirportFlatteningTests.cs
@@ -0,0 +1,231 @@
+using OrthoStreamXP.Setup;
+
+namespace OrthoStreamXP.Tests;
+
+public sealed class AirportFlatteningTests : IDisposable
+{
+ private const string Ebbr = """
+ 1 145 0 0 EBBR Brussels National
+ 1302 city Brussels
+ 1302 country BEL
+ 100 45.00 35 727 0.00 1 3 0 07R 50.8890356 4.4803936 126 0 6 0 0 2 25L 50.8989489 4.5233233 0 0 6 2 1 2
+ """;
+
+ private const string Lfmn = """
+ 1 12 0 0 LFMN Nice Cote d Azur
+ 1302 flatten 0
+ 100 45.00 1 0 0.00 1 3 0 04L 43.6513 7.2012 0 0 3 0 0 0 22R 43.6667 7.2205 0 0 3 0 0 0
+ """;
+
+ private const string Lsez = """
+ 17 5269 0 0 LSEZ Zermatt Heliport
+ 1302 flatten 1
+ """;
+
+ private readonly TempTree _tree = new();
+
+ public void Dispose() => _tree.Dispose();
+
+ private string XPlane => _tree.PathOf("X-Plane 12");
+ private string ScenerypacksText => File.ReadAllText(_tree.PathOf("X-Plane 12/Custom Scenery/scenery_packs.ini"));
+ private string PackageAptDat => _tree.PathOf($"X-Plane 12/Custom Scenery/{FlattenedAirports.PackageName}/Earth nav data/apt.dat");
+
+ private static string AptDat(params string[] airports) =>
+ "I\n1200 Generated by WorldEditor\n\n" + string.Join("\n\n", airports) + "\n\n99\n";
+
+ private void WriteGlobalAirports(params string[] airports) =>
+ _tree.WriteText("X-Plane 12/Global Scenery/Global Airports/Earth nav data/apt.dat", AptDat(airports));
+
+ private void WriteSceneryPacks(params string[] entries) =>
+ _tree.WriteText("X-Plane 12/Custom Scenery/scenery_packs.ini", "I\r\n1000 Version\r\nSCENERY\r\n\r\n" + string.Concat(entries.Select(e => e + "\r\n")));
+
+ private AirportFlattening Flattening() => new(XPlane, new AirportCatalog());
+
+ private static FlattenableAirport Find(IReadOnlyList airports, string ident) => airports.Single(a => a.Ident == ident);
+
+ [Fact]
+ public void An_apt_dat_lists_its_airports_with_their_place_and_flatten_flag()
+ {
+ string file = _tree.WriteText("apt.dat", AptDat(Ebbr, Lfmn, Lsez).ReplaceLineEndings("\r\n"));
+
+ IReadOnlyList airports = AptDatReader.Read(file, CancellationToken.None);
+
+ Assert.Equal(["EBBR", "LFMN", "LSEZ"], airports.Select(a => a.Ident));
+ Assert.Equal("Brussels National", airports[0].Name);
+ Assert.Equal("Brussels, BEL", airports[0].Place);
+ Assert.Equal([false, false, true], airports.Select(a => a.Flattened));
+ Assert.Equal("Zermatt Heliport", airports[2].Name);
+ Assert.Null(airports[2].Place);
+ // Each airport's lines are read back from where they were found.
+ Assert.Equal("LFMN", AptDatReader.ReadBlock(file, airports[1]).Ident);
+ Assert.True(AptDatReader.ReadBlock(file, airports[2]).IsFlattened);
+ }
+
+ [Fact]
+ public void Lines_longer_than_the_read_buffer_and_a_file_without_an_end_line_are_read()
+ {
+ string longLine = "1302 gw_credits " + new string('x', 3 << 20);
+ string file = _tree.WriteText("apt.dat", "I\n1200 Version\n\n" + Ebbr.Replace("1302 city", longLine + "\n1302 city") + "\n\n" + Lsez);
+
+ IReadOnlyList airports = AptDatReader.Read(file, CancellationToken.None);
+
+ Assert.Equal(["EBBR", "LSEZ"], airports.Select(a => a.Ident));
+ Assert.Equal("Brussels", airports[0].City);
+ Assert.True(airports[1].Flattened);
+ }
+
+ [Fact]
+ public void Flattening_adds_the_flag_after_the_metadata_or_sets_the_one_there()
+ {
+ AirportBlock ebbr = new AirportBlock(Ebbr).Flattened();
+ Assert.Equal(
+ "1 145 0 0 EBBR Brussels National\r\n1302 city Brussels\r\n1302 country BEL\r\n1302 flatten 1\r\n100 45.00 35 727 0.00 1 3 0 07R 50.8890356 4.4803936 126 0 6 0 0 2 25L 50.8989489 4.5233233 0 0 6 2 1 2\r\n",
+ ebbr.Text);
+ Assert.True(ebbr.IsFlattened);
+
+ AirportBlock lfmn = new AirportBlock(Lfmn).Flattened();
+ Assert.Contains("1302 flatten 1", lfmn.Text, StringComparison.Ordinal);
+ Assert.DoesNotContain("1302 flatten 0", lfmn.Text, StringComparison.Ordinal);
+ }
+
+ [Fact]
+ public void The_highest_package_in_the_scenery_list_gives_an_airport_and_its_state()
+ {
+ WriteGlobalAirports(Ebbr, Lfmn, Lsez);
+ _tree.WriteText("X-Plane 12/Custom Scenery/Aerosoft LFMN/Earth nav data/apt.dat", AptDat(Lfmn.Replace("Nice Cote d Azur", "Nice Aerosoft", StringComparison.Ordinal)));
+ _tree.WriteText("X-Plane 12/Custom Scenery/Off EBBR/Earth nav data/apt.dat", AptDat(Ebbr.Replace("Brussels National", "Switched off", StringComparison.Ordinal)));
+ WriteSceneryPacks("SCENERY_PACK Custom Scenery/Aerosoft LFMN/", "SCENERY_PACK_DISABLED Custom Scenery/Off EBBR/", "SCENERY_PACK *GLOBAL_AIRPORTS*");
+
+ IReadOnlyList airports = Flattening().Load(CancellationToken.None);
+
+ Assert.Equal("Nice Aerosoft", Find(airports, "LFMN").Name);
+ Assert.Equal("Aerosoft LFMN", Find(airports, "LFMN").Source!.Source.Name);
+ Assert.Equal("Brussels National", Find(airports, "EBBR").Name);
+ Assert.Equal("Global Airports", Find(airports, "EBBR").Source!.Source.Name);
+ Assert.Equal(FlattenState.NotFlattened, Find(airports, "EBBR").State);
+ Assert.Equal(FlattenState.FlattenedByScenery, Find(airports, "LSEZ").State);
+ }
+
+ [Fact]
+ public void Flattening_puts_a_flagged_copy_in_its_own_package_above_the_airports_scenery_and_undo_takes_it_out()
+ {
+ WriteGlobalAirports(Ebbr, Lsez);
+ string sourceText = File.ReadAllText(_tree.PathOf("X-Plane 12/Global Scenery/Global Airports/Earth nav data/apt.dat"));
+ WriteSceneryPacks("SCENERY_PACK Custom Scenery/KSEA Demo/", "SCENERY_PACK *GLOBAL_AIRPORTS*", "SCENERY_PACK Custom Scenery/OrthoStream_Eur/");
+ AirportFlattening flattening = Flattening();
+
+ FlattenableAirport flattened = flattening.Flatten(Find(flattening.Load(CancellationToken.None), "EBBR"));
+
+ Assert.Equal(FlattenState.Flattened, flattened.State);
+ Assert.True(flattened.InEffect);
+ IReadOnlyList copies = AirportBlock.Split(File.ReadAllText(PackageAptDat));
+ Assert.True(Assert.Single(copies).IsFlattened);
+ Assert.StartsWith("I\r\n1200 Version", File.ReadAllText(PackageAptDat), StringComparison.Ordinal);
+ Assert.EndsWith("99\r\n", File.ReadAllText(PackageAptDat), StringComparison.Ordinal);
+ Assert.Equal(
+ $"I\r\n1000 Version\r\nSCENERY\r\n\r\nSCENERY_PACK Custom Scenery/KSEA Demo/\r\nSCENERY_PACK {FlattenedAirports.EntryPath}\r\nSCENERY_PACK *GLOBAL_AIRPORTS*\r\nSCENERY_PACK Custom Scenery/OrthoStream_Eur/\r\n",
+ ScenerypacksText);
+ Assert.Equal(sourceText, File.ReadAllText(_tree.PathOf("X-Plane 12/Global Scenery/Global Airports/Earth nav data/apt.dat")));
+ Assert.Equal(FlattenState.Flattened, Find(Flattening().Load(CancellationToken.None), "EBBR").State);
+
+ FlattenableAirport undone = flattening.Undo(flattened);
+
+ Assert.Equal(FlattenState.NotFlattened, undone.State);
+ Assert.False(Directory.Exists(_tree.PathOf($"X-Plane 12/Custom Scenery/{FlattenedAirports.PackageName}")));
+ Assert.DoesNotContain(FlattenedAirports.PackageName, ScenerypacksText, StringComparison.Ordinal);
+ Assert.Equal(FlattenState.NotFlattened, Find(Flattening().Load(CancellationToken.None), "EBBR").State);
+ }
+
+ [Fact]
+ public void Undoing_one_of_two_airports_keeps_the_other()
+ {
+ WriteGlobalAirports(Ebbr, Lfmn);
+ WriteSceneryPacks("SCENERY_PACK *GLOBAL_AIRPORTS*");
+ AirportFlattening flattening = Flattening();
+ IReadOnlyList airports = flattening.Load(CancellationToken.None);
+ flattening.Flatten(Find(airports, "LFMN"));
+ FlattenableAirport ebbr = flattening.Flatten(Find(airports, "EBBR"));
+
+ flattening.Undo(ebbr);
+
+ Assert.Equal("LFMN", Assert.Single(AirportBlock.Split(File.ReadAllText(PackageAptDat))).Ident);
+ Assert.Single(new OrthoStreamXP.Scenery.SceneryPackList(_tree.PathOf("X-Plane 12/Custom Scenery")).Read(), e => e.IsAt(FlattenedAirports.EntryPath));
+ }
+
+ [Fact]
+ public void A_package_moved_below_the_airports_scenery_is_not_in_effect_until_flattened_again()
+ {
+ _tree.WriteText("X-Plane 12/Custom Scenery/Brussels HD/Earth nav data/apt.dat", AptDat(Ebbr));
+ WriteSceneryPacks("SCENERY_PACK Custom Scenery/Brussels HD/", "SCENERY_PACK *GLOBAL_AIRPORTS*");
+ AirportFlattening flattening = Flattening();
+ flattening.Flatten(Find(flattening.Load(CancellationToken.None), "EBBR"));
+ WriteSceneryPacks("SCENERY_PACK Custom Scenery/Brussels HD/", $"SCENERY_PACK {FlattenedAirports.EntryPath}", "SCENERY_PACK *GLOBAL_AIRPORTS*");
+
+ FlattenableAirport below = Find(flattening.Load(CancellationToken.None), "EBBR");
+ Assert.False(below.InEffect);
+
+ Assert.True(flattening.Flatten(below).InEffect);
+ Assert.StartsWith($"I\r\n1000 Version\r\nSCENERY\r\n\r\nSCENERY_PACK {FlattenedAirports.EntryPath}\r\n", ScenerypacksText, StringComparison.Ordinal);
+ }
+
+ [Fact]
+ public void A_new_package_goes_first_when_the_airports_package_is_not_listed()
+ {
+ WriteGlobalAirports(Ebbr);
+ WriteSceneryPacks("SCENERY_PACK Custom Scenery/KSEA Demo/");
+ AirportFlattening flattening = Flattening();
+
+ FlattenableAirport flattened = flattening.Flatten(Find(flattening.Load(CancellationToken.None), "EBBR"));
+
+ Assert.True(flattened.InEffect);
+ Assert.StartsWith($"I\r\n1000 Version\r\nSCENERY\r\n\r\nSCENERY_PACK {FlattenedAirports.EntryPath}\r\n", ScenerypacksText, StringComparison.Ordinal);
+ }
+
+ [Fact]
+ public void A_copy_whose_scenery_changed_since_is_outdated()
+ {
+ WriteGlobalAirports(Ebbr);
+ WriteSceneryPacks("SCENERY_PACK *GLOBAL_AIRPORTS*");
+ AirportFlattening flattening = Flattening();
+ flattening.Flatten(Find(flattening.Load(CancellationToken.None), "EBBR"));
+
+ WriteGlobalAirports(Ebbr.Replace("1302 city Brussels", "1302 city Bruxelles", StringComparison.Ordinal));
+ FlattenableAirport outdated = Find(flattening.Load(CancellationToken.None), "EBBR");
+
+ Assert.Equal(FlattenState.Outdated, outdated.State);
+ flattening.Flatten(outdated);
+ Assert.Equal(FlattenState.Flattened, Find(flattening.Load(CancellationToken.None), "EBBR").State);
+ Assert.Contains("Bruxelles", File.ReadAllText(PackageAptDat), StringComparison.Ordinal);
+ }
+
+ [Fact]
+ public void Without_a_scenery_list_the_package_is_written_and_X_Plane_lists_it_itself()
+ {
+ WriteGlobalAirports(Ebbr);
+ AirportFlattening flattening = Flattening();
+
+ FlattenableAirport flattened = flattening.Flatten(Find(flattening.Load(CancellationToken.None), "EBBR"));
+
+ Assert.True(flattened.InEffect);
+ Assert.True(File.Exists(PackageAptDat));
+ Assert.False(File.Exists(_tree.PathOf("X-Plane 12/Custom Scenery/scenery_packs.ini")));
+ }
+
+ [Fact]
+ public void A_flattened_airport_whose_scenery_is_gone_can_still_be_undone()
+ {
+ _tree.WriteText("X-Plane 12/Custom Scenery/Demo/Earth nav data/apt.dat", AptDat(Lsez.Replace("1302 flatten 1", "1302 city Zermatt", StringComparison.Ordinal)));
+ WriteSceneryPacks("SCENERY_PACK Custom Scenery/Demo/");
+ AirportFlattening flattening = Flattening();
+ flattening.Flatten(Find(flattening.Load(CancellationToken.None), "LSEZ"));
+ WriteSceneryPacks($"SCENERY_PACK {FlattenedAirports.EntryPath}");
+
+ FlattenableAirport orphan = Find(flattening.Load(CancellationToken.None), "LSEZ");
+
+ Assert.Null(orphan.Source);
+ Assert.Equal(FlattenState.Flattened, orphan.State);
+ Assert.Throws(() => flattening.Flatten(orphan));
+ flattening.Undo(orphan);
+ Assert.Empty(flattening.Load(CancellationToken.None));
+ }
+}
diff --git a/tests/OrthoStreamXP.Tests/ViewsTests.cs b/tests/OrthoStreamXP.Tests/ViewsTests.cs
index b4cbacd..9fdc888 100644
--- a/tests/OrthoStreamXP.Tests/ViewsTests.cs
+++ b/tests/OrthoStreamXP.Tests/ViewsTests.cs
@@ -18,7 +18,7 @@ public void Every_page_loads_with_the_theme()
app.ThemeMode = ThemeMode.Light;
#pragma warning restore WPF0001
app.Resources.MergedDictionaries.Add(new ResourceDictionary { Source = new Uri("pack://application:,,,/orthostreamxp;component/Gui/Theme.xaml") });
- foreach (Type view in new[] { typeof(OrthoStreamXP.Gui.HomeView), typeof(OrthoStreamXP.Gui.SettingsView), typeof(OrthoStreamXP.Gui.CacheView), typeof(OrthoStreamXP.Gui.PackagesView), typeof(OrthoStreamXP.Gui.LogView) })
+ foreach (Type view in new[] { typeof(OrthoStreamXP.Gui.HomeView), typeof(OrthoStreamXP.Gui.SettingsView), typeof(OrthoStreamXP.Gui.CacheView), typeof(OrthoStreamXP.Gui.PackagesView), typeof(OrthoStreamXP.Gui.AirportsView), typeof(OrthoStreamXP.Gui.LogView) })
{
var page = (FrameworkElement)Activator.CreateInstance(view, nonPublic: true)!;
page.Measure(new Size(1200, 900));