Compare commits

..

17 Commits

Author SHA1 Message Date
maj00r 9024e2a588 fix(settings): the graphics cards on Windows come from DXGI, as the drivers list them
The starter read the cards from the registry's list of video devices,
which each driver fills as it chooses: a player with an RTX 3060 beside
a Ryzen's Radeon saw only the Radeon. The cards now come from DXGI, the
adapters Windows draws with and whose drivers the simulator's OpenGL
runs on, without software adapters such as the Basic Render Driver.
The registry answers only when DXGI cannot be asked or lists no card.
DXGI is called through function pointers, which NativeAOT compiles
without reflection.
2026-11-30 01:56:38 +01:00
maj00r 5004a2889a Merge pull request #66 from MaSzyna-EU07/fix/zh-missing-keys
fix(lang): Chinese translation has every key of en.xml again, plus a script to keep languages in line
2026-11-29 23:18:30 +01:00
maj00r 4f57881902 ci(sonar): tools/ is left out of the coverage
The quality gate of #66 failed on coverage only: tools/sync_lang.py is new code
that the C# tests don't run. tools/ holds helper scripts outside the app and its
tests, so it isn't counted for coverage; Sonar still analyses it like the rest.
2026-11-29 23:16:57 +01:00
maj00r 7a03cc0c6a fix(lang): untranslated keys marked without TODO, and sync_lang.py split up
Sonar counted each "<!-- TODO: translate -->" as an open task (S1135, 73 of them):
the added keys are marked "<!-- untranslated -->" now. sync() is split into smaller
functions (S3776); what the script does is the same, zh.xml regenerated from main
comes out identical.
2026-11-29 23:14:35 +01:00
maj00r 9fe767cf9f fix(lang): the Chinese translation has every key of en.xml again, and a script keeps languages in line
zh.xml (#45) was translated from an older en.xml: 73 keys the tests require were
missing and 97 keys en.xml no longer has were still there. The localization test
failed on main, so no package and no release were made after the merge.

tools/sync_lang.py adds the missing keys with the English text, marked
<!-- TODO: translate -->, and removes the unused ones; the rest of the file stays
as it is. --check only lists the differences. The missing Chinese keys are filled
in with it, and the README says how to use it.
2026-11-29 22:23:07 +01:00
Hirek fdcf33069d Merge pull request #45 from NishizakiHayato/NishizakiHayato-patch-1
Add Chinese translation
2026-11-29 17:48:21 +00:00
maj00r ece440e566 Merge pull request #64 from MaSzyna-EU07/fix/steam-overlay
fix: the Steam overlay no longer draws its frame counter over the starter
2026-11-28 21:14:28 +01:00
maj00r 3dfcbca711 fix: the Steam overlay no longer draws its frame counter over the starter
Steam puts its overlay into the starter, the game it launches. In a
window's own redirection surface ANGLE draws through a swap chain of
that window, and the overlay hooks its Present and draws the frame
counter and notifications over the starter. Every window now draws
into a DirectComposition surface, which is drawn without a Present and
still keeps away from the WinUI composition visual that came up black
on 25H2. The redirection surface stays only as the fallback.
2026-11-28 19:38:44 +01:00
dependabot[bot] 9668b4d3b6 build(deps): bump actions/setup-dotnet from 6.0.0 to 6.1.0 (#39)
Bumps [actions/setup-dotnet](https://github.com/actions/setup-dotnet) from 6.0.0 to 6.1.0.
- [Release notes](https://github.com/actions/setup-dotnet/releases)
- [Commits](https://github.com/actions/setup-dotnet/compare/a98b56852c35b8e3190ac28c8c2271da59106c68...0f4a354dd5547a28c70b7853dbd95d5b67886e73)

---
updated-dependencies:
- dependency-name: actions/setup-dotnet
  dependency-version: 6.1.0
  dependency-type: direct:production
  update-type: version-update:semver-minor
...

Signed-off-by: dependabot[bot] <support@github.com>
Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com>
2026-11-27 18:06:07 +01:00
maj00r 42591bcddd Merge pull request #62 from MaSzyna-EU07/fix/ini-keeps-unknown-values
fix(settings): keep eu07.ini values the starter does not know until changed by hand
2026-11-27 04:06:04 +01:00
maj00r 50ca332438 fix: windows of the starter no longer come up black on Windows 11 25H2 (#63)
* 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.

* 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.

---------

Co-authored-by: maj00r <maj00r@host>
2026-11-27 04:00:39 +01:00
maj00r b778122fb5 fix(settings): a value of eu07.ini the starter does not know stays until changed by hand
A renderer written in by hand ("gfxrenderer vulkan") went back to "default"
on the next save, the Vulkan renderer's own keys were taken out, and saying
no to reading the file again lost every change made on disk meanwhile.

Such a value is now shown as the file writes it - on its list where the
control is one, with the note under the setting otherwise - and written back
as it is until the player sets that control, even to what the starter shows
by default. The move to the standard mode puts them right, as before for the
advanced settings. Declining to read the file again no longer forgets the
change on disk: the next save goes onto it.

The default UART features in another order are no longer named unknown.
2026-11-24 18:26:56 +01:00
NishizakiHayato a3fc1dd1ac Merge branch 'MaSzyna-EU07:main' into NishizakiHayato-patch-1 2026-11-24 20:32:14 +08:00
NishizakiHayato 2f0f7ebe43 Update zh.xml 2026-11-14 00:20:15 +08:00
NishizakiHayato b8c1560220 Update zh.xml 2026-11-13 13:25:00 +08:00
NishizakiHayato f2fbb6d0d6 Update zh.xml 2026-11-13 11:57:08 +08:00
NishizakiHayato ad58d0f838 Add Chinese 2026-11-13 11:04:31 +08:00
22 changed files with 2205 additions and 62 deletions
+2 -2
View File
@@ -52,7 +52,7 @@ jobs:
persist-credentials: false
- name: Setup .NET 10
uses: actions/setup-dotnet@a98b56852c35b8e3190ac28c8c2271da59106c68 # v6.0.0
uses: actions/setup-dotnet@0f4a354dd5547a28c70b7853dbd95d5b67886e73 # v6.1.0
with:
dotnet-version: 10.0.x
@@ -142,7 +142,7 @@ jobs:
persist-credentials: false
- name: Setup .NET 10
uses: actions/setup-dotnet@a98b56852c35b8e3190ac28c8c2271da59106c68 # v6.0.0
uses: actions/setup-dotnet@0f4a354dd5547a28c70b7853dbd95d5b67886e73 # v6.1.0
with:
dotnet-version: 10.0.x
+4 -1
View File
@@ -62,7 +62,7 @@ jobs:
persist-credentials: false
- name: Setup .NET 10
uses: actions/setup-dotnet@a98b56852c35b8e3190ac28c8c2271da59106c68 # v6.0.0
uses: actions/setup-dotnet@0f4a354dd5547a28c70b7853dbd95d5b67886e73 # v6.1.0
with:
dotnet-version: 10.0.x
@@ -71,6 +71,8 @@ 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 }}
@@ -84,6 +86,7 @@ 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,3 +46,17 @@ 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,6 +68,71 @@ 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()
{
@@ -97,6 +162,8 @@ 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));
+77
View File
@@ -99,6 +99,83 @@ 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()
{
+9 -8
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 it does not know gets the full renderer.
// As application.cpp on master has them; a word the starter does not know is the file's own, written back as it is.
[Theory]
[InlineData("default", "default")]
[InlineData("full", "default")]
[InlineData("gl46", "default")]
[InlineData("vulkan", "default")]
[InlineData("vulkan14", "default")]
[InlineData("full", "full")]
[InlineData("gl46", "gl46")]
[InlineData("vulkan", "vulkan")]
[InlineData("vulkan14", "vulkan14")]
[InlineData("legacy", "legacy")]
[InlineData("simpleshader", "legacy")]
[InlineData("off", "legacy")]
[InlineData("simple", "simple")]
[InlineData("experimental", "default")]
[InlineData("experimental", "experimental")]
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_go_on_a_save()
public void Keys_of_the_vulkan_renderer_master_does_not_have_stay_on_a_save()
{
string[] vulkan =
{
@@ -107,7 +107,8 @@ public class GraphicsSettingsTests
string saved = installation.Files.ReadAllText(UserIni);
Assert.Contains("calibratein 0 0 0 0", saved);
Assert.All(vulkan, line => Assert.Null(Line(saved, line.Split(' ')[0])));
// 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])));
}
[Fact]
+17 -6
View File
@@ -961,23 +961,34 @@ public class SettingsStoreTests
Assert.Contains($"gfxrenderer {word}\n", SavedLines(installation));
}
// 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.
// 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.
[Theory]
[InlineData("full")]
[InlineData("opengl")]
[InlineData("gl46")]
[InlineData("vulkan")]
[InlineData("vulkan14")]
[InlineData("experimental")]
[InlineData("null")]
public void A_renderer_word_master_does_not_run_is_saved_as_default(string word)
public void A_renderer_word_the_starter_does_not_know_stays_until_another_is_chosen(string word)
{
var installation = WithHome(new InMemoryFileSystem().WithFile(UserIni, $"gfxrenderer {word}\n"));
installation.SettingsStore.Load();
var installation = WithHome(new InMemoryFileSystem().WithFile(UserIni, $"gfxrenderer {word}\nfieldofview 45\n"));
var store = installation.SettingsStore;
store.Load();
installation.SettingsStore.Save();
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));
// 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]
@@ -0,0 +1,182 @@
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")));
});
}
}
+46
View File
@@ -0,0 +1,46 @@
using Avalonia;
using StarterNG.Infrastructure;
namespace StarterNG.Tests;
public class WindowSurfacesTests
{
[Fact]
public void Windows_draws_into_a_directcomposition_surface_and_never_through_winui_composition()
{
var options = WindowSurfaces.Win32Options;
Assert.Equal(Win32CompositionMode.DirectComposition, options.CompositionMode.First());
Assert.DoesNotContain(Win32CompositionMode.WinUIComposition, options.CompositionMode);
}
[Fact]
public void The_window_surface_is_only_the_fallback()
{
// There ANGLE presents through a swap chain, and the Steam overlay draws over it.
Assert.Equal(Win32CompositionMode.RedirectionSurface, WindowSurfaces.Win32Options.CompositionMode.Last());
}
[Fact]
public void No_swap_chain_of_its_own_is_asked_for()
{
Assert.DoesNotContain(Win32CompositionMode.LowLatencyDxgiSwapChain, WindowSurfaces.Win32Options.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));
}
}
+71 -3
View File
@@ -49,6 +49,41 @@ 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)
{
@@ -138,6 +173,7 @@ 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);
@@ -367,7 +403,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 && !SameValue(raw, shown))
if (read.TryGetValue(key, out string? shown) && shown == fallback && !Means(key, raw, shown))
unreadable[key] = raw;
}
@@ -385,6 +421,10 @@ 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;
}
@@ -473,8 +513,7 @@ public sealed class SettingsStore
return Uart.FeaturesStand(_config.GetRaw(key), value);
if (SettingsSerializer.FixedLengthKeys.Contains(key, StringComparer.OrdinalIgnoreCase))
return _config.GetRaw(key) == value;
if (string.Equals(key, "gfxrenderer", StringComparison.OrdinalIgnoreCase) &&
!SimulatorSettings.KeptRendererWord(_config.GetRaw(key)))
if (_chosen.Contains(key))
return false;
if (string.Equals(key, "mousescale", StringComparison.OrdinalIgnoreCase) &&
!SettingsSerializer.MouseScaleStands(_config.GetRaw(key)))
@@ -567,6 +606,35 @@ 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;
+10 -4
View File
@@ -53,6 +53,13 @@ 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;
@@ -197,11 +204,10 @@ public sealed class SimulatorSettings
public static readonly string[] RenderEngines = { "default", "legacy", "simple" };
/// <summary>
/// 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.
/// 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"/>.
/// </summary>
public static bool KeptRendererWord(string? word) =>
public static bool KnownRendererWord(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
@@ -0,0 +1,114 @@
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;
}
}
+29 -4
View File
@@ -30,14 +30,20 @@ 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<string>>? nvidiaSmi = null,
Func<IReadOnlyList<DxgiAdapter>?>? dxgi = null,
Func<IReadOnlyList<GraphicsCard>>? registry = 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>
@@ -46,15 +52,34 @@ public sealed class GraphicsCards
IEnumerable<GraphicsCard> cards = Array.Empty<GraphicsCard>();
if (_environment.IsLinux)
cards = FromLinux();
else if (_environment.IsWindows && OperatingSystem.IsWindows())
cards = FromRegistry();
else if (_environment.IsWindows)
cards = FromWindows();
// 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 IEnumerable<GraphicsCard> FromRegistry()
private static IReadOnlyList<GraphicsCard> FromRegistry()
{
try
{
@@ -91,7 +91,9 @@ public sealed class SettingsSerializer
s.VirtualShunting = c.GetBool("ai.trainman", true);
s.LogMissingVehicleFiles = c.GetBool("starter.logmissingvehicles", false);
s.RenderEngine = SimulatorSettings.RenderEngineOf(c.GetString("gfxrenderer", "default"));
string renderer = c.GetString("gfxrenderer", "default").Trim();
s.RenderEngine = SimulatorSettings.RenderEngineOf(renderer);
s.RendererWord = renderer.Length > 0 && !SimulatorSettings.KnownRendererWord(renderer) ? renderer : null;
s.Width = c.GetInt("width", 1280);
s.Height = c.GetInt("height", 720);
s.BufferScalePercent = ReadBufferScale(c);
@@ -226,13 +228,8 @@ public sealed class SettingsSerializer
{
"gfx.postfx.tonemapping",
"starter.developertools",
// 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",
// 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.
};
/// <summary>
@@ -286,7 +283,7 @@ public sealed class SettingsSerializer
c.SetBool("ai.trainman", s.VirtualShunting);
c.SetBool("starter.logmissingvehicles", s.LogMissingVehicleFiles);
c.Set("gfxrenderer", SimulatorSettings.RenderEngines[Clamp(s.RenderEngine, 0, SimulatorSettings.RenderEngines.Length - 1)]);
c.Set("gfxrenderer", s.RendererWord ?? 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);
@@ -0,0 +1,32 @@
using Avalonia;
namespace StarterNG.Infrastructure;
/// <summary>
/// On Windows the graphics card draws each window of the starter into a DirectComposition
/// surface, 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.
/// The window's own redirection surface is only the fallback: there ANGLE draws through a
/// swap chain of the window, and the Steam overlay, which Steam puts into the starter as
/// the game it launches, hooks that swap chain's Present and draws its frame counter and
/// notifications over the starter. A composition surface is drawn without a Present.
/// </summary>
public static class WindowSurfaces
{
public static Win32PlatformOptions Win32Options => new()
{
CompositionMode = new[]
{
Win32CompositionMode.DirectComposition,
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);
}
+2 -2
View File
@@ -845,7 +845,7 @@ public partial class MainWindow : Window
{
if (_askingAboutSettings || (DateTime.UtcNow - _openedUtc).TotalSeconds < 3)
return;
if (!AppServices.Current.SettingsStore.IsConfigNewerOnDisk())
if (!AppServices.Current.SettingsStore.HasChangeOnDiskToAskAbout())
return;
_askingAboutSettings = true;
@@ -862,7 +862,7 @@ public partial class MainWindow : Window
SettingsView?.ReloadFromSettings();
}
else
AppServices.Current.SettingsStore.TouchConfigAge();
AppServices.Current.SettingsStore.LeaveChangeOnDisk();
}
finally
{
+2 -1
View File
@@ -73,8 +73,9 @@ static class Program
};
}
// Without the switch the graphics card draws, into the window surfaces.
private static AppBuilder WithSoftwareRenderIfAsked(this AppBuilder builder) =>
_softwareRender ? SoftwareRender.ApplyTo(builder) : builder;
WindowSurfaces.ApplyTo(builder, _softwareRender);
public static AppBuilder BuildAvaloniaApp()
=> AppBuilder.Configure<App>()
+2
View File
@@ -7,6 +7,8 @@
<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>
+39 -3
View File
@@ -25,7 +25,7 @@ public partial class Settings
private void ShowGraphics(SimulatorSettings s)
{
RenderEngineCb.SelectedIndex = s.RenderEngine;
ShowRenderer(s);
SelectTag(AntiAliasingCb, AntiAliasingTag(s.AntiAliasing));
_fullscreenAsRead = s.Fullscreen;
SelectTag(DisplayModeCb, DisplayModeOf(s.Fullscreen, s.FullscreenWindowed));
@@ -35,8 +35,18 @@ public partial class Settings
private void CaptureGraphics(SimulatorSettings s)
{
s.RenderEngine = Math.Max(0, RenderEngineCb.SelectedIndex);
s.AntiAliasing = AntiAliasingFromTag(SelectedTag(AntiAliasingCb));
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.FullscreenMonitor = SelectedTag(MonitorCb) ?? string.Empty;
string mode = SelectedTag(DisplayModeCb) ?? FullscreenMode;
@@ -45,6 +55,32 @@ 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";
+126 -19
View File
@@ -416,9 +416,19 @@ 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();
}
@@ -533,12 +543,24 @@ 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>
private void ShowAsEdits(SimulatorSettings s)
/// <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)
{
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
{
@@ -628,7 +650,7 @@ public partial class Settings : UserControl, ISettingsCapture
{
var trial = Trial();
var applied = _presetMemory.Apply(preset, trial);
ShowAsEdits(trial);
ShowAsEdits(trial, applied.ChosenKeys.ToList());
// Chosen as a whole, its values are choices, not ones the screen could not show.
ForgetShown(applied.ChosenKeys);
@@ -640,7 +662,7 @@ public partial class Settings : UserControl, ISettingsCapture
private void ApplyGroupLevel(GraphicsGroup group, GraphicsPreset level)
{
var trial = Groups.Apply(group, level, Trial());
ShowAsEdits(trial);
ShowAsEdits(trial, group.Keys.ToList());
foreach (string key in group.Keys.Where(key => SimulatorKeys.All.Any(known => known.Key == key)))
_keyRows.Show(key, SimulatorKeys.Named(key).RawIn(trial));
@@ -825,9 +847,11 @@ 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);
@@ -855,7 +879,7 @@ public partial class Settings : UserControl, ISettingsCapture
}
private string SelectedRenderer() =>
SimulatorSettings.RenderEngines.ElementAtOrDefault(RenderEngineCb.SelectedIndex) ?? "full";
SelectedTag(RenderEngineCb) ?? SimulatorSettings.RenderEngines.ElementAtOrDefault(RenderEngineCb.SelectedIndex) ?? "full";
private RendererKind SelectedRendererKind() => Renderers.KindOf(SelectedRenderer());
@@ -882,7 +906,8 @@ public partial class Settings : UserControl, ISettingsCapture
s.InvertMouseVertical = IsChecked(MouseVertInvertCb);
s.IgnoreGamepad = IsChecked(GamepadIgnoreCb);
s.FeedbackMode = Math.Max(0, FeedbackCb.SelectedIndex);
// 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.FeedbackPort = (int)(FeedbackPortNud.Value ?? 888);
CaptureUart(s);
@@ -894,7 +919,7 @@ public partial class Settings : UserControl, ISettingsCapture
s.LogMissingVehicleFiles = IsChecked(LogMissingVehicleFilesCb);
CaptureGraphics(s);
s.Gpu = SelectedGpu();
if (!ShowsFileValue(GpuCb)) s.Gpu = SelectedGpu();
ReadResolution(s);
s.BufferScalePercent = (int)bufferScale.Value;
s.MaxTextureSize = 1 << (int)textureResolutionSlider.Value;
@@ -915,8 +940,8 @@ public partial class Settings : UserControl, ISettingsCapture
s.ShadowMapResolution = 1 << (int)shaderResolutionSlider.Value;
s.ShadowProjectionRange = (int)shaderRange.Value;
s.CabShadowsRange = (int)_cabShadows.Value;
s.ShadowRankCutoff = Math.Max(0, ShadowDisplayCb.SelectedIndex) + 1;
s.ReflectionsFidelity = Math.Max(0, ReflectionsDetailsCb.SelectedIndex);
if (!ShowsFileValue(ShadowDisplayCb)) s.ShadowRankCutoff = Math.Max(0, ShadowDisplayCb.SelectedIndex) + 1;
if (!ShowsFileValue(ReflectionsDetailsCb)) s.ReflectionsFidelity = Math.Max(0, ReflectionsDetailsCb.SelectedIndex);
s.FieldOfView = Math.Clamp((int)fovSlider.Value, 10, 75);
s.PythonScreens = IsChecked(RenderScreensCb);
s.PythonThreadedUpload = IsChecked(RenderScreensThreadCb);
@@ -951,12 +976,14 @@ public partial class Settings : UserControl, ISettingsCapture
s.AmbientVolume = (int)AmbientVolumeSlider.Value;
s.SkipPipeline = IsChecked(SkipPipelineCb);
s.DebugLogVisible = IsChecked(DebugLogVisibleCb);
s.PythonScreenUpdateRate = ParsePriorityTag((PyScreenPriorityCb.SelectedItem as ComboBoxItem)?.Tag);
if (!ShowsFileValue(PyScreenPriorityCb))
s.PythonScreenUpdateRate = ParsePriorityTag((PyScreenPriorityCb.SelectedItem as ComboBoxItem)?.Tag);
s.AutoCloseStarter = IsChecked(AutoCloseStarterCb);
s.LargeThumbnails = IsChecked(LargeThumbnailsCb);
s.AutoExpandSceneryTree = IsChecked(AutoExpandTreeCb);
s.ReadyOverride = (ConsistReadyOverride)Math.Clamp(ReadyOverrideCb.SelectedIndex, 0, 2);
if (!ShowsFileValue(ReadyOverrideCb))
s.ReadyOverride = (ConsistReadyOverride)Math.Clamp(ReadyOverrideCb.SelectedIndex, 0, 2);
s.CompressTextures = IsChecked(CompressTexCb);
s.ScaleSpeculars = IsChecked(ScaleSpecularsCb);
@@ -1420,6 +1447,8 @@ 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
@@ -1447,7 +1476,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));
ShowAsEdits(AppServices.Current.SettingsStore.WithDefaults(Trial(), keys), keys);
foreach (string key in keys)
_keyRows.ShowDefault(key);
// Put back by hand, a value is a choice like any other.
@@ -1505,10 +1534,86 @@ public partial class Settings : UserControl, ISettingsCapture
private bool Advanced => AppServices.Current.Settings.AdvancedSettings;
/// <summary>Under each setting, the value of eu07.ini for it the starter cannot read, as the file has it.</summary>
/// <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>
private void UpdateUnknownValues()
{
var unreadable = AppServices.Current.SettingsStore.UnreadableValues();
var unreadable = FileValues();
foreach (var row in SettingsStack.GetLogicalDescendants().OfType<SettingRow>())
{
var keys = (row.ConfigKey ?? string.Empty)
@@ -1698,16 +1803,16 @@ public partial class Settings : UserControl, ISettingsCapture
case { Tag: SimulatorKey }:
break;
case CheckBox cb:
cb.IsCheckedChanged += (_, _) => OnControlChanged();
cb.IsCheckedChanged += (_, _) => OnControlChanged(cb);
break;
case Slider slider:
slider.ValueChanged += (_, _) => OnControlChanged();
slider.ValueChanged += (_, _) => OnControlChanged(slider);
break;
case ComboBox combo:
combo.SelectionChanged += (_, _) => OnControlChanged();
combo.SelectionChanged += (_, _) => OnControlChanged(combo);
break;
case NumericUpDown nud:
nud.ValueChanged += (_, _) => OnControlChanged();
nud.ValueChanged += (_, _) => OnControlChanged(nud);
break;
}
}
@@ -1729,8 +1834,10 @@ public partial class Settings : UserControl, ISettingsCapture
edited();
};
private void OnControlChanged()
private void OnControlChanged(Control? control = null)
{
if (control is not null)
ChosenByHand(control);
MarkDirty();
QueuePresetMarks();
}
File diff suppressed because it is too large Load Diff
+173
View File
@@ -0,0 +1,173 @@
#!/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())