Skip to content

Free, open-source Windows optimization tool for performance, privacy, and simplicity.

i18n: update and add missing translation values (using Artificial Intelligence xd)

fatDuckd97f5c7062e9
diff --git a/.agents/skills/resx-translation/SKILL.md b/.agents/skills/resx-translation/SKILL.md
index 47cdeba..3c34848 100644
--- a/.agents/skills/resx-translation/SKILL.md
+++ b/.agents/skills/resx-translation/SKILL.md
@@ -5,138 +5,292 @@ description: Translate, extend, and create `.resx` localization files for .NET a
# Resx Translation
-The goal of this skill is to translate `.resx` files with product-aware context, preserve the resource structure, and change only what needs to be changed.
+## Golden Rule: Use helpers, NEVER `read` the full file
-## When to use it
+**Do NOT use `read`/`glob`/`grep`** to discover files, check encoding, or audit translations.
+Use the helper scripts — they return structured data in <10 lines, saving hundreds of tokens.
-Use this skill when the user wants to:
+**Never `read` an entire `.resx` file.** Files can exceed 100k tokens.
+Use `(filename:line)` annotations from `audit_translations.py` to `read` only the relevant lines:
-- Translate a `.resx` file into another language
-- Fill in missing strings in an existing localized file
-- Add a new resource file for a language code like `vi`, `ja`, or `fr-FR`
-- Update translations for a WPF, WinForms, .NET, or any app that uses `.resx`
+```
+# audit shows: - AppTitle = 'OptimizerDuck' (Translations.resx:42)
+read Translations.vi.resx offset=42 limit=5
+read Translations.resx offset=42 limit=5
+```
-## Workflow
-
-### 1. Understand the project before translating
-
-Before editing any file, inspect the project to understand what kind of app it is, who it is for, and what domain it belongs to. Prefer reading files like `README`, project files, UI screens, settings, menus, view models, or any code that reveals domain context so the translation sounds natural.
-
-The point is to avoid overly literal translations when the domain needs more specialized language. For example:
-
-- music apps: keep terms like playlist, mix, mastering, or equalizer when appropriate
-- configuration/system apps: prefer concise, professional, technical wording
-- business apps: prefer clarity, stability, and consistent business terminology
+Only `read` 1-5 lines around each flagged key — never the whole file.
-### 2. Identify the source resx file and its real format
+---
-Check the default/source resx file first. Priority order:
+## Helper Scripts Reference
-1. `Translations.resx` if it exists
-2. Any `*.resx` file that does not include a language code in the filename
-3. If the project uses English as a base language, also inspect `*.en.resx` if useful
+All scripts are in `<skill>\helpers\`. Replace `<skill>` with the skill base path (run `codegraph_node resx-translation` or check `.agents/skills/resx-translation`).
-The goal is to understand:
+---
-- the filename and naming convention
-- whether the project uses patterns like `Name.resx`, `Name.vi.resx`, `Name.ja.resx`, or something else
-- XML formatting, line breaks, node order, spacing, and any existing conventions
-- the file encoding and whether it uses BOM, UTF-8, UTF-16, or another existing pattern
-- which strings are actually user-facing text and which are metadata or technical values
+### `find_resx.py` — Discover `.resx` files, encoding, Designer.cs status
+
+**What it does**: Lists all `.resx` files in a directory — key count, encoding (UTF-8 with/without BOM), file size, and whether `.Designer.cs` is in sync. Use this **instead of** `glob` + `read`.
+
+**Usage**:
+```powershell
+python <skill>\helpers\find_resx.py Resources\Languages
+```
+
+**Flags**:
+| Flag | Description |
+|------|-------------|
+| `--json` | Output as JSON for programmatic use |
+| (none) | Human-readable table |
+
+**Output**:
+```
+════════════════════════
+resx discovery
+════════════════════════
+ directory: Resources\Languages
+ default : Translations.resx
+ pattern : Translations.*.resx
+ files : 3
+
+ Translations.resx
+ keys : 45
+ size : 3200 bytes
+ encoding: UTF-8 with BOM
+ designer: Translations.Designer.cs (synced)
+
+ Translations.vi.resx
+ keys : 30
+ size : 2400 bytes
+ encoding: UTF-8 with BOM
+ designer: (none)
+```
+
+**Next step**:
+- If adding a new locale → `create_locale.py`.
+- If auditing/translating → `audit_translations.py`.
-Follow the existing format. Do not regroup, reorder, reformat, add comments, or beautify the file unless the original file already does that.
+---
-Preserve encoding carefully. When saving `.resx` files, avoid introducing encoding changes unless there is a clear reason. Match the existing file encoding whenever possible so the XML declaration, localized characters, and tooling behavior stay stable.
+### `audit_translations.py` — Find missing / empty / untranslated keys
+
+**What it does**: Compares all locale files against the union of all keys. Reports keys that are **missing** (absent from a locale), **empty** (present but blank), or **untranslated** (identical to the default file). Use this **instead of** manually diffing files.
+
+**Usage**:
+```powershell
+python <skill>\helpers\audit_translations.py Resources\Languages --auto-detect --show-missing --show-untranslated
+```
+
+**Flags**:
+| Flag | Description |
+|------|-------------|
+| `--show-missing` | Keys absent from a locale that exist in others |
+| `--show-empty` | Keys with empty values |
+| `--show-untranslated` | Keys whose value matches the default file |
+| `--by-key` | Group results by key name instead of by locale |
+| `--fail-on-any` | Exit code 1 if any issues found (CI gate) |
+| `--auto-detect` | Auto-detect file pattern from directory |
+| `--check-designer` | Also audit `.Designer.cs` for missing/stale properties |
+| `--default-file` | Custom base filename (e.g. `Strings.resx`) |
+| `--pattern` | Custom locale glob (e.g. `Strings.*.resx`) |
+
+**Output** (with `--show-missing --show-untranslated`):
+```
+════════════════════════
+translation audit
+════════════════════════
+
+ [vi]
+ missing=15 | untranslated=5
+
+ missing keys (15):
+ - AppTitle = 'OptimizerDuck' (Translations.resx:42)
+ - ButtonCancel = 'Cancel' (Translations.resx:55)
+ ...
+
+ untranslated values (5):
+ - LabelStatus (Translations.vi.resx:120)
+ - TextWelcome (Translations.vi.resx:135)
+ ...
+
+ [ja]
+ ok
+
+════════════════════════
+summary
+════════════════════════
+ locales: 3
+ keys : 45
+ pattern: Translations.*.resx
+ missing: 15
+ untranslated: 5
+```
+
+**Clean output** (no issues):
+```
+ all translations look good across all locales
+```
+
+**Next step**:
+- Issues found → use `question` tool to ask user which locale → `read` that file + source → translate only flagged keys.
+- Clean → nothing to do.
-### 3. Check whether language support also needs code or settings updates
+---
-Do not stop at the `.resx` files. When the user asks to add a new language, also inspect the project for any language-selection or localization plumbing that must be updated so the new locale can actually appear and be used in the app.
+### `create_locale.py` — Add a new language file
-Look for related code such as:
+**What it does**: Duplicates the source `.resx` into a new locale file (e.g. `Translations.vi.resx`). Uses `shutil.copy2` to preserve exact encoding, BOM, metadata. **30x faster** than reading + rewriting XML.
-- settings pages or language dropdowns
-- supported language lists or culture registries
-- localization services, resource managers, or startup configuration
-- menu items, options screens, or app preferences tied to language selection
+**Usage**:
+```powershell
+python <skill>\helpers\create_locale.py Resources\Languages --locale vi
+```
-If the project requires these updates, make them together with the new `.resx` file. If the project already discovers languages automatically, avoid unnecessary code changes.
+**Flags**:
+| Flag | Description |
+|------|-------------|
+| `--locale` | **(Required)** Language code: `vi`, `ja`, `fr-FR`, `de`, etc. |
+| `--source` | Source filename (default: auto-detected base `.resx`) |
+| `--dry-run` | Preview without creating |
-### 4. Determine the request type
+**Output**:
+```
+Created: Translations.vi.resx (45 keys copied from Translations.resx)
+```
-Clearly distinguish between these two cases:
+If the file already exists:
+```
+already exists: Translations.vi.resx
+```
-- **Extend/fill an existing language**: update the existing localized file and translate only what is needed
-- **Create a new language**: duplicate the source file into a new file with the requested language code, then translate each entry
+**Next step**: Translate ALL values in the new file → run `sync_resx.py --fill-source` to catch any keys added to source after creation.
-If the user's request is explicit, follow it. If the request is ambiguous but the files make the intent obvious, prefer the least disruptive path: extend an existing localized file if it already exists; otherwise create a new one when the requested language code does not exist.
+---
-### 5. If the task is to extend an existing language
+### `sync_resx.py` — Propagate new keys from source to locales
+
+**What it does**: Copies newly added keys from the source `.resx` into all (or a specific) locale files. New `<data>` elements are inserted before `</root>`, preserving XML structure and indentation.
+
+**Usage**:
+```powershell
+python <skill>\helpers\sync_resx.py Resources\Languages --fill-source
+```
+
+**Flags**:
+| Flag | Description |
+|------|-------------|
+| `--fill-source` | Copy source value as-is (English fallback) |
+| `--fill-marker "TODO"` | Fill with a marker string instead |
+| (no fill flags) | Fill with empty string |
+| `--locale vi-VN` | Target a specific locale only |
+| `--dry-run` | Preview without writing |
+| `--source` | Custom source filename |
+| `--target` | Custom locale glob pattern |
+
+**Output**:
+```
+════════════════════════
+resx sync
+════════════════════════
+ Translations.vi.resx: added 3 key(s) (vi)
+ Translations.ja.resx: ok (already up to date)
+
+════════════════════════
+result
+════════════════════════
+ total keys added: 3
+```
+
+**Next step**:
+- `--fill-source` → those keys have English text and need translation → run `audit_translations.py --show-untranslated` to find them.
+- `--fill-marker "TODO"` → search for and translate markers.
-Read the existing localized file together with the source file, then translate entries that are missing, still left in the source language, or clearly wrong for the project context.
+---
-Prefer targeted edits. If the localized file already exists, update only missing, source-language, or clearly incorrect entries unless the user explicitly asks for a full translation pass or a rewrite of the whole locale.
+## Task Dispatch: Determine what the user needs
-When extending translations:
+| User says (Vietnamese) | Meaning | Action |
+|---|---|---|
+| *"dịch các translation còn thiếu"* / *"translate missing translations"* | Fill only missing/untranslated keys | Run `audit` → ask → translate **only flagged keys** |
+| *"dịch ngôn ngữ mới"* / *"add new language"* | Brand new locale | `create_locale.py` → translate **all keys** |
+| *"dịch các translation"* / *"translate translations"* | General translate request | Run `audit` → find untranslated → ask → translate |
+| *"cập nhật translations"* / *"update translations"* | Sync + translate new keys | `sync_resx.py` → `audit` → translate untranslated |
-- keep the original meaning but prefer wording that fits the product context
-- do not translate word-for-word mechanically
-- respect the tone of the existing localized file if it is already good
-- keep terminology consistent within the file and across the project
+---
-### 6. If the task is to create a new language
+## Workflow
-Duplicate the source `.resx` file into a new file using the requested language code. Example: `Translations.resx` -> `Translations.vi.resx`.
+### 0. Always ask before translating
-Then translate each translatable entry in the new file while preserving the XML structure and all attributes from the source.
+**Before any translation work**, use the `question` tool to:
-### 7. File update strategy
+1. **If multiple locales have issues**: Ask which locale(s) to work on
+2. **Confirm the approach**: Describe what `audit` found and what you plan to do (how many keys, which file)
+3. **Domain context**: If the app has specialized terminology, ask about preferred translations
-Apply changes in the least disruptive way that still keeps the file correct.
+This prevents wasted work. Example:
-- For small files or narrowly scoped edits, direct rewrite is fine if you can preserve the exact structure and encoding.
-- For larger files, prefer targeted updates that touch only the specific entries that need translation instead of regenerating or rewriting the whole file.
-- Avoid full-file rewrites when the task is only to fill missing entries or correct a subset of strings.
-- Preserve ordering, indentation, XML declaration, and surrounding nodes so diffs stay small and reviewable.
+> `audit` shows `vi` has 15 missing and 5 untranslated keys out of 45 total.
+> `ja` is fully translated.
+> Should I proceed with translating `vi` only?
-The goal is to keep the change set precise, safe, and easy for the user to review.
+---
-### 8. Translation rules
+### A. "Dịch các translation còn thiếu" — Fill Missing Translations
-Translate only the user-facing text. Do not change keys, node names, attributes, or XML structure.
+1. **Run `audit_translations.py --show-missing --show-untranslated`** to find issues
+2. **Ask user** (via `question`): which locale, confirm scope
+3. **`read` only specific lines** in the locale file + source file using line numbers from the audit output (e.g., `read Translations.vi.resx offset=42 limit=5`)
+4. **Translate only flagged keys** — skip everything else
+5. Report: which file, language, how many keys translated
-Preserve exactly:
+---
-- placeholders such as `{0}`, `{1}`, `%s`, `%d`
-- markup, HTML, XAML fragments, newline markers, and escaped characters
-- product names, feature names, shortcuts, error codes, commands, and any terminology that should remain unchanged in context
-- empty strings or technical strings that are not user-facing, unless the source file shows they are meant to be localized
+### B. "Dịch ngôn ngữ mới" — Add New Language
-Be careful with short strings like `Open`, `Save`, `Apply`, `Reset`, `Close`, `Track`, `Mix`, `Profile`, `Library`, `Device`, and `Output`, because the right translation depends heavily on the screen and domain. If needed, inspect nearby code or UI context before deciding.
+1. **Run `find_resx.py`** to see existing files and encoding
+2. **Ask user**: confirm language code + any domain-specific preferences
+3. **Run `create_locale.py --locale <code>`** to create the file
+4. **Translate ALL values** in the new file
+5. **Run `sync_resx.py --fill-source`** to catch any keys added after creation
+6. Report: file created, language, key count
-Keep English terms unchanged when they function more like product language, technical labels, or domain-specific jargon than ordinary UI text. This often applies to terms such as `Playlist`, `Profile`, `Output`, `Driver`, `Theme`, and `Preset` when the surrounding product language, target audience, or existing translations suggest they should stay in English. Translate them only when the app clearly treats them as normal user-facing words in the target locale and the rest of the product uses localized equivalents consistently.
+---
-### 9. File editing behavior
+### C. "Dịch các translation" — Translate Existing Translations
-Edit the target file directly. Do not add explanations into the file. Do not add comments. Do not create translation tables. Do not regroup entries. Do not change casing style, indentation, or layout unless the original file already follows a specific pattern.
+1. **Run `audit_translations.py --show-untranslated`** to find untranslated keys
+2. **Ask user** (via `question`): which locale(s), confirm scope
+3. **`read` only specific lines** in the locale file + source file using line numbers from the audit output
+4. **Translate only untranslated keys**
+5. Report: file, language, keys translated
-If you report back to the user, keep it brief and focus on:
+---
-- which file was updated
-- which file was created, if any
-- which language was added or extended
+## Translation Rules
-## Suggested execution order
+- Translate **only user-facing text**. Never change keys, node names, attributes, or XML structure.
+- Preserve exactly: `{0}`, `{1}`, `%s` placeholders; HTML/XAML fragments; product names; error codes; escaped characters.
+- Short strings (`Open`, `Save`, `Apply`, `Reset`, etc.) depend on screen context — inspect nearby code if unsure.
+- Keep English terms when they function as product language (`Playlist`, `Profile`, `Driver`, `Theme`, `Preset`) unless the app consistently localizes them.
+- Preserve original encoding (UTF-8 with/without BOM).
-1. Understand the project and domain
-2. Find the source resx file and any related localized files
-3. Check whether language settings or localization code also need updates
-4. Determine whether this is an extension task or a new-language task
-5. Update or create the correct file using the project's naming convention
-6. Translate strings with domain-aware wording while preserving format and encoding
-7. Recheck placeholders, XML integrity, terminology consistency, and any required language-selection wiring before finishing
+## Editing Behavior
-## Expected output
+- Edit the target file directly using `edit` tool.
+- No explanations, comments, translation tables, or layout changes added to the file.
+- Preserve ordering, indentation, XML declaration, surrounding nodes.
+- Report back briefly: which file was updated/created, language, key count.
-The main output is an updated `.resx` file that preserves the original format.
+## Quick Reference
-If you respond in chat, keep the response short and focused on the file result.
+| Need | Command |
+|---|---|
+| See all `.resx` files, encoding, Designer.cs | `find_resx.py <dir>` |
+| Find missing / untranslated keys | `audit_translations.py <dir> --show-missing --show-untranslated` |
+| Find empty values | `audit_translations.py <dir> --show-empty` |
+| Create new locale | `create_locale.py <dir> --locale <code>` |
+| Sync new keys to locales | `sync_resx.py <dir> --fill-source` |
+| Preview sync | `sync_resx.py <dir> --fill-marker "TODO" --dry-run` |
+| CI check | `audit_translations.py <dir> --fail-on-any` |
diff --git a/.agents/skills/resx-translation/helpers/audit_translations.py b/.agents/skills/resx-translation/helpers/audit_translations.py
new file mode 100644
index 0000000..4be0ad8
--- /dev/null
+++ b/.agents/skills/resx-translation/helpers/audit_translations.py
@@ -0,0 +1,263 @@
+# audit_translations.py — Audit .resx locale files for missing, empty, or untranslated keys
+
+from __future__ import annotations
+
+try:
+ import argparse
+ import sys
+ from pathlib import Path
+except ImportError as ex:
+ print(f"failed to import required module: {ex}")
+ raise SystemExit(1)
+
+sys.path.insert(0, str(Path(__file__).resolve().parent))
+from resx_helpers import (
+ auto_detect_pattern,
+ compute_issues,
+ ensure_utf8,
+ find_designer,
+ get_union_keys,
+ load_designer_keys,
+ load_resx,
+ load_resx_with_lines,
+ print_header,
+ resx_key_to_property,
+)
+
+
+def parse_args() -> argparse.Namespace:
+ p = argparse.ArgumentParser(description="Audit .resx translation files across all locales.")
+
+ p.add_argument("path", type=Path, help="Path to the translations directory")
+
+ p.add_argument("--default-file", default=None, help="Base .resx filename (default: auto-detected)")
+ p.add_argument("--pattern", default=None, help="Glob pattern for locale files (default: auto-detected)")
+ p.add_argument("--auto-detect", action="store_true", help="Auto-detect file pattern from directory")
+
+ p.add_argument("--show-missing", action="store_true", help="Show keys present in other locales but missing")
+ p.add_argument("--show-empty", action="store_true", help="Show keys with empty values")
+ p.add_argument("--show-untranslated", action="store_true", help="Show keys matching the default file value")
+
+ p.add_argument("--by-key", action="store_true", help="Group results by key name")
+ p.add_argument("--fail-on-any", action="store_true", help="Exit code 1 if any issues found")
+ p.add_argument("--check-designer", action="store_true", help="Check .Designer.cs for missing properties")
+
+ return p.parse_args()
+
+
+def designer_check(base: Path, default_name: str, all_keys: set[str]) -> None:
+ designer = find_designer(base, default_name)
+ if not designer:
+ print("\n [designer] no .Designer.cs found")
+ return
+
+ props = load_designer_keys(designer)
+ resx_props = {resx_key_to_property(k) for k in all_keys}
+ missing = sorted(resx_props - props)
+ stale = sorted(props - resx_props)
+
+ if not missing and not stale:
+ print(f"\n [designer] {designer.name}: ok ({len(props)} properties)")
+ return
+
+ if stale:
+ print(f"\n [designer] {designer.name}: {len(stale)} stale propert(y/ies) (in .Designer.cs but not in .resx):")
+ for s in stale:
+ print(f" - {s}")
+
+ if missing:
+ print(f"\n [designer] {designer.name}: {len(missing)} missing propert(y/ies) (in .resx but not in .Designer.cs):")
+ for m in missing:
+ print(f" - {m}")
+
+ print(" (regenerate by rebuilding the project or running ResGen)")
+
+
+def main():
+ try:
+ args = parse_args()
+ ensure_utf8()
+ base = args.path.resolve()
+
+ if not base.exists() or not base.is_dir():
+ print(f"directory not found:\n{base}")
+ sys.exit(1)
+
+ if args.auto_detect or not args.default_file:
+ default_name, pattern, detected = auto_detect_pattern(base)
+ default_name = args.default_file or default_name
+ pattern = args.pattern or pattern
+ else:
+ default_name = args.default_file
+ pattern = args.pattern or default_name.replace(".resx", ".*.resx")
+
+ if not pattern:
+ print("no locale pattern could be determined")
+ sys.exit(1)
+
+ default_path = base / default_name
+ default_data = load_resx(default_path) if default_path.exists() else {}
+ default_lang = None
+
+ locale_data: dict[str, dict[str, str]] = {}
+ locale_line_data: dict[str, dict[str, int]] = {}
+ locale_filenames: dict[str, str] = {}
+ for fp in sorted(base.glob(pattern)):
+ lang = fp.stem.split(".", 1)[1] if "." in fp.stem else fp.stem
+ result = load_resx_with_lines(fp)
+ if result is not None:
+ values = {}
+ lines_map = {}
+ for k, (v, ln) in result.items():
+ values[k] = v
+ lines_map[k] = ln
+ locale_data[lang] = values
+ locale_line_data[lang] = lines_map
+ locale_filenames[lang] = fp.name
+ if fp.name == default_name:
+ default_lang = lang
+
+ if default_data and default_lang is None:
+ default_lang = Path(default_name).stem
+ locale_data[default_lang] = default_data
+ locale_filenames[default_lang] = default_name
+ default_with_lines = load_resx_with_lines(default_path)
+ if default_with_lines is not None:
+ locale_line_data[default_lang] = {k: ln for k, (_, ln) in default_with_lines.items()}
+
+ if not locale_data:
+ print(f"no files matching '{pattern}' in {base}")
+ sys.exit(1)
+
+ all_keys = get_union_keys(locale_data)
+ if not all_keys:
+ print("all loaded files are empty")
+ sys.exit(1)
+
+ issues = compute_issues(locale_data, default_data, default_lang)
+
+ totals = {
+ kind: sum(len(issues[l][kind]) for l in locale_data)
+ for kind in ("missing", "empty", "untranslated")
+ }
+ any_issues = any(issues[l][k] for l in locale_data for k in ("missing", "empty", "untranslated"))
+ show_flags = args.show_missing or args.show_empty or args.show_untranslated
+ names = sorted(locale_data)
+
+ print_header("translation audit")
+
+ if not any_issues:
+ print("\n all translations look good across all locales")
+ print_header("summary")
+ print(f" locales: {len(names)}")
+ print(f" keys : {len(all_keys)}")
+ print(f" pattern: {pattern}")
+ if args.check_designer:
+ designer_check(base, default_name, all_keys)
+ return
+
+ if args.by_key:
+ key_map: dict[str, list[str]] = {}
+ for lang in names:
+ iss = issues[lang]
+ if args.show_missing:
+ for k in iss["missing"]:
+ key_map.setdefault(k, []).append(f"{lang}:missing")
+ if args.show_empty:
+ for k in iss["empty"]:
+ key_map.setdefault(k, []).append(f"{lang}:empty")
+ if args.show_untranslated:
+ for k in iss["untranslated"]:
+ key_map.setdefault(k, []).append(f"{lang}:untranslated")
+
+ if not show_flags:
+ for lang in names:
+ for kind in ("missing", "empty", "untranslated"):
+ for k in issues[lang][kind]:
+ key_map.setdefault(k, []).append(f"{lang}:{kind}")
+
+ print(f"\n {len(key_map)} key(s) with issues across {len(names)} locale(s)")
+ for key in sorted(key_map):
+ default_file = locale_filenames.get(default_lang, default_name) if default_lang else default_name
+ line_num = locale_line_data.get(default_lang, {}).get(key, 0)
+ line_str = f" ({default_file}:{line_num})" if line_num else ""
+ print(f"\n {key}{line_str}")
+ for entry in sorted(key_map[key]):
+ print(f" - {entry}")
+ else:
+ for lang in names:
+ iss = issues[lang]
+ missing = iss["missing"]
+ empty = iss["empty"]
+ untranslated = iss["untranslated"]
+
+ print(f"\n [{lang}]")
+ if not missing and not empty and not untranslated:
+ print(" ok")
+ continue
+
+ parts = []
+ if missing:
+ parts.append(f"missing={len(missing)}")
+ if empty:
+ parts.append(f"empty={len(empty)}")
+ if untranslated:
+ parts.append(f"untranslated={len(untranslated)}")
+ print(" " + " | ".join(parts))
+
+ if args.show_missing and missing:
+ print(f"\n missing keys ({len(missing)}):")
+ for key in missing:
+ sample = None
+ for olang in names:
+ if olang != lang and key in locale_data[olang]:
+ sample = locale_data[olang][key]
+ break
+ default_file = locale_filenames.get(default_lang, default_name) if default_lang else default_name
+ line_num = locale_line_data.get(default_lang, {}).get(key, 0)
+ line_str = f" ({default_file}:{line_num})" if line_num else ""
+ if sample is not None:
+ print(f" - {key} = {sample!r}{line_str}")
+ else:
+ print(f" - {key}{line_str}")
+
+ if args.show_empty and empty:
+ print(f"\n empty values ({len(empty)}):")
+ for k in empty:
+ locale_file = locale_filenames.get(lang, f"{lang}.resx")
+ line_num = locale_line_data.get(lang, {}).get(k, 0)
+ line_str = f" ({locale_file}:{line_num})" if line_num else ""
+ print(f" - {k}{line_str}")
+
+ if args.show_untranslated and untranslated:
+ print(f"\n untranslated values ({len(untranslated)}):")
+ for k in untranslated:
+ locale_file = locale_filenames.get(lang, f"{lang}.resx")
+ line_num = locale_line_data.get(lang, {}).get(k, 0)
+ line_str = f" ({locale_file}:{line_num})" if line_num else ""
+ print(f" - {k}{line_str}")
+
+ print_header("summary")
+ print(f" locales: {len(names)}")
+ print(f" keys : {len(all_keys)}")
+ print(f" pattern: {pattern}")
+ for kind in ("missing", "empty", "untranslated"):
+ if totals[kind]:
+ print(f" {kind}: {totals[kind]}")
+
+ if args.check_designer:
+ designer_check(base, default_name, all_keys)
+
+ if args.fail_on_any and any(totals.values()):
+ sys.exit(1)
+
+ except KeyboardInterrupt:
+ print("\ncancelled")
+ sys.exit(130)
+ except Exception as ex:
+ print(f"\nfatal: {ex}")
+ sys.exit(1)
+
+
+if __name__ == "__main__":
+ main()
diff --git a/.agents/skills/resx-translation/helpers/create_locale.py b/.agents/skills/resx-translation/helpers/create_locale.py
new file mode 100644
index 0000000..7689756
--- /dev/null
+++ b/.agents/skills/resx-translation/helpers/create_locale.py
@@ -0,0 +1,72 @@
+# create_locale.py — Create a new locale .resx file from the source
+
+from __future__ import annotations
+
+import argparse
+import sys
+import shutil
+from pathlib import Path
+
+sys.path.insert(0, str(Path(__file__).resolve().parent))
+from resx_helpers import auto_detect_pattern, ensure_utf8, load_resx
+
+
+def main():
+ try:
+ parser = argparse.ArgumentParser(
+ description="Create a new locale .resx file from the source."
+ )
+ parser.add_argument("path", type=Path, help="Translations directory")
+ parser.add_argument("--locale", required=True,
+ help="Language code (e.g. vi, ja, fr-FR)")
+ parser.add_argument("--source", default=None,
+ help="Source .resx (default: auto-detected base file)")
+ parser.add_argument("--dry-run", action="store_true",
+ help="Preview without creating")
+ args = parser.parse_args()
+
+ ensure_utf8()
+ base = args.path.resolve()
+
+ if not base.exists() or not base.is_dir():
+ print(f"directory not found: {base}")
+ sys.exit(1)
+
+ default_name, _, _ = auto_detect_pattern(base)
+ source_name = args.source or default_name
+ source_path = base / source_name
+
+ if not source_path.exists():
+ print(f"source not found: {source_path}")
+ sys.exit(1)
+
+ stem = Path(source_name).stem
+ ext = Path(source_name).suffix
+ new_name = f"{stem}.{args.locale}{ext}"
+ new_path = base / new_name
+
+ if new_path.exists():
+ print(f"already exists: {new_name}")
+ sys.exit(1)
+
+ source_data = load_resx(source_path)
+ if source_data is None:
+ sys.exit(1)
+
+ if args.dry_run:
+ print(f"[dry-run] would create: {new_name} ({len(source_data)} keys from {source_name})")
+ return
+
+ shutil.copy2(source_path, new_path)
+ print(f"Created: {new_name} ({len(source_data)} keys copied from {source_name})")
+
+ except KeyboardInterrupt:
+ print("\ncancelled")
+ sys.exit(130)
+ except Exception as ex:
+ print(f"\nfatal: {ex}")
+ sys.exit(1)
+
+
+if __name__ == "__main__":
+ main()
diff --git a/.agents/skills/resx-translation/helpers/find_resx.py b/.agents/skills/resx-translation/helpers/find_resx.py
new file mode 100644
index 0000000..7c9e168
--- /dev/null
+++ b/.agents/skills/resx-translation/helpers/find_resx.py
@@ -0,0 +1,131 @@
+# find_resx.py — Discover .resx files, naming patterns, and Designer.cs bindings
+
+from __future__ import annotations
+
+try:
+ import argparse
+ import json
+ import sys
+ from pathlib import Path
+except ImportError as ex:
+ print(f"failed to import required module: {ex}")
+ raise SystemExit(1)
+
+sys.path.insert(0, str(Path(__file__).resolve().parent))
+from resx_helpers import (
+ auto_detect_pattern,
+ ensure_utf8,
+ find_designer,
+ load_designer_keys,
+ load_resx,
+ print_header,
+ resx_key_to_property,
+)
+
+
+def detect_encoding(path: Path) -> str:
+ raw = path.read_bytes()
+ if raw[:3] == b"\xef\xbb\xbf":
+ return "UTF-8 with BOM"
+ return "UTF-8 (no BOM)" if raw[:5] == b"<?xml" else "unknown"
+
+
+def scan(base: Path) -> list[dict]:
+ if not base.is_dir():
+ print(f"not a directory: {base}")
+ sys.exit(1)
+
+ all_resx = sorted(base.glob("*.resx"))
+ if not all_resx:
+ return []
+
+ default_name, pattern, _ = auto_detect_pattern(base)
+
+ result = []
+ for rp in all_resx:
+ data = load_resx(rp)
+ if data is None:
+ continue
+
+ info = {
+ "file": rp.name,
+ "size": rp.stat().st_size,
+ "encoding": detect_encoding(rp),
+ "keys": len(data),
+ }
+
+ designer = find_designer(base, rp.name)
+ if designer:
+ props = load_designer_keys(designer)
+ resx_props = {resx_key_to_property(k) for k in data}
+ info["designer"] = designer.name
+ info["designer_props"] = len(props)
+ info["synced"] = props == resx_props
+ out_of_sync = (resx_props - props) | (props - resx_props)
+ info["out_of_sync_count"] = len(out_of_sync)
+
+ result.append(info)
+
+ return result
+
+
+def main():
+ try:
+ parser = argparse.ArgumentParser(
+ description="Discover .resx files, naming patterns, and Designer.cs bindings."
+ )
+ parser.add_argument("path", nargs="?", type=Path, default=Path("."),
+ help="Translations directory (default: current)")
+ parser.add_argument("--json", action="store_true", help="Output as JSON")
+ args = parser.parse_args()
+
+ ensure_utf8()
+ base = args.path.resolve()
+
+ if not base.exists():
+ print(f"directory not found: {base}")
+ sys.exit(1)
+
+ default_name, pattern, _ = auto_detect_pattern(base)
+ files = scan(base)
+
+ if not files:
+ print(f"no .resx files found in {base}")
+ sys.exit(0)
+
+ if args.json:
+ json.dump({"default": default_name, "pattern": pattern, "files": files},
+ sys.stdout, indent=2)
+ print()
+ return
+
+ print_header("resx discovery")
+ print(f" directory: {base}")
+ print(f" default : {default_name}")
+ print(f" pattern : {pattern}")
+ print(f" files : {len(files)}")
+
+ for info in files:
+ designer = info.get("designer")
+ synced = info.get("synced")
+ if designer:
+ status = "synced" if synced else f"{info['out_of_sync_count']} out of sync"
+ else:
+ status = "no Designer.cs"
+
+ print(f"\n {info['file']}")
+ print(f" keys : {info['keys']}")
+ print(f" size : {info['size']} bytes")
+ print(f" encoding: {info['encoding']}")
+ print(f" designer: {designer or '(none)'} ({status})")
+
+ except KeyboardInterrupt:
+ print("\ncancelled")
+ sys.exit(130)
+ except Exception as ex:
+ print(f"\nfatal: {ex}")
+ sys.exit(1)
+
+
+if __name__ == "__main__":
+ main()
diff --git a/.agents/skills/resx-translation/helpers/resx_helpers.py b/.agents/skills/resx-translation/helpers/resx_helpers.py
new file mode 100644
index 0000000..c55f2b1
--- /dev/null
+++ b/.agents/skills/resx-translation/helpers/resx_helpers.py
@@ -0,0 +1,170 @@
+# resx_helpers.py — Shared utilities for resx translation tools
+
+from __future__ import annotations
+
+import io
+import re
+import sys
+import xml.etree.ElementTree as ET
+from pathlib import Path
+from xml.sax.saxutils import escape as xml_escape
+
+DESIGNER_PROP_RE = re.compile(r'internal\s+static\s+string\s+(\w+)')
+
+
+def ensure_utf8() -> None:
+ try:
+ sys.stdout = io.TextIOWrapper(sys.stdout.buffer, encoding="utf-8")
+ except Exception:
+ pass
+
+
+def load_resx(path: Path) -> dict[str, str] | None:
+ try:
+ tree = ET.parse(path)
+ except (FileNotFoundError, ET.ParseError, PermissionError) as ex:
+ print(f" [error] {path.name}: {ex}", file=sys.stderr)
+ return None
+ except Exception as ex:
+ print(f" [error] unexpected: {path.name}: {ex}", file=sys.stderr)
+ return None
+
+ result = {}
+ for data in tree.getroot().findall("data"):
+ name = data.get("name")
+ if name:
+ val = data.findtext("value")
+ result[name] = (val or "").strip()
+ return result
+
+
+def load_resx_with_lines(path: Path) -> dict[str, tuple[str, int]] | None:
+ try:
+ tree = ET.parse(path)
+ except (FileNotFoundError, ET.ParseError, PermissionError) as ex:
+ print(f" [error] {path.name}: {ex}", file=sys.stderr)
+ return None
+ except Exception as ex:
+ print(f" [error] unexpected: {path.name}: {ex}", file=sys.stderr)
+ return None
+
+ try:
+ lines = path.read_text(encoding="utf-8-sig").splitlines()
+ except Exception as ex:
+ print(f" [error] scanning {path.name}: {ex}", file=sys.stderr)
+ return None
+
+ key_lines: dict[str, int] = {}
+ for i, line in enumerate(lines, 1):
+ m = re.search(r'<data\s+name="([^"]*)"', line)
+ if m:
+ key_lines[m.group(1)] = i
+
+ result: dict[str, tuple[str, int]] = {}
+ for data in tree.getroot().findall("data"):
+ name = data.get("name")
+ if name:
+ val = data.findtext("value")
+ result[name] = ((val or "").strip(), key_lines.get(name, 0))
+
+ return result
+
+
+def extract_lang(filepath: Path) -> str:
+ stem = filepath.stem
+ parts = stem.split(".", 1)
+ return parts[1] if len(parts) > 1 else parts[0]
+
+
+def auto_detect_pattern(directory: Path) -> tuple[str, str, list[Path]]:
+ all_resx = sorted(directory.glob("*.resx"))
+ if not all_resx:
+ return ("Translations.resx", "Translations.*.resx", [])
+
+ no_lang = [f for f in all_resx if "." not in f.stem]
+ has_lang = [f for f in all_resx if "." in f.stem]
+ default = no_lang[0].name if no_lang else all_resx[0].name
+
+ base_stem = Path(default).stem
+ pattern = f"{base_stem}.*.resx" if has_lang else default.replace(".resx", ".*.resx")
+ return default, pattern, has_lang
+
+
+def find_designer(base_dir: Path, resx_name: str) -> Path | None:
+ candidate = base_dir / resx_name.replace(".resx", ".Designer.cs")
+ return candidate if candidate.exists() else None
+
+
+def load_designer_keys(designer_path: Path) -> set[str]:
+ try:
+ text = designer_path.read_text(encoding="utf-8")
+ except Exception as ex:
+ print(f" [error] reading {designer_path.name}: {ex}", file=sys.stderr)
+ return set()
+ return {m.group(1) for m in DESIGNER_PROP_RE.finditer(text)}
+
+
+def resx_key_to_property(key: str) -> str:
+ return key.replace(".", "_")
+
+
+def get_union_keys(locale_data: dict[str, dict[str, str]]) -> set[str]:
+ keys: set[str] = set()
+ for data in locale_data.values():
+ keys.update(data.keys())
+ return keys
+
+
+def compute_issues(
+ locale_data: dict[str, dict[str, str]],
+ default_data: dict[str, str],
+ default_lang: str | None,
+) -> dict[str, dict[str, list[str]]]:
+ all_keys = get_union_keys(locale_data)
+ issues: dict[str, dict[str, list[str]]] = {}
+ for lang, data in locale_data.items():
+ issues[lang] = {
+ "missing": sorted(all_keys - data.keys()),
+ "empty": sorted(k for k, v in data.items() if not v),
+ "untranslated": sorted(
+ k for k, v in data.items()
+ if lang != default_lang and k in default_data and v == default_data[k]
+ ),
+ }
+ return issues
+
+
+def print_header(title: str) -> None:
+ n = min(len(title), 72)
+ print(f"\n{'=' * n}")
+ print(title)
+ print("=" * n)
+
+
+def add_keys_to_resx(resx_path: Path, new_entries: dict[str, str]) -> int:
+ try:
+ content = resx_path.read_text(encoding="utf-8-sig")
+ except Exception as ex:
+ print(f" [error] reading {resx_path.name}: {ex}", file=sys.stderr)
+ return -1
+
+ existing = set(re.findall(r'<data\s+name="([^"]*)"', content))
+ to_add = {k: v for k, v in new_entries.items() if k not in existing}
+ if not to_add:
+ return 0
+
+ buf = []
+ for key, val in to_add.items():
+ escaped = xml_escape(val)
+ buf.append(f' <data name="{key}" xml:space="preserve">\n <value>{escaped}</value>\n </data>')
+
+ repl = "\n".join(buf) + "\n</root>"
+ new_content = content.replace("</root>", repl)
+
+ try:
+ resx_path.write_text(new_content, encoding="utf-8-sig")
+ except Exception as ex:
+ print(f" [error] writing {resx_path.name}: {ex}", file=sys.stderr)
+ return -1
+
+ return len(to_add)
diff --git a/.agents/skills/resx-translation/helpers/sync_resx.py b/.agents/skills/resx-translation/helpers/sync_resx.py
new file mode 100644
index 0000000..bdb5862
--- /dev/null
+++ b/.agents/skills/resx-translation/helpers/sync_resx.py
@@ -0,0 +1,123 @@
+# sync_resx.py — Synchronise missing keys from a source .resx into locale files
+
+from __future__ import annotations
+
+try:
+ import argparse
+ import sys
+ from pathlib import Path
+except ImportError as ex:
+ print(f"failed to import required module: {ex}")
+ raise SystemExit(1)
+
+sys.path.insert(0, str(Path(__file__).resolve().parent))
+from resx_helpers import (
+ add_keys_to_resx,
+ auto_detect_pattern,
+ ensure_utf8,
+ load_resx,
+ print_header,
+)
+
+
+def main():
+ try:
+ parser = argparse.ArgumentParser(
+ description="Sync missing keys from a source .resx into locale files."
+ )
+ parser.add_argument("path", type=Path, help="Translations directory")
+ parser.add_argument("--source", default=None,
+ help="Source .resx file (default: auto-detected base file)")
+ parser.add_argument("--target", default=None,
+ help="Target locale glob pattern (default: auto-detected)")
+ parser.add_argument("--fill-source", action="store_true",
+ help="Copy source value as-is (default: empty string)")
+ parser.add_argument("--fill-marker", default=None,
+ help="Fill with a marker string instead of empty (e.g. 'TODO')")
+ parser.add_argument("--dry-run", action="store_true",
+ help="Show what would be added without writing")
+ parser.add_argument("--locale", default=None,
+ help="Only sync a specific locale (e.g. 'vi-VN')")
+ args = parser.parse_args()
+
+ ensure_utf8()
+ base = args.path.resolve()
+
+ if not base.exists() or not base.is_dir():
+ print(f"directory not found: {base}")
+ sys.exit(1)
+
+ default_name, pattern, _ = auto_detect_pattern(base)
+ source_name = args.source or default_name
+ locale_pattern = args.target or pattern
+
+ source_path = base / source_name
+ if not source_path.exists():
+ print(f"source not found: {source_path}")
+ sys.exit(1)
+
+ source_data = load_resx(source_path)
+ if source_data is None:
+ sys.exit(1)
+
+ targets = sorted(base.glob(locale_pattern))
+ if args.locale:
+ targets = [t for t in targets if args.locale in t.stem]
+ if not targets:
+ print(f"no locale files matching '{args.locale}' in {base}")
+ sys.exit(1)
+
+ print_header("resx sync")
+
+ total_added = 0
+ for fp in targets:
+ if fp.name == source_name and not args.locale:
+ continue
+
+ locale_data = load_resx(fp)
+ if locale_data is None:
+ continue
+
+ missing = {k: v for k, v in source_data.items() if k not in locale_data}
+ if not missing:
+ print(f" {fp.name}: ok (no missing keys)")
+ continue
+
+ lang = fp.stem.split(".", 1)[1] if "." in fp.stem else fp.stem
+
+ if args.fill_source:
+ fill = {k: source_data[k] for k in missing}
+ elif args.fill_marker is not None:
+ fill = {k: args.fill_marker for k in missing}
+ else:
+ fill = {k: "" for k in missing}
+
+ if args.dry_run:
+ print(f" {fp.name}: would add {len(missing)} key(s)")
+ for k in sorted(missing):
+ print(f" + {k} = {fill[k]!r}")
+ continue
+
+ added = add_keys_to_resx(fp, fill)
+ if added > 0:
+ print(f" {fp.name}: added {added} key(s) ({lang})")
+ total_added += added
+ elif added == 0:
+ print(f" {fp.name}: ok (already up to date)")
+ else:
+ print(f" {fp.name}: error")
+
+ if not args.dry_run:
+ print_header("result")
+ print(f" total keys added: {total_added}")
+
+ except KeyboardInterrupt:
+ print("\ncancelled")
+ sys.exit(130)
+ except Exception as ex:
+ print(f"\nfatal: {ex}")
+ sys.exit(1)
+
+
+if __name__ == "__main__":
+ main()
diff --git a/optimizerDuck/Resources/Languages/Translations.ru-RU.resx b/optimizerDuck/Resources/Languages/Translations.ru-RU.resx
index c422665..d10c7af 100644
--- a/optimizerDuck/Resources/Languages/Translations.ru-RU.resx
+++ b/optimizerDuck/Resources/Languages/Translations.ru-RU.resx
@@ -406,6 +406,9 @@
<data name="Optimization.Apply.Error.Failed" xml:space="preserve">
<value>Не удалось применить {0}.</value>
</data>
+ <data name="Optimization.Apply.Error.Unknown" xml:space="preserve">
+ <value>Неизвестный результат для {0}.</value>
+ </data>
<data name="Service.Common.Error.AccessDenied" xml:space="preserve">
<value>Доступ запрещен</value>
</data>
diff --git a/optimizerDuck/Resources/Languages/Translations.vi-VN.resx b/optimizerDuck/Resources/Languages/Translations.vi-VN.resx
index c585483..e84a722 100644
--- a/optimizerDuck/Resources/Languages/Translations.vi-VN.resx
+++ b/optimizerDuck/Resources/Languages/Translations.vi-VN.resx
@@ -400,6 +400,9 @@
<data name="Optimization.Apply.Error.Failed" xml:space="preserve">
<value>Không thể áp dụng {0}.</value>
</data>
+ <data name="Optimization.Apply.Error.Unknown" xml:space="preserve">
+ <value>Kết quả không xác định cho {0}.</value>
+ </data>
<data name="Service.Common.Error.AccessDenied" xml:space="preserve">
<value>Không có quyền truy cập</value>
</data>
@@ -1505,6 +1508,15 @@ Cập nhật ngay để trải nghiệm các tính năng mới, cải tiến và
<data name="Revert.Shell.Description.Run" xml:space="preserve">
<value>Chạy lệnh {0}: {1}</value>
</data>
+ <data name="Revert.Shell.Error.UnknownShellType" xml:space="preserve">
+ <value>Loại shell không xác định</value>
+ </data>
+ <data name="Revert.Shell.Error.CommandFailed" xml:space="preserve">
+ <value>Lệnh hoàn tác thất bại với mã thoát {0}</value>
+ </data>
+ <data name="Revert.UsbPower.Error.CommandFailed" xml:space="preserve">
+ <value>Hoàn tác nguồn USB thất bại với mã thoát {0}</value>
+ </data>
<data name="Settings.Optimize.ShowCompletionNotification.Title" xml:space="preserve">
<value>Hiển thị thông báo hoàn tất</value>
</data>
diff --git a/optimizerDuck/Resources/Languages/Translations.zh-CN.resx b/optimizerDuck/Resources/Languages/Translations.zh-CN.resx
index cb6f74e..77b9008 100644
--- a/optimizerDuck/Resources/Languages/Translations.zh-CN.resx
+++ b/optimizerDuck/Resources/Languages/Translations.zh-CN.resx
@@ -406,12 +406,12 @@
<data name="Optimization.Apply.Error.Failed" xml:space="preserve">
<value>{0} 应用失败。</value>
</data>
+ <data name="Optimization.Apply.Error.Unknown" xml:space="preserve">
+ <value>{0} 的结果未知。</value>
+ </data>
<data name="Service.Common.Error.AccessDenied" xml:space="preserve">
<value>权限拒绝</value>
</data>
- <data name="Service.Registry.Error.BackupTruncated" xml:space="preserve">
- <value>注册表子树太大,无法安全备份;已中止删除 {0}</value>
- </data>
<data name="Service.Registry.Error.AccessDeniedProtectedHive" xml:space="preserve">
<value>权限拒绝(受保护的注册表配置单元)</value>
</data>
@@ -658,7 +658,6 @@
<data name="Optimizer.PowerManagement.InstallOptimizerDuckPowerPlan.ShortDescription" xml:space="preserve">
<value>安装定制的高性能电源计划,让系统始终以最高速度运行。</value>
</data>
-
<data name="Optimizer.PowerManagement.InstallOptimizerDuckPowerPlan.Progress.Importing" xml:space="preserve">
<value>正在导入并激活电源计划...</value>
</data>
diff --git a/optimizerDuck/Resources/Languages/Translations.zh-TW.resx b/optimizerDuck/Resources/Languages/Translations.zh-TW.resx
index 728290c..de6df32 100644
--- a/optimizerDuck/Resources/Languages/Translations.zh-TW.resx
+++ b/optimizerDuck/Resources/Languages/Translations.zh-TW.resx
@@ -375,6 +375,9 @@
<data name="Optimization.Apply.Error.Failed" xml:space="preserve">
<value>無法套用 {0}。</value>
</data>
+ <data name="Optimization.Apply.Error.Unknown" xml:space="preserve">
+ <value>{0} 的結果未知。</value>
+ </data>
<data name="Service.Common.Error.AccessDenied" xml:space="preserve">
<value>存取被拒</value>
</data>
@@ -1262,6 +1265,15 @@
<data name="Revert.Shell.Description.Run" xml:space="preserve">
<value>執行 {0} 命令:{1}</value>
</data>
+ <data name="Revert.Shell.Error.UnknownShellType" xml:space="preserve">
+ <value>未知的外殼類型</value>
+ </data>
+ <data name="Revert.Shell.Error.CommandFailed" xml:space="preserve">
+ <value>還原命令執行失敗,結束代碼為 {0}</value>
+ </data>
+ <data name="Revert.UsbPower.Error.CommandFailed" xml:space="preserve">
+ <value>USB 電源還原操作失敗,結束代碼為 {0}</value>
+ </data>
<data name="Settings.Optimize.ShowCompletionNotification.Title" xml:space="preserve">
<value>顯示完成通知</value>
</data>