Compare commits

..

2 Commits

Author SHA1 Message Date
maj00r ac8ed6d5fe test: the choice between window surfaces and the processor is covered
The choice moves out of Program, which no test runs, into
WindowSurfaces, where both branches are tested. Sonar's quality gate
failed on the coverage of the new code.
2026-11-25 18:10:22 +01:00
maj00r f9939fd566 fix: windows of the starter no longer come up black on Windows 11 25H2
Avalonia composes each window through a WinUI composition visual by
default, and on 25H2 that visual was often left empty: the main window
or a dialog opened later stayed black while the others drew. The
starter has no see-through windows or backdrops, so every window now
draws into its own redirection surface, still on the graphics card.
--software-render comes after and keeps its own options.
2026-11-25 17:56:28 +01:00
28 changed files with 136 additions and 2459 deletions
+2 -2
View File
@@ -52,7 +52,7 @@ jobs:
persist-credentials: false
- name: Setup .NET 10
uses: actions/setup-dotnet@0f4a354dd5547a28c70b7853dbd95d5b67886e73 # v6.1.0
uses: actions/setup-dotnet@a98b56852c35b8e3190ac28c8c2271da59106c68 # v6.0.0
with:
dotnet-version: 10.0.x
@@ -142,7 +142,7 @@ jobs:
persist-credentials: false
- name: Setup .NET 10
uses: actions/setup-dotnet@0f4a354dd5547a28c70b7853dbd95d5b67886e73 # v6.1.0
uses: actions/setup-dotnet@a98b56852c35b8e3190ac28c8c2271da59106c68 # v6.0.0
with:
dotnet-version: 10.0.x
+1 -4
View File
@@ -62,7 +62,7 @@ jobs:
persist-credentials: false
- name: Setup .NET 10
uses: actions/setup-dotnet@0f4a354dd5547a28c70b7853dbd95d5b67886e73 # v6.1.0
uses: actions/setup-dotnet@a98b56852c35b8e3190ac28c8c2271da59106c68 # v6.0.0
with:
dotnet-version: 10.0.x
@@ -71,8 +71,6 @@ jobs:
# sonar.qualitygate.wait=true blocks the end step until the server has
# processed the report, so the job's result is the quality gate's.
# tools/ holds the developers' helper scripts, outside the app and its tests:
# analysed like the rest, but not counted for coverage.
- name: Begin analysis
env:
SONAR_TOKEN: ${{ secrets.SONAR_TOKEN }}
@@ -86,7 +84,6 @@ jobs:
/d:sonar.scm.revision="${{ github.event.pull_request.head.sha || github.sha }}"
/d:sonar.cs.opencover.reportsPaths="TestResults/**/coverage.opencover.xml"
/d:sonar.cs.vstest.reportsPaths="TestResults/*.trx"
/d:sonar.coverage.exclusions="tools/**"
/d:sonar.qualitygate.wait=true
# A full, non-incremental build: the analyzers only see what is compiled.
-14
View File
@@ -46,17 +46,3 @@ the packaged artifacts — tagged `latest` for `main` and `staging` for `staging
```sh
dotnet build StarterNG/StarterNG.csproj
```
## Translations
The texts are in `StarterNG/startercfg/lang/<code>.xml`; `en.xml` is the reference.
The tests require every language to have every key of `en.xml` except the optional
ones (ending in `Desc`, starting with `Cmd.`), which fall back to English. After a
change to `en.xml`, or before merging a translation made from an older one:
```sh
python tools/sync_lang.py --check # lists what is missing or no longer used
python tools/sync_lang.py # adds missing keys in English, removes the unused ones
```
Added keys are marked `<!-- untranslated -->` for the translator.
-67
View File
@@ -68,71 +68,6 @@ public class ExternalIniTests
Assert.Contains("fieldofview 60", installation.Files.ReadAllText(UserIni));
}
[Fact]
public void A_renderer_written_in_by_hand_while_the_starter_runs_survives_its_save()
{
// Notepad: "gfxrenderer vulkan", a word the starter does not offer.
var installation = WithIni("gfxrenderer default\nfieldofview 45\n");
Edited(installation, "gfxrenderer vulkan\nfieldofview 45\n");
installation.SettingsStore.Settings.FieldOfView = 60;
installation.SettingsStore.Save();
string saved = installation.Files.ReadAllText(UserIni);
Assert.Contains("gfxrenderer vulkan", saved);
Assert.Contains("fieldofview 60", saved);
Assert.Equal("vulkan", installation.SettingsStore.Settings.RendererWord);
}
[Fact]
public void A_renderer_written_in_by_hand_and_read_again_survives_the_next_save()
{
var installation = WithIni("gfxrenderer default\n");
Edited(installation, "gfxrenderer vulkan\n");
// "Wczytać ponownie?" - yes.
installation.SettingsStore.Load();
installation.SettingsStore.Save();
Assert.Contains("gfxrenderer vulkan", installation.Files.ReadAllText(UserIni));
}
[Fact]
public void A_change_on_disk_not_read_again_is_not_lost_on_the_next_save()
{
var installation = WithIni("gfxrenderer default\nfieldofview 45\nvsync no\n");
var store = installation.SettingsStore;
Edited(installation, "gfxrenderer vulkan\nfieldofview 45\nvsync yes\n");
Assert.True(store.HasChangeOnDiskToAskAbout());
// "Wczytać ponownie?" - no: not asked again about the same change.
store.LeaveChangeOnDisk();
Assert.False(store.HasChangeOnDiskToAskAbout());
store.Settings.FieldOfView = 60;
store.Save();
string saved = installation.Files.ReadAllText(UserIni);
Assert.Contains("gfxrenderer vulkan", saved);
Assert.Contains("vsync yes", saved);
Assert.Contains("fieldofview 60", saved);
Assert.True(store.LastSaveMerged);
}
[Fact]
public void A_later_change_on_disk_is_asked_about_again()
{
var installation = WithIni("fieldofview 45\n");
var store = installation.SettingsStore;
Edited(installation, "fieldofview 50\n");
store.LeaveChangeOnDisk();
installation.Files.WithFile(UserIni, "fieldofview 55\n")
.WrittenAt(UserIni, installation.Files.GetLastWriteTimeUtc(UserIni).AddMinutes(1));
Assert.True(store.HasChangeOnDiskToAskAbout());
}
[Fact]
public void A_file_nobody_else_touched_saves_as_before()
{
@@ -162,8 +97,6 @@ public class ExternalIniTests
Assert.False(unreadable.ContainsKey("gfxrenderer"));
Assert.False(unreadable.ContainsKey("gfx.framebuffer.width"));
Assert.False(unreadable.ContainsKey("calibratein"));
// The default features in another order: the same line.
Assert.False(WithIni("uartfeature local|main|scnd|train\n").SettingsStore.UnreadableValues().ContainsKey("uartfeature"));
// The file keeps what it says until the setting is changed.
installation.SettingsStore.Save();
Assert.Contains("fieldofview abc", installation.Files.ReadAllText(UserIni));
-155
View File
@@ -1,155 +0,0 @@
using Avalonia.Controls;
using Avalonia.Input;
using Avalonia.Interactivity;
using Avalonia.VisualTree;
using StarterNG.Controls;
namespace StarterNG.Tests;
/// <summary>Windows under gamescope, which gives them no title bar, no close button and no maximizing.</summary>
[Collection(AvaloniaControls.Name)]
public class GamescopeWindowsTests
{
static GamescopeWindowsTests()
{
HeadlessDrawing.Ensure();
DialogKeyboard.Install();
GamescopeWindows.Install(false, () => "Zamknij");
}
[Theory]
[InlineData("gamescope", null, true)]
[InlineData("Gamescope", null, true)]
[InlineData("KDE", "gamescope-0", true)]
[InlineData(null, "gamescope-0", true)]
[InlineData("KDE", null, false)]
[InlineData("KDE", "", false)]
[InlineData(null, null, false)]
public void Gamescope_is_told_by_its_session_or_by_its_display(string? desktop, string? display, bool expected)
{
var variables = new Dictionary<string, string?>
{
["XDG_CURRENT_DESKTOP"] = desktop,
["GAMESCOPE_WAYLAND_DISPLAY"] = display,
// Big Picture on a desktop, whose window manager still draws the bars.
["SteamGamepadUI"] = "1"
};
Assert.Equal(expected, GamescopeWindows.IsGamescope(name => variables.GetValueOrDefault(name)));
}
private static (Window Owner, Window Window) Open(Control content, bool gamescope, bool escapeCloses = true)
{
GamescopeWindows.Active = gamescope;
var owner = new Window();
owner.Show();
var window = new Window { Title = "Taśmy", Width = 300, Height = 200, Content = content };
DialogKeyboard.SetEscapeCloses(window, escapeCloses);
window.Show(owner);
// Headless a window says it opened before it is given its owner; it says so again once it has one.
Assert.Same(owner, window.Owner);
window.RaiseEvent(new RoutedEventArgs(Window.WindowOpenedEvent));
Controls.Settle();
return (owner, window);
}
private static Button? CloseButton(Window window) =>
window.GetVisualDescendants().OfType<Button>().FirstOrDefault(b => Equals(b.Content, "Zamknij"));
[Fact]
public void Under_gamescope_a_window_over_another_gets_its_title_and_a_close_button()
{
var content = new TextBlock { Text = "zawartość" };
var (owner, window) = Open(content, gamescope: true);
try
{
bool closed = false;
window.Closed += (_, _) => closed = true;
Assert.Contains(window.GetVisualDescendants().OfType<TextBlock>(), t => t.Text == "Taśmy");
Assert.Same(content, window.GetVisualDescendants().OfType<TextBlock>().First(t => t.Text == "zawartość"));
var close = CloseButton(window);
Assert.NotNull(close);
close.RaiseEvent(Controls.Click());
Assert.True(closed);
}
finally
{
GamescopeWindows.Active = false;
owner.Close();
}
}
[Fact]
public void Under_gamescope_esc_closes_even_a_window_that_stays_open_beside_the_starter()
{
var (owner, window) = Open(new TextBox(), gamescope: true, escapeCloses: false);
try
{
bool closed = false;
window.Closed += (_, _) => closed = true;
Assert.True(Controls.Press(window, Key.Escape));
Assert.True(closed);
}
finally
{
GamescopeWindows.Active = false;
owner.Close();
}
}
[Fact]
public void The_window_shows_what_it_had_first_and_the_bar_after_it_in_tab_order()
{
var first = new Button { Content = "Pierwszy" };
var (owner, window) = Open(new StackPanel { Children = { first } }, gamescope: true);
try
{
var grid = Assert.IsType<Grid>(window.Content);
Assert.IsType<StackPanel>(grid.Children[0]);
Assert.True(first.IsFocused);
}
finally
{
GamescopeWindows.Active = false;
owner.Close();
}
}
[Fact]
public void A_window_that_says_twice_it_opened_gets_one_bar()
{
var (owner, window) = Open(new TextBlock { Text = "zawartość" }, gamescope: true);
try
{
window.RaiseEvent(new RoutedEventArgs(Window.WindowOpenedEvent));
Controls.Settle();
Assert.Single(window.GetVisualDescendants().OfType<Button>(), b => Equals(b.Content, "Zamknij"));
}
finally
{
GamescopeWindows.Active = false;
owner.Close();
}
}
[Fact]
public void Elsewhere_a_window_keeps_what_it_shows_and_esc_keeps_its_choice()
{
var content = new TextBox();
var (owner, window) = Open(content, gamescope: false, escapeCloses: false);
try
{
Assert.Same(content, window.Content);
Assert.Null(CloseButton(window));
Assert.False(Controls.Press(window, Key.Escape));
}
finally
{
owner.Close();
}
}
}
-77
View File
@@ -99,83 +99,6 @@ public class GraphicsCardsTests
Assert.Equal(new[] { "AMD Radeon RX 6700 XT", "AMD Radeon 780M" }, cards.Select(card => card.Name));
}
private static GraphicsCards WindowsReader(IReadOnlyList<DxgiAdapter>? dxgi, params GraphicsCard[] registry) =>
new(new InMemoryFileSystem(), new FakeEnvironment().AsWindows(), new LinuxGpus(new InMemoryFileSystem(), new FakeEnvironment()),
() => Array.Empty<string>(), () => dxgi, () => registry);
private static DxgiAdapter Adapter(string name, uint vendor, long memory, uint flags = 0) =>
new(name, vendor, (ulong)memory, flags);
[Fact]
public void Windows_takes_the_cards_dxgi_lists_and_the_discrete_one_first()
{
var reader = WindowsReader(
new[] { Adapter("AMD Radeon(TM) Graphics", 0x1002, GiB / 2), Adapter("NVIDIA GeForce RTX 3060", 0x10DE, 12 * GiB) },
new GraphicsCard("AMD Radeon(TM) Graphics", GiB / 2));
var cards = reader.List();
Assert.Equal(new[] { "NVIDIA GeForce RTX 3060", "AMD Radeon(TM) Graphics" }, cards.Select(card => card.Name));
Assert.Equal(12, cards[0].MemoryGb);
}
[Fact]
public void Software_adapters_are_no_cards()
{
var cards = DxgiAdapters.Cards(new[]
{
Adapter("Microsoft Basic Render Driver", 0x1414, 0, flags: 2),
Adapter("Microsoft Remote Display Adapter", 0x1414, 0),
Adapter("Some software rasterizer", 0x1234, 0, flags: 2),
Adapter("NVIDIA GeForce RTX 5060 Laptop GPU", 0x10DE, 8546942976)
});
Assert.Equal("NVIDIA GeForce RTX 5060 Laptop GPU", Assert.Single(cards).Name);
}
[Fact]
public void A_card_dxgi_lists_twice_is_shown_once()
{
var cards = DxgiAdapters.Cards(new[]
{
Adapter("AMD Radeon 780M Graphics", 0x1002, GiB / 2),
Adapter("AMD Radeon 780M Graphics ", 0x1002, GiB / 2)
});
Assert.Equal("AMD Radeon 780M Graphics", Assert.Single(cards).Name);
}
[Fact]
public void The_registry_answers_when_dxgi_cannot_be_asked()
{
var card = Assert.Single(WindowsReader(null, new GraphicsCard("NVIDIA GeForce RTX 3060", 12 * GiB)).List());
Assert.Equal("NVIDIA GeForce RTX 3060", card.Name);
}
[Fact]
public void The_registry_answers_when_dxgi_lists_only_software()
{
var reader = WindowsReader(new[] { Adapter("Microsoft Basic Render Driver", 0x1414, 0, flags: 2) },
new GraphicsCard("AMD Radeon(TM) Graphics", GiB / 2));
Assert.Equal("AMD Radeon(TM) Graphics", Assert.Single(reader.List()).Name);
}
[Fact]
public void Dxgi_answers_on_this_machine()
{
if (!OperatingSystem.IsWindows())
return;
// Every Windows lists at least the Basic Render Driver, so an answer means the calls work.
var adapters = DxgiAdapters.Read();
Assert.NotNull(adapters);
Assert.NotEmpty(adapters);
Assert.All(adapters, adapter => Assert.False(string.IsNullOrWhiteSpace(adapter.Description)));
}
[Fact]
public void There_are_no_cards_on_a_mac()
{
+8 -9
View File
@@ -37,18 +37,18 @@ public class GraphicsSettingsTests
private static string? Line(string text, string key) =>
Lines(text).FirstOrDefault(l => l == key || l.StartsWith(key + " ", StringComparison.Ordinal));
// As application.cpp on master has them; a word the starter does not know is the file's own, written back as it is.
// As application.cpp on master has them: a word it does not know gets the full renderer.
[Theory]
[InlineData("default", "default")]
[InlineData("full", "full")]
[InlineData("gl46", "gl46")]
[InlineData("vulkan", "vulkan")]
[InlineData("vulkan14", "vulkan14")]
[InlineData("full", "default")]
[InlineData("gl46", "default")]
[InlineData("vulkan", "default")]
[InlineData("vulkan14", "default")]
[InlineData("legacy", "legacy")]
[InlineData("simpleshader", "legacy")]
[InlineData("off", "legacy")]
[InlineData("simple", "simple")]
[InlineData("experimental", "experimental")]
[InlineData("experimental", "default")]
public void A_renderer_is_written_by_the_name_master_knows(string read, string written)
{
Assert.Equal($"gfxrenderer {written}", Line(Write(Read($"gfxrenderer {read}\n")), "gfxrenderer"));
@@ -93,7 +93,7 @@ public class GraphicsSettingsTests
}
[Fact]
public void Keys_of_the_vulkan_renderer_master_does_not_have_stay_on_a_save()
public void Keys_of_the_vulkan_renderer_master_does_not_have_go_on_a_save()
{
string[] vulkan =
{
@@ -107,8 +107,7 @@ public class GraphicsSettingsTests
string saved = installation.Files.ReadAllText(UserIni);
Assert.Contains("calibratein 0 0 0 0", saved);
// Written in by hand for a build that has that renderer: the starter does not know them, and leaves them.
Assert.All(vulkan, line => Assert.Equal(line, Line(saved, line.Split(' ')[0])));
Assert.All(vulkan, line => Assert.Null(Line(saved, line.Split(' ')[0])));
}
[Fact]
+6 -17
View File
@@ -961,34 +961,23 @@ public class SettingsStoreTests
Assert.Contains($"gfxrenderer {word}\n", SavedLines(installation));
}
// A word the starter does not know is written in by hand for a build that has it, such as one with Vulkan:
// shown, and left as it is until another renderer is chosen.
// Words master does not know start the full renderer with a line in its log, and the
// experimental renderer is not in a player's build: a save puts "default" in their place.
[Theory]
[InlineData("full")]
[InlineData("opengl")]
[InlineData("gl46")]
[InlineData("vulkan")]
[InlineData("vulkan14")]
[InlineData("experimental")]
[InlineData("null")]
public void A_renderer_word_the_starter_does_not_know_stays_until_another_is_chosen(string word)
public void A_renderer_word_master_does_not_run_is_saved_as_default(string word)
{
var installation = WithHome(new InMemoryFileSystem().WithFile(UserIni, $"gfxrenderer {word}\nfieldofview 45\n"));
var store = installation.SettingsStore;
store.Load();
var installation = WithHome(new InMemoryFileSystem().WithFile(UserIni, $"gfxrenderer {word}\n"));
installation.SettingsStore.Load();
Assert.Equal(word, store.Settings.RendererWord);
Assert.Equal(word, store.UnreadableValues()["gfxrenderer"]);
store.Settings.FieldOfView = 60;
store.Save();
Assert.Contains($"gfxrenderer {word}\n", SavedLines(installation));
installation.SettingsStore.Save();
// Picking one from the list, even the full renderer it runs as, is a choice.
store.Settings.RendererWord = null;
store.Settings.RenderEngine = 0;
store.Save();
Assert.Contains("gfxrenderer default\n", SavedLines(installation));
Assert.False(store.UnreadableValues().ContainsKey("gfxrenderer"));
}
[Theory]
@@ -1,182 +0,0 @@
using Avalonia.Controls;
using StarterNG.Application;
using StarterNG.Controls;
using StarterNG.Tests.Fakes;
namespace StarterNG.Tests;
/// <summary>
/// Values of eu07.ini the starter does not know, or a control cannot show, as the settings page
/// shows them: as the file writes them, with a note, until the player sets them by hand - or the
/// move to the standard mode puts them right.
/// </summary>
[Collection(AvaloniaControls.Name)]
public class SettingsUnknownValueTests
{
// The standard mode already, unless a test moves to it.
private const string Standard = "starter.settings.standard yes\n";
private static void WithPage(string ini, Action<StarterNG.Views.Settings, AppServices, Func<string>> act)
{
var installation = new TestInstallation(new InMemoryFileSystem());
installation.Environment.AsWindows();
var services = AppServices.Initialize(installation.Paths, installation.Files, installation.Clock,
installation.Environment);
string path = services.SettingsPaths.UserConfigPath();
installation.Files.WriteAllText(path, ini);
services.SettingsStore.Load();
HeadlessDrawing.Ensure();
var context = SynchronizationContext.Current;
SynchronizationContext.SetSynchronizationContext(new Avalonia.Threading.AvaloniaSynchronizationContext());
Window? window = null;
try
{
var page = new StarterNG.Views.Settings();
window = Controls.Show(page, 1600, 1000, themed: true);
act(page, services, () => installation.Files.ReadAllText(path).Replace("\r\n", "\n"));
}
finally
{
window?.Close();
SynchronizationContext.SetSynchronizationContext(context);
}
}
private static ComboBox List(StarterNG.Views.Settings page, string name) => page.FindControl<ComboBox>(name)!;
private static string? Shown(ComboBox list) => (list.SelectedItem as ComboBoxItem)?.Content as string;
private static string? Note(StarterNG.Views.Settings page, string key) =>
Avalonia.LogicalTree.LogicalExtensions.GetLogicalDescendants(page).OfType<SettingRow>()
.First(row => row.ConfigKey == key).UnknownValue;
[Fact]
public void A_renderer_word_is_on_the_list_chosen_and_saved_as_it_is()
{
WithPage(Standard + "gfxrenderer vulkan\nfieldofview 45\n", (page, _, saved) =>
{
Assert.Equal("vulkan", Shown(List(page, "RenderEngineCb")));
Assert.Contains("vulkan", Note(page, "gfxrenderer"));
Assert.False(page.HasUnsavedChanges);
page.Save();
Assert.Contains("gfxrenderer vulkan\n", saved());
});
}
[Fact]
public void Another_renderer_picked_from_the_list_replaces_it()
{
WithPage(Standard + "gfxrenderer vulkan\n", (page, services, saved) =>
{
List(page, "RenderEngineCb").SelectedIndex = 0;
page.Save();
Assert.Contains("gfxrenderer default\n", saved());
Assert.Null(services.Settings.RendererWord);
Assert.Null(Note(page, "gfxrenderer"));
});
}
[Fact]
public void A_value_a_list_does_not_offer_is_listed_as_written_and_kept()
{
WithPage(Standard + "starter.batterydefault 7\ngfx.shadow.rank.cutoff 9\n", (page, _, saved) =>
{
Assert.Equal("7", Shown(List(page, "ReadyOverrideCb")));
Assert.Equal("9", Shown(List(page, "ShadowDisplayCb")));
Assert.Contains("7", Note(page, "starter.batterydefault"));
Assert.Contains("9", Note(page, "gfx.shadow.rank.cutoff"));
Assert.False(page.HasUnsavedChanges);
page.Save();
Assert.Contains("starter.batterydefault 7\n", saved());
Assert.Contains("gfx.shadow.rank.cutoff 9\n", saved());
});
}
[Fact]
public void Picking_the_value_the_starter_shows_by_default_replaces_the_files_own()
{
// "7" is read as the scenery's choice, the first on the list: picked by hand, it is written.
WithPage(Standard + "starter.batterydefault 7\n", (page, _, saved) =>
{
List(page, "ReadyOverrideCb").SelectedIndex = 0;
Assert.Null(Note(page, "starter.batterydefault"));
page.Save();
Assert.Contains("starter.batterydefault 0\n", saved());
});
}
[Fact]
public void A_list_put_back_at_the_files_value_keeps_it()
{
WithPage(Standard + "starter.batterydefault 7\n", (page, _, saved) =>
{
var list = List(page, "ReadyOverrideCb");
var fileValue = list.SelectedItem;
list.SelectedIndex = 1;
list.SelectedItem = fileValue;
page.Save();
Assert.Contains("starter.batterydefault 7\n", saved());
});
}
[Fact]
public void A_control_set_by_hand_to_the_default_replaces_a_value_it_could_not_read()
{
WithPage(Standard + "vsync moze\n", (page, _, saved) =>
{
Assert.Contains("moze", Note(page, "vsync"));
var box = page.FindControl<CheckBox>("VSyncCb")!;
box.IsChecked = true;
box.IsChecked = false;
page.Save();
Assert.Contains("vsync no\n", saved());
});
}
[Fact]
public void A_level_for_other_settings_leaves_a_value_of_the_file_alone()
{
WithPage(Standard + "starter.batterydefault 7\ngfxrenderer vulkan\n", (page, _, saved) =>
{
page.FindControl<Panel>("PresetButtons")!.Children.OfType<Button>().First()
.RaiseEvent(new Avalonia.Interactivity.RoutedEventArgs(Button.ClickEvent));
Assert.Equal("7", Shown(List(page, "ReadyOverrideCb")));
page.Save();
Assert.Contains("starter.batterydefault 7\n", saved());
Assert.Contains("gfxrenderer vulkan\n", saved());
});
}
[Fact]
public void The_move_to_the_standard_mode_puts_values_of_the_file_right()
{
WithPage("gfxrenderer vulkan\nstarter.batterydefault 7\nvsync moze\ngfx.usegles yes\n", (page, _, saved) =>
{
page.MoveToStandardOnce();
string text = saved();
Assert.Contains("gfxrenderer default\n", text);
Assert.Contains("starter.batterydefault 0\n", text);
Assert.Contains("vsync no\n", text);
// What lets some machines run the simulator at all stays.
Assert.Contains("gfx.usegles yes\n", text);
Assert.Null(Note(page, "gfxrenderer"));
Assert.NotEqual("7", Shown(List(page, "ReadyOverrideCb")));
});
}
}
+5 -9
View File
@@ -14,7 +14,7 @@ public class SoftwareRenderTests
}
[Fact]
public void Without_the_switch_it_is_not_asked_for()
public void Without_the_switch_the_graphics_card_draws()
{
Assert.False(SoftwareRender.AskedIn(Array.Empty<string>()));
Assert.False(SoftwareRender.AskedIn(new[] { "--software" }));
@@ -25,25 +25,21 @@ public class SoftwareRenderTests
{
var options = SoftwareRender.Win32Options;
// No WinUI composition, DirectComposition or swap chain of the graphics card's.
Assert.Equal(new[] { Win32RenderingMode.Software }, options.RenderingMode);
Assert.Equal(new[] { Win32CompositionMode.RedirectionSurface }, options.CompositionMode);
}
[Fact]
public void X11_draws_on_the_processor_when_asked()
public void X11_draws_on_the_processor()
{
Assert.Equal(new[] { X11RenderingMode.Software }, SoftwareRender.X11Options.RenderingMode);
}
[Theory]
[InlineData(false)]
[InlineData(true)]
public void The_options_go_to_the_same_builder_with_or_without_the_switch(bool asked)
[Fact]
public void Both_platforms_options_go_to_the_same_builder()
{
var builder = AppBuilder.Configure<Avalonia.Application>();
string[] args = asked ? new[] { SoftwareRender.Switch } : Array.Empty<string>();
Assert.Same(builder, SoftwareRender.ApplyTo(builder, args));
Assert.Same(builder, SoftwareRender.ApplyTo(builder));
}
}
+33
View File
@@ -0,0 +1,33 @@
using Avalonia;
using StarterNG.Infrastructure;
namespace StarterNG.Tests;
public class WindowSurfacesTests
{
[Fact]
public void Windows_draws_into_the_window_surface_and_never_through_winui_composition()
{
var options = WindowSurfaces.Win32Options;
Assert.Equal(new[] { Win32CompositionMode.RedirectionSurface }, options.CompositionMode);
Assert.DoesNotContain(Win32CompositionMode.WinUIComposition, options.CompositionMode);
}
[Fact]
public void The_graphics_card_still_draws()
{
Assert.Equal(new Win32PlatformOptions().RenderingMode, WindowSurfaces.Win32Options.RenderingMode);
Assert.Contains(Win32RenderingMode.AngleEgl, WindowSurfaces.Win32Options.RenderingMode);
}
[Theory]
[InlineData(false)]
[InlineData(true)]
public void The_options_go_to_the_same_builder_with_or_without_the_processor(bool softwareRender)
{
var builder = AppBuilder.Configure<Avalonia.Application>();
Assert.Same(builder, WindowSurfaces.ApplyTo(builder, softwareRender));
}
}
-2
View File
@@ -28,8 +28,6 @@ public partial class App : Avalonia.Application
// Before any control exists: the names are given as controls are filled in.
ScreenReaderNames.Install();
DialogKeyboard.Install();
GamescopeWindows.Install(GamescopeWindows.IsGamescope(AppServices.Current.Environment.GetVariable),
() => Loc["Close"]);
AvaloniaXamlLoader.Load(this);
+3 -71
View File
@@ -49,41 +49,6 @@ public sealed class SettingsStore
// it has it: a value outside what the starter offers, its spacing, its comment.
private IReadOnlyDictionary<string, string> _synced = new Dictionary<string, string>();
// Keys set by the player's hand since the file was read: written as the screen has them,
// even where that is what the starter shows for a value of the file it does not know.
private readonly HashSet<string> _chosen = new(StringComparer.OrdinalIgnoreCase);
/// <summary>
/// <paramref name="keys"/> were set by hand - a control moved, a level or the defaults
/// put on them, the move to the standard mode: a save writes them, and a value of the
/// file the starter does not know goes. Until then it stays as it is.
/// </summary>
public void Choose(IEnumerable<string> keys) => _chosen.UnionWith(keys);
/// <summary>The value of the file is chosen again, as it is: it stays in the file.</summary>
public void Unchoose(IEnumerable<string> keys) => _chosen.ExceptWith(keys);
public bool IsChosen(string key) => _chosen.Contains(key);
/// <summary>
/// Whether the file's value of <paramref name="key"/> means what <paramref name="shown"/> does,
/// written its own way: yes and tak, 45 and 45.0, the UART features in another order.
/// </summary>
public bool FileMeans(string key, string? shown)
{
string? raw = FileValueOf(key);
return raw is null || shown is null ? raw == shown : Means(key, raw, shown);
}
private static bool Means(string key, string raw, string shown) =>
string.Equals(key, "uartfeature", StringComparison.OrdinalIgnoreCase)
? Uart.FeaturesStand(raw, shown)
: SameValue(raw, shown);
/// <summary>The key as the file writes it, where the simulator gets to it; null where it does not.</summary>
public string? FileValueOf(string key) =>
_config.IsPastEnd(key) || _config.GetRaw(key) is not { Length: > 0 } raw ? null : raw;
public SettingsStore(IFileSystem files, IClock clock, IDiagnosticsLog log, SettingsPaths paths,
SettingsSerializer serializer, ExecutableLocator executables)
{
@@ -173,7 +138,6 @@ public sealed class SettingsStore
_serializer.Read(Settings, _config);
_synced = Render(Settings);
_chosen.Clear();
// after the snapshot, so the next save writes it; a profile of before goes the same way as the ini would
if (!LoadFailed)
SettingsSerializer.MoveToTrainTapes(Settings);
@@ -403,7 +367,7 @@ public sealed class SettingsStore
continue;
if (_config.IsPastEnd(key) || _config.GetRaw(key) is not { Length: > 0 } raw)
continue;
if (read.TryGetValue(key, out string? shown) && shown == fallback && !Means(key, raw, shown))
if (read.TryGetValue(key, out string? shown) && shown == fallback && !SameValue(raw, shown))
unreadable[key] = raw;
}
@@ -421,10 +385,6 @@ public sealed class SettingsStore
if (!readable)
unreadable[key.Key] = raw;
}
// Kept as written, and offered on the list under its own word.
if (!_config.IsPastEnd("gfxrenderer") && WithFile(_config).RendererWord is { } renderer)
unreadable["gfxrenderer"] = renderer;
return unreadable;
}
@@ -513,7 +473,8 @@ public sealed class SettingsStore
return Uart.FeaturesStand(_config.GetRaw(key), value);
if (SettingsSerializer.FixedLengthKeys.Contains(key, StringComparer.OrdinalIgnoreCase))
return _config.GetRaw(key) == value;
if (_chosen.Contains(key))
if (string.Equals(key, "gfxrenderer", StringComparison.OrdinalIgnoreCase) &&
!SimulatorSettings.KeptRendererWord(_config.GetRaw(key)))
return false;
if (string.Equals(key, "mousescale", StringComparison.OrdinalIgnoreCase) &&
!SettingsSerializer.MouseScaleStands(_config.GetRaw(key)))
@@ -606,35 +567,6 @@ public sealed class SettingsStore
}
}
// When the file stood as it was last asked about; a save still goes onto what it holds.
private DateTime _askedAboutUtc = DateTime.MinValue;
/// <summary>
/// Whether the file changed elsewhere since it was read here, written here or last asked
/// about. Declined (<see cref="LeaveChangeOnDisk"/>), a change is not asked about again.
/// </summary>
public bool HasChangeOnDiskToAskAbout() =>
IsConfigNewerOnDisk() && DiskWriteTimeUtc() is { } written && written > _askedAboutUtc;
/// <summary>
/// The player chose not to read the file again. The screen stays as it is, but what was
/// written in elsewhere is no more lost for that: the next save goes onto it.
/// </summary>
public void LeaveChangeOnDisk() => _askedAboutUtc = DiskWriteTimeUtc() ?? _clock.UtcNow;
private DateTime? DiskWriteTimeUtc()
{
string path = string.IsNullOrEmpty(_savePath) ? _paths.UserConfigPath() : _savePath;
try
{
return _files.FileExists(path) ? _files.GetLastWriteTimeUtc(path) : null;
}
catch (Exception)
{
return null;
}
}
public bool IsConfigNewerOnDisk()
{
string path = string.IsNullOrEmpty(_savePath) ? _paths.UserConfigPath() : _savePath;
+1 -3
View File
@@ -41,9 +41,7 @@ public static class DialogKeyboard
// button or a window of its own that handles the key keep it.
private static void OnEscape(Window window, KeyEventArgs e)
{
// Under gamescope a window has no other way out than Esc and the bar it is given there.
if (e.Handled || e.Key != Key.Escape || e.KeyModifiers != KeyModifiers.None ||
!(GetEscapeCloses(window) || GamescopeWindows.Active))
if (e.Handled || e.Key != Key.Escape || e.KeyModifiers != KeyModifiers.None || !GetEscapeCloses(window))
return;
window.Close();
-140
View File
@@ -1,140 +0,0 @@
using System;
using Avalonia;
using Avalonia.Controls;
using Avalonia.Layout;
using Avalonia.Media;
namespace StarterNG.Controls;
/// <summary>
/// The starter's windows under gamescope, SteamOS's game mode (or gamescope started by
/// hand): it shows one window at a time over the whole screen and is no window manager.
/// No window gets a title bar or a close button from it, and a request to maximize is
/// not answered, so gamescope stretches a window of its first size over the screen.
/// Here each window over another gets a bar with its title and a close button, Esc closes
/// it whatever it says otherwise, and every window takes the size of the screen itself.
/// </summary>
public static class GamescopeWindows
{
private static readonly AttachedProperty<bool> FittedProperty =
AvaloniaProperty.RegisterAttached<Window, bool>("GamescopeFitted", typeof(GamescopeWindows));
private static readonly IBrush BarLine = new SolidColorBrush(Color.FromArgb(0x40, 0x80, 0x80, 0x80));
private static Func<string> _closeLabel = () => "Close";
private static bool _installed;
/// <summary>
/// XDG_CURRENT_DESKTOP is gamescope in SteamOS's game mode and in the sessions made
/// after it; GAMESCOPE_WAYLAND_DISPLAY is set by any gamescope for what it starts,
/// one started by hand on a desktop too. Steam's Big Picture on a desktop is neither:
/// its window manager still draws the bars.
/// </summary>
public static bool IsGamescope(Func<string, string?> variable) =>
string.Equals(variable("XDG_CURRENT_DESKTOP"), "gamescope", StringComparison.OrdinalIgnoreCase)
|| !string.IsNullOrEmpty(variable("GAMESCOPE_WAYLAND_DISPLAY"));
/// <summary>Whether the starter runs under gamescope; set once by <see cref="Install"/>.</summary>
public static bool Active { get; set; }
public static void Install(bool active, Func<string> closeLabel)
{
Active = active;
_closeLabel = closeLabel;
if (_installed)
return;
_installed = true;
Window.WindowOpenedEvent.AddClassHandler<Window>((window, _) => OnOpened(window));
}
private static void OnOpened(Window window)
{
// The main window has a bar of its own and fills the screen from its constructor;
// the splash goes by itself. A window may say twice that it opened.
if (!Active || window.Owner is null || window.GetValue(FittedProperty))
return;
window.SetValue(FittedProperty, true);
AddTitleBar(window);
FillScreen(window);
}
/// <summary>The window's title and a close button above what it shows, after it in Tab order.</summary>
public static void AddTitleBar(Window window)
{
if (window.Content is not Control content)
return;
// Over the whole screen a window sized to what it shows keeps it in the middle.
if (window.SizeToContent != SizeToContent.Manual)
{
content.HorizontalAlignment = HorizontalAlignment.Center;
content.VerticalAlignment = VerticalAlignment.Center;
}
var title = new TextBlock
{
VerticalAlignment = VerticalAlignment.Center,
Margin = new Thickness(12, 0),
FontWeight = FontWeight.SemiBold,
TextTrimming = TextTrimming.CharacterEllipsis
};
title[!TextBlock.TextProperty] = window[!Window.TitleProperty];
var close = new Button
{
Content = _closeLabel(),
VerticalAlignment = VerticalAlignment.Center,
Margin = new Thickness(8, 4)
};
close.Classes.Add("Flat");
close.Click += (_, _) => window.Close();
var bar = new DockPanel
{
Background = Brushes.Transparent,
Children = { close, title }
};
DockPanel.SetDock(close, Dock.Right);
var line = new Border
{
BorderBrush = BarLine,
BorderThickness = new Thickness(0, 0, 0, 1),
Child = bar
};
window.Content = null;
Grid.SetRow(content, 1);
Grid.SetRow(line, 0);
// What the window shows first, so Tab and the first focus reach it before the bar.
window.Content = new Grid
{
RowDefinitions = new RowDefinitions("Auto,*"),
Children = { content, line }
};
}
/// <summary>The size and place of the screen's working area, which gamescope then shows as it is.</summary>
public static void FillScreen(Window window)
{
var screen = window.Screens.ScreenFromWindow(window)
?? window.Screens.ScreenFromPoint(window.Position)
?? window.Screens.Primary;
if (screen is null)
return;
var area = screen.WorkingArea;
double width = area.Width / screen.Scaling;
double height = area.Height / screen.Scaling;
window.SizeToContent = SizeToContent.Manual;
window.MinWidth = Math.Min(window.MinWidth, width);
window.MinHeight = Math.Min(window.MinHeight, height);
window.MaxWidth = Math.Max(window.MaxWidth, width);
window.MaxHeight = Math.Max(window.MaxHeight, height);
window.Position = area.Position;
window.Width = width;
window.Height = height;
}
}
+4 -10
View File
@@ -53,13 +53,6 @@ public sealed class SimulatorSettings
public bool LogMissingVehicleFiles;
public int RenderEngine;
/// <summary>
/// The file's gfxrenderer word where it is none the starter knows - vulkan, written in by
/// hand for a build that has it: written back as it is until another renderer is chosen.
/// </summary>
public string? RendererWord;
public int Width = 1280;
public int Height = 720;
public int BufferScalePercent = 100;
@@ -204,10 +197,11 @@ public sealed class SimulatorSettings
public static readonly string[] RenderEngines = { "default", "legacy", "simple" };
/// <summary>
/// The words the starter places among <see cref="RenderEngines"/>: those application.cpp on
/// master knows, but "experimental". Any other word is kept as <see cref="RendererWord"/>.
/// The words of the file that stay as they are while the choice stands: those application.cpp
/// on master knows, but "experimental". Any other word starts the full renderer with a line in
/// the log, so a save puts "default" in its place.
/// </summary>
public static bool KnownRendererWord(string? word) =>
public static bool KeptRendererWord(string? word) =>
word?.Trim().ToLowerInvariant() is "default" or "legacy" or "simple" or "simpleshader" or "off";
/// <summary>Where <paramref name="word"/> stands among <see cref="RenderEngines"/>, as the simulator reads it.</summary>
-114
View File
@@ -1,114 +0,0 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Runtime.InteropServices;
using System.Runtime.Versioning;
using StarterNG.Domain.Settings;
namespace StarterNG.Infrastructure;
/// <summary>An adapter as DXGI describes it (DXGI_ADAPTER_DESC1).</summary>
/// <param name="DedicatedVideoMemory">The card's own memory; for a card in a processor, the share the firmware sets aside.</param>
public sealed record DxgiAdapter(string Description, uint VendorId, ulong DedicatedVideoMemory, uint Flags);
/// <summary>
/// The graphics cards of a Windows machine as DXGI lists them: the adapters Windows
/// draws with, whose drivers the simulator's OpenGL runs on too. The registry's list of
/// video devices is what each driver chose to write there, and some leave their card out of it.
/// </summary>
public static unsafe class DxgiAdapters
{
private const uint MicrosoftVendor = 0x1414;
private const uint SoftwareFlag = 2; // DXGI_ADAPTER_FLAG_SOFTWARE
private const int NotFound = unchecked((int)0x887A0002); // DXGI_ERROR_NOT_FOUND
private const int MostAdapters = 64;
private static readonly Guid FactoryInterface = new("770aae78-f26f-4dba-a829-253c83d1b387"); // IDXGIFactory1
/// <summary>The cards among the adapters: not the Microsoft Basic Render Driver or any other software one.</summary>
public static IReadOnlyList<GraphicsCard> Cards(IEnumerable<DxgiAdapter> adapters) =>
adapters
.Where(adapter => (adapter.Flags & SoftwareFlag) == 0 && adapter.VendorId != MicrosoftVendor)
.Select(adapter => new GraphicsCard(adapter.Description.Trim(), (long)adapter.DedicatedVideoMemory))
.Where(card => card.Name.Length > 0)
// Two of the same card tell no more than one, as in the registry's list.
.DistinctBy(card => card.Name)
.ToList();
/// <summary>Every adapter DXGI lists, software ones too; null when DXGI could not be asked.</summary>
[SupportedOSPlatform("windows")]
public static IReadOnlyList<DxgiAdapter>? Read()
{
IntPtr factory;
try
{
Guid iid = FactoryInterface;
if (CreateDXGIFactory1(&iid, &factory) < 0 || factory == IntPtr.Zero)
return null;
}
catch (Exception e) when (e is DllNotFoundException or EntryPointNotFoundException)
{
return null;
}
try
{
// IDXGIFactory1::EnumAdapters1, after IUnknown's 3, IDXGIObject's 4 and IDXGIFactory's 5.
var enumAdapters1 = (delegate* unmanaged[Stdcall]<IntPtr, uint, IntPtr*, int>)Method(factory, 12);
var adapters = new List<DxgiAdapter>();
for (uint i = 0; i < MostAdapters; i++)
{
IntPtr adapter;
int result = enumAdapters1(factory, i, &adapter);
if (result == NotFound)
break;
if (result < 0 || adapter == IntPtr.Zero)
return null;
try
{
// IDXGIAdapter1::GetDesc1, after IUnknown's 3, IDXGIObject's 4 and IDXGIAdapter's 3.
var getDesc1 = (delegate* unmanaged[Stdcall]<IntPtr, AdapterDesc1*, int>)Method(adapter, 10);
AdapterDesc1 desc;
if (getDesc1(adapter, &desc) >= 0)
adapters.Add(new DxgiAdapter(new string(desc.Description), desc.VendorId,
desc.DedicatedVideoMemory, desc.Flags));
}
finally
{
Release(adapter);
}
}
return adapters;
}
finally
{
Release(factory);
}
}
private static void* Method(IntPtr instance, int slot) => (*(void***)instance)[slot];
private static void Release(IntPtr instance) =>
((delegate* unmanaged[Stdcall]<IntPtr, uint>)Method(instance, 2))(instance);
[DllImport("dxgi.dll", ExactSpelling = true)]
private static extern int CreateDXGIFactory1(Guid* riid, IntPtr* factory);
[StructLayout(LayoutKind.Sequential, CharSet = CharSet.Unicode)]
private struct AdapterDesc1
{
public fixed char Description[128];
public uint VendorId;
public uint DeviceId;
public uint SubSysId;
public uint Revision;
public nuint DedicatedVideoMemory;
public nuint DedicatedSystemMemory;
public nuint SharedSystemMemory;
public uint AdapterLuidLow;
public int AdapterLuidHigh;
public uint Flags;
}
}
+4 -29
View File
@@ -30,20 +30,14 @@ public sealed class GraphicsCards
private readonly IEnvironment _environment;
private readonly LinuxGpus _gpus;
private readonly Func<IReadOnlyList<string>> _nvidiaSmi;
private readonly Func<IReadOnlyList<DxgiAdapter>?> _dxgi;
private readonly Func<IReadOnlyList<GraphicsCard>> _registry;
public GraphicsCards(IFileSystem files, IEnvironment environment, LinuxGpus gpus,
Func<IReadOnlyList<string>>? nvidiaSmi = null,
Func<IReadOnlyList<DxgiAdapter>?>? dxgi = null,
Func<IReadOnlyList<GraphicsCard>>? registry = null)
Func<IReadOnlyList<string>>? nvidiaSmi = null)
{
_files = files;
_environment = environment;
_gpus = gpus;
_nvidiaSmi = nvidiaSmi ?? AskNvidiaSmi;
_dxgi = dxgi ?? AskDxgi;
_registry = registry ?? ReadRegistry;
}
/// <summary>Takes a while on Linux, where the PCI list is read: not for the UI thread.</summary>
@@ -52,34 +46,15 @@ public sealed class GraphicsCards
IEnumerable<GraphicsCard> cards = Array.Empty<GraphicsCard>();
if (_environment.IsLinux)
cards = FromLinux();
else if (_environment.IsWindows)
cards = FromWindows();
else if (_environment.IsWindows && OperatingSystem.IsWindows())
cards = FromRegistry();
// A program goes to the discrete card, on Windows by its own request.
return cards.OrderBy(card => card.SharedMemory).ThenByDescending(card => card.MemoryBytes).ToList();
}
/// <summary>
/// DXGI's list, the adapters the simulator's OpenGL runs on. The registry's list of
/// video devices only when DXGI cannot be asked or lists no card: there each driver
/// writes what it chooses, and some leave their card out (an RTX 3060 beside a Ryzen's
/// Radeon was missing from it).
/// </summary>
private IReadOnlyList<GraphicsCard> FromWindows()
{
var adapters = _dxgi();
var cards = adapters is null ? Array.Empty<GraphicsCard>() : DxgiAdapters.Cards(adapters);
return cards.Count > 0 ? cards : _registry();
}
private static IReadOnlyList<DxgiAdapter>? AskDxgi() =>
OperatingSystem.IsWindows() ? DxgiAdapters.Read() : null;
private static IReadOnlyList<GraphicsCard> ReadRegistry() =>
OperatingSystem.IsWindows() ? FromRegistry() : Array.Empty<GraphicsCard>();
[SupportedOSPlatform("windows")]
private static IReadOnlyList<GraphicsCard> FromRegistry()
private static IEnumerable<GraphicsCard> FromRegistry()
{
try
{
@@ -91,9 +91,7 @@ public sealed class SettingsSerializer
s.VirtualShunting = c.GetBool("ai.trainman", true);
s.LogMissingVehicleFiles = c.GetBool("starter.logmissingvehicles", false);
string renderer = c.GetString("gfxrenderer", "default").Trim();
s.RenderEngine = SimulatorSettings.RenderEngineOf(renderer);
s.RendererWord = renderer.Length > 0 && !SimulatorSettings.KnownRendererWord(renderer) ? renderer : null;
s.RenderEngine = SimulatorSettings.RenderEngineOf(c.GetString("gfxrenderer", "default"));
s.Width = c.GetInt("width", 1280);
s.Height = c.GetInt("height", 720);
s.BufferScalePercent = ReadBufferScale(c);
@@ -228,8 +226,13 @@ public sealed class SettingsSerializer
{
"gfx.postfx.tonemapping",
"starter.developertools",
// The keys of the OpenGL 4.6 and Vulkan renderers (gfx.vulkan.device, gfx.raytracing...) are not here:
// written in by hand for a build that has them, they stay as the file has them.
// The OpenGL 4.6 and Vulkan renderers', which the simulator's master does not have.
"gfx.antialiasing", "gfx.buffer.percent", "gfx.vulkan.device", "gfx.dlss.preset", "gfx.framegeneration",
"gfx.reflex", "gfx.raytracing", "gfx.raytracing.range", "gfx.ssr", "gfx.lights.clustered", "gfx.lights.shadows",
"gfx.contactshadows", "gfx.shadow.sdsm", "gfx.postfx.ao", "gfx.postfx.ao.lighting", "gfx.postfx.ao.quality",
"gfx.cabprobe", "gfx.cabprobe.interval", "gfx.cabprobe.bounce", "gfx.cabprobe.reflections", "gfx.fog",
"gfx.fog.quality", "gfx.clouds", "gfx.clouds.shadows", "gfx.postfx.bloom", "gfx.postfx.autoexposure",
"gfx.grass", "gfx.grass.distance", "gfx.grass.fadedistance", "gfx.grass.density", "gfx.precipitation.particles",
};
/// <summary>
@@ -283,7 +286,7 @@ public sealed class SettingsSerializer
c.SetBool("ai.trainman", s.VirtualShunting);
c.SetBool("starter.logmissingvehicles", s.LogMissingVehicleFiles);
c.Set("gfxrenderer", s.RendererWord ?? SimulatorSettings.RenderEngines[Clamp(s.RenderEngine, 0, SimulatorSettings.RenderEngines.Length - 1)]);
c.Set("gfxrenderer", SimulatorSettings.RenderEngines[Clamp(s.RenderEngine, 0, SimulatorSettings.RenderEngines.Length - 1)]);
c.SetInt("width", s.Width);
c.SetInt("height", s.Height);
c.SetInt("starter.bufferscale", s.BufferScalePercent);
+4 -14
View File
@@ -6,15 +6,8 @@ using Avalonia;
namespace StarterNG.Infrastructure;
/// <summary>
/// On Windows the processor draws the starter's windows, and each frame is copied into its window
/// by GDI. Every way of the graphics card's failed on some machine: Avalonia's WinUI composition
/// visual left windows black on Windows 11 25H2, the Steam overlay drew its frame counter over a
/// window's own swap chain, and with DirectComposition the starter vanished a few seconds after its
/// window came up on a Windows 10 machine with a GTX 1650, without a word in its log. A frame copied
/// by GDI has no swap chain for an overlay to hook, and lists, text and pictures are no work for the
/// processor.
/// On X11 the graphics card draws, unless <see cref="Switch"/> asks the processor, for a machine on
/// which the window comes up empty. Each platform reads only its own options.
/// Drawn by the processor instead of the graphics card, for a machine on which the
/// window comes up empty. Each platform reads only its own options, so both are given.
/// </summary>
public static class SoftwareRender
{
@@ -34,9 +27,6 @@ public static class SoftwareRender
RenderingMode = new[] { X11RenderingMode.Software }
};
public static AppBuilder ApplyTo(AppBuilder builder, IEnumerable<string> args)
{
builder.With(Win32Options);
return AskedIn(args) ? builder.With(X11Options) : builder;
}
public static AppBuilder ApplyTo(AppBuilder builder) =>
builder.With(Win32Options).With(X11Options);
}
@@ -0,0 +1,25 @@
using Avalonia;
namespace StarterNG.Infrastructure;
/// <summary>
/// On Windows the graphics card draws each window of the starter into a surface of that
/// window, not into Avalonia's default WinUI composition visual. On Windows 11 25H2 that
/// visual was left empty on many starts: the main window, or a dialog opened later,
/// stayed black while the others drew, and came back only now and then. Composition is
/// there for see-through windows and backdrops, and the starter has none.
/// </summary>
public static class WindowSurfaces
{
public static Win32PlatformOptions Win32Options => new()
{
CompositionMode = new[] { Win32CompositionMode.RedirectionSurface }
};
/// <summary>
/// The options a platform reads are the last given, so the processor, when asked
/// for, draws with <see cref="SoftwareRender"/>'s own and these are left out.
/// </summary>
public static AppBuilder ApplyTo(AppBuilder builder, bool softwareRender) =>
softwareRender ? SoftwareRender.ApplyTo(builder) : builder.With(Win32Options);
}
+3 -6
View File
@@ -57,9 +57,6 @@ public partial class MainWindow : Window
ExtendClientAreaTitleBarHeightHint = TitleBarHeight;
FitToScreen();
// Gamescope does not maximize a window: it would stretch the first size over the screen.
if (GamescopeWindows.Active)
GamescopeWindows.FillScreen(this);
// Ahead of the layout a new size starts: changed during it, the bar keeps the old width.
Resized += (_, e) => FitTopBar(e.ClientSize.Width);
Opened += (_, _) => FitTopBar(ClientSize.Width);
@@ -435,7 +432,7 @@ public partial class MainWindow : Window
private bool wantsMaximized()
{
// make sure the window fills the whole screen on gamescope sessions
if (GamescopeWindows.Active)
if (Environment.GetEnvironmentVariable("XDG_CURRENT_DESKTOP") == "gamescope")
return true;
// catch being launched via Steam Big Picture mode as well
@@ -848,7 +845,7 @@ public partial class MainWindow : Window
{
if (_askingAboutSettings || (DateTime.UtcNow - _openedUtc).TotalSeconds < 3)
return;
if (!AppServices.Current.SettingsStore.HasChangeOnDiskToAskAbout())
if (!AppServices.Current.SettingsStore.IsConfigNewerOnDisk())
return;
_askingAboutSettings = true;
@@ -865,7 +862,7 @@ public partial class MainWindow : Window
SettingsView?.ReloadFromSettings();
}
else
AppServices.Current.SettingsStore.LeaveChangeOnDisk();
AppServices.Current.SettingsStore.TouchConfigAge();
}
finally
{
+6 -7
View File
@@ -10,8 +10,7 @@ namespace StarterNG;
static class Program
{
// What --software-render is looked for in; none for the designer, which calls BuildAvaloniaApp itself.
private static string[] _args = Array.Empty<string>();
private static bool _softwareRender;
[STAThread]
public static void Main(string[] args)
@@ -20,7 +19,7 @@ static class Program
var graphics = SystemGraphicsLibraries.TakeOnWindows();
graphics?.ServeTo(typeof(Win32PlatformOptions).Assembly);
_args = args;
_softwareRender = SoftwareRender.AskedIn(args);
// Composition root first: everything below, including the crash handlers,
// resolves its collaborators from this graph.
@@ -74,14 +73,14 @@ static class Program
};
}
// On Windows the processor draws; on X11 the graphics card, unless --software-render.
private static AppBuilder WithSoftwareRender(this AppBuilder builder) =>
SoftwareRender.ApplyTo(builder, _args);
// Without the switch the graphics card draws, into the window surfaces.
private static AppBuilder WithSoftwareRenderIfAsked(this AppBuilder builder) =>
WindowSurfaces.ApplyTo(builder, _softwareRender);
public static AppBuilder BuildAvaloniaApp()
=> AppBuilder.Configure<App>()
.UsePlatformDetect()
.WithSoftwareRender()
.WithSoftwareRenderIfAsked()
.WithInterFont()
.WithDiagnosticsLogging()
.AfterSetup(_ => LogUiExceptions());
-2
View File
@@ -7,8 +7,6 @@
<TargetFramework>net10.0</TargetFramework>
<Nullable>enable</Nullable>
<BuiltInComInteropSupport>true</BuiltInComInteropSupport>
<!-- DXGI is asked through function pointers, which NativeAOT compiles without reflection. -->
<AllowUnsafeBlocks>true</AllowUnsafeBlocks>
<ApplicationManifest>app.manifest</ApplicationManifest>
<ApplicationIcon>Assets\starter.ico</ApplicationIcon>
<AvaloniaUseCompiledBindingsByDefault>true</AvaloniaUseCompiledBindingsByDefault>
+3 -39
View File
@@ -25,7 +25,7 @@ public partial class Settings
private void ShowGraphics(SimulatorSettings s)
{
ShowRenderer(s);
RenderEngineCb.SelectedIndex = s.RenderEngine;
SelectTag(AntiAliasingCb, AntiAliasingTag(s.AntiAliasing));
_fullscreenAsRead = s.Fullscreen;
SelectTag(DisplayModeCb, DisplayModeOf(s.Fullscreen, s.FullscreenWindowed));
@@ -35,18 +35,8 @@ public partial class Settings
private void CaptureGraphics(SimulatorSettings s)
{
if (_fileRendererItem is not null && ReferenceEquals(RenderEngineCb.SelectedItem, _fileRendererItem))
{
s.RenderEngine = 0;
s.RendererWord = _fileRendererItem.Tag as string;
}
else
{
s.RenderEngine = Math.Max(0, RenderEngineCb.SelectedIndex);
s.RendererWord = null;
}
if (!ShowsFileValue(AntiAliasingCb))
s.AntiAliasing = AntiAliasingFromTag(SelectedTag(AntiAliasingCb));
s.RenderEngine = Math.Max(0, RenderEngineCb.SelectedIndex);
s.AntiAliasing = AntiAliasingFromTag(SelectedTag(AntiAliasingCb));
s.FullscreenMonitor = SelectedTag(MonitorCb) ?? string.Empty;
string mode = SelectedTag(DisplayModeCb) ?? FullscreenMode;
@@ -55,32 +45,6 @@ public partial class Settings
s.Fullscreen = mode == BorderlessMode ? _fullscreenAsRead : mode == FullscreenMode;
}
/// <summary>The renderer the file names in a word the list does not offer, listed under that word.</summary>
private ComboBoxItem? _fileRendererItem;
private void ShowRenderer(SimulatorSettings s)
{
if (_fileRendererItem is not null)
{
if (s.RendererWord is not null && Equals(_fileRendererItem.Tag, s.RendererWord))
{
RenderEngineCb.SelectedItem = _fileRendererItem;
return;
}
RenderEngineCb.Items.Remove(_fileRendererItem);
_fileRendererItem = null;
}
if (s.RendererWord is { } word)
{
_fileRendererItem = new ComboBoxItem { Tag = word, Content = word };
RenderEngineCb.Items.Add(_fileRendererItem);
RenderEngineCb.SelectedItem = _fileRendererItem;
}
else
RenderEngineCb.SelectedIndex = s.RenderEngine;
}
// ── How the simulator shows: full screen, borderless or in a window ──────
private const string FullscreenMode = "fullscreen";
+19 -126
View File
@@ -416,19 +416,9 @@ public partial class Settings : UserControl, ISettingsCapture
// A reloaded file may name another simulator, or start a server.
RefreshDerivedRows();
UpdateUnknownValues();
UpdateGpuNote();
NoteShownValues();
// The language is the starter's to keep (App.Initialize), and a value written another way is no unknown one.
var store = AppServices.Current.SettingsStore;
_unlikeOnScreen = new HashSet<string>(
_shownUnlikeSettings.Where(pair => !string.Equals(pair.Key, "lang", StringComparison.OrdinalIgnoreCase) &&
!store.FileMeans(pair.Key, pair.Value.Shown))
.Select(pair => pair.Key),
StringComparer.OrdinalIgnoreCase);
ShowFileValueItems(FileValues());
// A list at the file's value now hands over what the settings hold.
NoteShownValues();
UpdateUnknownValues();
UpdatePresetMarks();
}
@@ -543,24 +533,12 @@ public partial class Settings : UserControl, ISettingsCapture
/// Puts <paramref name="s"/> on the screen as edits waiting for Save: what it
/// changes marks the screen dirty, as a change by hand would.
/// </summary>
/// <param name="chosen">The keys these edits choose; a list at the file's value keeps it for any other.</param>
private void ShowAsEdits(SimulatorSettings s, IReadOnlyCollection<string> chosen)
private void ShowAsEdits(SimulatorSettings s)
{
var store = AppServices.Current.SettingsStore;
var held = store.Render(AppServices.Current.Settings);
var shown = store.Render(s);
var atFileValue = FileValueLists()
.Where(pair => ShowsFileValue(pair.List) && !chosen.Contains(pair.Key, StringComparer.OrdinalIgnoreCase) &&
held.GetValueOrDefault(pair.Key) == shown.GetValueOrDefault(pair.Key))
.Select(pair => (pair.List, Item: pair.List.SelectedItem))
.ToList();
_showingEdits = true;
try
{
ShowValues(s);
foreach (var (list, item) in atFileValue)
list.SelectedItem = item;
}
finally
{
@@ -650,7 +628,7 @@ public partial class Settings : UserControl, ISettingsCapture
{
var trial = Trial();
var applied = _presetMemory.Apply(preset, trial);
ShowAsEdits(trial, applied.ChosenKeys.ToList());
ShowAsEdits(trial);
// Chosen as a whole, its values are choices, not ones the screen could not show.
ForgetShown(applied.ChosenKeys);
@@ -662,7 +640,7 @@ public partial class Settings : UserControl, ISettingsCapture
private void ApplyGroupLevel(GraphicsGroup group, GraphicsPreset level)
{
var trial = Groups.Apply(group, level, Trial());
ShowAsEdits(trial, group.Keys.ToList());
ShowAsEdits(trial);
foreach (string key in group.Keys.Where(key => SimulatorKeys.All.Any(known => known.Key == key)))
_keyRows.Show(key, SimulatorKeys.Named(key).RawIn(trial));
@@ -847,11 +825,9 @@ public partial class Settings : UserControl, ISettingsCapture
private void NoteShownValues() =>
_shownUnlikeSettings = AppServices.Current.SettingsStore.ShownUnlike(Trial());
/// <summary><paramref name="keys"/> are the player's choice now: a value of the file the screen could not show goes on a save.</summary>
private void ForgetShown(IEnumerable<string> keys)
{
var forgotten = new HashSet<string>(keys, StringComparer.OrdinalIgnoreCase);
AppServices.Current.SettingsStore.Choose(forgotten);
_shownUnlikeSettings = _shownUnlikeSettings
.Where(pair => !forgotten.Contains(pair.Key))
.ToDictionary(pair => pair.Key, pair => pair.Value, StringComparer.OrdinalIgnoreCase);
@@ -879,7 +855,7 @@ public partial class Settings : UserControl, ISettingsCapture
}
private string SelectedRenderer() =>
SelectedTag(RenderEngineCb) ?? SimulatorSettings.RenderEngines.ElementAtOrDefault(RenderEngineCb.SelectedIndex) ?? "full";
SimulatorSettings.RenderEngines.ElementAtOrDefault(RenderEngineCb.SelectedIndex) ?? "full";
private RendererKind SelectedRendererKind() => Renderers.KindOf(SelectedRenderer());
@@ -906,8 +882,7 @@ public partial class Settings : UserControl, ISettingsCapture
s.InvertMouseVertical = IsChecked(MouseVertInvertCb);
s.IgnoreGamepad = IsChecked(GamepadIgnoreCb);
// A list at the file's own value leaves the setting as it was read.
if (!ShowsFileValue(FeedbackCb)) s.FeedbackMode = Math.Max(0, FeedbackCb.SelectedIndex);
s.FeedbackMode = Math.Max(0, FeedbackCb.SelectedIndex);
s.FeedbackPort = (int)(FeedbackPortNud.Value ?? 888);
CaptureUart(s);
@@ -919,7 +894,7 @@ public partial class Settings : UserControl, ISettingsCapture
s.LogMissingVehicleFiles = IsChecked(LogMissingVehicleFilesCb);
CaptureGraphics(s);
if (!ShowsFileValue(GpuCb)) s.Gpu = SelectedGpu();
s.Gpu = SelectedGpu();
ReadResolution(s);
s.BufferScalePercent = (int)bufferScale.Value;
s.MaxTextureSize = 1 << (int)textureResolutionSlider.Value;
@@ -940,8 +915,8 @@ public partial class Settings : UserControl, ISettingsCapture
s.ShadowMapResolution = 1 << (int)shaderResolutionSlider.Value;
s.ShadowProjectionRange = (int)shaderRange.Value;
s.CabShadowsRange = (int)_cabShadows.Value;
if (!ShowsFileValue(ShadowDisplayCb)) s.ShadowRankCutoff = Math.Max(0, ShadowDisplayCb.SelectedIndex) + 1;
if (!ShowsFileValue(ReflectionsDetailsCb)) s.ReflectionsFidelity = Math.Max(0, ReflectionsDetailsCb.SelectedIndex);
s.ShadowRankCutoff = Math.Max(0, ShadowDisplayCb.SelectedIndex) + 1;
s.ReflectionsFidelity = Math.Max(0, ReflectionsDetailsCb.SelectedIndex);
s.FieldOfView = Math.Clamp((int)fovSlider.Value, 10, 75);
s.PythonScreens = IsChecked(RenderScreensCb);
s.PythonThreadedUpload = IsChecked(RenderScreensThreadCb);
@@ -976,14 +951,12 @@ public partial class Settings : UserControl, ISettingsCapture
s.AmbientVolume = (int)AmbientVolumeSlider.Value;
s.SkipPipeline = IsChecked(SkipPipelineCb);
s.DebugLogVisible = IsChecked(DebugLogVisibleCb);
if (!ShowsFileValue(PyScreenPriorityCb))
s.PythonScreenUpdateRate = ParsePriorityTag((PyScreenPriorityCb.SelectedItem as ComboBoxItem)?.Tag);
s.PythonScreenUpdateRate = ParsePriorityTag((PyScreenPriorityCb.SelectedItem as ComboBoxItem)?.Tag);
s.AutoCloseStarter = IsChecked(AutoCloseStarterCb);
s.LargeThumbnails = IsChecked(LargeThumbnailsCb);
s.AutoExpandSceneryTree = IsChecked(AutoExpandTreeCb);
if (!ShowsFileValue(ReadyOverrideCb))
s.ReadyOverride = (ConsistReadyOverride)Math.Clamp(ReadyOverrideCb.SelectedIndex, 0, 2);
s.ReadyOverride = (ConsistReadyOverride)Math.Clamp(ReadyOverrideCb.SelectedIndex, 0, 2);
s.CompressTextures = IsChecked(CompressTexCb);
s.ScaleSpeculars = IsChecked(ScaleSpecularsCb);
@@ -1447,8 +1420,6 @@ public partial class Settings : UserControl, ISettingsCapture
store.KeepCopy(".before-standard");
var moved = AdvancedKeys();
// A value the starter does not know, or a control cannot show, is put right too.
moved.UnionWith(FileValues().Keys);
moved.ExceptWith(SettingsStore.KeptOnMoveToStandard);
_clamping = true;
try
@@ -1476,7 +1447,7 @@ public partial class Settings : UserControl, ISettingsCapture
/// <summary>Puts <paramref name="keys"/> at the simulator's own values, as edits waiting for Save.</summary>
private void ShowDefaults(IReadOnlyCollection<string> keys)
{
ShowAsEdits(AppServices.Current.SettingsStore.WithDefaults(Trial(), keys), keys);
ShowAsEdits(AppServices.Current.SettingsStore.WithDefaults(Trial(), keys));
foreach (string key in keys)
_keyRows.ShowDefault(key);
// Put back by hand, a value is a choice like any other.
@@ -1534,86 +1505,10 @@ public partial class Settings : UserControl, ISettingsCapture
private bool Advanced => AppServices.Current.Settings.AdvancedSettings;
/// <summary>A value of eu07.ini a list does not offer, listed under the file's own words.</summary>
private sealed record FileValue(string Raw);
/// <summary>The lists that take a value of the file they do not offer, with their keys.</summary>
private IEnumerable<(ComboBox List, string Key)> FileValueLists() => new[]
{
(FeedbackCb, "feedbackmode"), (GpuCb, "starter.gpu"), (ShadowDisplayCb, "gfx.shadow.rank.cutoff"),
(ReflectionsDetailsCb, "gfx.reflections.fidelity"), (PyScreenPriorityCb, "python.updatetime"),
(ReadyOverrideCb, "starter.batterydefault"), (AntiAliasingCb, "multisampling")
};
private static bool ShowsFileValue(ComboBox list) => list.SelectedItem is ComboBoxItem { Tag: FileValue };
// Keys the controls showed otherwise than the file has them when it was read.
private HashSet<string> _unlikeOnScreen = new(StringComparer.OrdinalIgnoreCase);
/// <summary>
/// The values of eu07.ini the starter does not know, or that a control cannot show, as the
/// file writes them, but for those the player has set since.
/// </summary>
private Dictionary<string, string> FileValues()
{
var store = AppServices.Current.SettingsStore;
var values = new Dictionary<string, string>(store.UnreadableValues(), StringComparer.OrdinalIgnoreCase);
foreach (string key in _unlikeOnScreen)
if (!values.ContainsKey(key) && store.FileValueOf(key) is { } raw)
values[key] = raw;
foreach (string key in values.Keys.Where(store.IsChosen).ToList())
values.Remove(key);
return values;
}
/// <summary>
/// The lists put at the file's value where they do not offer it, chosen as it is until the player picks another.
/// </summary>
private void ShowFileValueItems(IReadOnlyDictionary<string, string> values)
{
WhileLoading(() =>
{
foreach (var (list, key) in FileValueLists())
{
foreach (var item in list.Items.OfType<ComboBoxItem>().Where(item => item.Tag is FileValue).ToList())
list.Items.Remove(item);
if (!values.TryGetValue(key, out string? raw))
continue;
var shown = new ComboBoxItem { Tag = new FileValue(raw), Content = raw };
list.Items.Add(shown);
list.SelectedItem = shown;
}
});
}
/// <summary>The keys of the row <paramref name="control"/> sits in.</summary>
private static string[] RowKeys(Control control) =>
(control.FindLogicalAncestorOfType<SettingRow>()?.ConfigKey ?? string.Empty)
.Split(',', StringSplitOptions.RemoveEmptyEntries | StringSplitOptions.TrimEntries);
/// <summary>
/// A control moved: its keys are the player's choice now, written as the screen has them -
/// but for a list put back at the file's own value, which stays as the file has it.
/// </summary>
private void ChosenByHand(Control control)
{
if (_loading || _showingEdits)
return;
var keys = RowKeys(control);
if (keys.Length == 0)
return;
if (control is ComboBox list &&
(ShowsFileValue(list) || (_fileRendererItem is not null && ReferenceEquals(list.SelectedItem, _fileRendererItem))))
AppServices.Current.SettingsStore.Unchoose(keys);
else
ForgetShown(keys);
UpdateUnknownValues();
}
/// <summary>Under each setting, the value of eu07.ini for it the starter does not know or cannot show, as the file has it.</summary>
/// <summary>Under each setting, the value of eu07.ini for it the starter cannot read, as the file has it.</summary>
private void UpdateUnknownValues()
{
var unreadable = FileValues();
var unreadable = AppServices.Current.SettingsStore.UnreadableValues();
foreach (var row in SettingsStack.GetLogicalDescendants().OfType<SettingRow>())
{
var keys = (row.ConfigKey ?? string.Empty)
@@ -1803,16 +1698,16 @@ public partial class Settings : UserControl, ISettingsCapture
case { Tag: SimulatorKey }:
break;
case CheckBox cb:
cb.IsCheckedChanged += (_, _) => OnControlChanged(cb);
cb.IsCheckedChanged += (_, _) => OnControlChanged();
break;
case Slider slider:
slider.ValueChanged += (_, _) => OnControlChanged(slider);
slider.ValueChanged += (_, _) => OnControlChanged();
break;
case ComboBox combo:
combo.SelectionChanged += (_, _) => OnControlChanged(combo);
combo.SelectionChanged += (_, _) => OnControlChanged();
break;
case NumericUpDown nud:
nud.ValueChanged += (_, _) => OnControlChanged(nud);
nud.ValueChanged += (_, _) => OnControlChanged();
break;
}
}
@@ -1834,10 +1729,8 @@ public partial class Settings : UserControl, ISettingsCapture
edited();
};
private void OnControlChanged(Control? control = null)
private void OnControlChanged()
{
if (control is not null)
ChosenByHand(control);
MarkDirty();
QueuePresetMarks();
}
File diff suppressed because it is too large Load Diff
-173
View File
@@ -1,173 +0,0 @@
#!/usr/bin/env python3
"""Brings the language files of the starter in line with en.xml.
For every language file in StarterNG/startercfg/lang (or the codes given):
- a key en.xml has and the language lacks is added with the English text, right after the
key it follows in en.xml, and marked <!-- untranslated -->;
- a key en.xml no longer has is removed.
Keys the starter falls back to English for by itself (ending in "Desc", starting with "Cmd.")
are only added with --all. Everything else in the file - comments, order, line endings - stays
as it is.
python tools/sync_lang.py # every language
python tools/sync_lang.py zh cz # only these
python tools/sync_lang.py --check # only report; exit code 1 when a file is out of line
"""
import argparse
import re
import sys
from pathlib import Path
LANG_DIR = Path(__file__).resolve().parent.parent / "StarterNG" / "startercfg" / "lang"
STRING = re.compile(r'<String key="(?P<key>[^"]+)">.*?</String>', re.DOTALL)
LANGUAGE_TAG = re.compile(r"<Language\b[^>]*>")
UNTRANSLATED = "<!-- untranslated -->"
def is_optional(key):
return key.endswith("Desc") or key.startswith("Cmd.")
def read(path):
raw = path.read_bytes()
bom = raw.startswith(b"\xef\xbb\xbf")
text = raw[3 if bom else 0:].decode("utf-8")
newline = "\r\n" if "\r\n" in text else "\n"
return text, bom, newline
def write(path, text, bom):
path.write_bytes((b"\xef\xbb\xbf" if bom else b"") + text.encode("utf-8"))
def strings(text):
"""key -> match, in the order of the file; a key given twice keeps its first."""
found = {}
for match in STRING.finditer(text):
found.setdefault(match.group("key"), match)
return found
def line_start(text, pos):
return text.rfind("\n", 0, pos) + 1
def line_end(text, pos):
"""Just past the newline ending the line that pos is on."""
end = text.find("\n", pos)
return len(text) if end < 0 else end + 1
def removal_span(text, match):
"""The element with its whole lines when nothing but blanks and a comment share them."""
start, end = match.span()
first = line_start(text, start)
last = line_end(text, end)
before = text[first:start]
after = text[end:last].strip()
if before.strip() == "" and (after == "" or (after.startswith("<!--") and after.endswith("-->"))):
return first, last
return start, end
def english_line(en_text, match, newline):
indent = en_text[line_start(en_text, match.start()):match.start()]
if indent.strip():
indent = " "
element = match.group(0).replace("\r\n", "\n").replace("\n", newline)
return f"{indent}{element} {UNTRANSLATED}{newline}"
def insert_position(text, own, en_keys, key, after_tag):
"""Just after the nearest key before this one in en.xml that the file has and keeps."""
for previous in reversed(en_keys[:en_keys.index(key)]):
if previous in own:
return line_end(text, own[previous].end())
return after_tag
def apply_edits(text, edits):
"""edits: (start, end, replacement) on the original text.
Applied from the end so the offsets stay valid. Where a removal starts at the place of an
insert, the removal goes first, or it would take away the inserted line instead of its own.
Inserts at one place keep the order of en.xml.
"""
def order(edit):
index, (start, end, _) = edit
return start, 1 if end > start else 0, index
for _, (start, end, replacement) in sorted(enumerate(edits), key=order, reverse=True):
text = text[:start] + replacement + text[end:]
return text
def synced_text(path, text, newline, own, missing, obsolete, en_text, en_strings):
edits = [(*removal_span(text, own[key]), "") for key in obsolete]
tag = LANGUAGE_TAG.search(text)
if tag is None:
sys.exit(f"{path.name}: no <Language> element")
after_tag = line_end(text, tag.end())
en_keys = list(en_strings)
for key in missing:
anchor = insert_position(text, own, en_keys, key, after_tag)
edits.append((anchor, anchor, english_line(en_text, en_strings[key], newline)))
return apply_edits(text, edits)
def report(name, missing, obsolete, detailed):
print(f"{name}: {len(missing)} to add in English, {len(obsolete)} no longer in en.xml")
if detailed:
for key in missing:
print(f" missing {key}")
for key in obsolete:
print(f" obsolete {key}")
def sync(path, en_text, en_strings, add_optional, check):
"""True when the file was out of line with en.xml (and, without check, is now brought in line)."""
text, bom, newline = read(path)
own = strings(text)
obsolete = [key for key in own if key not in en_strings]
missing = [key for key in en_strings
if key not in own and (add_optional or not is_optional(key))]
if not obsolete and not missing:
print(f"{path.name}: in line with en.xml")
return False
report(path.name, missing, obsolete, check)
if not check:
write(path, synced_text(path, text, newline, own, missing, obsolete, en_text, en_strings), bom)
return True
def main():
parser = argparse.ArgumentParser(description=__doc__.splitlines()[0])
parser.add_argument("codes", nargs="*", help="language codes, e.g. zh cz; every language when none")
parser.add_argument("--all", action="store_true", help="add the optional keys (*Desc, Cmd.*) too")
parser.add_argument("--check", action="store_true", help="only report, change nothing")
args = parser.parse_args()
en_text, _, _ = read(LANG_DIR / "en.xml")
en_strings = strings(en_text)
if args.codes:
paths = [LANG_DIR / f"{code}.xml" for code in args.codes]
for path in paths:
if not path.is_file():
sys.exit(f"no language file {path}")
else:
paths = sorted(p for p in LANG_DIR.glob("*.xml") if p.name != "en.xml")
out_of_line = False
for path in paths:
out_of_line |= sync(path, en_text, en_strings, args.all, args.check)
return 1 if args.check and out_of_line else 0
if __name__ == "__main__":
sys.exit(main())