Compare commits

..

14 Commits

Author SHA1 Message Date
maj00r 92ed2c39f0 fix(settings): the graphics cards on Windows come from DXGI, as the drivers list them (#67)
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.

Co-authored-by: maj00r <maj00r@host>
2026-11-30 17:15:21 +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
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
11 changed files with 1623 additions and 14 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.
+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()
{
+15 -2
View File
@@ -6,14 +6,27 @@ namespace StarterNG.Tests;
public class WindowSurfacesTests
{
[Fact]
public void Windows_draws_into_the_window_surface_and_never_through_winui_composition()
public void Windows_draws_into_a_directcomposition_surface_and_never_through_winui_composition()
{
var options = WindowSurfaces.Win32Options;
Assert.Equal(new[] { Win32CompositionMode.RedirectionSurface }, options.CompositionMode);
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()
{
+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
{
+12 -5
View File
@@ -3,17 +3,24 @@ 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
/// 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. Composition is
/// there for see-through windows and backdrops, and the starter has none.
/// 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.RedirectionSurface }
CompositionMode = new[]
{
Win32CompositionMode.DirectComposition,
Win32CompositionMode.RedirectionSurface
}
};
/// <summary>
+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>
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())