diff --git a/.github/CONTRIBUTING.md b/.github/CONTRIBUTING.md index 9f2ef258..9f7dca88 100644 --- a/.github/CONTRIBUTING.md +++ b/.github/CONTRIBUTING.md @@ -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` | @@ -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. @@ -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//*.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//*.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. diff --git a/.github/CONTRIBUTING.ru.md b/.github/CONTRIBUTING.ru.md index edce0db1..d1aeafc8 100644 --- a/.github/CONTRIBUTING.ru.md +++ b/.github/CONTRIBUTING.ru.md @@ -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` | @@ -106,7 +107,7 @@ cdpiui/ │ ├── Extensions/ # Методы расширения GUI │ ├── Help/ # Справочные статьи. Одна папка на каждый язык (EN, RU). │ ├── Helper/ # Помощники GUI, которые используют переводы или типы XAML -│ ├── Strings/ # Генерируется в выходном каталоге при сборке из Localization/*.json. +│ ├── Strings/ # Копируется в выходной каталог из Localization/*.resw. │ ├── Template/ # Файлы, которые сборка копирует в выходную папку │ ├── ViewModels/ # Модели представления │ ├── Views/ # Страницы. Страницы одного окна находятся в папке с именем окна. @@ -216,9 +217,9 @@ Shared — общая библиотека GUI и трея. В документах для разработчиков термин «пресет» означает готовый файл настроек компонента. Английский интерфейс использует для пресета слово «Config». Русский интерфейс использует слово «Пресет». -Редактируйте переводы в `Localization//*.json` (`en-us` и `ru`). Это общий источник текстов интерфейса, трея, обновлятора и редактора hosts. Сохраняйте одинаковые ключи в обоих языках и параметры форматирования `{0}`, `{1}`. +Редактируйте переводы в `Localization//*.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) переводятся в своих каталогах. diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index e18107e1..40bc0fbd 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -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 @@ -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 { $_ }) diff --git a/CDPIUI.Shared/CDPIUI.Shared.csproj b/CDPIUI.Shared/CDPIUI.Shared.csproj index 090719fc..1f56b7d3 100644 --- a/CDPIUI.Shared/CDPIUI.Shared.csproj +++ b/CDPIUI.Shared/CDPIUI.Shared.csproj @@ -23,8 +23,8 @@ - - + + diff --git a/CDPIUI.Shared/Localization/JsonCatalog.cs b/CDPIUI.Shared/Localization/JsonCatalog.cs deleted file mode 100644 index 23c9f9c5..00000000 --- a/CDPIUI.Shared/Localization/JsonCatalog.cs +++ /dev/null @@ -1,49 +0,0 @@ -#nullable enable -using System; -using System.Collections.Concurrent; -using System.Collections.Generic; -using System.IO; -using System.Runtime.Serialization.Json; - -#if UPDATE_TOOL -namespace Update.Localization; -#elif HOSTS_TOOL -namespace EditHostFile.Localization; -#else -namespace CDPIUI.Shared.Localization; -#endif - -internal sealed class JsonCatalog(Func openResource) -{ - private readonly ConcurrentDictionary<(string Catalog, string Language), Dictionary> _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 Read(string catalog, string language) => - _catalogs.GetOrAdd((catalog, language), resource => - { - try - { - using var stream = openResource(resource.Catalog, resource.Language); - if (stream != null) - { - var serializer = new DataContractJsonSerializer(typeof(Dictionary), - new DataContractJsonSerializerSettings { UseSimpleDictionaryFormat = true }); - return (Dictionary?)serializer.ReadObject(stream) ?? new Dictionary(); - } - } - catch (Exception exception) when (exception is not OutOfMemoryException and not StackOverflowException and not AccessViolationException) - { - // Do not call the logger or UI here: localization is also used to report their failures. - } - return new Dictionary(); - }); -} diff --git a/CDPIUI.Shared/Localization/ReswCatalog.cs b/CDPIUI.Shared/Localization/ReswCatalog.cs new file mode 100644 index 00000000..ee669813 --- /dev/null +++ b/CDPIUI.Shared/Localization/ReswCatalog.cs @@ -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 + +/// Reads embedded string-only RESW catalogs without external XML dependencies. +internal sealed class ReswCatalog(Func 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> _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 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(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(); + }); +} diff --git a/CDPIUI.Shared/Localization/JsonLocalizer.cs b/CDPIUI.Shared/Localization/ReswLocalizer.cs similarity index 67% rename from CDPIUI.Shared/Localization/JsonLocalizer.cs rename to CDPIUI.Shared/Localization/ReswLocalizer.cs index 195c8c09..68fca926 100644 --- a/CDPIUI.Shared/Localization/JsonLocalizer.cs +++ b/CDPIUI.Shared/Localization/ReswLocalizer.cs @@ -9,13 +9,13 @@ namespace EditHostFile.Localization; namespace CDPIUI.Shared.Localization; #endif -/// Looks up embedded JSON catalogs, with English fallback for an absent translation. -public static class JsonLocalizer +/// Looks up embedded RESW catalogs, with English fallback for an absent translation. +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) { diff --git a/CDPIUI.Tests/Shared/LocalizationCatalogTests.cs b/CDPIUI.Tests/Shared/LocalizationCatalogTests.cs index e29d1c74..43f6f823 100644 --- a/CDPIUI.Tests/Shared/LocalizationCatalogTests.cs +++ b/CDPIUI.Tests/Shared/LocalizationCatalogTests.cs @@ -1,4 +1,4 @@ -using System.Text.Json; +using System.Xml; using System.Text.RegularExpressions; using System.Xml.Linq; using CDPIUI.Shared.Localization; @@ -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))); @@ -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")); } } } @@ -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)) @@ -97,9 +97,13 @@ public void VisibleToggleStateLabelsUseTheApplicationLocale() private static Dictionary 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, @"(?")] + [InlineData("")] + [InlineData(" ")] + [InlineData("")] + [InlineData("incomplete")] + [InlineData("Wrong root")] + [InlineData("firstsecond")] + [InlineData("]>&text;")] + public void MissingOrDamagedSelectedCatalogUsesEnglish(string? selectedXml) { - var catalog = new JsonCatalog((_, language) => Stream(language == "ru" ? selectedJson : "{\"Message\":\"Error details: {0}\"}")); + var catalog = new ReswCatalog((_, language) => Stream(language == "ru" ? selectedXml : Xml("Error details: {0}"))); Assert.Equal("Error details: disk", string.Format(catalog.Get("Errors", "Message", "ru"), "disk")); } [Fact] public void ResourceReadFailureStillUsesEnglish() { - var catalog = new JsonCatalog((_, language) => language == "ru" + var catalog = new ReswCatalog((_, language) => language == "ru" ? throw new IOException("Resource unavailable") - : Stream("{\"Message\":\"Something went wrong\"}")); + : Stream(Xml("Something went wrong"))); Assert.Equal("Something went wrong", catalog.Get("Errors", "Message", "ru")); } [Fact] public void FailureOfBothCatalogsStillShowsAResourceId() { - var catalog = new JsonCatalog((_, _) => throw new InvalidOperationException("Resource failure")); + var catalog = new ReswCatalog((_, _) => throw new InvalidOperationException("Resource failure")); Assert.Equal("CriticalErrorTitle.Text", catalog.Get("Resources", "CriticalErrorTitle.Text", "ru")); } @@ -41,5 +45,32 @@ public void FailureReadingPreferenceUsesWindowsLanguage() Assert.Equal("en-us", LocalePreference.Read(() => throw new TypeInitializationException("Settings", null), "de-DE")); } - private static MemoryStream? Stream(string? json) => json == null ? null : new MemoryStream(Encoding.UTF8.GetBytes(json)); + [Fact] + public void OversizedSelectedCatalogUsesEnglish() + { + string oversized = Xml(new string('x', 4 * 1024 * 1024)); + var catalog = new ReswCatalog((_, language) => Stream(language == "ru" ? oversized : Xml("English"))); + Assert.Equal("English", catalog.Get("Errors", "Message", "ru")); + } + + [Fact] + public void CatalogCacheKeepsLanguagesAndCatalogNamesSeparate() + { + var reads = new Dictionary<(string, string), int>(); + var catalog = new ReswCatalog((name, language) => + { + reads[(name, language)] = reads.GetValueOrDefault((name, language)) + 1; + return Stream(Xml(name + ":" + language)); + }); + Assert.Equal("Errors:ru", catalog.Get("Errors", "Message", "ru")); + Assert.Equal("Errors:ru", catalog.Get("Errors", "Message", "ru")); + Assert.Equal("Errors:en-us", catalog.Get("Errors", "Message", "en-us")); + Assert.Equal("Tray:ru", catalog.Get("Tray", "Message", "ru")); + Assert.Equal(3, reads.Count); + Assert.All(reads.Values, count => Assert.Equal(1, count)); + } + + private static string Xml(string value) => "" + value + ""; + + private static MemoryStream? Stream(string? xml) => xml == null ? null : new MemoryStream(Encoding.UTF8.GetBytes(xml)); } diff --git a/CDPIUI.Tests/Shared/ReswAuthoringTests.cs b/CDPIUI.Tests/Shared/ReswAuthoringTests.cs new file mode 100644 index 00000000..99d006d6 --- /dev/null +++ b/CDPIUI.Tests/Shared/ReswAuthoringTests.cs @@ -0,0 +1,46 @@ +using System.Xml.Linq; + +namespace CDPIUI.Tests.Shared; + +public class ReswAuthoringTests +{ + private static string RepositoryRoot + { + get + { + var directory = new DirectoryInfo(AppContext.BaseDirectory); + while (directory != null && !File.Exists(Path.Combine(directory.FullName, "CDPI.sln"))) + directory = directory.Parent; + return directory?.FullName ?? throw new DirectoryNotFoundException("Repository root not found."); + } + } + + [Fact] + public void EveryApplicationCatalogUsesEditableResw() + { + string root = Path.Combine(RepositoryRoot, "Localization"); + string[] catalogs = ["EditHostFile", "Flashlight", "GoodCheckAdditionalSettings", + "GraphicDesignerDescriptions", "Help", "Resources", "SettingTiles", "Tray", + "Troubleshooting", "UIHelper", "Update", "WelcomeWizard", "Widgets"]; + foreach (string language in new[] { "en-us", "ru" }) + { + string folder = Path.Combine(root, language); + Assert.Empty(Directory.GetFiles(folder, "*.json")); + Assert.Equal(catalogs.Order(), Directory.GetFiles(folder, "*.resw") + .Select(Path.GetFileNameWithoutExtension).Order()); + } + Assert.False(File.Exists(Path.Combine(RepositoryRoot, "build", "Generate-Localization.ps1"))); + Assert.False(File.Exists(Path.Combine(RepositoryRoot, "build", "Localization.targets"))); + } + + [Fact] + public void EnglishReswRetainsTranslatorContext() + { + var document = XDocument.Load(Path.Combine(RepositoryRoot, "Localization", "en-us", "Resources.resw")); + foreach (string key in new[] { "AboutButton.Content", "ORSeparatorTextBlock.Text" }) + { + var entry = Assert.Single(document.Root!.Elements("data"), element => (string?)element.Attribute("name") == key); + Assert.False(string.IsNullOrWhiteSpace((string?)entry.Element("comment")), key); + } + } +} diff --git a/CDPIUI.Tests/Shared/JsonLocalizerTests.cs b/CDPIUI.Tests/Shared/ReswLocalizerTests.cs similarity index 87% rename from CDPIUI.Tests/Shared/JsonLocalizerTests.cs rename to CDPIUI.Tests/Shared/ReswLocalizerTests.cs index 82d31b08..6671c976 100644 --- a/CDPIUI.Tests/Shared/JsonLocalizerTests.cs +++ b/CDPIUI.Tests/Shared/ReswLocalizerTests.cs @@ -3,7 +3,7 @@ namespace CDPIUI.Tests.Shared; -public class JsonLocalizerTests +public class ReswLocalizerTests { [Theory] [InlineData("ru", "en-US", "ru")] @@ -22,17 +22,17 @@ public void UsesSelectedLanguageBeforeWindowsAndEnglishFallback(string? selected [Fact] public void EmbeddedCatalogsContainBothLanguagesAndMultilineFormats() { - Assert.Equal("Exit", JsonLocalizer.Get("Tray", "Exit", "en-US")); - Assert.Equal("Выход", JsonLocalizer.Get("Tray", "Exit", "ru-RU")); - string template = JsonLocalizer.Get("Tray", "ExecutableTrustQuestion", "ru"); + Assert.Equal("Exit", ReswLocalizer.Get("Tray", "Exit", "en-US")); + Assert.Equal("Выход", ReswLocalizer.Get("Tray", "Exit", "ru-RU")); + string template = ReswLocalizer.Get("Tray", "ExecutableTrustQuestion", "ru"); string text = string.Format(template, "component.exe", "hash", "publisher"); Assert.Contains("component.exe", text); Assert.Contains("\n\n", text); Assert.Contains("hash", text); Assert.Contains("publisher", text); - Assert.Equal("Critical error", JsonLocalizer.Get("Resources", "CriticalErrorWindowTitle", "en")); - Assert.Equal("Критическая ошибка", JsonLocalizer.Get("Resources", "CriticalErrorWindowTitle", "ru")); - Assert.Equal("MissingKey", JsonLocalizer.Get("Tray", "MissingKey", "ru")); + Assert.Equal("Critical error", ReswLocalizer.Get("Resources", "CriticalErrorWindowTitle", "en")); + Assert.Equal("Критическая ошибка", ReswLocalizer.Get("Resources", "CriticalErrorWindowTitle", "ru")); + Assert.Equal("MissingKey", ReswLocalizer.Get("Tray", "MissingKey", "ru")); } [Fact] diff --git a/CDPIUI.Tests/Shared/ReswProjectLayoutTests.cs b/CDPIUI.Tests/Shared/ReswProjectLayoutTests.cs new file mode 100644 index 00000000..dd4a32cf --- /dev/null +++ b/CDPIUI.Tests/Shared/ReswProjectLayoutTests.cs @@ -0,0 +1,92 @@ +using System.Xml.Linq; + +namespace CDPIUI.Tests.Shared; + +public class ReswProjectLayoutTests +{ + private static readonly string[] Languages = ["en-us", "ru"]; + private static readonly string[] Catalogs = ["EditHostFile", "Flashlight", "GoodCheckAdditionalSettings", + "GraphicDesignerDescriptions", "Help", "Resources", "SettingTiles", "Tray", + "Troubleshooting", "UIHelper", "Update", "WelcomeWizard", "Widgets"]; + + private static string RepositoryRoot + { + get + { + var directory = new DirectoryInfo(AppContext.BaseDirectory); + while (directory != null && !File.Exists(Path.Combine(directory.FullName, "CDPI.sln"))) + directory = directory.Parent; + return directory?.FullName ?? throw new DirectoryNotFoundException("Repository root not found."); + } + } + + [Fact] + public void GuiResourcesHaveAllRuntimeAndCompiledDestinations() + { + var project = ReadProject("CDPIUI"); + var content = Expand(project, "Content", "CDPIUI").Where(item => item.Source.EndsWith(".resw", StringComparison.Ordinal)).ToArray(); + string[] expected = [.. Languages.SelectMany(language => Catalogs + .Where(catalog => catalog is not "Tray" and not "Update" and not "EditHostFile") + .Select(catalog => "Strings/" + language + "/" + catalog + ".resw"))]; + Assert.Equal(expected.Order(), content.Select(item => Metadata(item, "Link")).Order()); + Assert.Equal(expected.Order(), content.Select(item => Metadata(item, "TargetPath")).Order()); + foreach (var item in content) + { + Assert.Equal("PreserveNewest", Metadata(item, "CopyToOutputDirectory")); + Assert.Equal("PreserveNewest", Metadata(item, "CopyToPublishDirectory")); + Assert.Equal("Localization/" + Metadata(item, "Link")["Strings/".Length..], item.Source); + } + + var pri = Expand(project, "PRIResource", "CDPIUI").ToArray(); + string[] expectedPri = [.. Languages.Select(language => "Strings/" + language + "/Resources.resw")]; + Assert.Equal(expectedPri.Order(), pri.Select(item => Metadata(item, "Link")).Order()); + foreach (var item in pri) + Assert.Equal("Localization/" + Metadata(item, "Link")["Strings/".Length..], item.Source); + } + + [Fact] + public void SharedAndStandaloneManifestNamesMatchCatalogContract() + { + foreach (string projectName in new[] { "CDPIUI.Shared", "Update", "EditHostFile" }) + { + var items = Expand(ReadProject(projectName), "EmbeddedResource", projectName) + .Where(item => item.Source.StartsWith("Localization/", StringComparison.Ordinal)).ToArray(); + string[] catalogs = projectName == "CDPIUI.Shared" ? Catalogs : [projectName]; + string[] expected = [.. Languages.SelectMany(language => catalogs + .Select(catalog => "Localization." + language + "." + catalog + ".resw"))]; + Assert.Equal(expected.Order(), items.Select(item => Metadata(item, "LogicalName")).Order()); + foreach (var item in items) + Assert.Equal(item.Source.Replace('/', '.'), Metadata(item, "LogicalName")); + } + } + + private static XDocument ReadProject(string name) => + XDocument.Load(Path.Combine(RepositoryRoot, name, name + ".csproj")); + + // These declarations use literal local paths and Filename metadata. Keep this source-level + // contract explicit; actual MSBuild outputs and PRI maps retain their separate artifact check. + private static IEnumerable<(XElement Declaration, string Source)> Expand(XDocument project, string kind, string projectName) + { + string directory = Path.Combine(RepositoryRoot, projectName); + foreach (var declaration in project.Descendants(kind).Where(element => element.Attribute("Include") != null)) + { + string include = ((string)declaration.Attribute("Include")!).Replace('\\', '/'); + string absolute = Path.GetFullPath(Path.Combine(directory, include)); + // Non-localization assets are outside this contract and can use other MSBuild metadata. + if (!absolute.StartsWith(Path.Combine(RepositoryRoot, "Localization") + Path.DirectorySeparatorChar, StringComparison.Ordinal)) + continue; + Assert.Null(declaration.Attribute("Condition")); + string[] excluded = ((string?)declaration.Attribute("Exclude") ?? "").Split(';', StringSplitOptions.RemoveEmptyEntries) + .Select(path => Path.GetFullPath(Path.Combine(directory, path.Replace('\\', '/')))).ToArray(); + string[] files = include.Contains('*') + ? Directory.GetFiles(Path.GetDirectoryName(absolute)!, Path.GetFileName(absolute)) + : [absolute]; + foreach (string file in files.Except(excluded, StringComparer.Ordinal)) + yield return (declaration, Path.GetRelativePath(RepositoryRoot, file).Replace('\\', '/')); + } + } + + private static string Metadata((XElement Declaration, string Source) item, string name) => + (((string?)item.Declaration.Attribute(name) ?? (string?)item.Declaration.Element(name)) ?? "") + .Replace("%(Filename)", Path.GetFileNameWithoutExtension(item.Source)).Replace('\\', '/'); +} diff --git a/CDPIUI.TrayIcon.Tests/CDPIUI.TrayIcon.Tests.csproj b/CDPIUI.TrayIcon.Tests/CDPIUI.TrayIcon.Tests.csproj new file mode 100644 index 00000000..409e2ec4 --- /dev/null +++ b/CDPIUI.TrayIcon.Tests/CDPIUI.TrayIcon.Tests.csproj @@ -0,0 +1,20 @@ + + + net8.0-windows10.0.17763.0 + true + x64 + enable + enable + false + true + + + + + + + + + + + diff --git a/CDPIUI.TrayIcon.Tests/ModernButtonFontLifetimeTests.cs b/CDPIUI.TrayIcon.Tests/ModernButtonFontLifetimeTests.cs new file mode 100644 index 00000000..707cf1f0 --- /dev/null +++ b/CDPIUI.TrayIcon.Tests/ModernButtonFontLifetimeTests.cs @@ -0,0 +1,95 @@ +using System.Diagnostics; +using System.Drawing; +using System.Reflection; +using System.Runtime.ExceptionServices; +using System.Runtime.InteropServices; +using System.Windows.Forms; +using CDPIUI.TrayIcon.Controls; +using Xunit.Abstractions; + +[assembly: CollectionBehavior(DisableTestParallelization = true)] + +namespace CDPIUI.TrayIcon.Tests; + +public sealed class ModernButtonFontLifetimeTests(ITestOutputHelper output) +{ + [Theory] + [InlineData("Exit", false, false, false)] + [InlineData("Выход", false, false, false)] + [InlineData("Exit", true, true, true)] + [InlineData("Выход", true, true, true)] + [InlineData("Exit", true, false, false)] + [InlineData("Выход", true, false, false)] + [InlineData("Exit", false, true, false)] + [InlineData("Выход", false, true, false)] + [InlineData("Exit", true, false, true)] + [InlineData("Выход", true, false, true)] + public void BoldAssignmentsKeepTheActualCaptionDrawable(string caption, bool first, bool second, bool third) + { + output.WriteLine(RuntimeInformation.FrameworkDescription); + WriteAssemblyIdentity(typeof(Control).Assembly); + WriteAssemblyIdentity(typeof(Font).Assembly); + WriteAssemblyIdentity(typeof(ModernButtonUserControl).Assembly); + + RunOnStaThread(() => + { + // Construct only this control. Do not run the tray entry point or create a visible window. + using var button = new ModernButtonUserControl { DisplayText = caption }; + var label = Assert.Single(button.Controls.OfType