Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
7 changes: 4 additions & 3 deletions .github/CONTRIBUTING.md
Original file line number Diff line number Diff line change
Expand Up @@ -63,6 +63,7 @@ CAUTION: Do not start the GUI as administrator. Some GUI functions do not operat
| Task | Command |
|---|---|
| Run the unit tests | `dotnet test CDPIUI.Tests/CDPIUI.Tests.csproj` |
| Run real Windows Forms caption-font tests on Windows | `dotnet test CDPIUI.TrayIcon.Tests/CDPIUI.TrayIcon.Tests.csproj -c Release -p:Platform=x64` |
| Run the unit tests on Linux or macOS | `dotnet test CDPIUI.Tests/CDPIUI.Tests.csproj -p:EnableWindowsTargeting=true` |
| Build the release layout | `pwsh .github/scripts/build_portable.ps1` |
| Compare the installer file list with the release layout | `pwsh .github/scripts/check_setup_files.ps1` |
Expand Down Expand Up @@ -106,7 +107,7 @@ cdpiui/
│ ├── Extensions/ # Extension methods of the GUI
│ ├── Help/ # The help articles. One folder for each language (EN, RU).
│ ├── Helper/ # GUI helpers that use translations or XAML types
│ ├── Strings/ # Generated in the build output from Localization/*.json.
│ ├── Strings/ # Copied to the build output from Localization/*.resw.
│ ├── Template/ # Files that the build copies to the output folder
│ ├── ViewModels/ # View models
│ ├── Views/ # Pages. The pages of one window are in a folder with the window name.
Expand Down Expand Up @@ -216,9 +217,9 @@ A new preset pack or a new subscription does not need code.

The developer documents use the term "preset" for a ready settings file of a component. The English UI uses the word "Config" for a preset. The Russian UI uses the word "Пресет".

Edit translations in `Localization/<code>/*.json` (`en-us` and `ru`). This is the shared source for UI, tray, updater, and hosts editor copy. Keep keys and formatting arguments such as `{0}` and `{1}` consistent across languages.
Edit translations in `Localization/<code>/*.resw` (`en-us` and `ru`). This is the shared source for UI, tray, updater, and hosts editor copy. Keep keys and formatting arguments such as `{0}` and `{1}` consistent across languages.

The build automatically generates `.resw` under `obj` and copies them to `Strings` for WinUI3Localizer. Do not edit generated files. C# translation dictionaries and `Pick(english, russian)` are no longer used.
The build copies the editable `.resw` sources directly to `Strings` for WinUI3Localizer. No resource generator is required. C# translation dictionaries and `Pick(english, russian)` are no longer used.

See [Localization/README.md](../Localization/README.md) for the format, examples, language selection, checks, and adding a language. License agreements, help articles, and [Store content](https://github.com/Storik4pro/cdpiui-store) are translated in their own directories.

Expand Down
7 changes: 4 additions & 3 deletions .github/CONTRIBUTING.ru.md
Original file line number Diff line number Diff line change
Expand Up @@ -63,6 +63,7 @@ GUI не запускает компоненты. GUI отправляет за
| Задача | Команда |
|---|---|
| Запустить модульные тесты | `dotnet test CDPIUI.Tests/CDPIUI.Tests.csproj` |
| Проверить шрифты подписей на настоящих Windows Forms-контролах в Windows | `dotnet test CDPIUI.TrayIcon.Tests/CDPIUI.TrayIcon.Tests.csproj -c Release -p:Platform=x64` |
| Запустить модульные тесты в Linux или macOS | `dotnet test CDPIUI.Tests/CDPIUI.Tests.csproj -p:EnableWindowsTargeting=true` |
| Собрать раскладку релиза | `pwsh .github/scripts/build_portable.ps1` |
| Сравнить список файлов установщика с раскладкой релиза | `pwsh .github/scripts/check_setup_files.ps1` |
Expand Down Expand Up @@ -106,7 +107,7 @@ cdpiui/
│ ├── Extensions/ # Методы расширения GUI
│ ├── Help/ # Справочные статьи. Одна папка на каждый язык (EN, RU).
│ ├── Helper/ # Помощники GUI, которые используют переводы или типы XAML
│ ├── Strings/ # Генерируется в выходном каталоге при сборке из Localization/*.json.
│ ├── Strings/ # Копируется в выходной каталог из Localization/*.resw.
│ ├── Template/ # Файлы, которые сборка копирует в выходную папку
│ ├── ViewModels/ # Модели представления
│ ├── Views/ # Страницы. Страницы одного окна находятся в папке с именем окна.
Expand Down Expand Up @@ -216,9 +217,9 @@ Shared — общая библиотека GUI и трея.

В документах для разработчиков термин «пресет» означает готовый файл настроек компонента. Английский интерфейс использует для пресета слово «Config». Русский интерфейс использует слово «Пресет».

Редактируйте переводы в `Localization/<code>/*.json` (`en-us` и `ru`). Это общий источник текстов интерфейса, трея, обновлятора и редактора hosts. Сохраняйте одинаковые ключи в обоих языках и параметры форматирования `{0}`, `{1}`.
Редактируйте переводы в `Localization/<code>/*.resw` (`en-us` и `ru`). Это общий источник текстов интерфейса, трея, обновлятора и редактора hosts. Сохраняйте одинаковые ключи в обоих языках и параметры форматирования `{0}`, `{1}`.

Сборка автоматически создаёт `.resw` в `obj` и копирует их в `Strings` для WinUI3Localizer. Не редактируйте сгенерированные файлы. Словари переводов и выбор текста через `Pick(english, russian)` в C# больше не используются.
Сборка копирует редактируемые исходные `.resw` прямо в `Strings` для WinUI3Localizer. Генератор ресурсов не требуется. Словари переводов и выбор текста через `Pick(english, russian)` в C# больше не используются.

Формат, примеры, выбор языка, проверки и порядок добавления языка описаны в [Localization/README.md](../Localization/README.md). Лицензии, справочные статьи и содержимое [Магазина](https://github.com/Storik4pro/cdpiui-store) переводятся в своих каталогах.

Expand Down
8 changes: 6 additions & 2 deletions .github/workflows/ci.yml
Original file line number Diff line number Diff line change
Expand Up @@ -71,7 +71,10 @@ jobs:
dotnet build CDPIUI.TrayIcon/CDPIUI.TrayIcon.csproj -c Release -p:Platform=x64

- name: Test
run: dotnet test CDPIUI.Tests/CDPIUI.Tests.csproj -c Release
run: |
dotnet test CDPIUI.Tests/CDPIUI.Tests.csproj -c Release
if ($LASTEXITCODE -ne 0) { exit $LASTEXITCODE }
dotnet test CDPIUI.TrayIcon.Tests/CDPIUI.TrayIcon.Tests.csproj -c Release -p:Platform=x64

# Direct and transitive packages with a known vulnerability of moderate or higher severity fail the job.
- name: Check packages for known vulnerabilities
Expand All @@ -83,7 +86,8 @@ jobs:
@('CDPIUI.AddOns/CDPIUI.AddOns.csproj', ''),
@('CDPIUI.TrayIcon/CDPIUI.TrayIcon.csproj', '-p:Platform=x64'),
@('CDPIUI/CDPIUI.csproj', '-p:Platform=x64'),
@('CDPIUI.Tests/CDPIUI.Tests.csproj', '')
@('CDPIUI.Tests/CDPIUI.Tests.csproj', ''),
@('CDPIUI.TrayIcon.Tests/CDPIUI.TrayIcon.Tests.csproj', '-p:Platform=x64')
)
foreach ($project in $projects) {
$extra = @($project[1] | Where-Object { $_ })
Expand Down
4 changes: 2 additions & 2 deletions CDPIUI.Shared/CDPIUI.Shared.csproj
Original file line number Diff line number Diff line change
Expand Up @@ -23,8 +23,8 @@
<ItemGroup>
<InternalsVisibleTo Include="CDPIUI.Tests" />
<Compile Remove="Secrets/SecretExample.cs" />
<EmbeddedResource Include="..\Localization\en-us\*.json" LogicalName="Localization.en-us.%(Filename).json" />
<EmbeddedResource Include="..\Localization\ru\*.json" LogicalName="Localization.ru.%(Filename).json" />
<EmbeddedResource Include="..\Localization\en-us\*.resw" LogicalName="Localization.en-us.%(Filename).resw" />
<EmbeddedResource Include="..\Localization\ru\*.resw" LogicalName="Localization.ru.%(Filename).resw" />
</ItemGroup>

</Project>
49 changes: 0 additions & 49 deletions CDPIUI.Shared/Localization/JsonCatalog.cs

This file was deleted.

73 changes: 73 additions & 0 deletions CDPIUI.Shared/Localization/ReswCatalog.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,73 @@
#nullable enable
using System;
using System.Collections.Concurrent;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Xml;
using System.Xml.Linq;

#if UPDATE_TOOL
namespace Update.Localization;
#elif HOSTS_TOOL
namespace EditHostFile.Localization;
#else
namespace CDPIUI.Shared.Localization;
#endif

/// <summary>Reads embedded string-only RESW catalogs without external XML dependencies.</summary>
internal sealed class ReswCatalog(Func<string, string, Stream?> openResource)
{
// The largest current catalog is below 0.5 MiB. This bounds damaged input with ample translation margin.
private const long MaximumDocumentCharacters = 4L * 1024 * 1024;
private readonly ConcurrentDictionary<(string Catalog, string Language), Dictionary<string, string>> _catalogs = new();

internal string Get(string catalog, string key, string language)
{
if (Read(catalog, language).TryGetValue(key, out string? text) && !string.IsNullOrWhiteSpace(text))
return text;
if (Read(catalog, "en-us").TryGetValue(key, out text) && !string.IsNullOrWhiteSpace(text))
return text;
// Even a broken deployment must not turn an error dialog's labels into empty strings.
return key;
}

private Dictionary<string, string> Read(string catalog, string language) =>
_catalogs.GetOrAdd((catalog, language), resource =>
{
try
{
using var stream = openResource(resource.Catalog, resource.Language);
if (stream != null)
{
using var reader = XmlReader.Create(stream, new XmlReaderSettings
{
DtdProcessing = DtdProcessing.Prohibit,
XmlResolver = null,
MaxCharactersInDocument = MaximumDocumentCharacters
});
var document = XDocument.Load(reader, LoadOptions.PreserveWhitespace);
var root = document.Root;
if (root == null || root.Name != "root")
throw new XmlException("A RESW catalog requires a root element.");

var values = new Dictionary<string, string>(StringComparer.Ordinal);
foreach (var entry in root.Elements("data"))
{
string? name = (string?)entry.Attribute("name");
var value = entry.Element("value");
if (string.IsNullOrWhiteSpace(name) || value == null || value.HasElements || entry.Elements("value").Count() != 1)
throw new XmlException("A RESW string requires a name and one text value.");
// Add rejects duplicate names. A malformed catalog never publishes a partial dictionary.
values.Add(name!, value.Value);
}
return values;
}
}
catch (Exception exception) when (exception is not OutOfMemoryException and not StackOverflowException and not AccessViolationException)
{
// Do not call the logger, settings or UI here: localization also reports their failures.
}
return new Dictionary<string, string>();
});
}
Original file line number Diff line number Diff line change
Expand Up @@ -9,13 +9,13 @@ namespace EditHostFile.Localization;
namespace CDPIUI.Shared.Localization;
#endif

/// <summary>Looks up embedded JSON catalogs, with English fallback for an absent translation.</summary>
public static class JsonLocalizer
/// <summary>Looks up embedded RESW catalogs, with English fallback for an absent translation.</summary>
public static class ReswLocalizer
{
// Standalone tools link this source and embed their own catalogs. They never load
// translations or assemblies from the installation directory while running elevated.
private static readonly JsonCatalog Catalogs = new((catalog, language) =>
typeof(JsonLocalizer).Assembly.GetManifestResourceStream("Localization." + language + "." + catalog + ".json"));
private static readonly ReswCatalog Catalogs = new((catalog, language) =>
typeof(ReswLocalizer).Assembly.GetManifestResourceStream("Localization." + language + "." + catalog + ".resw"));

public static string Get(string catalog, string key, string? language = null)
{
Expand Down
24 changes: 14 additions & 10 deletions CDPIUI.Tests/Shared/LocalizationCatalogTests.cs
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
using System.Text.Json;
using System.Xml;
using System.Text.RegularExpressions;
using System.Xml.Linq;
using CDPIUI.Shared.Localization;
Expand All @@ -22,8 +22,8 @@ private static string RepositoryRoot
public void CatalogsHaveMatchingKeysAndFormattingArguments()
{
string root = Path.Combine(RepositoryRoot, "Localization");
Assert.True(Directory.Exists(Path.Combine(root, "en-us")), "JSON localization catalogs must exist.");
foreach (string englishPath in Directory.GetFiles(Path.Combine(root, "en-us"), "*.json"))
Assert.True(Directory.Exists(Path.Combine(root, "en-us")), "RESW localization catalogs must exist.");
foreach (string englishPath in Directory.GetFiles(Path.Combine(root, "en-us"), "*.resw"))
{
var english = Read(englishPath);
var russian = Read(Path.Combine(root, "ru", Path.GetFileName(englishPath)));
Expand All @@ -33,8 +33,8 @@ public void CatalogsHaveMatchingKeysAndFormattingArguments()
Assert.False(string.IsNullOrWhiteSpace(value), $"Empty English resource: {englishPath}/{key}");
Assert.False(string.IsNullOrWhiteSpace(russian[key]), $"Empty Russian resource: {englishPath}/{key}");
Assert.Equal(Arguments(value), Arguments(russian[key]));
Assert.Equal(value, JsonLocalizer.Get(Path.GetFileNameWithoutExtension(englishPath), key, "en-us"));
Assert.Equal(russian[key], JsonLocalizer.Get(Path.GetFileNameWithoutExtension(englishPath), key, "ru"));
Assert.Equal(value, ReswLocalizer.Get(Path.GetFileNameWithoutExtension(englishPath), key, "en-us"));
Assert.Equal(russian[key], ReswLocalizer.Get(Path.GetFileNameWithoutExtension(englishPath), key, "ru"));
}
}
}
Expand Down Expand Up @@ -77,8 +77,8 @@ public void XamlUsesResourcesForVisibleCopy()
[Fact]
public void VisibleToggleStateLabelsUseTheApplicationLocale()
{
var english = Read(Path.Combine(RepositoryRoot, "Localization", "en-us", "Resources.json"));
var russian = Read(Path.Combine(RepositoryRoot, "Localization", "ru", "Resources.json"));
var english = Read(Path.Combine(RepositoryRoot, "Localization", "en-us", "Resources.resw"));
var russian = Read(Path.Combine(RepositoryRoot, "Localization", "ru", "Resources.resw"));
XNamespace localizer = "using:WinUI3Localizer";
foreach (string folder in new[] { "Controls", "Views", "Windows" })
foreach (string path in Directory.EnumerateFiles(Path.Combine(RepositoryRoot, "CDPIUI", folder), "*.xaml", SearchOption.AllDirectories))
Expand All @@ -97,9 +97,13 @@ public void VisibleToggleStateLabelsUseTheApplicationLocale()

private static Dictionary<string, string> Read(string path)
{
using var document = JsonDocument.Parse(File.ReadAllText(path));
// ToDictionary also rejects duplicate keys instead of silently overwriting a translation.
return document.RootElement.EnumerateObject().ToDictionary(property => property.Name, property => property.Value.GetString()!);
using var reader = XmlReader.Create(path, new XmlReaderSettings { DtdProcessing = DtdProcessing.Prohibit, XmlResolver = null });
var document = XDocument.Load(reader, LoadOptions.PreserveWhitespace);
Assert.Equal("root", document.Root!.Name.LocalName);
// ToDictionary rejects duplicate names instead of silently overwriting a translation.
return document.Root.Elements("data").ToDictionary(
element => (string?)element.Attribute("name") ?? throw new InvalidDataException("Missing resource name."),
element => element.Element("value")?.Value ?? throw new InvalidDataException("Missing resource value."));
}

private static string[] Arguments(string text) => Regex.Matches(text, @"(?<!\{)\{(\d+)(?:[^{}]*)\}(?!\})")
Expand Down
Loading
Loading