From a94ef39600f7544ded6a47f6384b82c7dd53e379 Mon Sep 17 00:00:00 2001 From: Omarchybot <317366263+omarchybot@users.noreply.github.com> Date: Thu, 12 Nov 2026 12:10:56 +0100 Subject: [PATCH 1/4] Translate the window into Omarchy's languages Hype takes the shared Translator every Omarchy app carries, marks every string the window shows for translation, lists them in src/i18n/en.json beside 49 empty catalogs, and gets folio's translation sync, by way of signed's, to fill them. Co-Authored-By: Claude Opus 5.5 --- .github/workflows/i18n-sync.yml | 230 +++++++++++++++++ README.md | 4 +- docs/i18n.md | 31 +++ scripts/i18n-sync.py | 299 ++++++++++++++++++++++ src/Main.qml | 187 +++++++------- src/animationexport.cpp | 18 +- src/deck.cpp | 141 ++++++----- src/filedialog.cpp | 16 +- src/i18n/ar.json | 1 + src/i18n/bg.json | 1 + src/i18n/bn.json | 1 + src/i18n/ca.json | 1 + src/i18n/cs.json | 1 + src/i18n/da.json | 1 + src/i18n/de.json | 1 + src/i18n/el.json | 1 + src/i18n/en.json | 244 ++++++++++++++++++ src/i18n/es-MX.json | 1 + src/i18n/et.json | 1 + src/i18n/fa.json | 1 + src/i18n/fi.json | 1 + src/i18n/fil.json | 1 + src/i18n/fr.json | 1 + src/i18n/ga.json | 1 + src/i18n/he.json | 1 + src/i18n/hi.json | 1 + src/i18n/hr.json | 1 + src/i18n/hu.json | 1 + src/i18n/id.json | 1 + src/i18n/is.json | 1 + src/i18n/it.json | 1 + src/i18n/ja.json | 1 + src/i18n/ko.json | 1 + src/i18n/lt.json | 1 + src/i18n/lv.json | 1 + src/i18n/ms.json | 1 + src/i18n/nl.json | 1 + src/i18n/no.json | 1 + src/i18n/pl.json | 1 + src/i18n/pt-BR.json | 1 + src/i18n/pt.json | 1 + src/i18n/ro.json | 1 + src/i18n/ru.json | 1 + src/i18n/si.json | 1 + src/i18n/sk.json | 1 + src/i18n/sl.json | 1 + src/i18n/sr.json | 1 + src/i18n/sv.json | 1 + src/i18n/sw.json | 1 + src/i18n/ta.json | 1 + src/i18n/th.json | 1 + src/i18n/tr.json | 1 + src/i18n/uk.json | 1 + src/i18n/ur.json | 1 + src/i18n/uz.json | 1 + src/i18n/vi.json | 1 + src/i18n/zh-CN.json | 1 + src/i18n/zh-TW.json | 1 + src/main.cpp | 14 +- src/pptx.cpp | 45 ++-- src/recovery.cpp | 26 +- src/renderer.cpp | 43 ++-- src/resources.qrc | 2 +- src/translator.cpp | 163 ++++++++++++ src/translator.h | 57 +++++ tests/tests.cpp | 427 ++++++++++++++++++++++++++++++++ 66 files changed, 1761 insertions(+), 235 deletions(-) create mode 100644 .github/workflows/i18n-sync.yml create mode 100644 docs/i18n.md create mode 100755 scripts/i18n-sync.py create mode 100644 src/i18n/ar.json create mode 100644 src/i18n/bg.json create mode 100644 src/i18n/bn.json create mode 100644 src/i18n/ca.json create mode 100644 src/i18n/cs.json create mode 100644 src/i18n/da.json create mode 100644 src/i18n/de.json create mode 100644 src/i18n/el.json create mode 100644 src/i18n/en.json create mode 100644 src/i18n/es-MX.json create mode 100644 src/i18n/et.json create mode 100644 src/i18n/fa.json create mode 100644 src/i18n/fi.json create mode 100644 src/i18n/fil.json create mode 100644 src/i18n/fr.json create mode 100644 src/i18n/ga.json create mode 100644 src/i18n/he.json create mode 100644 src/i18n/hi.json create mode 100644 src/i18n/hr.json create mode 100644 src/i18n/hu.json create mode 100644 src/i18n/id.json create mode 100644 src/i18n/is.json create mode 100644 src/i18n/it.json create mode 100644 src/i18n/ja.json create mode 100644 src/i18n/ko.json create mode 100644 src/i18n/lt.json create mode 100644 src/i18n/lv.json create mode 100644 src/i18n/ms.json create mode 100644 src/i18n/nl.json create mode 100644 src/i18n/no.json create mode 100644 src/i18n/pl.json create mode 100644 src/i18n/pt-BR.json create mode 100644 src/i18n/pt.json create mode 100644 src/i18n/ro.json create mode 100644 src/i18n/ru.json create mode 100644 src/i18n/si.json create mode 100644 src/i18n/sk.json create mode 100644 src/i18n/sl.json create mode 100644 src/i18n/sr.json create mode 100644 src/i18n/sv.json create mode 100644 src/i18n/sw.json create mode 100644 src/i18n/ta.json create mode 100644 src/i18n/th.json create mode 100644 src/i18n/tr.json create mode 100644 src/i18n/uk.json create mode 100644 src/i18n/ur.json create mode 100644 src/i18n/uz.json create mode 100644 src/i18n/vi.json create mode 100644 src/i18n/zh-CN.json create mode 100644 src/i18n/zh-TW.json create mode 100644 src/translator.cpp create mode 100644 src/translator.h diff --git a/.github/workflows/i18n-sync.yml b/.github/workflows/i18n-sync.yml new file mode 100644 index 0000000..20df294 --- /dev/null +++ b/.github/workflows/i18n-sync.yml @@ -0,0 +1,230 @@ +name: Sync translations + +# Keeps the 49 translations in step with src/i18n/en.json without ever +# blocking English, the way Omarchy's and folio's i18n-sync workflows do. One +# credential-less Muse runner per pending language translates; a +# credential-less collect job takes only each language's own catalog, +# validates the result with the catalog tests, and hands it on as a patch; +# a trusted land job, which runs no repository code, path-checks that patch +# and lands it as one pull request it merges itself. +# +# Repository settings this needs: the MUSE_API_KEY Actions secret (and an +# optional MUSE_MODEL variable), and an I18N_SYNC_TOKEN secret (a +# fine-grained PAT with contents + pull-requests write on this repo) for +# the bot that opens and merges the pull request. +on: + push: + branches: [master] + paths: + - 'src/i18n/en.json' + workflow_dispatch: + schedule: + # Retry unfinished translations. + - cron: '17 4 * * *' + +permissions: + contents: read + +concurrency: + group: i18n-sync + cancel-in-progress: false + +jobs: + prepare: + runs-on: ubuntu-latest + timeout-minutes: 5 + outputs: + locales: ${{ steps.pending.outputs.locales }} + sha: ${{ steps.pending.outputs.sha }} + steps: + - uses: actions/checkout@v4 + with: + ref: master + persist-credentials: false + - name: Find pending translations + id: pending + run: | + echo "sha=$(git rev-parse HEAD)" >> "$GITHUB_OUTPUT" + echo "locales=$(python3 scripts/i18n-sync.py pending | jq -c .locales)" >> "$GITHUB_OUTPUT" + + translate: + needs: prepare + if: needs.prepare.outputs.locales != '[]' + strategy: + fail-fast: false + matrix: + locale: ${{ fromJSON(needs.prepare.outputs.locales) }} + runs-on: ubuntu-latest + timeout-minutes: 45 + steps: + - uses: actions/checkout@v4 + with: + ref: ${{ needs.prepare.outputs.sha }} + persist-credentials: false + - name: Install Muse + # Keep the pin in step with omacom/omarchy's i18n-sync workflow. + run: | + mkdir -p "$RUNNER_TEMP/muse-bin" + curl --fail --silent --show-error --location https://api.meta.ai/muse-launcher.sh --output "$RUNNER_TEMP/muse-bin/muse" + echo "c6db294799a190ca380da274beb3b9c0e160e0da9681a3d364ce8b0e5fa3a4bc $RUNNER_TEMP/muse-bin/muse" | sha256sum --check + chmod +x "$RUNNER_TEMP/muse-bin/muse" + MUSE_LAUNCHER_INSTALL=1 "$RUNNER_TEMP/muse-bin/muse" + echo "MUSE_NO_AUTO_UPDATE=1" >> "$GITHUB_ENV" + echo "$RUNNER_TEMP/muse-bin" >> "$GITHUB_PATH" + - name: Configure Muse + env: + MUSE_API_KEY: ${{ secrets.MUSE_API_KEY }} + run: | + python3 - <<'PY' + import json, os + from pathlib import Path + key = os.environ.get('MUSE_API_KEY') + if not key: + raise SystemExit('Add the MUSE_API_KEY Actions secret to enable automatic translations.') + config = Path.home() / '.config/muse' + config.mkdir(parents=True, exist_ok=True) + auth = config / 'auth.json' + auth.write_text(json.dumps({'schema_version': 1, 'providers': {'meta': {'api_key': key}}})) + auth.chmod(0o600) + PY + - name: Translate this language's pending strings + # What fails stays pending for the next run; what worked still lands. + continue-on-error: true + timeout-minutes: 35 + env: + MUSE_MODEL: ${{ vars.MUSE_MODEL || 'muse-spark-1.3-contributor' }} + LOCALE: ${{ matrix.locale }} + run: python3 scripts/i18n-sync.py translate --locale "$LOCALE" --model "$MUSE_MODEL" + - name: Remove Muse credentials + if: always() + run: rm -f "$HOME/.config/muse/auth.json" + - name: Stage this language's catalog + # A lone file would lose its folders in the artifact; collect looks + # for it under src/i18n. + if: always() + env: + LOCALE: ${{ matrix.locale }} + run: | + mkdir -p "$RUNNER_TEMP/out/src/i18n" + cp "src/i18n/$LOCALE.json" "$RUNNER_TEMP/out/src/i18n/" + - uses: actions/upload-artifact@v4 + if: always() + with: + name: translations-${{ matrix.locale }} + path: ${{ runner.temp }}/out + retention-days: 3 + if-no-files-found: error + + # Takes each runner's own catalog and nothing else, and validates the + # whole set with the catalog tests, with no credentials. The outcome + # leaves as a patch for land. + collect: + needs: [prepare, translate] + # Keep the languages that finished even when another runner failed. + if: ${{ always() && !cancelled() && needs.prepare.result == 'success' && needs.prepare.outputs.locales != '[]' }} + runs-on: ubuntu-latest + timeout-minutes: 30 + steps: + - uses: actions/checkout@v4 + with: + ref: ${{ needs.prepare.outputs.sha }} + persist-credentials: false + - uses: actions/download-artifact@v4 + with: + pattern: translations-* + path: ${{ runner.temp }}/translations + - name: Collect completed translations + env: + EXPECTED: ${{ needs.prepare.outputs.locales }} + run: python3 scripts/i18n-sync.py collect "$RUNNER_TEMP/translations" --expected "$(jq -r 'join(",")' <<< "$EXPECTED")" + - name: Validate with the catalog tests + # Built against Arch's Qt, like Hype's own CI. The packages are + # listed here rather than read from omarchy-pkgs' PKGBUILD, so no + # code from outside this repository runs beside what land trusts. + run: | + docker run --rm -v "$PWD:/hype" -w /hype archlinux:latest bash -euc ' + pacman -Syu --noconfirm --needed base-devel cmake libwebp zlib \ + qt6-base qt6-declarative qt6-multimedia qt6-svg qt6-webengine >/dev/null + cmake -S . -B build -DCMAKE_BUILD_TYPE=Release >/dev/null + cmake --build build --target hype_tests -j"$(nproc)" + QT_QPA_PLATFORM=offscreen build/hype_tests catalogsMatchTheEnglishOne everyCatalogIsCompiledIn + ' + - name: Package the collected translations + run: | + mkdir -p "$RUNNER_TEMP/collected" + git diff --binary --no-renames -- src/i18n > "$RUNNER_TEMP/collected/translations.patch" + - uses: actions/upload-artifact@v4 + with: + name: collected + path: ${{ runner.temp }}/collected/translations.patch + retention-days: 3 + if-no-files-found: error + - name: Report what's still pending + if: always() + run: | + python3 scripts/i18n-sync.py pending | jq -r '"Strings still pending: **\([.jobs[].pending | length] | add // 0)** across \(.locales | length) languages. English shows meanwhile; the next run retries them."' >> "$GITHUB_STEP_SUMMARY" + + # Lands the collected translations as one pull request. This job holds the + # write token, so it runs no repository code: only git, gh, and the path + # check written inline here. + land: + needs: [prepare, collect] + if: ${{ always() && !cancelled() && needs.collect.result == 'success' }} + runs-on: ubuntu-latest + timeout-minutes: 10 + permissions: + contents: write + pull-requests: write + steps: + - uses: actions/checkout@v4 + with: + ref: ${{ needs.prepare.outputs.sha }} + token: ${{ secrets.I18N_SYNC_TOKEN || github.token }} + - uses: actions/download-artifact@v4 + with: + name: collected + path: ${{ runner.temp }}/collected + - name: Commit, open and merge the pull request + env: + GH_TOKEN: ${{ secrets.I18N_SYNC_TOKEN || github.token }} + run: | + patch="$RUNNER_TEMP/collected/translations.patch" + if [ ! -s "$patch" ]; then + echo "No translations to land." + exit 0 + fi + # Only edits to catalogs already here, never en.json, judged from what + # the patch staged: its headers can name one file and change another. + git apply --index "$patch" + # Read as plain commands, so a git failure stops the step rather than reading as empty. + summary=$(git diff --cached --summary) + git diff --cached --name-status --no-renames -z > "$RUNNER_TEMP/staged" + if [ -n "$summary" ]; then + echo "collected translations do more than change catalogs:" >&2 + echo "$summary" >&2 + exit 1 + fi + while IFS= read -r -d '' status && IFS= read -r -d '' path; do + if [[ "$status" != M ]] || ! [[ "$path" =~ ^src/i18n/[a-zA-Z-]+\.json$ ]] || [[ "$path" == */en.json ]] \ + || [[ "$(git ls-tree HEAD -- "$path" | cut -c1-6)" != 100644 ]]; then + echo "collected translations contain a disallowed change: $status $path" >&2 + exit 1 + fi + done < "$RUNNER_TEMP/staged" + git config user.name 'github-actions[bot]' + git config user.email '41898282+github-actions[bot]@users.noreply.github.com' + git commit -m 'Update translations' + git push --force origin HEAD:refs/heads/i18n-sync + # Only this repository's own sync branch: owner:branch matches + # exactly that head, where gh pr list --head also matches forks. + pr=$(gh api "repos/$GITHUB_REPOSITORY/pulls?head=$GITHUB_REPOSITORY_OWNER:i18n-sync&base=master&state=open" --jq '.[0].number // empty') + if [ -z "$pr" ]; then + pr=$(basename "$(gh pr create --base master --head i18n-sync --title 'Update translations' \ + --body 'Automated translation sync: fills pending strings in the 49 language catalogs from src/i18n/en.json. Generated by the Sync translations workflow, which validated these catalogs with the catalog tests and merges this pull request itself.')") + fi + # Merged here rather than left open: the next run rebuilds + # i18n-sync from master, so an open pull request would lose these. + if ! gh pr merge --squash --delete-branch "$pr"; then + echo "Could not merge #$pr; its translations stay pending and are redone by the next run." >&2 + exit 1 + fi diff --git a/README.md b/README.md index d63f8c0..df0a35f 100644 --- a/README.md +++ b/README.md @@ -155,7 +155,7 @@ Each slide supports one image or video. Copy the whole presentation folder when ## Choose your look -The palette and font icons in the toolbar choose an installed Omarchy theme and a presentation font. Hover to see the current choices. Theme colors apply to text, code, and slide backgrounds; your images keep their original colors. Code stays monospaced. Hype’s interface follows your current desktop theme independently and updates when you change it. +The palette and font icons in the toolbar choose an installed Omarchy theme and a presentation font. Hover to see the current choices. Theme colors apply to text, code, and slide backgrounds; your images keep their original colors. Code stays monospaced. Hype’s interface follows your current desktop theme independently and updates when you change it. It speaks the language picked under Omarchy's **Setup > Language** too, switching as soon as you pick another; your slides stay as you wrote them. The header shows the presentation's name with your position in it, such as “Slide 4 of 45”; saving and exporting report their progress on that line. The file icon beside it holds New, Open, Save, Export, and Version history, and is highlighted when you have unsaved changes. @@ -256,7 +256,7 @@ The build uses a Qt toolchain from Qt's installer under `build/qt/` when present For a launcher entry that rebuilds this checkout when opened, run `./bin/install-dev` and choose **Hype (Development)**. -Run `./bin/test` for the regression suite: the C++ tests (`hype_tests`, which read exported PDFs back with Qt Pdf from `qt6-webengine`) and the command-line tests (`hype_commands`, in Python). Arguments go to `ctest`, so `./bin/test -R hype_commands` runs only those. Set `HYPE_GUI_TESTS=0` to skip the C++ window-level tests on a machine without multimedia. After building the tests, the presenter check can also run with two virtual displays: +Run `./bin/test` for the regression suite: the C++ tests (`hype_tests`, which read exported PDFs back with Qt Pdf from `qt6-webengine`) and the command-line tests (`hype_commands`, in Python). Arguments go to `ctest`, so `./bin/test -R hype_commands` runs only those. Set `HYPE_GUI_TESTS=0` to skip the C++ window-level tests on a machine without multimedia. Every string the window shows is translated; [docs/i18n.md](docs/i18n.md) covers adding one and how the translations are kept in sync. After building the tests, the presenter check can also run with two virtual displays: ```sh QT_QPA_PLATFORMTHEME=generic QT_STYLE_OVERRIDE=Fusion \ diff --git a/docs/i18n.md b/docs/i18n.md new file mode 100644 index 0000000..db1ea1d --- /dev/null +++ b/docs/i18n.md @@ -0,0 +1,31 @@ +# Translations + +Hype's window follows the language picked under Omarchy's **Setup > Language**, live: English plus Omarchy's 49 translations. Each language has a catalog, `src/i18n/.json`, a flat JSON object from English source text to its translation, compiled into the binary through `src/resources.qrc`. A counted string, `qsTr("%Ln slides selected", "", count)`, maps to an object of plural forms keyed by CLDR category (`{"one": "%Ln slide selected", "other": "%Ln slides selected"}`), and each language gives exactly the categories its counts reach, by the rules in `Translator::pluralCategory`. A string a catalog doesn't have yet shows in English (a regional catalog such as `pt-BR` falls back to `pt` first). + +The window and the export worker it starts are translated, so an export's progress and errors arrive in the window's language. The commands (`hype check`, `hype render`, `hype export`) and the command-line exports never install the translator: their output is read by scripts and agents, and stays in English. Slides are the author's and are never translated or mirrored; `slidesRenderTheSameRightToLeft` checks that a right-to-left desktop draws them exactly as written. + +`src/translator.h` and `src/translator.cpp` are the copy every Omarchy app carries, byte for byte, from the omarchy-app skill's templates. Change them there, not here. + +## Adding or changing a string + +Pull requests only ever touch English: wrap the text in `qsTr()` (QML) or `tr()` (C++), with `%1` placeholders filled by `.arg()` rather than a sentence glued together, and add it to `src/i18n/en.json` as itself, or with its `one` and `other` forms when it's counted. A free function in C++ uses its file's `tr()` helper. The `englishCatalogMatchesTheSources` test keeps `en.json` exactly in step with the sources. Leave the other catalogs alone. Since the English is the key, rewording a string makes a new key; its translations become pending, and the old key is dropped by the next sync. The catalog tests check the translations that are there (placeholders, plural forms, language codes, every catalog listed in `resources.qrc`), but never require them to be complete, so English is never blocked. + +## Keeping translations in sync + +The `Sync translations` workflow (`.github/workflows/i18n-sync.yml`) does the converging, the way Omarchy's, Folio's and Signed's do. It runs on pushes to `master` that change `src/i18n/en.json`, daily, and on demand. `scripts/i18n-sync.py pending` lists, per language, the strings that are missing or whose translation no longer fits, and the keys `en.json` no longer has. Then: + +1. One runner per pending language, holding only the Muse key and no repository credentials, runs `translate --locale `. Muse only returns text: the script validates every value and writes that one catalog, dropping keys English no longer has. Whatever fails stays pending. +2. A collect job, with no credentials, takes from each runner only its own `.json`, keeps its current and valid entries, and runs the catalog tests against the result in an Arch container. +3. A land job, holding the `I18N_SYNC_TOKEN`, runs no repository code: it checks that applying the patch staged nothing but edits to catalogs already here (never `en.json`, nothing created, deleted, renamed or given another mode), commits it to the `i18n-sync` branch, and opens and merges an `Update translations` pull request. The next run rebuilds that branch from `master`, so a sync pull request is never left open. + +A language that failed, or a run that broke, just leaves strings pending for the next run. The same script works locally: `python3 scripts/i18n-sync.py pending` shows the queue, and `translate --locale da` fills one language with a local Muse. + +Repository settings this needs: + +- `MUSE_API_KEY`, an Actions secret for the translation runners. +- `I18N_SYNC_TOKEN`, an Actions secret holding a fine-grained PAT with Contents and Pull requests read and write on this repository, for the bot that opens and merges the sync pull request. Without it the workflow falls back to its own token, which can still open and merge the pull request, but GitHub runs no CI on a pull request that token opens. +- Optionally `MUSE_MODEL`, an Actions variable naming the Muse model (default `muse-spark-1.3-contributor`). + +## Translator brief + +The brief Muse gets lives in `scripts/i18n-sync.py` (`BRIEF`); it applies to people translating by hand too. Keep the name Hype, and translate "slide", "presentation", "overview", "presenter view" and "speaker notes" the way the language's presentation software names them. Write like the interface was made in the language: short, natural, the register of consumer desktop software. Keep exactly: product and brand names, file formats and names, the `images/` and `videos/` folders, the words an author types into a slide (`span`, `fit`, an `svg` block, `--name` theme colors), key names and symbols, units, and placeholders: `%1` to `%9` and `%Ln` must all be there, though they may be reordered. In a plural entry, `other` keeps every placeholder, and another form may drop `%Ln` only where the language says that number with a word. `pt` is European Portuguese and `pt-BR` Brazilian; `sr` is Serbian in Cyrillic. diff --git a/scripts/i18n-sync.py b/scripts/i18n-sync.py new file mode 100755 index 0000000..731deba --- /dev/null +++ b/scripts/i18n-sync.py @@ -0,0 +1,299 @@ +#!/usr/bin/env python3 +"""Keep Hype's 49 translations in step with its English catalog, +src/i18n/en.json. Ported from omacom/folio's scripts/i18n-sync.py, by way of +omacom/signed's; keep them in step. + +Subcommands: + pending Print what each language still needs, as JSON. + translate Fill one language's pending strings with Muse. Muse only + returns text; this script validates every value and writes + each .json itself. + collect Take each language's catalog from its translate runner, + re-validate it against en.json, and write it in place. + +A catalog maps English source text to its translation, so a changed +English string is a new key: a string is pending when its key is missing +from a language's catalog or its translation doesn't fit (a broken +placeholder, the wrong plural forms). Keys en.json no longer has are +pruned. Pending strings fall back to English in the window. +""" +import argparse +import json +import os +import re +import subprocess +import sys +import tempfile +import time +from pathlib import Path + +ROOT = Path(__file__).resolve().parents[1] +# Every folder of catalogs. Hype has the one; the list keeps the script +# shaped like folio's, which has its plugins' too. +CATALOGS = [ROOT / "src/i18n"] +MODEL = os.environ.get("MUSE_MODEL", "muse-spark-1.3-contributor") +MUSE = os.environ.get("MUSE_BIN", "muse") +TIMEOUT = 600 +RETRIES = 2 +BATCH = 40 +REFERENCE = 60 + +# Omarchy's 49 translations (default/i18n/locales.json), by English name. +LANGUAGES = { + "ar": "Arabic", "bg": "Bulgarian", "bn": "Bengali", "ca": "Catalan", "cs": "Czech", "da": "Danish", + "de": "German", "el": "Greek", "es-MX": "Mexican Spanish", "et": "Estonian", "fa": "Persian", + "fi": "Finnish", "fil": "Filipino", "fr": "French", "ga": "Irish", "he": "Hebrew", "hi": "Hindi", + "hr": "Croatian", "hu": "Hungarian", "id": "Indonesian", "is": "Icelandic", "it": "Italian", + "ja": "Japanese", "ko": "Korean", "lt": "Lithuanian", "lv": "Latvian", "ms": "Malay", "nl": "Dutch", + "no": "Norwegian Bokmål", "pl": "Polish", "pt": "European Portuguese", "pt-BR": "Brazilian Portuguese", + "ro": "Romanian", "ru": "Russian", "si": "Sinhala", "sk": "Slovak", "sl": "Slovenian", "sr": "Serbian", + "sv": "Swedish", "sw": "Swahili", "ta": "Tamil", "th": "Thai", "tr": "Turkish", "uk": "Ukrainian", + "ur": "Urdu", "uz": "Uzbek", "vi": "Vietnamese", "zh-CN": "Simplified Chinese", + "zh-TW": "Traditional Chinese", +} + +# The CLDR categories a plural entry needs in each language: every category +# Translator::pluralCategory (src/translator.cpp) reaches, plus "other". The +# catalog test checks translations against the C++ rules, so a drift here +# fails the sync's validation rather than shipping. +PLURALS = { + **dict.fromkeys(["ja", "ko", "zh-CN", "zh-TW", "th", "vi", "id", "ms"], ["other"]), + **dict.fromkeys(["fr", "pt-BR", "ca", "es-MX", "it", "pt"], ["one", "many", "other"]), + **dict.fromkeys(["cs", "sk", "hr", "sr", "lt", "ro"], ["one", "few", "other"]), + **dict.fromkeys(["pl", "ru", "uk"], ["one", "few", "many", "other"]), + "sl": ["one", "two", "few", "other"], + "lv": ["zero", "one", "other"], + "ar": ["zero", "one", "two", "few", "many", "other"], + "he": ["one", "two", "other"], + "ga": ["one", "two", "few", "many", "other"], +} + +NOTES = { + "pt": "Portuguese as written in Portugal (ficheiro, ecrã, utilizador, estar a fazer); Brazilian forms are a defect.", + "sr": "Serbian in Cyrillic script.", +} + +BRIEF = """Hype is an app for the Omarchy Linux desktop that makes presentations from Markdown: each slide is a section of one Markdown file, edited either visually or as Markdown source, then presented full screen with a presenter view and speaker notes, or exported to PDF and PowerPoint. Keep the app name Hype as it is. Translate "slide", "presentation", "overview", "presenter view" and "speaker notes" the way the language's presentation software (PowerPoint, Keynote, LibreOffice Impress) names them. Write like the interface was made in the language: short, natural, the register of consumer desktop software; buttons and menu items are one to three words where the language allows. Each key is the English source text itself. +Keep exactly: product and brand names (Hype, Omarchy, Markdown, PowerPoint, Qt, ffmpeg, ffprobe, WebP, SVG), file formats and names (PDF, ZIP, slides.json), folder names (images/, videos/), the words an author types into a slide's Markdown (the media directives span and fit, an svg block, the element and its viewBox, theme colors written --name), key names and symbols (Ctrl, Shift, Esc, Space, Tab, Enter, F5, ←, →), units (px, %, GiB, 1080p, 16:9), and the punctuation marks "…", "·", "—", "/" where they separate things. The menu items "Fit" and "Span" are labels, and are translated. +Placeholders (%1 to %9, %Ln) must appear in the translation exactly as in the English, though they may be reordered: %1 is usually a file name, a slide number or a presentation's title, %2 an error message or a slide count, %Ln a count. Lowercase error fragments follow a colon in a longer message, so keep them lowercase where the script has case. Keep Title Case only where the language uses it for dialog titles.""" + + +class SyncError(Exception): + pass + + +def read_json(path, default=None): + path = Path(path) + return json.loads(path.read_text(encoding="utf-8")) if path.exists() else default + + +def write_catalog(path, data): + text = json.dumps(dict(sorted(data.items())), ensure_ascii=False, indent=2) + "\n" + fd, temporary = tempfile.mkstemp(prefix=f".{path.name}.", dir=path.parent) + with os.fdopen(fd, "w", encoding="utf-8") as stream: + stream.write(text) + os.replace(temporary, path) + + +def placeholders(text): + return sorted(re.findall(r"%L?[1-9n]", text)) + + +def valid(source, value, categories): + """Whether a translation fits its English source, by the catalog test's + rules (catalogProblems in tests/tests.cpp).""" + if isinstance(source, str): + return isinstance(value, str) and bool(value.strip()) and placeholders(value) == placeholders(source) + if not isinstance(value, dict) or set(value) != set(categories): + return False + needed = set(placeholders(source["other"])) + fixed = needed - {"%n", "%Ln"} + for form, text in value.items(): + if not isinstance(text, str) or not text.strip(): + return False + present = set(placeholders(text)) + if form == "other" and present != needed or not fixed <= present <= needed: + return False + return True + + +def checked(code, catalog, english): + """The entries of a catalog that are current and valid.""" + categories = PLURALS.get(code, ["one", "other"]) + return {key: value for key, value in catalog.items() + if key in english and valid(english[key], value, categories)} + + +def english(): + """Every English string, from all the catalogs.""" + return {key: value for folder in CATALOGS for key, value in read_json(folder / "en.json").items()} + + +def translations(code): + """A language's translations, from all its catalogs.""" + return {key: value for folder in CATALOGS for key, value in read_json(folder / f"{code}.json", {}).items()} + + +def write_translations(code, catalog): + """Writes each folder's .json with the valid entries for its own + English strings.""" + for folder in CATALOGS: + write_catalog(folder / f"{code}.json", checked(code, catalog, read_json(folder / "en.json"))) + + +def language(code): + if code not in LANGUAGES: + raise SyncError(f"not one of Omarchy's language codes: {code}") + return code + + +def cmd_pending(args): + source = english() + jobs = {} + for code in [language(args.locale)] if args.locale else LANGUAGES: + catalog = translations(code) + good = checked(code, catalog, source) + pending = [key for key in source if key not in good] + # A folder's entries for strings it doesn't have, even ones another + # folder has, are stale there. + stale = [key for folder in CATALOGS + for key in read_json(folder / f"{code}.json", {}) + if key not in checked(code, catalog, read_json(folder / "en.json"))] + if pending or stale: + jobs[code] = {"pending": pending, "stale": stale} + print(json.dumps({"locales": sorted(jobs), "jobs": jobs}, ensure_ascii=False, indent=2)) + + +def muse_json(prompt, model): + with tempfile.TemporaryDirectory(prefix="hype-i18n-") as directory: + prompt_path = Path(directory) / "prompt.txt" + prompt_path.write_text(prompt, encoding="utf-8") + command = [MUSE, "exec", "--prompt-file", str(prompt_path), "--disable-write", + "--disable-shell", "--disable-web-tools", "--no-foreign-personal-context", + "--no-session-log", "--max-model-steps", "1", "--model", model] + error = SyncError("Muse failed") + for attempt in range(RETRIES + 1): + try: + result = subprocess.run(command, cwd=directory, capture_output=True, + text=True, timeout=TIMEOUT, check=False) + if result.returncode: + raise SyncError(f"Muse exited with status {result.returncode}") + text = result.stdout.strip() + return json.loads(text[text.find("{"):text.rfind("}") + 1]) + except subprocess.TimeoutExpired: + error = SyncError("Muse timed out") + except ValueError: + error = SyncError("Muse's answer is not JSON") + except SyncError as exc: + error = exc + except OSError: + raise SyncError("could not launch Muse") from None + if attempt < RETRIES: + time.sleep(2 ** attempt) + raise error + + +def translate_batch(batch, code, model, reference): + name = LANGUAGES[code] + categories = PLURALS.get(code, ["one", "other"]) + note = f" {NOTES[code]}" if code in NOTES else "" + plural = f""" +Some values are objects of plural forms keyed by CLDR category: return an object with exactly the {name} categories {", ".join(categories)}, each the whole string for counts in that category. "other" keeps every placeholder; another form may drop %Ln only where {name} says that number with a word. +""" if any(isinstance(value, dict) for value in batch.values()) else "" + terms = f""" +Existing {name} translations, for consistent terms (do not return these): + +{json.dumps(reference, ensure_ascii=False)} + +""" if reference else "" + prompt = f"""Translate these strings of a desktop presentation app's interface from English into {name} ({code}).{note} +Return ONLY a JSON object mapping each input key to its translation, with exactly the same keys. +{BRIEF} +{plural}{terms} +{json.dumps(batch, ensure_ascii=False)} + +""" + result = muse_json(prompt, model) + if not isinstance(result, dict): + raise SyncError("Muse's answer is not an object") + good = {key: result[key] for key in batch if key in result and valid(batch[key], result[key], categories)} + return good, len(batch) - len(good) + + +def cmd_translate(args): + code = language(args.locale) + source = english() + catalog = checked(code, translations(code), source) + pending = [key for key in source if key not in catalog] + write_translations(code, catalog) + failed = 0 + # One batch at a time, each seeing what the earlier ones chose, so a + # term like "slide" comes out the same throughout. + for start in range(0, len(pending), BATCH): + batch = {key: source[key] for key in pending[start:start + BATCH]} + reference = {key: catalog[key] for key in list(catalog)[-REFERENCE:]} + try: + translated, rejected = translate_batch(batch, code, args.model, reference) + except SyncError as exc: + print(f"{code}: batch failed: {exc}", file=sys.stderr) + failed += len(batch) + continue + failed += rejected + catalog.update(translated) + write_translations(code, catalog) + print(f"{code}: {len(pending) - failed} translated, {failed} still pending") + return 1 if failed else 0 + + +def cmd_collect(args): + """Takes /translations-//.json, for each + expected language and each catalog folder, and nothing else, and merges + its current, valid entries into that folder's .json.""" + directory = Path(args.directory) + collected = [] + for code in filter(None, args.expected.split(",")): + found = False + for folder in CATALOGS: + source = directory / f"translations-{language(code)}" / folder.relative_to(ROOT) / f"{code}.json" + if not source.is_file(): + continue + try: + incoming = json.loads(source.read_text(encoding="utf-8")) + except ValueError: + print(f"{code}: {source.name} in {folder.relative_to(ROOT)} is not JSON; left pending", file=sys.stderr) + continue + if not isinstance(incoming, dict): + continue + own = read_json(folder / "en.json") + path = folder / f"{code}.json" + write_catalog(path, {**checked(code, read_json(path, {}), own), **checked(code, incoming, own)}) + found = True + if found: + collected.append(code) + print(f"Collected {len(collected)} languages: {', '.join(collected) or 'none'}") + + +def main(): + parser = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter) + sub = parser.add_subparsers(dest="command", required=True) + p = sub.add_parser("pending") + p.add_argument("--locale") + p.set_defaults(fn=cmd_pending) + p = sub.add_parser("translate") + p.add_argument("--locale", required=True) + p.add_argument("--model", default=MODEL) + p.set_defaults(fn=cmd_translate) + p = sub.add_parser("collect") + p.add_argument("directory") + p.add_argument("--expected", required=True, help="comma-separated language codes") + p.set_defaults(fn=cmd_collect) + args = parser.parse_args() + try: + return args.fn(args) or 0 + except SyncError as exc: + print(f"i18n-sync: {exc}", file=sys.stderr) + return 1 + + +if __name__ == "__main__": + sys.exit(main()) diff --git a/src/Main.qml b/src/Main.qml index dc8d316..eb61875 100644 --- a/src/Main.qml +++ b/src/Main.qml @@ -271,6 +271,12 @@ ApplicationWindow { return deck.sourcePosition() + deck.slideSource.indexOf(deck.slideText) } function setMode(name) { changeMode(name, false) } + // A placed image's position, by the id slides write in their Markdown. + function positionName(id) { + return ({ "top-left": qsTr("Top left"), "top": qsTr("Top"), "top-right": qsTr("Top right"), + "left": qsTr("Left"), "center": qsTr("Center"), "right": qsTr("Right"), + "bottom-left": qsTr("Bottom left"), "bottom": qsTr("Bottom"), "bottom-right": qsTr("Bottom right") })[id] || id + } function changeMode(name, preserveEditing) { const switchingEditors = preserveEditing && !overview && name !== "overview" const editorFocused = sourceEditor.activeFocus || slideEditor.activeFocus @@ -440,7 +446,7 @@ ApplicationWindow { ApplicationWindow { id: presenterWindow; objectName: "presenterWindow" visible: false; minimumWidth: 800; minimumHeight: 520 - title: deck.title + " — Presenter View" + title: qsTr("%1 — Presenter View").arg(deck.title) color: win.ui.background palette.window: win.ui.panel; palette.base: win.ui.background; palette.text: win.ui.foreground palette.windowText: win.ui.foreground; palette.button: win.ui.button; palette.buttonText: win.ui.foreground @@ -461,11 +467,11 @@ ApplicationWindow { Layout.fillWidth: true; elide: Text.ElideRight } Label { - text: "Slide " + (deck.selected + 1) + " of " + deck.count + text: qsTr("Slide %1 of %2").arg(deck.selected + 1).arg(deck.count) color: win.ui.muted; font.pixelSize: 16 } Button { - text: "End show" + text: qsTr("End show") onClicked: win.togglePresent() contentItem: Text { text: parent.text; color: win.ui.foreground; horizontalAlignment: Text.AlignHCenter; verticalAlignment: Text.AlignVCenter } background: Rectangle { color: parent.hovered ? win.ui.hover : win.ui.button; radius: win.softRadius; border.color: win.ui.border } @@ -475,7 +481,7 @@ ApplicationWindow { Layout.fillWidth: true; Layout.preferredHeight: presenterWindow.height * 0.42; spacing: 22 ColumnLayout { Layout.fillWidth: true; Layout.fillHeight: true; Layout.preferredWidth: 2 - Label { text: "CURRENT"; color: win.ui.muted; font.pixelSize: 12; font.bold: true } + Label { text: qsTr("Current"); font.capitalization: Font.AllUppercase; color: win.ui.muted; font.pixelSize: 12; font.bold: true } Item { Layout.fillWidth: true; Layout.fillHeight: true Rectangle { @@ -494,7 +500,7 @@ ApplicationWindow { } ColumnLayout { Layout.fillWidth: true; Layout.fillHeight: true; Layout.preferredWidth: 1 - Label { text: "NEXT"; color: win.ui.muted; font.pixelSize: 12; font.bold: true } + Label { text: qsTr("Next"); font.capitalization: Font.AllUppercase; color: win.ui.muted; font.pixelSize: 12; font.bold: true } Item { Layout.fillWidth: true; Layout.fillHeight: true Rectangle { @@ -511,20 +517,20 @@ ApplicationWindow { } Label { anchors.centerIn: parent; visible: deck.selected + 1 >= deck.count - text: "End of presentation"; color: win.ui.muted; font.pixelSize: 16 + text: qsTr("End of presentation"); color: win.ui.muted; font.pixelSize: 16 } } } } } Rectangle { Layout.fillWidth: true; height: 1; color: win.ui.border } - Label { text: "SPEAKER NOTES"; color: win.ui.muted; font.pixelSize: 12; font.bold: true } + Label { text: qsTr("Speaker notes"); font.capitalization: Font.AllUppercase; color: win.ui.muted; font.pixelSize: 12; font.bold: true } ScrollView { Layout.fillWidth: true; Layout.fillHeight: true; clip: true background: Rectangle { color: win.ui.panel; radius: win.rounding; border.color: win.ui.border } TextArea { objectName: "presenterNotes"; readOnly: true; selectByMouse: true - text: deck.speakerNotes || "No speaker notes for this slide." + text: deck.speakerNotes || qsTr("No speaker notes for this slide.") color: deck.speakerNotes ? win.ui.foreground : win.ui.muted font.pixelSize: 24; wrapMode: TextEdit.Wrap leftPadding: 24; rightPadding: 24; topPadding: 20; bottomPadding: 20 @@ -533,27 +539,27 @@ ApplicationWindow { } Label { Layout.fillWidth: true - text: "←/→ change slide · Space plays media · Esc ends the show" + text: qsTr("←/→ change slide · Space plays media · Esc ends the show") color: win.ui.muted; font.pixelSize: 13; horizontalAlignment: Text.AlignHCenter } } } Dialog { - id: closeDialog; title: "Unsaved changes"; modal: true; anchors.centerIn: parent + id: closeDialog; title: qsTr("Unsaved changes"); modal: true; anchors.centerIn: parent standardButtons: Dialog.Discard | Dialog.Cancel - Label { text: "Changes could not be backed up. Discard them and quit?" } + Label { text: qsTr("Changes could not be backed up. Discard them and quit?") } onDiscarded: { win.allowClose = true; win.close() } } Dialog { id: historyDialog; objectName: "historyDialog" parent: Overlay.overlay; anchors.centerIn: parent - modal: true; focus: true; title: "Version history" + modal: true; focus: true; title: qsTr("Version history") width: Math.min(460, win.width - 48); height: Math.min(480, win.height - 80) standardButtons: Dialog.Cancel property var versions: [] onOpened: { deck.flushAutosave(); versions = deck.recoveryVersions() } contentItem: ColumnLayout { - Label { text: "Choose a version to restore. Your current version stays in history."; wrapMode: Text.WordWrap; Layout.fillWidth: true } + Label { text: qsTr("Choose a version to restore. Your current version stays in history."); wrapMode: Text.WordWrap; Layout.fillWidth: true } ListView { id: versionList Layout.fillWidth: true; Layout.fillHeight: true; clip: true @@ -565,7 +571,7 @@ ApplicationWindow { text: modelData.label onClicked: if (deck.restoreVersion(modelData.name)) historyDialog.close() } - Label { parent: versionList; anchors.centerIn: parent; visible: versionList.count === 0; text: "No earlier versions yet"; color: win.ui.muted } + Label { parent: versionList; anchors.centerIn: parent; visible: versionList.count === 0; text: qsTr("No earlier versions yet"); color: win.ui.muted } } } } @@ -587,17 +593,17 @@ ApplicationWindow { Overlay.modal: Rectangle { color: "#660b0d14" } contentItem: ColumnLayout { spacing: 18 - Label { text: "Compressing image…"; color: win.ui.foreground; font.pixelSize: 20; font.bold: true } + Label { text: qsTr("Compressing image…"); color: win.ui.foreground; font.pixelSize: 20; font.bold: true } ProgressBar { Layout.fillWidth: true indeterminate: true palette.highlight: win.ui.accent palette.dark: win.ui.border - Accessible.name: "Compressing image" + Accessible.name: qsTr("Compressing image") } Button { Layout.alignment: Qt.AlignRight - text: "Cancel"; onClicked: compressionDialog.close() + text: qsTr("Cancel"); onClicked: compressionDialog.close() } } } @@ -634,14 +640,14 @@ ApplicationWindow { spacing: 18 ColumnLayout { spacing: 6 - Label { text: pasteDialog.isVideo ? "Paste video" : "Paste image"; color: win.ui.foreground; font.pixelSize: 20; font.bold: true } - Label { text: "Save to " + (pasteDialog.isVideo ? "videos/" : "images/"); color: win.ui.muted; font.pixelSize: 14 } + Label { text: pasteDialog.isVideo ? qsTr("Paste video") : qsTr("Paste image"); color: win.ui.foreground; font.pixelSize: 20; font.bold: true } + Label { text: qsTr("Save to %1").arg(pasteDialog.isVideo ? "videos/" : "images/"); color: win.ui.muted; font.pixelSize: 14 } } RowLayout { Layout.fillWidth: true; spacing: 10 TextField { id: pasteName; objectName: "pasteName" - Accessible.name: "Filename" + Accessible.name: qsTr("Filename") Layout.fillWidth: true; implicitHeight: 44 font.pixelSize: 16; color: win.ui.foreground selectionColor: win.ui.selection; selectedTextColor: win.ui.selectionText @@ -660,13 +666,13 @@ ApplicationWindow { Layout.fillWidth: true; spacing: 10 Item { Layout.fillWidth: true } Button { - id: cancelPasteButton; text: "Cancel"; implicitHeight: 38; implicitWidth: 84 + id: cancelPasteButton; text: qsTr("Cancel"); implicitHeight: 38; implicitWidth: 84 contentItem: Text { text: parent.text; color: win.ui.foreground; font.pixelSize: 14; horizontalAlignment: Text.AlignHCenter; verticalAlignment: Text.AlignVCenter } background: Rectangle { color: cancelPasteButton.hovered ? win.ui.hover : win.ui.button; radius: Math.min(4, win.rounding); border.color: cancelPasteButton.activeFocus ? win.ui.accent : "transparent" } onClicked: pasteDialog.close() } Button { - id: savePasteButton; text: "Save " + (pasteDialog.isVideo ? "video" : "image") + id: savePasteButton; text: pasteDialog.isVideo ? qsTr("Save video") : qsTr("Save image") implicitHeight: 38; implicitWidth: 112; enabled: pasteName.text.trim().length > 0 contentItem: Text { text: parent.text; color: win.ui.accentText; font.pixelSize: 14; font.bold: true; horizontalAlignment: Text.AlignHCenter; verticalAlignment: Text.AlignVCenter } background: Rectangle { color: !savePasteButton.enabled ? win.ui.border : savePasteButton.hovered ? win.ui.accentHover : win.ui.accent; radius: Math.min(4, win.rounding); border.color: savePasteButton.activeFocus ? win.ui.foreground : "transparent" } @@ -821,7 +827,7 @@ ApplicationWindow { width: badgeLabel.implicitWidth + 12; height: badgeLabel.implicitHeight + 6 color: current ? (active ? win.ui.accent : win.ui.inactiveSelection) : win.ui.border topRightRadius: win.softRadius; bottomLeftRadius: win.rounding - Label { id: badgeLabel; anchors.centerIn: parent; text: "Slide " + (parent.slide + 1); font.pixelSize: 10; color: parent.current ? (parent.active ? win.ui.accentText : win.ui.inactiveSelectionText) : win.ui.foreground } + Label { id: badgeLabel; anchors.centerIn: parent; text: qsTr("Slide %1").arg(parent.slide + 1); font.pixelSize: 10; color: parent.current ? (parent.active ? win.ui.accentText : win.ui.inactiveSelectionText) : win.ui.foreground } } component AppMenu: Menu { id: appMenu @@ -885,33 +891,32 @@ ApplicationWindow { } RowLayout { anchors.fill: parent; anchors.leftMargin: editorBar.textInset - 10; anchors.rightMargin: 14; spacing: 2 - EditorButton { compact: editorBar.compact; objectName: editorBar.scope + "boldButton"; iconName: "bold"; label: "Bold"; description: "Bold (Ctrl+B)"; onClicked: win.formatSlide("bold") } - EditorButton { compact: editorBar.compact; objectName: editorBar.scope + "italicButton"; iconName: "italic"; label: "Italic"; description: "Italic (Ctrl+I)"; onClicked: win.formatSlide("italic") } - EditorButton { compact: editorBar.compact; objectName: editorBar.scope + "underlineButton"; iconName: "underline"; label: "Underline"; description: "Underline (Ctrl+U)"; onClicked: win.formatSlide("underline") } - EditorButton { compact: editorBar.compact; objectName: editorBar.scope + "headlineButton"; iconName: "headline"; label: "Headline"; description: "Headline (Ctrl+H)"; onClicked: win.formatSlide("headline") } - EditorButton { compact: editorBar.compact; objectName: editorBar.scope + "codeButton"; iconName: "code"; label: "Code"; description: "Code block (Ctrl+K)"; onClicked: win.formatSlide("code") } - EditorButton { compact: editorBar.compact; objectName: editorBar.scope + "commentButton"; iconName: "comment"; label: "Note"; description: "Comment, hidden on slide (Ctrl+/)"; onClicked: win.formatSlide("comment") } + EditorButton { compact: editorBar.compact; objectName: editorBar.scope + "boldButton"; iconName: "bold"; label: qsTr("Bold"); description: qsTr("Bold") + " (Ctrl+B)"; onClicked: win.formatSlide("bold") } + EditorButton { compact: editorBar.compact; objectName: editorBar.scope + "italicButton"; iconName: "italic"; label: qsTr("Italic"); description: qsTr("Italic") + " (Ctrl+I)"; onClicked: win.formatSlide("italic") } + EditorButton { compact: editorBar.compact; objectName: editorBar.scope + "underlineButton"; iconName: "underline"; label: qsTr("Underline"); description: qsTr("Underline") + " (Ctrl+U)"; onClicked: win.formatSlide("underline") } + EditorButton { compact: editorBar.compact; objectName: editorBar.scope + "headlineButton"; iconName: "headline"; label: qsTr("Headline"); description: qsTr("Headline") + " (Ctrl+H)"; onClicked: win.formatSlide("headline") } + EditorButton { compact: editorBar.compact; objectName: editorBar.scope + "codeButton"; iconName: "code"; label: qsTr("Code"); description: qsTr("Code block") + " (Ctrl+K)"; onClicked: win.formatSlide("code") } + EditorButton { compact: editorBar.compact; objectName: editorBar.scope + "commentButton"; iconName: "comment"; label: qsTr("Note"); description: qsTr("Comment, hidden on slide") + " (Ctrl+/)"; onClicked: win.formatSlide("comment") } Item { Layout.fillWidth: true } - EditorButton { compact: editorBar.compact; iconName: "media-add"; label: "Media"; description: "Add image / video"; onClicked: deck.importDialog() } + EditorButton { compact: editorBar.compact; iconName: "media-add"; label: qsTr("Media"); description: qsTr("Add image / video"); onClicked: deck.importDialog() } EditorButton { compact: editorBar.compact - objectName: editorBar.scope + "mediaOptionsButton"; iconName: "adjust"; label: "Layout"; description: "Image / video options"; menu: true + objectName: editorBar.scope + "mediaOptionsButton"; iconName: "adjust"; label: qsTr("Layout"); description: qsTr("Image / video options"); menu: true enabled: !!deck.media.url.toString() dropdown: mediaMenu AppMenu { hasChecks: true id: mediaMenu; objectName: editorBar.scope + "mediaMenu"; y: parent.height + 4 readonly property bool placed: !!deck.media.position - AppMenuItem { text: "Fit"; checkable: true; checked: !deck.media.span && !mediaMenu.placed; onTriggered: deck.setMediaMode("fit") } - AppMenuItem { text: "Span"; checkable: true; checked: deck.media.span; onTriggered: deck.setMediaMode("span") } + AppMenuItem { text: qsTr("Fit"); checkable: true; checked: !deck.media.span && !mediaMenu.placed; onTriggered: deck.setMediaMode("fit") } + AppMenuItem { text: qsTr("Span"); checkable: true; checked: deck.media.span; onTriggered: deck.setMediaMode("span") } AppMenu { id: placeMenu; objectName: editorBar.scope + "placeMenu" - title: "Place"; hasChecks: true; enabled: !deck.media.video + title: qsTr("Place"); hasChecks: true; enabled: !deck.media.video Instantiator { model: deck.mediaPositions delegate: AppMenuItem { - // "bottom-right" reads as "Bottom right". - text: modelData.charAt(0).toUpperCase() + modelData.slice(1).replace("-", " ") + text: win.positionName(modelData) checkable: true; checked: deck.media.position === modelData onTriggered: deck.setMediaPosition(modelData) } @@ -921,17 +926,17 @@ ApplicationWindow { } AppMenu { objectName: editorBar.scope + "sizeMenu" - title: "Size"; hasChecks: true; enabled: mediaMenu.placed - AppMenuItem { text: "Small (10%)"; checkable: true; checked: deck.media.size === 10; onTriggered: deck.setMediaSize(10) } - AppMenuItem { text: "Medium (20%)"; checkable: true; checked: deck.media.size === 20; onTriggered: deck.setMediaSize(20) } - AppMenuItem { text: "Large (35%)"; checkable: true; checked: deck.media.size === 35; onTriggered: deck.setMediaSize(35) } + title: qsTr("Size"); hasChecks: true; enabled: mediaMenu.placed + AppMenuItem { text: qsTr("Small (10%)"); checkable: true; checked: deck.media.size === 10; onTriggered: deck.setMediaSize(10) } + AppMenuItem { text: qsTr("Medium (20%)"); checkable: true; checked: deck.media.size === 20; onTriggered: deck.setMediaSize(20) } + AppMenuItem { text: qsTr("Large (35%)"); checkable: true; checked: deck.media.size === 35; onTriggered: deck.setMediaSize(35) } } AppMenuSeparator {} - AppMenuItem { text: "Match image edges"; enabled: !mediaMenu.placed; checkable: true; checked: deck.media.background === "auto"; onTriggered: deck.matchImageBackground(true) } - AppMenuItem { text: deck.media.video ? "Blurred first frame" : "Blurred image"; enabled: !mediaMenu.placed; checkable: true; checked: deck.media.background === "blur"; onTriggered: deck.setMediaBackground("blur") } - AppMenuItem { objectName: editorBar.scope + "whiteBackgroundItem"; text: "White"; enabled: !mediaMenu.placed; checkable: true; checked: deck.media.background === "white"; onTriggered: deck.setMediaBackground("white") } - AppMenuItem { text: "Black"; enabled: !mediaMenu.placed; checkable: true; checked: deck.media.background === "black"; onTriggered: deck.setMediaBackground("black") } - AppMenuItem { text: "Use theme color"; enabled: !mediaMenu.placed; checkable: true; checked: deck.media.background === "theme"; onTriggered: deck.matchImageBackground(false) } + AppMenuItem { text: qsTr("Match image edges"); enabled: !mediaMenu.placed; checkable: true; checked: deck.media.background === "auto"; onTriggered: deck.matchImageBackground(true) } + AppMenuItem { text: deck.media.video ? qsTr("Blurred first frame") : qsTr("Blurred image"); enabled: !mediaMenu.placed; checkable: true; checked: deck.media.background === "blur"; onTriggered: deck.setMediaBackground("blur") } + AppMenuItem { objectName: editorBar.scope + "whiteBackgroundItem"; text: qsTr("White"); enabled: !mediaMenu.placed; checkable: true; checked: deck.media.background === "white"; onTriggered: deck.setMediaBackground("white") } + AppMenuItem { text: qsTr("Black"); enabled: !mediaMenu.placed; checkable: true; checked: deck.media.background === "black"; onTriggered: deck.setMediaBackground("black") } + AppMenuItem { text: qsTr("Use theme color"); enabled: !mediaMenu.placed; checkable: true; checked: deck.media.background === "theme"; onTriggered: deck.matchImageBackground(false) } } } } @@ -948,8 +953,8 @@ ApplicationWindow { anchors.left: parent.left; anchors.leftMargin: win.inset; anchors.verticalCenter: parent.verticalCenter text: "Hype"; font.pixelSize: 22; font.bold: true color: logoHover.hovered ? win.ui.accentHover : win.ui.accent - Accessible.role: Accessible.Button; Accessible.name: "Keyboard shortcuts" - ToolTip.visible: logoHover.hovered; ToolTip.delay: 400; ToolTip.text: "Keyboard shortcuts (?)" + Accessible.role: Accessible.Button; Accessible.name: qsTr("Keyboard shortcuts") + ToolTip.visible: logoHover.hovered; ToolTip.delay: 400; ToolTip.text: qsTr("Keyboard shortcuts") + " (?)" HoverHandler { id: logoHover; cursorShape: Qt.PointingHandCursor } TapHandler { onTapped: shortcutsOverlay.open() } } @@ -970,14 +975,14 @@ ApplicationWindow { width: Math.min(implicitWidth, summary.room); elide: Text.ElideRight text: deck.exporting ? deck.exportStatus : win.flash ? win.flash - : deck.selectionCount > 1 ? deck.selectionCount + " slides selected" : "Slide " + (deck.selected+1) + " of " + deck.count + : deck.selectionCount > 1 ? qsTr("%Ln slides selected", "", deck.selectionCount) : qsTr("Slide %1 of %2").arg(deck.selected + 1).arg(deck.count) font.pixelSize: 12; color: win.flash && win.flashFailed && !deck.exporting ? win.ui.error : win.ui.muted ToolTip.visible: statusHover.hovered && truncated; ToolTip.text: text HoverHandler { id: statusHover } } } Rectangle { - visible: deck.exporting; Accessible.name: "Export progress" + visible: deck.exporting; Accessible.name: qsTr("Export progress") x: win.inset; anchors.bottom: parent.bottom width: (parent.width - 2 * win.inset) * deck.exportProgress; height: 2; color: win.ui.accent } @@ -988,7 +993,7 @@ ApplicationWindow { ToolButton { id: cancelExport visible: deck.exporting; Layout.preferredHeight: 36; leftPadding: 10; rightPadding: 10 - contentItem: Label { text: "Cancel export"; font.pixelSize: 12; color: cancelExport.hovered ? win.ui.foreground : win.ui.muted; verticalAlignment: Text.AlignVCenter } + contentItem: Label { text: qsTr("Cancel export"); font.pixelSize: 12; color: cancelExport.hovered ? win.ui.foreground : win.ui.muted; verticalAlignment: Text.AlignVCenter } background: Rectangle { color: cancelExport.hovered || cancelExport.down ? win.ui.hover : "transparent"; radius: win.softRadius } onClicked: deck.cancelExport() } @@ -999,8 +1004,8 @@ ApplicationWindow { contentItem: Item { AppIcon { anchors.centerIn: parent; width: 18; height: 18; name: "theme"; color: themes.hovered || themes.popup.visible ? win.ui.foreground : win.ui.muted } } - Accessible.name: "Theme: " + currentText - ToolTip.visible: hovered; ToolTip.text: "Theme: " + currentText + Accessible.name: qsTr("Theme: %1").arg(currentText) + ToolTip.visible: hovered; ToolTip.text: qsTr("Theme: %1").arg(currentText) delegate: ItemDelegate { required property string modelData required property int index @@ -1034,7 +1039,7 @@ ApplicationWindow { return showNotoVariants || !name.startsWith("Noto ") || ["Noto Sans", "Noto Serif", "Noto Sans Mono", deck.fontName].indexOf(name) >= 0 }) - model: visibleFonts.concat([showNotoVariants ? "Fewer Noto fonts" : "More Noto fonts…"]) + model: visibleFonts.concat([showNotoVariants ? qsTr("Fewer Noto fonts") : qsTr("More Noto fonts…")]) currentIndex: visibleFonts.indexOf(deck.fontName) displayText: deck.fontName onActivated: function(index) { @@ -1049,7 +1054,7 @@ ApplicationWindow { contentItem: Item { AppIcon { anchors.centerIn: parent; width: 18; height: 18; name: "font"; color: fonts.hovered || fonts.popup.visible ? win.ui.foreground : win.ui.muted } } - Accessible.name: "Font: " + deck.fontName + Accessible.name: qsTr("Font: %1").arg(deck.fontName) delegate: ItemDelegate { required property string modelData required property int index @@ -1071,43 +1076,43 @@ ApplicationWindow { } onOpened: contentItem.positionViewAtIndex(fonts.currentIndex, ListView.Contain) } - ToolTip.visible: hovered; ToolTip.text: "Font: " + deck.fontName + ToolTip.visible: hovered; ToolTip.text: qsTr("Font: %1").arg(deck.fontName) } // Two switches, like their shortcuts: the overview on or off, and slides or source. ToolbarIconButton { objectName: "overviewButton"; iconName: "overview" ink: win.overview ? win.ui.accent : win.ui.muted - description: (win.overview ? "Leave the overview" : "Overview") + " (Ctrl+M)" + description: (win.overview ? qsTr("Leave the overview") : qsTr("Overview")) + " (Ctrl+M)" onClicked: win.toggleOverview() } ToolbarIconButton { objectName: "modeButton" focusPolicy: Qt.NoFocus iconName: win.editingMode - description: (win.editingMode === "markdown" ? "Markdown · Switch to Visual" : "Visual · Switch to Markdown") + " (Ctrl+.)" + description: (win.editingMode === "markdown" ? qsTr("Markdown · Switch to Visual") : qsTr("Visual · Switch to Markdown")) + " (Ctrl+.)" onClicked: win.overview ? win.setMode(win.editingMode === "markdown" ? "visual" : "markdown") : win.toggleSource() } ToolbarIconButton { objectName: "fileButton"; iconName: "file"; ink: deck.dirty ? win.ui.accent : win.ui.muted - description: deck.dirty ? "File · Unsaved changes" : "File" + description: deck.dirty ? qsTr("File · Unsaved changes") : qsTr("File") dropdown: fileMenu AppMenu { id: fileMenu; objectName: "fileMenu" y: parent.height + 4 - AppMenuItem { text: "New presentation"; hint: "Ctrl+N"; onTriggered: deck.newDeck() } - AppMenuItem { text: "Open…"; hint: "Ctrl+O"; onTriggered: deck.openDialog() } + AppMenuItem { text: qsTr("New presentation"); hint: "Ctrl+N"; onTriggered: deck.newDeck() } + AppMenuItem { text: qsTr("Open…"); hint: "Ctrl+O"; onTriggered: deck.openDialog() } AppMenuSeparator {} - AppMenuItem { text: deck.dirty ? "Save changes" : "Save"; hint: "Ctrl+S"; onTriggered: deck.save() } - AppMenuItem { text: "Save as…"; hint: "Ctrl+Shift+S"; onTriggered: deck.saveAs() } + AppMenuItem { text: deck.dirty ? qsTr("Save changes") : qsTr("Save"); hint: "Ctrl+S"; onTriggered: deck.save() } + AppMenuItem { text: qsTr("Save as…"); hint: "Ctrl+Shift+S"; onTriggered: deck.saveAs() } AppMenuSeparator {} - AppMenuItem { text: "Export as PDF…"; hint: "Ctrl+E"; enabled: !deck.exporting; onTriggered: deck.exportDialog("pdf") } - AppMenuItem { text: "Export as PowerPoint…"; hint: "Ctrl+Shift+E"; enabled: !deck.exporting; onTriggered: deck.exportDialog("pptx") } + AppMenuItem { text: qsTr("Export as PDF…"); hint: "Ctrl+E"; enabled: !deck.exporting; onTriggered: deck.exportDialog("pdf") } + AppMenuItem { text: qsTr("Export as PowerPoint…"); hint: "Ctrl+Shift+E"; enabled: !deck.exporting; onTriggered: deck.exportDialog("pptx") } AppMenuSeparator {} - AppMenuItem { text: "Version history…"; onTriggered: historyDialog.open() } + AppMenuItem { text: qsTr("Version history…"); onTriggered: historyDialog.open() } } } ToolbarIconButton { - objectName: "presentButton"; iconName: "present"; description: "Present (Ctrl+Space)"; primary: true + objectName: "presentButton"; iconName: "present"; description: qsTr("Present") + " (Ctrl+Space)"; primary: true onClicked: win.togglePresent() } } @@ -1120,25 +1125,25 @@ ApplicationWindow { Overlay.modal: Rectangle { color: Qt.rgba(0, 0, 0, 0.35) } background: Rectangle { color: Qt.alpha(win.ui.panel, 0.92); border.color: win.ui.windowBorder; border.width: 2; radius: win.rounding } readonly property var groups: [ - { title: "Presentation", keys: [ - ["Ctrl+N", "New presentation"], ["Ctrl+O", "Open"], ["Ctrl+S", "Save"], ["Ctrl+Shift+S", "Save as"], ["Ctrl+Q", "Quit"], - ["Ctrl+E", "Export as PDF"], ["Ctrl+Shift+E", "Export as PowerPoint"], ["Ctrl+Space / F5", "Present"], ["Shift+F5", "Present from first slide"], ["Esc", "Stop presenting"], - ["Space", "Play or pause video while presenting"] ] }, - { title: "View", keys: [ - ["Ctrl+M", "Overview on or off"], ["Ctrl+.", "Markdown source on or off"], - ["Tab", "Switch between slides and editor"], ["Enter", "Open slide from Overview"], - ["? / F1", "Show these shortcuts"] ] }, - { title: "Slides", keys: [ - ["Arrows", "Previous or next slide, by row in Overview"], ["Page Up / Page Down", "Jump five slides, or five rows in Overview"], - ["Home / End", "First or last slide when focused in Slides list"], ["Shift+Arrows", "Extend the selection"], - ["Ctrl+Arrows", "Move selected slides"], ["Ctrl+Page Up / Page Down", "Move selected slides five places"], - ["Ctrl+Home / End", "Move selected slides to first or last"], ["Ctrl+Enter", "Add a slide"], - ["Ctrl+D", "Duplicate"], ["Delete", "Delete"] ] }, - { title: "Editing", keys: [ - ["Ctrl+B", "Bold"], ["Ctrl+I", "Italic"], ["Ctrl+U", "Underline"], ["Ctrl+H", "Headline"], ["Ctrl+K", "Code block"], - ["Ctrl+Up / Down", "Previous or next slide"], ["Ctrl+Page Up / Page Down", "Jump five slides"], - ["Ctrl+/", "Comment, hidden on slide"], - ["Home / End", "Start or end of the line"], ["Ctrl+Z", "Undo"], ["Ctrl+Shift+Z", "Redo"], ["Ctrl+V", "Paste text, or add and name media"] ] } + { title: qsTr("Presentation"), keys: [ + ["Ctrl+N", qsTr("New presentation")], ["Ctrl+O", qsTr("Open")], ["Ctrl+S", qsTr("Save")], ["Ctrl+Shift+S", qsTr("Save as")], ["Ctrl+Q", qsTr("Quit")], + ["Ctrl+E", qsTr("Export as PDF")], ["Ctrl+Shift+E", qsTr("Export as PowerPoint")], ["Ctrl+Space / F5", qsTr("Present")], ["Shift+F5", qsTr("Present from first slide")], ["Esc", qsTr("Stop presenting")], + ["Space", qsTr("Play or pause video while presenting")] ] }, + { title: qsTr("View"), keys: [ + ["Ctrl+M", qsTr("Overview on or off")], ["Ctrl+.", qsTr("Markdown source on or off")], + ["Tab", qsTr("Switch between slides and editor")], ["Enter", qsTr("Open slide from Overview")], + ["? / F1", qsTr("Show these shortcuts")] ] }, + { title: qsTr("Slides"), keys: [ + ["Arrows", qsTr("Previous or next slide, by row in Overview")], ["Page Up / Page Down", qsTr("Jump five slides, or five rows in Overview")], + ["Home / End", qsTr("First or last slide when focused in Slides list")], ["Shift+Arrows", qsTr("Extend the selection")], + ["Ctrl+Arrows", qsTr("Move selected slides")], ["Ctrl+Page Up / Page Down", qsTr("Move selected slides five places")], + ["Ctrl+Home / End", qsTr("Move selected slides to first or last")], ["Ctrl+Enter", qsTr("Add a slide")], + ["Ctrl+D", qsTr("Duplicate")], ["Delete", qsTr("Delete")] ] }, + { title: qsTr("Editing"), keys: [ + ["Ctrl+B", qsTr("Bold")], ["Ctrl+I", qsTr("Italic")], ["Ctrl+U", qsTr("Underline")], ["Ctrl+H", qsTr("Headline")], ["Ctrl+K", qsTr("Code block")], + ["Ctrl+Up / Down", qsTr("Previous or next slide")], ["Ctrl+Page Up / Page Down", qsTr("Jump five slides")], + ["Ctrl+/", qsTr("Comment, hidden on slide")], + ["Home / End", qsTr("Start or end of the line")], ["Ctrl+Z", qsTr("Undo")], ["Ctrl+Shift+Z", qsTr("Redo")], ["Ctrl+V", qsTr("Paste text, or add and name media")] ] } ] contentItem: ColumnLayout { spacing: 22; focus: true @@ -1146,7 +1151,7 @@ ApplicationWindow { Keys.onPressed: function(event) { if (event.text === "?" || event.key === Qt.Key_F1) { shortcutsOverlay.close(); event.accepted = true } } - Label { text: "Keyboard shortcuts"; font.pixelSize: 16; font.bold: true; color: win.ui.foreground } + Label { text: qsTr("Keyboard shortcuts"); font.pixelSize: 16; font.bold: true; color: win.ui.foreground } GridLayout { columns: win.width < 820 ? 1 : 2; columnSpacing: 48; rowSpacing: 22 Repeater { @@ -1171,10 +1176,10 @@ ApplicationWindow { } // Shared by the sidebar and the overview, so it cannot live inside either. AppMenu { id: slideMenu - AppMenuItem { text: "New slide after this"; hint: "Ctrl+Enter"; onTriggered: { win.addSlide() } } - AppMenuItem { text: deck.selectionCount > 1 ? "Duplicate slides" : "Duplicate slide"; hint: "Ctrl+D"; onTriggered: deck.duplicateSlide() } + AppMenuItem { text: qsTr("New slide after this"); hint: "Ctrl+Enter"; onTriggered: { win.addSlide() } } + AppMenuItem { text: deck.selectionCount > 1 ? qsTr("Duplicate slides") : qsTr("Duplicate slide"); hint: "Ctrl+D"; onTriggered: deck.duplicateSlide() } AppMenuSeparator {} - AppMenuItem { text: deck.selectionCount > 1 ? "Delete slides" : "Delete slide"; hint: "Del"; destructive: true; onTriggered: deck.deleteSlide() } + AppMenuItem { text: deck.selectionCount > 1 ? qsTr("Delete slides") : qsTr("Delete slide"); hint: "Del"; destructive: true; onTriggered: deck.deleteSlide() } } RowLayout { anchors.fill: parent; spacing: 0 @@ -1548,7 +1553,7 @@ ApplicationWindow { fillMode: deck.media.span ? VideoOutput.PreserveAspectCrop : VideoOutput.PreserveAspectFit } Image { anchors.fill: parent; source: visible ? "image://slides/" + (deck.revision, deck.renderId(deck.selected)) + "/overlay" : ""; asynchronous: true; retainWhileLoading: true; sourceSize: Qt.size(1920,1080); visible: animation.active || (video.visible && deck.media.span) } - Button { visible: deck.media.video && !win.presenting; anchors.centerIn: parent; text: player.playbackState === MediaPlayer.PlayingState ? "Pause" : "▶ Play"; onClicked: win.toggleVideo() } + Button { visible: deck.media.video && !win.presenting; anchors.centerIn: parent; text: player.playbackState === MediaPlayer.PlayingState ? qsTr("Pause") : "▶ " + qsTr("Play"); onClicked: win.toggleVideo() } MouseArea { anchors.fill: parent enabled: win.presenting @@ -1580,7 +1585,7 @@ ApplicationWindow { TextArea { id: slideEditor; objectName: "slideEditor"; persistentSelection: true; textFormat: TextEdit.PlainText; color: win.ui.foreground; selectionColor: win.ui.selection; selectedTextColor: win.ui.selectionText; font.family: "JetBrains Mono"; font.pixelSize: 16 onActiveFocusChanged: if (activeFocus) win.focusedEditor = "slide" - wrapMode: TextEdit.Wrap; leftPadding: 24; topPadding: 16; placeholderText: "# Your headline" + wrapMode: TextEdit.Wrap; leftPadding: 24; topPadding: 16; placeholderText: "# " + qsTr("Your headline") onTextChanged: { if (!win.syncingEditor && activeFocus) { const previousCount = deck.count diff --git a/src/animationexport.cpp b/src/animationexport.cpp index 731f5c0..84b877a 100644 --- a/src/animationexport.cpp +++ b/src/animationexport.cpp @@ -1,6 +1,7 @@ #include "animationexport.h" #include "pptx.h" #include "renderer.h" +#include #include #include #include @@ -9,6 +10,9 @@ #include #include #include + +// Hype's free functions translate like its classes do; the Translator ignores the context. +static QString tr(const char *text) { return QCoreApplication::translate("Hype", text); } #include bool exportAnimation(const QString &source, const QString &base, const QVariantMap &palette, @@ -35,7 +39,7 @@ bool exportAnimation(const QString &source, const QString &base, const QVariantM size_t(webpBytes.size())}; webp.reset(WebPAnimDecoderNew(&data, nullptr)); if (!webp || !WebPAnimDecoderGetInfo(webp.get(), &info)) { - *error = "Cannot decode WebP animation"; + *error = tr("Cannot decode WebP animation"); return false; } frames = int(info.frame_count); @@ -90,7 +94,7 @@ bool exportAnimation(const QString &source, const QString &base, const QVariantM "+faststart", QFileInfo(output).absoluteFilePath()}); if (!encoder.waitForStarted()) { - *error = "Cannot start ffmpeg for animation conversion: " + encoder.errorString(); + *error = tr("Cannot start ffmpeg for animation conversion: %1").arg(encoder.errorString()); return false; } const auto cleanup = qScopeGuard([&] { @@ -127,7 +131,7 @@ bool exportAnimation(const QString &source, const QString &base, const QVariantM uint8_t *pixels = nullptr; int timestamp = 0; if (!WebPAnimDecoderGetNext(webp.get(), &pixels, ×tamp)) { - *error = "Cannot decode WebP frame " + QString::number(i + 1); + *error = tr("Cannot decode WebP frame %1").arg(i + 1); return false; } frame = QImage(pixels, int(info.canvas_width), int(info.canvas_height), @@ -139,8 +143,7 @@ bool exportAnimation(const QString &source, const QString &base, const QVariantM delay = qMax(1, reader.nextImageDelay()); } if (frame.isNull()) { - *error = "Cannot decode animation frame " + QString::number(i + 1) + ": " + - reader.errorString(); + *error = tr("Cannot decode animation frame %1: %2").arg(QString::number(i + 1), reader.errorString()); return false; } QImage slide = background.copy(); @@ -163,8 +166,7 @@ bool exportAnimation(const QString &source, const QString &base, const QVariantM const QImage pixels = slide.convertToFormat(QImage::Format_RGBA8888); while (writtenFrames < targetFrames) { if (!writeFrame(pixels)) { - *error = "Animation conversion failed: " + - QString::fromUtf8(diagnostics + encoder.readAllStandardError()).trimmed(); + *error = tr("Animation conversion failed: %1").arg(QString::fromUtf8(diagnostics + encoder.readAllStandardError()).trimmed()); return false; } ++writtenFrames; @@ -176,7 +178,7 @@ bool exportAnimation(const QString &source, const QString &base, const QVariantM diagnostics = (diagnostics + encoder.readAllStandardError()).right(8192); } while (encoder.state() != QProcess::NotRunning); if (encoder.exitStatus() != QProcess::NormalExit || encoder.exitCode() != 0) { - *error = "Animation conversion failed: " + QString::fromUtf8(diagnostics).trimmed(); + *error = tr("Animation conversion failed: %1").arg(QString::fromUtf8(diagnostics).trimmed()); return false; } if (progress) diff --git a/src/deck.cpp b/src/deck.cpp index 4a78fb8..5a91650 100644 --- a/src/deck.cpp +++ b/src/deck.cpp @@ -43,6 +43,9 @@ #include #include #include + +// Hype's free functions translate like its classes do; the Translator ignores the context. +static QString tr(const char *text) { return QCoreApplication::translate("Hype", text); } #include ParsedDeck parseDeck(const QString &source) { @@ -70,7 +73,7 @@ ParsedDeck parseDeck(const QString &source) { offset = next; } if (!closed) { - result.error = "Front matter needs a closing ---"; + result.error = tr("Front matter needs a closing ---"); result.errorOffset = contentStart; result.slides.append({source, 0, int(source.size())}); return result; @@ -100,7 +103,7 @@ ParsedDeck parseDeck(const QString &source) { } result.slides.append({source.mid(start), start, int(source.size())}); if (fenceLength && result.error.isEmpty()) { - result.error = "Unclosed code fence"; + result.error = tr("Unclosed code fence"); result.errorOffset = fenceStart; } return result; @@ -167,7 +170,7 @@ Deck::Deck(QObject *parent, const QString &exportProgram) : QAbstractListModel(p return; if (!file.open(QIODevice::ReadOnly)) { m_externalChange = true; - setStatus("Presentation changed or was removed outside Hype."); + setStatus(tr("Presentation changed or was removed outside Hype.")); return; } const QString disk = QString::fromUtf8(file.readAll()); @@ -176,7 +179,7 @@ Deck::Deck(QObject *parent, const QString &exportProgram) : QAbstractListModel(p reloadExternal(disk); } else { m_externalChange = true; - setStatus("Changed on disk. Save a copy or reopen to reload."); + setStatus(tr("Changed on disk. Save a copy or reopen to reload.")); } } watch(); @@ -226,7 +229,7 @@ void Deck::reloadExternal(const QString &disk) { // Matching text leaves the source alone, but the saved state changed. if (unchanged) notifyChanged(); - setStatus("Reloaded external changes."); + setStatus(tr("Reloaded external changes.")); } int Deck::rowCount(const QModelIndex &parent) const { return parent.isValid() ? 0 : count(); } QVariant Deck::data(const QModelIndex &index, int role) const { @@ -254,7 +257,7 @@ QString Deck::baseDir() const { } QString Deck::title() const { return scalar(m_parsed.header, "title", - m_path.isEmpty() ? "Untitled" : QFileInfo(m_path).completeBaseName()); + m_path.isEmpty() ? tr("Untitled") : QFileInfo(m_path).completeBaseName()); } void Deck::setStatus(const QString &s) { m_status = s; @@ -696,7 +699,7 @@ bool Deck::reopenLastPresentation() { apply(QString(), 0, false); m_externalChange = true; notifyChanged(); - setStatus("The last presentation is missing. Use Save As to recover it to a new file."); + setStatus(tr("The last presentation is missing. Use Save As to recover it to a new file.")); return false; } bool Deck::loadPath(const QString &path, bool remember) { @@ -714,7 +717,7 @@ bool Deck::loadPath(const QString &path, bool remember) { m_externalChange = false; watch(); notifyChanged(); - setStatus("Opened " + title()); + setStatus(tr("Opened %1").arg(title())); if (remember) rememberPresentation(m_path); recoverDraft(); @@ -729,9 +732,11 @@ bool Deck::validateStructure(const QString &operation) { sameSlides = parsed.slides[i].source == m_parsed.slides[i].source; if (!parsed.error.isEmpty() || !m_parsed.error.isEmpty() || !sameSlides) { const QString problem = !m_parsed.error.isEmpty() ? m_parsed.error : - !parsed.error.isEmpty() ? parsed.error : "Unfinished slide boundaries"; - setStatus("Cannot " + operation + ": " + problem + - ". Finish the Markdown first; your changes are still in the editor."); + !parsed.error.isEmpty() ? parsed.error : tr("Unfinished slide boundaries"); + setStatus((operation == "save" + ? tr("Cannot save: %1. Finish the Markdown first; your changes are still in the editor.") + : tr("Cannot export: %1. Finish the Markdown first; your changes are still in the editor.")) + .arg(problem)); return false; } return true; @@ -740,24 +745,24 @@ bool Deck::savePath(const QString &path) { if (!validateStructure("save")) return false; if (QFileInfo(path).absoluteFilePath() == m_path && m_externalChange) { - setStatus("File changed on disk. Use Save As to keep both versions."); + setStatus(tr("File changed on disk. Use Save As to keep both versions.")); return false; } QByteArray previous; if (QFile::exists(path)) { QFile disk(path); if (!disk.open(QIODevice::ReadOnly)) { - setStatus("Cannot read the existing presentation: " + disk.errorString()); + setStatus(tr("Cannot read the existing presentation: %1").arg(disk.errorString())); return false; } previous = disk.readAll(); if (disk.error() != QFile::NoError) { - setStatus("Cannot read the existing presentation: " + disk.errorString()); + setStatus(tr("Cannot read the existing presentation: %1").arg(disk.errorString())); return false; } if (QFileInfo(path).absoluteFilePath() == m_path && QString::fromUtf8(previous) != m_saved) { m_externalChange = true; - setStatus("File changed on disk. Save a copy or reopen."); + setStatus(tr("File changed on disk. Save a copy or reopen.")); return false; } } @@ -771,7 +776,7 @@ bool Deck::savePath(const QString &path) { QSaveFile backup(backups.filePath(backupPrefix + stamp + "-" + hash + ".bak")); if (!QDir().mkpath(backups.absolutePath()) || !backup.open(QIODevice::WriteOnly) || backup.write(previous) != previous.size() || !backup.commit()) { - setStatus("Could not create a recovery backup. The saved presentation was left untouched."); + setStatus(tr("Could not create a recovery backup. The saved presentation was left untouched.")); return false; } } @@ -789,7 +794,7 @@ bool Deck::savePath(const QString &path) { m_externalChange = false; watch(); notifyChanged(); - setStatus("Saved"); + setStatus(tr("Saved")); rememberPresentation(m_path); if (!m_recoveryDirectory.isEmpty()) checkpoint(); @@ -800,7 +805,7 @@ bool Deck::confirmDiscard() { return flushAutosave(); if (!dirty()) return true; - setStatus("Save this presentation before opening another one."); + setStatus(tr("Save this presentation before opening another one.")); return false; } void Deck::openDialog() { @@ -839,7 +844,7 @@ bool Deck::saveCopyPath(const QString &path) { const QDir destination(QFileInfo(path).absolutePath()); QTemporaryDir staging(destination.filePath(".hype-save-XXXXXX")); if (!staging.isValid()) { - setStatus("Could not prepare the presentation directory."); + setStatus(tr("Could not prepare the presentation directory.")); return false; } QList> copies; @@ -866,18 +871,18 @@ bool Deck::saveCopyPath(const QString &path) { QCryptographicHash ah(QCryptographicHash::Sha256), bh(QCryptographicHash::Sha256); if (!a.open(QIODevice::ReadOnly) || !b.open(QIODevice::ReadOnly) || !ah.addData(&a) || !bh.addData(&b)) { - setStatus("Could not read media while copying"); + setStatus(tr("Could not read media while copying")); return false; } if (ah.result() != bh.result()) { - setStatus("Save As media collision: " + relative); + setStatus(tr("Save As media collision: %1").arg(relative)); return false; } } else { const QString staged = staging.filePath(relative); QDir().mkpath(QFileInfo(staged).absolutePath()); if (!QFile::copy(file, staged)) { - setStatus("Could not copy " + relative); + setStatus(tr("Could not copy %1").arg(relative)); return false; } copies.append({staged, target}); @@ -901,14 +906,14 @@ bool Deck::saveCopyPath(const QString &path) { for (const auto &directory : missing) { if (!QDir().mkdir(directory)) { rollback(); - setStatus("Could not create media directory"); + setStatus(tr("Could not create media directory")); return false; } directories << directory; } if (!QFile::rename(copy.first, copy.second)) { rollback(); - setStatus("Could not publish copied media"); + setStatus(tr("Could not publish copied media")); return false; } published << copy.second; @@ -920,7 +925,7 @@ bool Deck::saveCopyPath(const QString &path) { for (const QString &problem : slideProblems(slide(i), destination.absolutePath())) { if (!before.contains(problem)) { rollback(); - setStatus(QString("Save As could not copy media for slide %1: %2") + setStatus(tr("Save As could not copy media for slide %1: %2") .arg(i + 1) .arg(problem)); return false; @@ -952,7 +957,7 @@ void Deck::newDeck() { } void Deck::importDialog() { QString error; - const QString p = FileDialog::choose(false, baseDir(), "Media", + const QString p = FileDialog::choose(false, baseDir(), tr("Media"), {"*.png", "*.jpg", "*.jpeg", "*.webp", "*.gif", "*.svg", "*.mp4", "*.mov", "*.mkv", "*.webm", "*.m4v"}, &error); if (!error.isEmpty()) setStatus(error); @@ -961,7 +966,7 @@ void Deck::importDialog() { } bool Deck::importMedia(const QUrl &url, bool newSlide) { if (!url.isLocalFile()) { - setStatus("Choose a local image or video."); + setStatus(tr("Choose a local image or video.")); return false; } if (m_path.isEmpty()) { @@ -974,7 +979,7 @@ bool Deck::importMedia(const QUrl &url, bool newSlide) { return false; bool video = QStringList{"mp4", "mov", "mkv", "webm", "m4v"}.contains(info.suffix().toLower()); if (!video && !QImageReader(info.absoluteFilePath()).canRead()) { - setStatus("Choose a supported image or video."); + setStatus(tr("Choose a supported image or video.")); return false; } QString dir = baseDir() + (video ? "/videos" : "/images"); @@ -995,7 +1000,7 @@ bool Deck::importMedia(const QUrl &url, bool newSlide) { while (QFile::exists(dest)) { QFile old(dest); if (!old.open(QIODevice::ReadOnly)) { - setStatus("Cannot read existing media: " + name); + setStatus(tr("Cannot read existing media: %1").arg(name)); return false; } QCryptographicHash oldHash(QCryptographicHash::Sha256); @@ -1009,7 +1014,7 @@ bool Deck::importMedia(const QUrl &url, bool newSlide) { dest = dir + "/" + name; } if (!QFile::exists(dest) && !QFile::copy(info.absoluteFilePath(), dest)) { - setStatus("Could not import " + name); + setStatus(tr("Could not import %1").arg(name)); return false; } if (newSlide) @@ -1101,7 +1106,7 @@ bool Deck::pasteMedia() { if (m_path != result.first.path || m_source != result.first.document || m_selected != result.first.selected) { m_paste = {}; - setStatus("The slide changed. Paste the image again."); + setStatus(tr("The slide changed. Paste the image again.")); return; } m_paste = std::move(result.first); @@ -1126,11 +1131,11 @@ bool Deck::pasteMedia() { image = image.scaled(target, Qt::IgnoreAspectRatio, Qt::SmoothTransformation); } if (image.isNull()) - return {{}, "Could not read the pasted image."}; + return {{}, tr("Could not read the pasted image.")}; QString optimizedExtension; QByteArray encoded = compressedImage(image, &optimizedExtension); if (encoded.isEmpty()) - return {{}, "Could not compress the pasted image."}; + return {{}, tr("Could not compress the pasted image.")}; // Keep an already-small JPEG/WebP when it beats the lossless rewrite. if (pending.source.isEmpty() || image.size() != original || encoded.size() < QFileInfo(pending.source).size()) { @@ -1152,24 +1157,24 @@ void Deck::cancelPaste() { } QString Deck::savePastedMedia(const QString &value) { if (m_compressingImage) - return "The image is still being compressed."; + return tr("The image is still being compressed."); if (m_paste.extension.isEmpty()) - return "Paste an image or video first."; + return tr("Paste an image or video first."); if (m_path != m_paste.path || m_source != m_paste.document || m_selected != m_paste.selected) - return "The slide changed. Cancel and paste again."; + return tr("The slide changed. Cancel and paste again."); QString stem = value.trimmed(); if (stem.endsWith("." + m_paste.extension, Qt::CaseInsensitive)) stem.chop(m_paste.extension.size() + 1); if (stem.isEmpty() || stem == "." || stem == ".." || stem.contains(QRegularExpression(R"([/\\<>\x00-\x1f])"))) - return "Use a filename without folders or special characters."; + return tr("Use a filename without folders or special characters."); const QString name = stem + "." + m_paste.extension; const QString directory = QDir(baseDir()).filePath(m_paste.video ? "videos" : "images"); const QString destination = QDir(directory).filePath(name); if (QFile::exists(destination)) return name + " already exists. Choose another name."; if (!QDir().mkpath(directory)) - return "Could not create " + directory; + return tr("Could not create %1").arg(directory); bool saved = false; if (!m_paste.source.isEmpty()) saved = QFile::copy(m_paste.source, destination); @@ -1184,7 +1189,7 @@ QString Deck::savePastedMedia(const QString &value) { } } if (!saved) - return "Could not save " + name; + return tr("Could not save %1").arg(name); cancelPaste(); editSlide(withReplacedMedia(slideSource(), name)); setStatus("Added " + name); @@ -1299,7 +1304,7 @@ bool Deck::loadExportSnapshot(const QString &path) { } const auto snapshot = QJsonDocument::fromJson(file.readAll()).object(); if (!snapshot["source"].isString() || !snapshot["path"].isString()) { - setStatus("Invalid export snapshot."); + setStatus(tr("Invalid export snapshot.")); return false; } m_path = snapshot["path"].toString(); @@ -1329,7 +1334,7 @@ void Deck::startExport(const QString &format, const QString &path) { {"palette", QJsonObject::fromVariantMap(palette())}}).toJson(); if (!temporary->isValid() || !staged->isValid() || !snapshot.open(QIODevice::WriteOnly) || snapshot.write(data) != data.size()) { m_exportFailed = true; - m_exportStatus = "Could not prepare the export."; + m_exportStatus = tr("Could not prepare the export."); emit exportChanged(); emit exportFinished(false); return; @@ -1339,7 +1344,7 @@ void Deck::startExport(const QString &format, const QString &path) { m_exportCancelled = false; m_exportFailed = false; m_exportProgress = 0; - m_exportStatus = "Preparing " + format.toUpper() + " export…"; + m_exportStatus = tr("Preparing %1 export…").arg(format.toUpper()); emit exportChanged(); auto *process = new QProcess(this); m_exportProcess = process; @@ -1382,13 +1387,13 @@ void Deck::startExport(const QString &format, const QString &path) { if (success && ::rename(QFile::encodeName(staged->filePath("output")).constData(), QFile::encodeName(destination).constData()) != 0) { success = false; - message = "Could not save the export: " + QString::fromLocal8Bit(std::strerror(errno)); + message = tr("Could not save the export: %1").arg(QString::fromLocal8Bit(std::strerror(errno))); } m_exporting = false; m_exportProcess = nullptr; m_exportFailed = !success && !m_exportCancelled; if (success) m_exportProgress = 1; - m_exportStatus = m_exportCancelled ? "Export cancelled" : success ? "Exported " + QFileInfo(destination).fileName() : "Export failed: " + message; + m_exportStatus = m_exportCancelled ? tr("Export cancelled") : success ? tr("Exported %1").arg(QFileInfo(destination).fileName()) : tr("Export failed: %1").arg(message); process->deleteLater(); emit exportChanged(); emit exportFinished(success); @@ -1399,7 +1404,7 @@ void Deck::startExport(const QString &format, const QString &path) { const bool success = exitStatus == QProcess::NormalExit && code == 0; QString error = *failure; if (error.isEmpty()) error = QString::fromUtf8(*diagnostics + process->readAllStandardError()).trimmed(); - if (error.isEmpty()) error = "The export process stopped unexpectedly."; + if (error.isEmpty()) error = tr("The export process stopped unexpectedly."); finish(success, error); }); connect(process, &QProcess::errorOccurred, this, [process, finish](QProcess::ProcessError error) { @@ -1414,7 +1419,7 @@ bool Deck::exportPdf(const QString &path) { for (int i = 0; i < count(); ++i) { auto errors = slideProblems(slide(i), baseDir()); if (!errors.isEmpty()) { - setStatus(QString("Slide %1: %2").arg(i + 1).arg(errors.join("; "))); + setStatus(tr("Slide %1: %2").arg(i + 1).arg(errors.join("; "))); return false; } } @@ -1433,13 +1438,13 @@ bool Deck::exportPdf(const QString &path) { // is three times faster and a fifth of the size of lossless PNG. QPainter painter(&writer); if (!painter.isActive()) { - setStatus("Could not initialize PDF painter"); + setStatus(tr("Could not initialize PDF painter")); return false; } for (int i = 0; i < count(); ++i) { - emit exportAdvanced(double(i) / count(), QString("Exporting slide %1 of %2").arg(i + 1).arg(count())); + emit exportAdvanced(double(i) / count(), tr("Exporting slide %1 of %2").arg(i + 1).arg(count())); if (i && !writer.newPage()) { - setStatus("Could not create PDF page"); + setStatus(tr("Could not create PDF page")); return false; } paintSlide(&painter, QRectF(0, 0, writer.width(), writer.height()), slide(i), baseDir(), @@ -1451,7 +1456,7 @@ bool Deck::exportPdf(const QString &path) { setStatus(file.errorString()); return false; } - setStatus("Exported " + path); + setStatus(tr("Exported %1").arg(path)); return true; } // Slides are opaque unless a custom background is translucent. Without an alpha @@ -1471,7 +1476,7 @@ bool Deck::renderImages(const QString &directory, int width, bool powerPoint) { for (int i = 0; i < count(); ++i) { auto errors = slideProblems(slide(i), baseDir()); if (!errors.isEmpty()) { - setStatus(QString("Slide %1: %2").arg(i + 1).arg(errors.join("; "))); + setStatus(tr("Slide %1: %2").arg(i + 1).arg(errors.join("; "))); return false; } } @@ -1523,7 +1528,7 @@ bool Deck::renderImages(const QString &directory, int width, bool powerPoint) { const double portion = 0.8; while (!stills.waitForDone(100)) { const auto done = std::count_if(rendered.cbegin(), rendered.cend(), [](const auto &f) { return f.isFinished(); }); - emit exportAdvanced(portion * done / count(), QString("Exporting slide %1 of %2").arg(qMin(count(), done + 1)).arg(count())); + emit exportAdvanced(portion * done / count(), tr("Exporting slide %1 of %2").arg(qMin(count(), done + 1)).arg(count())); } // Return the workers' freed canvases to the system before the encoder starts. malloc_trim(0); @@ -1532,15 +1537,15 @@ bool Deck::renderImages(const QString &directory, int width, bool powerPoint) { QHash convertedVideos; for (int i = 0; i < count(); ++i) { const double portion = powerPoint ? 0.8 : 1.0; - auto progress = [this, i, portion](double fraction, const QString &stage) { - emit exportAdvanced(portion * (i + fraction) / count(), - QString("%1 slide %2 of %3").arg(stage).arg(i + 1).arg(count())); + // `message` names the slide as %1 and the slide count as %2. + auto progress = [this, i, portion](double fraction, const QString &message) { + emit exportAdvanced(portion * (i + fraction) / count(), message.arg(i + 1).arg(count())); }; - progress(0, "Exporting"); + progress(0, tr("Exporting slide %1 of %2")); const Still still = rendered[i].result(); const QString name = still.name, warning = still.warning; if (!still.saved) { - setStatus("Could not save rendered slide"); + setStatus(tr("Could not save rendered slide")); return false; } auto media = parseMedia(slide(i), baseDir()); @@ -1553,9 +1558,9 @@ bool Deck::renderImages(const QString &directory, int width, bool powerPoint) { if (movie.isEmpty()) movie = preparePowerPointVideo( media.path, QString("%1/video-%2.mp4").arg(directory).arg(i + 1), &error, - [&](double fraction) { progress(fraction, "Converting video on"); }); + [&](double fraction) { progress(fraction, tr("Converting the video on slide %1 of %2")); }); if (movie.isEmpty()) { - setStatus(QString("Slide %1: %2").arg(i + 1).arg(error)); + setStatus(tr("Slide %1: %2").arg(i + 1).arg(error)); return false; } convertedVideos.insert(media.path, movie); @@ -1575,11 +1580,11 @@ bool Deck::renderImages(const QString &directory, int width, bool powerPoint) { const QString movie = QString("animation-%1.mp4").arg(i + 1); int repeats = 1; QString error; - progress(0, "Converting animation"); + progress(0, tr("Converting the animation on slide %1 of %2")); if (!exportAnimation(slide(i), baseDir(), palette(), directory + "/" + movie, width, &repeats, &error, - [&](double fraction) { progress(fraction, "Converting animation"); })) { - setStatus(QString("Slide %1: %2").arg(i + 1).arg(error)); + [&](double fraction) { progress(fraction, tr("Converting the animation on slide %1 of %2")); })) { + setStatus(tr("Slide %1: %2").arg(i + 1).arg(error)); return false; } // Composite the complete slide to preserve crop and alpha. @@ -1600,7 +1605,7 @@ bool Deck::renderImages(const QString &directory, int width, bool powerPoint) { op.end(); QString name = QString("overlay-%1.png").arg(i + 1); if (!overlay.save(directory + "/" + name)) { - setStatus("Could not save video overlay"); + setStatus(tr("Could not save video overlay")); return false; } entry["overlay_image"] = name; @@ -1610,7 +1615,7 @@ bool Deck::renderImages(const QString &directory, int width, bool powerPoint) { QSaveFile manifest(directory + "/slides.json"); const QByteArray json = QJsonDocument(QJsonObject{{"title", title()}, {"slides", slides}}).toJson(); if (!manifest.open(QIODevice::WriteOnly) || manifest.write(json) != json.size() || !manifest.commit()) { - setStatus("Could not save slides.json: " + manifest.errorString()); + setStatus(tr("Could not save slides.json: %1").arg(manifest.errorString())); return false; } return true; @@ -1620,18 +1625,18 @@ bool Deck::exportPptx(const QString &path) { // 4K slide images and converted videos would otherwise sit in memory until packaged. QTemporaryDir temp(QFileInfo(path).absoluteDir().filePath(".hype-render-XXXXXX")); if (!temp.isValid()) { - setStatus("Could not prepare the export: " + temp.errorString()); + setStatus(tr("Could not prepare the export: %1").arg(temp.errorString())); return false; } if (!renderImages(temp.path(), 3840, true)) return false; QString error; - emit exportAdvanced(0.8, "Packaging PowerPoint…"); + emit exportAdvanced(0.8, tr("Packaging PowerPoint…")); if (!writePptx(temp.path() + "/slides.json", path, &error, - [this](double fraction) { emit exportAdvanced(0.8 + 0.2 * fraction, "Packaging PowerPoint…"); })) { + [this](double fraction) { emit exportAdvanced(0.8 + 0.2 * fraction, tr("Packaging PowerPoint…")); })) { setStatus("PowerPoint export failed: " + error); return false; } - setStatus("Exported " + path); + setStatus(tr("Exported %1").arg(path)); return true; } diff --git a/src/filedialog.cpp b/src/filedialog.cpp index eaa6f8d..ec1892d 100644 --- a/src/filedialog.cpp +++ b/src/filedialog.cpp @@ -51,13 +51,13 @@ QString FileDialog::choose(bool save, const QString &location, const QString &la QByteArray folder = (save ? QFileInfo(location).absolutePath() : QDir(location).absolutePath()).toUtf8(); folder.append('\0'); QVariantMap options{{"handle_token", token}, {"modal", true}, {"multiple", false}, - {"accept_label", save ? "Save" : "Open"}, {"current_folder", folder}, + {"accept_label", save ? tr("Save") : tr("Open")}, {"current_folder", folder}, {"filters", QVariant::fromValue(Filters{filter})}, {"current_filter", QVariant::fromValue(filter)}}; if (save) options.insert("current_name", QFileInfo(location).fileName()); // Subscribe before sending: a fast response may arrive before the method reply. if (!bus.isConnected() || !dialog.listen("/org/freedesktop/portal/desktop/request/" + sender + "/" + token)) { - *error = "Could not connect to the desktop file chooser."; + *error = tr("Could not connect to the desktop file chooser."); return {}; } const auto cleanup = qScopeGuard([&] { @@ -73,25 +73,25 @@ QString FileDialog::choose(bool save, const QString &location, const QString &la connect(&portal, &QDBusServiceWatcher::serviceOwnerChanged, &dialog, [&](const QString &, const QString &oldOwner, const QString &) { if (dialog.m_done || oldOwner.isEmpty()) return; - dialog.m_error = "The desktop file chooser closed without answering."; + dialog.m_error = tr("The desktop file chooser closed without answering."); dialog.m_done = true; dialog.m_loop.quit(); }); auto call = QDBusMessage::createMethodCall(service, "/org/freedesktop/portal/desktop", "org.freedesktop.portal.FileChooser", save ? "SaveFile" : "OpenFile"); - call.setArguments({QString(), save ? QString("Save File") : QString("Open File"), options}); + call.setArguments({QString(), save ? tr("Save File") : tr("Open File"), options}); QDBusPendingCallWatcher watcher(bus.asyncCall(call)); connect(&watcher, &QDBusPendingCallWatcher::finished, &dialog, [&] { if (dialog.m_done) return; QDBusPendingReply reply = watcher; if (reply.isError()) { - dialog.m_error = "Could not open the desktop file chooser: " + reply.error().message(); + dialog.m_error = tr("Could not open the desktop file chooser: %1").arg(reply.error().message()); dialog.m_done = true; dialog.m_loop.quit(); } else if (reply.value().path() != dialog.m_request) { dialog.disconnectRequest(); if (!dialog.listen(reply.value().path())) { - dialog.m_error = "Could not receive the desktop file chooser response."; + dialog.m_error = tr("Could not receive the desktop file chooser response."); dialog.m_loop.quit(); } } @@ -121,9 +121,9 @@ void FileDialog::response(uint result, const QVariantMap &values) { const auto uris = values.value("uris").toStringList(); const QUrl url(uris.value(0)); if (url.isLocalFile()) m_file = url.toLocalFile(); - else m_error = "Choose a local file."; + else m_error = tr("Choose a local file."); } else if (result != 1) { - m_error = "The desktop file chooser failed."; + m_error = tr("The desktop file chooser failed."); } m_loop.quit(); } diff --git a/src/i18n/ar.json b/src/i18n/ar.json new file mode 100644 index 0000000..0967ef4 --- /dev/null +++ b/src/i18n/ar.json @@ -0,0 +1 @@ +{} diff --git a/src/i18n/bg.json b/src/i18n/bg.json new file mode 100644 index 0000000..0967ef4 --- /dev/null +++ b/src/i18n/bg.json @@ -0,0 +1 @@ +{} diff --git a/src/i18n/bn.json b/src/i18n/bn.json new file mode 100644 index 0000000..0967ef4 --- /dev/null +++ b/src/i18n/bn.json @@ -0,0 +1 @@ +{} diff --git a/src/i18n/ca.json b/src/i18n/ca.json new file mode 100644 index 0000000..0967ef4 --- /dev/null +++ b/src/i18n/ca.json @@ -0,0 +1 @@ +{} diff --git a/src/i18n/cs.json b/src/i18n/cs.json new file mode 100644 index 0000000..0967ef4 --- /dev/null +++ b/src/i18n/cs.json @@ -0,0 +1 @@ +{} diff --git a/src/i18n/da.json b/src/i18n/da.json new file mode 100644 index 0000000..0967ef4 --- /dev/null +++ b/src/i18n/da.json @@ -0,0 +1 @@ +{} diff --git a/src/i18n/de.json b/src/i18n/de.json new file mode 100644 index 0000000..0967ef4 --- /dev/null +++ b/src/i18n/de.json @@ -0,0 +1 @@ +{} diff --git a/src/i18n/el.json b/src/i18n/el.json new file mode 100644 index 0000000..0967ef4 --- /dev/null +++ b/src/i18n/el.json @@ -0,0 +1 @@ +{} diff --git a/src/i18n/en.json b/src/i18n/en.json new file mode 100644 index 0000000..d197dab --- /dev/null +++ b/src/i18n/en.json @@ -0,0 +1,244 @@ +{ + "%1 — Presenter View": "%1 — Presenter View", + "%Ln slides selected": { + "one": "%Ln slide selected", + "other": "%Ln slides selected" + }, + "Add a slide": "Add a slide", + "Add image / video": "Add image / video", + "An svg block holds one element": "An svg block holds one element", + "Animation conversion failed: %1": "Animation conversion failed: %1", + "Black": "Black", + "Blurred first frame": "Blurred first frame", + "Blurred image": "Blurred image", + "Bold": "Bold", + "Bottom": "Bottom", + "Bottom left": "Bottom left", + "Bottom right": "Bottom right", + "Cancel": "Cancel", + "Cancel export": "Cancel export", + "Cannot convert %1: %2": "Cannot convert %1: %2", + "Cannot create the export directory.": "Cannot create the export directory.", + "Cannot decode WebP animation": "Cannot decode WebP animation", + "Cannot decode WebP frame %1": "Cannot decode WebP frame %1", + "Cannot decode animation frame %1: %2": "Cannot decode animation frame %1: %2", + "Cannot decode image: %1": "Cannot decode image: %1", + "Cannot encode image for PowerPoint: %1": "Cannot encode image for PowerPoint: %1", + "Cannot export: %1. Finish the Markdown first; your changes are still in the editor.": "Cannot export: %1. Finish the Markdown first; your changes are still in the editor.", + "Cannot inspect video %1: %2": "Cannot inspect video %1: %2", + "Cannot inspect video: %1": "Cannot inspect video: %1", + "Cannot read %1: %2": "Cannot read %1: %2", + "Cannot read existing media: %1": "Cannot read existing media: %1", + "Cannot read image: %1": "Cannot read image: %1", + "Cannot read slide manifest: %1": "Cannot read slide manifest: %1", + "Cannot read the existing presentation: %1": "Cannot read the existing presentation: %1", + "Cannot save: %1. Finish the Markdown first; your changes are still in the editor.": "Cannot save: %1. Finish the Markdown first; your changes are still in the editor.", + "Cannot start ffmpeg for animation conversion: %1": "Cannot start ffmpeg for animation conversion: %1", + "Cannot start ffprobe: %1": "Cannot start ffprobe: %1", + "Cannot start video conversion: %1": "Cannot start video conversion: %1", + "Center": "Center", + "Changed on disk. Save a copy or reopen to reload.": "Changed on disk. Save a copy or reopen to reload.", + "Changes could not be backed up. Discard them and quit?": "Changes could not be backed up. Discard them and quit?", + "Choose a local file.": "Choose a local file.", + "Choose a local image or video.": "Choose a local image or video.", + "Choose a supported image or video.": "Choose a supported image or video.", + "Choose a version to restore. Your current version stays in history.": "Choose a version to restore. Your current version stays in history.", + "Choose either span or fit": "Choose either span or fit", + "Code": "Code", + "Code block": "Code block", + "Comment, hidden on slide": "Comment, hidden on slide", + "Compressing image": "Compressing image", + "Compressing image…": "Compressing image…", + "Converting the animation on slide %1 of %2": "Converting the animation on slide %1 of %2", + "Converting the video on slide %1 of %2": "Converting the video on slide %1 of %2", + "Could not back up this version. Changes are still in the editor.": "Could not back up this version. Changes are still in the editor.", + "Could not compress the pasted image.": "Could not compress the pasted image.", + "Could not connect to the desktop file chooser.": "Could not connect to the desktop file chooser.", + "Could not copy %1": "Could not copy %1", + "Could not create %1": "Could not create %1", + "Could not create PDF page": "Could not create PDF page", + "Could not create a recovery backup. The saved presentation was left untouched.": "Could not create a recovery backup. The saved presentation was left untouched.", + "Could not create media directory": "Could not create media directory", + "Could not create the recovery folder. Changes are still in the editor.": "Could not create the recovery folder. Changes are still in the editor.", + "Could not import %1": "Could not import %1", + "Could not initialize PDF painter": "Could not initialize PDF painter", + "Could not open the desktop file chooser: %1": "Could not open the desktop file chooser: %1", + "Could not prepare the export.": "Could not prepare the export.", + "Could not prepare the export: %1": "Could not prepare the export: %1", + "Could not prepare the presentation directory.": "Could not prepare the presentation directory.", + "Could not publish copied media": "Could not publish copied media", + "Could not read media while copying": "Could not read media while copying", + "Could not read that version.": "Could not read that version.", + "Could not read the pasted image.": "Could not read the pasted image.", + "Could not read the recovery draft. Earlier versions are available in History.": "Could not read the recovery draft. Earlier versions are available in History.", + "Could not receive the desktop file chooser response.": "Could not receive the desktop file chooser response.", + "Could not save %1": "Could not save %1", + "Could not save rendered slide": "Could not save rendered slide", + "Could not save slides.json: %1": "Could not save slides.json: %1", + "Could not save the export: %1": "Could not save the export: %1", + "Could not save the recovery draft. Changes are still in the editor.": "Could not save the recovery draft. Changes are still in the editor.", + "Could not save video overlay": "Could not save video overlay", + "Current": "Current", + "Delete": "Delete", + "Delete slide": "Delete slide", + "Delete slides": "Delete slides", + "Draft backed up · Ctrl+S to choose a file": "Draft backed up · Ctrl+S to choose a file", + "Draft backed up · file changed outside Hype; use Save As to keep both": "Draft backed up · file changed outside Hype; use Save As to keep both", + "Draft backed up · finish the Markdown to save the presentation": "Draft backed up · finish the Markdown to save the presentation", + "Duplicate": "Duplicate", + "Duplicate slide": "Duplicate slide", + "Duplicate slides": "Duplicate slides", + "Editing": "Editing", + "End of presentation": "End of presentation", + "End show": "End show", + "Export as PDF": "Export as PDF", + "Export as PDF…": "Export as PDF…", + "Export as PowerPoint": "Export as PowerPoint", + "Export as PowerPoint…": "Export as PowerPoint…", + "Export cancelled": "Export cancelled", + "Export failed: %1": "Export failed: %1", + "Export progress": "Export progress", + "Exported %1": "Exported %1", + "Exporting slide %1 of %2": "Exporting slide %1 of %2", + "Extend the selection": "Extend the selection", + "Fewer Noto fonts": "Fewer Noto fonts", + "File": "File", + "File changed on disk. Save a copy or reopen.": "File changed on disk. Save a copy or reopen.", + "File changed on disk. Use Save As to keep both versions.": "File changed on disk. Use Save As to keep both versions.", + "File · Unsaved changes": "File · Unsaved changes", + "Filename": "Filename", + "First or last slide when focused in Slides list": "First or last slide when focused in Slides list", + "Fit": "Fit", + "Font: %1": "Font: %1", + "Front matter needs a closing ---": "Front matter needs a closing ---", + "Give the SVG a viewBox, or a width and height": "Give the SVG a viewBox, or a width and height", + "Headline": "Headline", + "Image / video options": "Image / video options", + "Invalid background color": "Invalid background color", + "Invalid export snapshot.": "Invalid export snapshot.", + "Invalid media directive": "Invalid media directive", + "Invalid slide in manifest.": "Invalid slide in manifest.", + "Invalid slide manifest: %1": "Invalid slide manifest: %1", + "Italic": "Italic", + "Jump five slides": "Jump five slides", + "Jump five slides, or five rows in Overview": "Jump five slides, or five rows in Overview", + "Keyboard shortcuts": "Keyboard shortcuts", + "Large (35%)": "Large (35%)", + "Layout": "Layout", + "Leave the overview": "Leave the overview", + "Left": "Left", + "Markdown source on or off": "Markdown source on or off", + "Markdown · Switch to Visual": "Markdown · Switch to Visual", + "Match image edges": "Match image edges", + "Media": "Media", + "Medium (20%)": "Medium (20%)", + "Missing media": "Missing media", + "Missing media: %1": "Missing media: %1", + "Missing poster": "Missing poster", + "More Noto fonts…": "More Noto fonts…", + "Move selected slides": "Move selected slides", + "Move selected slides five places": "Move selected slides five places", + "Move selected slides to first or last": "Move selected slides to first or last", + "New presentation": "New presentation", + "New slide after this": "New slide after this", + "Next": "Next", + "No earlier versions yet": "No earlier versions yet", + "No speaker notes for this slide.": "No speaker notes for this slide.", + "No video stream in %1": "No video stream in %1", + "Note": "Note", + "Only images can be placed": "Only images can be placed", + "Open": "Open", + "Open File": "Open File", + "Open slide from Overview": "Open slide from Overview", + "Opened %1": "Opened %1", + "Open…": "Open…", + "Overlay must be between 0 and 1": "Overlay must be between 0 and 1", + "Overview": "Overview", + "Overview on or off": "Overview on or off", + "Packaging PowerPoint…": "Packaging PowerPoint…", + "Paste an image or video first.": "Paste an image or video first.", + "Paste image": "Paste image", + "Paste text, or add and name media": "Paste text, or add and name media", + "Paste video": "Paste video", + "Pause": "Pause", + "Place": "Place", + "Play": "Play", + "Play or pause video while presenting": "Play or pause video while presenting", + "PowerPoint export exceeds the 4 GiB ZIP limit.": "PowerPoint export exceeds the 4 GiB ZIP limit.", + "Preparing %1 export…": "Preparing %1 export…", + "Present": "Present", + "Present from first slide": "Present from first slide", + "Presentation": "Presentation", + "Presentation changed or was removed outside Hype.": "Presentation changed or was removed outside Hype.", + "Previous or next slide": "Previous or next slide", + "Previous or next slide, by row in Overview": "Previous or next slide, by row in Overview", + "Qt can't draw this SVG": "Qt can't draw this SVG", + "Quit": "Quit", + "Recovered draft · file also changed outside Hype; use Save As to keep both": "Recovered draft · file also changed outside Hype; use Save As to keep both", + "Recovered from version history; the latest recovery file was missing or damaged": "Recovered from version history; the latest recovery file was missing or damaged", + "Recovered your last draft": "Recovered your last draft", + "Redo": "Redo", + "Reloaded external changes.": "Reloaded external changes.", + "Restored earlier version": "Restored earlier version", + "Right": "Right", + "Save": "Save", + "Save As could not copy media for slide %1: %2": "Save As could not copy media for slide %1: %2", + "Save As media collision: %1": "Save As media collision: %1", + "Save File": "Save File", + "Save as": "Save as", + "Save as…": "Save as…", + "Save changes": "Save changes", + "Save image": "Save image", + "Save this presentation before opening another one.": "Save this presentation before opening another one.", + "Save to %1": "Save to %1", + "Save video": "Save video", + "Saved": "Saved", + "Show these shortcuts": "Show these shortcuts", + "Size": "Size", + "Size must be a percentage from 1% to 100%": "Size must be a percentage from 1% to 100%", + "Slide %1": "Slide %1", + "Slide %1 of %2": "Slide %1 of %2", + "Slide %1: %2": "Slide %1: %2", + "Slides": "Slides", + "Small (10%)": "Small (10%)", + "Span": "Span", + "Spanning video must be 16:9 for PowerPoint: %1. Use fit.": "Spanning video must be 16:9 for PowerPoint: %1. Use fit.", + "Speaker notes": "Speaker notes", + "Start or end of the line": "Start or end of the line", + "Stop presenting": "Stop presenting", + "Switch between slides and editor": "Switch between slides and editor", + "Text fits below 24px on a 1080p slide": "Text fits below 24px on a 1080p slide", + "That recovery version is damaged.": "That recovery version is damaged.", + "The desktop file chooser closed without answering.": "The desktop file chooser closed without answering.", + "The desktop file chooser failed.": "The desktop file chooser failed.", + "The export process stopped unexpectedly.": "The export process stopped unexpectedly.", + "The image is still being compressed.": "The image is still being compressed.", + "The last presentation is missing. Use Save As to recover it to a new file.": "The last presentation is missing. Use Save As to recover it to a new file.", + "The slide changed. Cancel and paste again.": "The slide changed. Cancel and paste again.", + "The slide changed. Paste the image again.": "The slide changed. Paste the image again.", + "Theme: %1": "Theme: %1", + "There are no slides to export.": "There are no slides to export.", + "Timed out inspecting video: %1": "Timed out inspecting video: %1", + "Top": "Top", + "Top left": "Top left", + "Top right": "Top right", + "Unclosed code fence": "Unclosed code fence", + "Underline": "Underline", + "Undo": "Undo", + "Unfinished slide boundaries": "Unfinished slide boundaries", + "Unknown media directive: %1": "Unknown media directive: %1", + "Unknown position": "Unknown position", + "Unknown theme color --%1; use --%2": "Unknown theme color --%1; use --%2", + "Unsaved changes": "Unsaved changes", + "Untitled": "Untitled", + "Use a filename without folders or special characters.": "Use a filename without folders or special characters.", + "Use one media item per slide (combine artwork before importing)": "Use one media item per slide (combine artwork before importing)", + "Use theme color": "Use theme color", + "Version history": "Version history", + "Version history…": "Version history…", + "View": "View", + "Visual · Switch to Markdown": "Visual · Switch to Markdown", + "White": "White", + "Your headline": "Your headline", + "←/→ change slide · Space plays media · Esc ends the show": "←/→ change slide · Space plays media · Esc ends the show" +} diff --git a/src/i18n/es-MX.json b/src/i18n/es-MX.json new file mode 100644 index 0000000..0967ef4 --- /dev/null +++ b/src/i18n/es-MX.json @@ -0,0 +1 @@ +{} diff --git a/src/i18n/et.json b/src/i18n/et.json new file mode 100644 index 0000000..0967ef4 --- /dev/null +++ b/src/i18n/et.json @@ -0,0 +1 @@ +{} diff --git a/src/i18n/fa.json b/src/i18n/fa.json new file mode 100644 index 0000000..0967ef4 --- /dev/null +++ b/src/i18n/fa.json @@ -0,0 +1 @@ +{} diff --git a/src/i18n/fi.json b/src/i18n/fi.json new file mode 100644 index 0000000..0967ef4 --- /dev/null +++ b/src/i18n/fi.json @@ -0,0 +1 @@ +{} diff --git a/src/i18n/fil.json b/src/i18n/fil.json new file mode 100644 index 0000000..0967ef4 --- /dev/null +++ b/src/i18n/fil.json @@ -0,0 +1 @@ +{} diff --git a/src/i18n/fr.json b/src/i18n/fr.json new file mode 100644 index 0000000..0967ef4 --- /dev/null +++ b/src/i18n/fr.json @@ -0,0 +1 @@ +{} diff --git a/src/i18n/ga.json b/src/i18n/ga.json new file mode 100644 index 0000000..0967ef4 --- /dev/null +++ b/src/i18n/ga.json @@ -0,0 +1 @@ +{} diff --git a/src/i18n/he.json b/src/i18n/he.json new file mode 100644 index 0000000..0967ef4 --- /dev/null +++ b/src/i18n/he.json @@ -0,0 +1 @@ +{} diff --git a/src/i18n/hi.json b/src/i18n/hi.json new file mode 100644 index 0000000..0967ef4 --- /dev/null +++ b/src/i18n/hi.json @@ -0,0 +1 @@ +{} diff --git a/src/i18n/hr.json b/src/i18n/hr.json new file mode 100644 index 0000000..0967ef4 --- /dev/null +++ b/src/i18n/hr.json @@ -0,0 +1 @@ +{} diff --git a/src/i18n/hu.json b/src/i18n/hu.json new file mode 100644 index 0000000..0967ef4 --- /dev/null +++ b/src/i18n/hu.json @@ -0,0 +1 @@ +{} diff --git a/src/i18n/id.json b/src/i18n/id.json new file mode 100644 index 0000000..0967ef4 --- /dev/null +++ b/src/i18n/id.json @@ -0,0 +1 @@ +{} diff --git a/src/i18n/is.json b/src/i18n/is.json new file mode 100644 index 0000000..0967ef4 --- /dev/null +++ b/src/i18n/is.json @@ -0,0 +1 @@ +{} diff --git a/src/i18n/it.json b/src/i18n/it.json new file mode 100644 index 0000000..0967ef4 --- /dev/null +++ b/src/i18n/it.json @@ -0,0 +1 @@ +{} diff --git a/src/i18n/ja.json b/src/i18n/ja.json new file mode 100644 index 0000000..0967ef4 --- /dev/null +++ b/src/i18n/ja.json @@ -0,0 +1 @@ +{} diff --git a/src/i18n/ko.json b/src/i18n/ko.json new file mode 100644 index 0000000..0967ef4 --- /dev/null +++ b/src/i18n/ko.json @@ -0,0 +1 @@ +{} diff --git a/src/i18n/lt.json b/src/i18n/lt.json new file mode 100644 index 0000000..0967ef4 --- /dev/null +++ b/src/i18n/lt.json @@ -0,0 +1 @@ +{} diff --git a/src/i18n/lv.json b/src/i18n/lv.json new file mode 100644 index 0000000..0967ef4 --- /dev/null +++ b/src/i18n/lv.json @@ -0,0 +1 @@ +{} diff --git a/src/i18n/ms.json b/src/i18n/ms.json new file mode 100644 index 0000000..0967ef4 --- /dev/null +++ b/src/i18n/ms.json @@ -0,0 +1 @@ +{} diff --git a/src/i18n/nl.json b/src/i18n/nl.json new file mode 100644 index 0000000..0967ef4 --- /dev/null +++ b/src/i18n/nl.json @@ -0,0 +1 @@ +{} diff --git a/src/i18n/no.json b/src/i18n/no.json new file mode 100644 index 0000000..0967ef4 --- /dev/null +++ b/src/i18n/no.json @@ -0,0 +1 @@ +{} diff --git a/src/i18n/pl.json b/src/i18n/pl.json new file mode 100644 index 0000000..0967ef4 --- /dev/null +++ b/src/i18n/pl.json @@ -0,0 +1 @@ +{} diff --git a/src/i18n/pt-BR.json b/src/i18n/pt-BR.json new file mode 100644 index 0000000..0967ef4 --- /dev/null +++ b/src/i18n/pt-BR.json @@ -0,0 +1 @@ +{} diff --git a/src/i18n/pt.json b/src/i18n/pt.json new file mode 100644 index 0000000..0967ef4 --- /dev/null +++ b/src/i18n/pt.json @@ -0,0 +1 @@ +{} diff --git a/src/i18n/ro.json b/src/i18n/ro.json new file mode 100644 index 0000000..0967ef4 --- /dev/null +++ b/src/i18n/ro.json @@ -0,0 +1 @@ +{} diff --git a/src/i18n/ru.json b/src/i18n/ru.json new file mode 100644 index 0000000..0967ef4 --- /dev/null +++ b/src/i18n/ru.json @@ -0,0 +1 @@ +{} diff --git a/src/i18n/si.json b/src/i18n/si.json new file mode 100644 index 0000000..0967ef4 --- /dev/null +++ b/src/i18n/si.json @@ -0,0 +1 @@ +{} diff --git a/src/i18n/sk.json b/src/i18n/sk.json new file mode 100644 index 0000000..0967ef4 --- /dev/null +++ b/src/i18n/sk.json @@ -0,0 +1 @@ +{} diff --git a/src/i18n/sl.json b/src/i18n/sl.json new file mode 100644 index 0000000..0967ef4 --- /dev/null +++ b/src/i18n/sl.json @@ -0,0 +1 @@ +{} diff --git a/src/i18n/sr.json b/src/i18n/sr.json new file mode 100644 index 0000000..0967ef4 --- /dev/null +++ b/src/i18n/sr.json @@ -0,0 +1 @@ +{} diff --git a/src/i18n/sv.json b/src/i18n/sv.json new file mode 100644 index 0000000..0967ef4 --- /dev/null +++ b/src/i18n/sv.json @@ -0,0 +1 @@ +{} diff --git a/src/i18n/sw.json b/src/i18n/sw.json new file mode 100644 index 0000000..0967ef4 --- /dev/null +++ b/src/i18n/sw.json @@ -0,0 +1 @@ +{} diff --git a/src/i18n/ta.json b/src/i18n/ta.json new file mode 100644 index 0000000..0967ef4 --- /dev/null +++ b/src/i18n/ta.json @@ -0,0 +1 @@ +{} diff --git a/src/i18n/th.json b/src/i18n/th.json new file mode 100644 index 0000000..0967ef4 --- /dev/null +++ b/src/i18n/th.json @@ -0,0 +1 @@ +{} diff --git a/src/i18n/tr.json b/src/i18n/tr.json new file mode 100644 index 0000000..0967ef4 --- /dev/null +++ b/src/i18n/tr.json @@ -0,0 +1 @@ +{} diff --git a/src/i18n/uk.json b/src/i18n/uk.json new file mode 100644 index 0000000..0967ef4 --- /dev/null +++ b/src/i18n/uk.json @@ -0,0 +1 @@ +{} diff --git a/src/i18n/ur.json b/src/i18n/ur.json new file mode 100644 index 0000000..0967ef4 --- /dev/null +++ b/src/i18n/ur.json @@ -0,0 +1 @@ +{} diff --git a/src/i18n/uz.json b/src/i18n/uz.json new file mode 100644 index 0000000..0967ef4 --- /dev/null +++ b/src/i18n/uz.json @@ -0,0 +1 @@ +{} diff --git a/src/i18n/vi.json b/src/i18n/vi.json new file mode 100644 index 0000000..0967ef4 --- /dev/null +++ b/src/i18n/vi.json @@ -0,0 +1 @@ +{} diff --git a/src/i18n/zh-CN.json b/src/i18n/zh-CN.json new file mode 100644 index 0000000..0967ef4 --- /dev/null +++ b/src/i18n/zh-CN.json @@ -0,0 +1 @@ +{} diff --git a/src/i18n/zh-TW.json b/src/i18n/zh-TW.json new file mode 100644 index 0000000..0967ef4 --- /dev/null +++ b/src/i18n/zh-TW.json @@ -0,0 +1 @@ +{} diff --git a/src/main.cpp b/src/main.cpp index c3df95a..59ab220 100644 --- a/src/main.cpp +++ b/src/main.cpp @@ -2,6 +2,7 @@ #include "cli.h" #include "deck.h" #include "renderer.h" +#include "translator.h" #include #include #include @@ -18,6 +19,7 @@ #include #include #include +#include // The desktop's interface font, e.g. "Adwaita Sans 11", which the gtk3 platform // theme used to supply. Without a settings portal Qt's default font stays. static void adoptDesktopFont() { @@ -78,8 +80,16 @@ int main(int argc, char **argv) { if (arguments.value(1) == "open") arguments.removeAt(1); args.process(arguments); - Deck deck; const bool exportWorker = args.isSet(snapshotOption); + const bool exporting = args.isSet("pdf") || args.isSet("pptx") || args.isSet("render") || args.isSet("save"); + // The window, and the export worker whose progress it shows, follow the Omarchy language; commands and + // command-line exports stay in English for the scripts and agents that read them. + std::optional translator; + if (!exporting || exportWorker) { + translator.emplace(); + app.installTranslator(&*translator); + } + Deck deck; auto report = [](const QJsonObject &event) { const auto line = QJsonDocument(event).toJson(QJsonDocument::Compact); fprintf(stdout, "%s\n", line.constData()); @@ -96,7 +106,6 @@ int main(int argc, char **argv) { }); } auto positional = args.positionalArguments(); - const bool exporting = args.isSet("pdf") || args.isSet("pptx") || args.isSet("render") || args.isSet("save"); if (exporting && positional.isEmpty() && !exportWorker) { fprintf(stderr, "Name a Markdown presentation to %s.\n", args.isSet("save") ? "save" : "export"); return 1; @@ -139,6 +148,7 @@ int main(int argc, char **argv) { qmlRegisterType("Hype", 1, 0, "SlideCanvas"); qmlRegisterType("Hype", 1, 0, "AppTheme"); QQmlApplicationEngine engine; + QObject::connect(&*translator, &Translator::changed, &engine, &QQmlEngine::retranslate); QObject::connect(&engine, &QQmlEngine::warnings, [](const QList &errors) { for (const auto &error : errors) fprintf(stderr, "%s\n", qPrintable(error.toString())); diff --git a/src/pptx.cpp b/src/pptx.cpp index 6eea4a4..f06316d 100644 --- a/src/pptx.cpp +++ b/src/pptx.cpp @@ -1,6 +1,7 @@ #include "pptx.h" #include "budget.h" #include "renderer.h" +#include #include #include #include @@ -16,6 +17,9 @@ #include #include #include + +// Hype's free functions translate like its classes do; the Translator ignores the context. +static QString tr(const char *text) { return QCoreApplication::translate("Hype", text); } #include namespace { @@ -55,7 +59,7 @@ class Zip { if (entries.size() >= 65534 || quint64(output.pos()) >= zipLimit || input.size() < 0 || quint64(input.size()) >= zipLimit || quint64(output.pos()) + quint64(input.size()) + 65536 >= zipLimit) - return fail("PowerPoint export exceeds the 4 GiB ZIP limit."); + return fail(tr("PowerPoint export exceeds the 4 GiB ZIP limit.")); Entry entry{name.toUtf8(), quint32(output.pos()), 0, quint32(crc32(0, nullptr, 0))}; stream << quint32(0x04034b50) << quint16(20) << quint16(0x800) << quint16(0) << quint16(0) << quint16(33) << quint32(0) << quint32(0) << quint32(0) @@ -71,7 +75,7 @@ class Zip { break; if (quint64(entry.size) + quint64(count) >= zipLimit || quint64(output.pos()) + quint64(count) + 16 >= zipLimit) - return fail("PowerPoint export exceeds the 4 GiB ZIP limit."); + return fail(tr("PowerPoint export exceeds the 4 GiB ZIP limit.")); if (output.write(buffer.constData(), count) != count) return fail(output.errorString()); entry.crc = quint32( @@ -90,7 +94,7 @@ class Zip { bool file(const QString &name, const QString &path) { QFile file(path); if (!file.open(QIODevice::ReadOnly)) - return fail("Cannot read " + path + ": " + file.errorString()); + return fail(tr("Cannot read %1: %2").arg(path, file.errorString())); return add(name, file); } bool data(const QString &name, const QByteArray &bytes) { @@ -112,7 +116,7 @@ class Zip { return fail(output.errorString()); } if (quint64(output.pos()) + 22 >= zipLimit) - return fail("PowerPoint export exceeds the 4 GiB ZIP limit."); + return fail(tr("PowerPoint export exceeds the 4 GiB ZIP limit.")); const auto directorySize = output.pos() - offset; stream << quint32(0x06054b50) << quint16(0) << quint16(0) << quint16(entries.size()) << quint16(entries.size()) << quint32(directorySize) << quint32(offset) @@ -334,7 +338,7 @@ bool readSlide(const QJsonObject &entry, const QDir &base, PowerPointSlide &slid // Check contents rather than relying on a filename extension. QImageReader reader(path); if (!reader.canRead() || reader.size().isEmpty()) { - error = "Cannot read image: " + path; + error = tr("Cannot read image: %1").arg(path); return false; } return true; @@ -356,18 +360,17 @@ bool readSlide(const QJsonObject &entry, const QDir &base, PowerPointSlide &slid QProcess probe; probe.start("ffprobe", {"-v", "error", "-show_streams", "-of", "json", slide.video}); if (!probe.waitForStarted()) { - error = "Cannot start ffprobe: " + probe.errorString(); + error = tr("Cannot start ffprobe: %1").arg(probe.errorString()); return false; } if (!probe.waitForFinished(30000)) { probe.kill(); probe.waitForFinished(); - error = "Timed out inspecting video: " + slide.video; + error = tr("Timed out inspecting video: %1").arg(slide.video); return false; } if (probe.exitStatus() != QProcess::NormalExit || probe.exitCode() != 0) { - error = "Cannot inspect video " + slide.video + ": " + - QString::fromUtf8(probe.readAllStandardError()).trimmed(); + error = tr("Cannot inspect video %1: %2").arg(slide.video, QString::fromUtf8(probe.readAllStandardError()).trimmed()); return false; } QJsonParseError jsonError; @@ -390,9 +393,7 @@ bool readSlide(const QJsonObject &entry, const QDir &base, PowerPointSlide &slid const double ratio = double(video["width"].toInt()) / video["height"].toInt(); if (entry["span"].toBool()) { if (std::abs(ratio - 16.0 / 9.0) > .01) { - error = - "Spanning video must be 16:9 for PowerPoint: " + QFileInfo(slide.video).fileName() + - ". Use fit."; + error = tr("Spanning video must be 16:9 for PowerPoint: %1. Use fit.").arg(QFileInfo(slide.video).fileName()); return false; } } else { @@ -427,7 +428,7 @@ QString preparePowerPointVideo(const QString &source, const QString &output, QSt if (!probe.waitForFinished(30000) || probe.exitCode() != 0) { probe.kill(); probe.waitForFinished(); - *error = "Cannot inspect video: " + QFileInfo(source).fileName(); + *error = tr("Cannot inspect video: %1").arg(QFileInfo(source).fileName()); return {}; } const auto info = QJsonDocument::fromJson(probe.readAllStandardOutput()).object(); @@ -438,7 +439,7 @@ QString preparePowerPointVideo(const QString &source, const QString &output, QSt if (stream["codec_type"] == "audio" && audio.isEmpty()) audio = stream; } if (video.isEmpty()) { - *error = "No video stream in " + QFileInfo(source).fileName(); + *error = tr("No video stream in %1").arg(QFileInfo(source).fileName()); return {}; } if (QFileInfo(source).suffix().toLower() == "mp4" && video["codec_name"] == "h264" && @@ -451,7 +452,7 @@ QString preparePowerPointVideo(const QString &source, const QString &output, QSt "-threads", QString::number(encoderThreads()), "-vf", "pad=ceil(iw/2)*2:ceil(ih/2)*2", "-pix_fmt", "yuv420p", "-c:a", "aac", "-b:a", "192k", "-movflags", "+faststart", "-progress", "pipe:1", output}); if (!encoder.waitForStarted()) { - *error = "Cannot start video conversion: " + encoder.errorString(); + *error = tr("Cannot start video conversion: %1").arg(encoder.errorString()); return {}; } QByteArray pending, errors; @@ -468,7 +469,7 @@ QString preparePowerPointVideo(const QString &source, const QString &output, QSt } } while (encoder.state() != QProcess::NotRunning); if (encoder.exitStatus() != QProcess::NormalExit || encoder.exitCode() != 0) { - *error = "Cannot convert " + QFileInfo(source).fileName() + ": " + QString::fromUtf8(errors).trimmed(); + *error = tr("Cannot convert %1: %2").arg(QFileInfo(source).fileName(), QString::fromUtf8(errors).trimmed()); return {}; } return output; @@ -485,27 +486,27 @@ bool writePptx(const QString &manifestPath, const QString &destination, QString }; QFile manifest(manifestPath); if (!manifest.open(QIODevice::ReadOnly)) - return fail("Cannot read slide manifest: " + manifest.errorString()); + return fail(tr("Cannot read slide manifest: %1").arg(manifest.errorString())); QJsonParseError parseError; const auto document = QJsonDocument::fromJson(manifest.readAll(), &parseError); if (parseError.error != QJsonParseError::NoError || !document.isObject() || !document.object()["slides"].isArray()) - return fail("Invalid slide manifest: " + parseError.errorString()); + return fail(tr("Invalid slide manifest: %1").arg(parseError.errorString())); QList slides; const auto deck = document.object(); for (const auto &value : deck["slides"].toArray()) { PowerPointSlide slide; QString problem; if (!value.isObject()) - return fail("Invalid slide in manifest."); + return fail(tr("Invalid slide in manifest.")); if (!readSlide(value.toObject(), QFileInfo(manifestPath).absoluteDir(), slide, problem)) return fail(problem); slides.append(slide); } if (slides.isEmpty()) - return fail("There are no slides to export."); + return fail(tr("There are no slides to export.")); if (!QDir().mkpath(QFileInfo(destination).absolutePath())) - return fail("Cannot create the export directory."); + return fail(tr("Cannot create the export directory.")); Zip zip(destination); if (!zip.error.isEmpty()) return fail(zip.error); @@ -601,7 +602,7 @@ bool writePptx(const QString &manifestPath, const QString &destination, QString QBuffer encoded; encoded.open(QIODevice::WriteOnly); if (!reader.read().save(&encoded, "PNG")) - zip.fail("Cannot encode image for PowerPoint: " + path); + zip.fail(tr("Cannot encode image for PowerPoint: %1").arg(path)); else zip.data("ppt/" + target, encoded.data()); } diff --git a/src/recovery.cpp b/src/recovery.cpp index ed70756..1bbad32 100644 --- a/src/recovery.cpp +++ b/src/recovery.cpp @@ -57,7 +57,7 @@ bool Deck::checkpoint() { {"selected", m_selected}, {"anchor", m_anchor}, {"conflict", m_externalChange}, {"timestamp", QDateTime::currentDateTimeUtc().toString(Qt::ISODateWithMs)}}).toJson(); if (!QDir().mkpath(folder + "/versions")) { - setStatus("Could not create the recovery folder. Changes are still in the editor."); + setStatus(tr("Could not create the recovery folder. Changes are still in the editor.")); return false; } // Keep every distinct checkpoint. These contain Markdown, never media copies. @@ -69,12 +69,12 @@ bool Deck::checkpoint() { '-' + QString::number(order).rightJustified(20, '0') + '-' + digest(m_source.toUtf8()).left(16) + ".json"; if (!writeAtomically(folder + "/versions/" + version, bytes)) { - setStatus("Could not back up this version. Changes are still in the editor."); + setStatus(tr("Could not back up this version. Changes are still in the editor.")); return false; } } if (!writeAtomically(folder + "/latest.json", bytes)) { - setStatus("Could not save the recovery draft. Changes are still in the editor."); + setStatus(tr("Could not save the recovery draft. Changes are still in the editor.")); return false; } m_checkpointSource = m_source; @@ -93,11 +93,11 @@ bool Deck::flushAutosave() { bool complete = parsed.error.isEmpty() && m_parsed.error.isEmpty() && parsed.slides.size() == count(); for (int i = 0; complete && i < count(); ++i) complete = parsed.slides[i].source == m_parsed.slides[i].source; - if (!complete) setStatus("Draft backed up · finish the Markdown to save the presentation"); + if (!complete) setStatus(tr("Draft backed up · finish the Markdown to save the presentation")); else if (!m_externalChange) { savePath(m_path); - } else setStatus("Draft backed up · file changed outside Hype; use Save As to keep both"); - } else if (m_path.isEmpty()) setStatus("Draft backed up · Ctrl+S to choose a file"); + } else setStatus(tr("Draft backed up · file changed outside Hype; use Save As to keep both")); + } else if (m_path.isEmpty()) setStatus(tr("Draft backed up · Ctrl+S to choose a file")); return true; // A recoverable draft is sufficient to close, even if the file cannot be saved. } bool Deck::restoreSnapshot(const QByteArray &bytes, bool opening) { @@ -136,9 +136,9 @@ bool Deck::restoreSnapshot(const QByteArray &bytes, bool opening) { m_checkpointSource = source; m_checkpointPath = m_path; if (opening && dirty()) - setStatus(conflict ? "Recovered draft · file also changed outside Hype; use Save As to keep both" - : "Recovered your last draft"); - if (!opening) setStatus("Restored earlier version"); + setStatus(conflict ? tr("Recovered draft · file also changed outside Hype; use Save As to keep both") + : tr("Recovered your last draft")); + if (!opening) setStatus(tr("Restored earlier version")); return true; } void Deck::recoverDraft() { @@ -157,12 +157,12 @@ void Deck::recoverDraft() { for (const auto &entry : recoveryVersions()) { QFile version(recoveryFolder() + "/versions/" + entry.toMap()["name"].toString()); if (version.open(QIODevice::ReadOnly) && restoreSnapshot(version.readAll(), true)) { - setStatus("Recovered from version history; the latest recovery file was missing or damaged"); + setStatus(tr("Recovered from version history; the latest recovery file was missing or damaged")); return; } } if (latest.exists()) - setStatus("Could not read the recovery draft. Earlier versions are available in History."); + setStatus(tr("Could not read the recovery draft. Earlier versions are available in History.")); } void Deck::retireDraft() { if (m_recoveryDirectory.isEmpty()) return; @@ -188,9 +188,9 @@ QVariantList Deck::recoveryVersions() const { bool Deck::restoreVersion(const QString &name) { if (m_recoveryDirectory.isEmpty() || name != QFileInfo(name).fileName() || !name.endsWith(".json")) return false; QFile version(recoveryFolder() + "/versions/" + name); - if (!version.open(QIODevice::ReadOnly)) { setStatus("Could not read that version."); return false; } + if (!version.open(QIODevice::ReadOnly)) { setStatus(tr("Could not read that version.")); return false; } if (!checkpoint()) return false; - if (!restoreSnapshot(version.readAll(), false)) { setStatus("That recovery version is damaged."); return false; } + if (!restoreSnapshot(version.readAll(), false)) { setStatus(tr("That recovery version is damaged.")); return false; } // Capture the restoration as a new version; preserve the version being restored. m_checkpointSource.clear(); return flushAutosave(); diff --git a/src/renderer.cpp b/src/renderer.cpp index 3e85cde..0eaa307 100644 --- a/src/renderer.cpp +++ b/src/renderer.cpp @@ -2,6 +2,7 @@ #include "budget.h" #include "images.h" #include "syntax.h" +#include #include #include #include @@ -25,6 +26,9 @@ #include #include #include + +// Hype's free functions translate like its classes do; the Translator ignores the context. +static QString tr(const char *text) { return QCoreApplication::translate("Hype", text); } #include static QRegularExpression mediaRe(R"(!\[([^\]]*)\]\((?:<([^>]+)>|([^\s)]+))\))"); @@ -231,7 +235,7 @@ static Media readMedia(const QString &source, const QString &base) { while (it.hasNext()) { auto token = it.next(); if (!flags.mid(consumed, token.capturedStart() - consumed).trimmed().isEmpty()) - result.error = "Invalid media directive"; + result.error = tr("Invalid media directive"); consumed = token.capturedEnd(); QString key = token.captured(1), value = token.captured(2); if (value.startsWith('"')) @@ -254,14 +258,14 @@ static Media readMedia(const QString &source, const QString &base) { // Errors name the directive, never the author's value, which may hold markup. result.position = value; if (!mediaPositions().contains(value)) - result.error = "Unknown position"; + result.error = tr("Unknown position"); } else if (key == "size") { // Plain decimals only: toDouble() would also accept "nan" and "1e1". static const QRegularExpression percentage(R"(^(\d{1,3}(?:\.\d+)?)%$)"); const auto number = percentage.match(value); result.size = number.hasMatch() ? number.captured(1).toDouble() : 0; if (result.size < 1 || result.size > 100) { - result.error = "Size must be a percentage from 1% to 100%"; + result.error = tr("Size must be a percentage from 1% to 100%"); result.size = 0; } if (result.position.isEmpty()) @@ -269,20 +273,20 @@ static Media readMedia(const QString &source, const QString &base) { } else if (key == "background") { result.background = value; if (value != "auto" && value != "theme" && value != "blur" && !QColor(value).isValid()) - result.error = "Invalid background color"; + result.error = tr("Invalid background color"); } else if (key == "poster") result.poster = assetPath(base, value, false); else if (key != "alt") - result.error = "Unknown media directive: " + key; + result.error = tr("Unknown media directive: %1").arg(key); } if (!flags.mid(consumed).trimmed().isEmpty()) - result.error = "Invalid media directive"; + result.error = tr("Invalid media directive"); } if (fit && span) - result.error = "Choose either span or fit"; + result.error = tr("Choose either span or fit"); if (result.placed()) { if (result.video) - result.error = "Only images can be placed"; + result.error = tr("Only images can be placed"); else if (fit || span || !result.background.isEmpty() || !explicitOverlay.isEmpty()) result.error = "A placed image cannot use fit, span, background, or overlay"; if (result.size == 0) @@ -303,7 +307,7 @@ static Media readMedia(const QString &source, const QString &base) { bool ok; double opacity = explicitOverlay.toDouble(&ok); if (!ok || opacity < 0 || opacity > 1) - result.error = "Overlay must be between 0 and 1"; + result.error = tr("Overlay must be between 0 and 1"); else result.overlay = opacity; } @@ -382,7 +386,7 @@ static QString svgProblem(const QString &svg) { if (xml.readNext() == QXmlStreamReader::StartElement && first) { first = false; if (xml.name() != QLatin1String("svg")) - return "An svg block holds one element"; + return tr("An svg block holds one element"); } } if (xml.hasError()) @@ -394,14 +398,13 @@ static QString svgProblem(const QString &svg) { for (auto it = variable.globalMatch(svg); it.hasNext();) { const QString name = it.next().captured(1); if (!colors.contains(QString(name).replace('-', '_'))) - return "Unknown theme color --" + name + "; use --" + - colors.mid(0, 9).join(", --").replace('_', '-'); + return tr("Unknown theme color --%1; use --%2").arg(name, colors.mid(0, 9).join(", --").replace('_', '-')); } QSvgRenderer renderer(themedSvg(svg, {{"foreground", "#000000"}})); if (!renderer.isValid()) - return "Qt can't draw this SVG"; + return tr("Qt can't draw this SVG"); if (renderer.viewBoxF().isEmpty()) - return "Give the SVG a viewBox, or a width and height"; + return tr("Give the SVG a viewBox, or a width and height"); return {}; } Media parseMedia(const QString &source, const QString &base) { @@ -486,12 +489,12 @@ QStringList slideProblems(const QString &source, const QString &base) { errors << problem; } if (!media.file.isEmpty() && !QFileInfo::exists(media.path)) - errors << "Missing media: " + media.file; + errors << tr("Missing media: %1").arg(media.file); if (!media.file.isEmpty() && !media.video && QFileInfo::exists(media.path) && !QImageReader(media.path).canRead()) - errors << "Cannot decode image: " + media.file; + errors << tr("Cannot decode image: %1").arg(media.file); if (!media.poster.isEmpty() && !QFileInfo::exists(media.poster)) - errors << "Missing poster"; + errors << tr("Missing poster"); auto matches = mediaRe.globalMatch(outsideCode(withoutComments(source))); int count = 0; while (matches.hasNext()) { @@ -499,7 +502,7 @@ QStringList slideProblems(const QString &source, const QString &base) { ++count; } if (count + media.svgBlocks > 1) - errors << "Use one media item per slide (combine artwork before importing)"; + errors << tr("Use one media item per slide (combine artwork before importing)"); return errors; } static QImage loadedImage(const QString &path, QSize canvas, bool span) { @@ -927,7 +930,7 @@ void paintSlide(QPainter *p, const QRectF &target, const QString &source, const p->restore(); } else if (!overlayOnly && !backgroundOnly) { p->setPen(QColor(palette["accent"].toString())); - const QString message = "Missing media\n" + media.file; + const QString message = tr("Missing media") + "\n" + media.file; QFont diagnostic("sans"); // Shrink the notice to fit small placed boxes, and never draw past them. for (int size = 32; size >= 8; size -= 2) { @@ -1002,7 +1005,7 @@ void paintSlide(QPainter *p, const QRectF &target, const QString &source, const } highlightCode(doc, palette); if (low < 24 && warning) - *warning = "Text fits below 24px on a 1080p slide"; + *warning = tr("Text fits below 24px on a 1080p slide"); p->save(); p->translate(area.x(), area.y() + qMax(0.0, (area.height() - doc.size().height()) / 2)); QAbstractTextDocumentLayout::PaintContext context; diff --git a/src/resources.qrc b/src/resources.qrc index 0cdc378..0d44683 100644 --- a/src/resources.qrc +++ b/src/resources.qrc @@ -1 +1 @@ -Main.qmlAppIcon.qmlMarkdown.jsformat.mdskill.md +Main.qmlAppIcon.qmlMarkdown.jsformat.mdskill.mdi18n/en.jsoni18n/ar.jsoni18n/bg.jsoni18n/bn.jsoni18n/ca.jsoni18n/cs.jsoni18n/da.jsoni18n/de.jsoni18n/el.jsoni18n/es-MX.jsoni18n/et.jsoni18n/fa.jsoni18n/fi.jsoni18n/fil.jsoni18n/fr.jsoni18n/ga.jsoni18n/he.jsoni18n/hi.jsoni18n/hr.jsoni18n/hu.jsoni18n/id.jsoni18n/is.jsoni18n/it.jsoni18n/ja.jsoni18n/ko.jsoni18n/lt.jsoni18n/lv.jsoni18n/ms.jsoni18n/nl.jsoni18n/no.jsoni18n/pl.jsoni18n/pt-BR.jsoni18n/pt.jsoni18n/ro.jsoni18n/ru.jsoni18n/si.jsoni18n/sk.jsoni18n/sl.jsoni18n/sr.jsoni18n/sv.jsoni18n/sw.jsoni18n/ta.jsoni18n/th.jsoni18n/tr.jsoni18n/uk.jsoni18n/ur.jsoni18n/uz.jsoni18n/vi.jsoni18n/zh-CN.jsoni18n/zh-TW.json diff --git a/src/translator.cpp b/src/translator.cpp new file mode 100644 index 0000000..18c6b0c --- /dev/null +++ b/src/translator.cpp @@ -0,0 +1,163 @@ +#include "translator.h" + +#include +#include +#include +#include +#include +#include +#include +#include +#include + +Translator::Translator(const QString &languageFile, const QString &catalogDirectory, QObject *parent) + : QTranslator(parent), + m_languageFile(languageFile.isEmpty() ? QDir::homePath() + "/.config/omarchy/language" : languageFile), + m_catalogDirectory(catalogDirectory) { + m_debounce.setSingleShot(true); + m_debounce.setInterval(80); + connect(&m_watcher, &QFileSystemWatcher::directoryChanged, this, [this] { m_debounce.start(); }); + connect(&m_watcher, &QFileSystemWatcher::fileChanged, this, [this] { m_debounce.start(); }); + connect(&m_debounce, &QTimer::timeout, this, &Translator::reload); + reload(); +} + +QString Translator::language() const { + QReadLocker locker(&m_lock); + return m_language; +} + +bool Translator::isEmpty() const { + QReadLocker locker(&m_lock); + return m_strings.isEmpty(); +} + +// Unregistered before the catalog and its lock go, since a worker thread can +// still be translating through QCoreApplication while the app shuts down; +// one outliving the application (a test's) has nothing to unregister from. +Translator::~Translator() { + if (QCoreApplication::instance()) + QCoreApplication::removeTranslator(this); +} + +// One registry code on the first line; anything else, or no file, is English. +QString Translator::readLanguage(const QString &path) { + QFile file(path); + if (!file.open(QIODevice::ReadOnly)) + return "en"; + const QString code = QString::fromUtf8(file.readLine()).trimmed(); + static const QRegularExpression valid("^[a-z]{2,3}(-[A-Za-z]{2})?$"); + return valid.match(code).hasMatch() ? code : "en"; +} + +// CLDR cardinal plural categories for whole counts, for Omarchy's languages +// (the same rules as Omarchy's shell/Commons/Plural.js). +QString Translator::pluralCategory(const QString &language, long long count) { + const long long n = count < 0 ? -count : count, n10 = n % 10, n100 = n % 100; + const bool millions = n != 0 && n % 1000000 == 0; + const bool teens = n100 >= 12 && n100 <= 14; + const QString code = language; + auto in = [&](std::initializer_list codes) { + for (const char *c : codes) if (code == QLatin1String(c)) return true; + return false; + }; + if (in({"ja", "ko", "zh-CN", "zh-TW", "th", "vi", "id", "ms"})) return "other"; + if (in({"hi", "bn", "fa", "si"})) return n <= 1 ? "one" : "other"; + if (in({"fr", "pt-BR"})) return n <= 1 ? "one" : millions ? "many" : "other"; + if (in({"ca", "es-MX", "it", "pt"})) return n == 1 ? "one" : millions ? "many" : "other"; + if (code == "fil") return (n10 == 4 || n10 == 6 || n10 == 9) ? "other" : "one"; + if (code == "is") return n10 == 1 && n100 != 11 ? "one" : "other"; + if (in({"cs", "sk"})) return n == 1 ? "one" : n >= 2 && n <= 4 ? "few" : "other"; + if (code == "pl") return n == 1 ? "one" : n10 >= 2 && n10 <= 4 && !teens ? "few" : "many"; + if (in({"ru", "uk"})) return n10 == 1 && n100 != 11 ? "one" : n10 >= 2 && n10 <= 4 && !teens ? "few" : "many"; + if (in({"hr", "sr"})) return n10 == 1 && n100 != 11 ? "one" : n10 >= 2 && n10 <= 4 && !teens ? "few" : "other"; + if (code == "sl") return n100 == 1 ? "one" : n100 == 2 ? "two" : n100 >= 3 && n100 <= 4 ? "few" : "other"; + if (code == "lt") return n100 >= 11 && n100 <= 19 ? "other" : n10 == 1 ? "one" : n10 >= 2 ? "few" : "other"; + if (code == "lv") return n10 == 0 || (n100 >= 11 && n100 <= 19) ? "zero" : n10 == 1 ? "one" : "other"; + if (code == "ro") return n == 1 ? "one" : n == 0 || (n100 >= 1 && n100 <= 19) ? "few" : "other"; + if (code == "ar") { + if (n <= 2) return n == 0 ? "zero" : n == 1 ? "one" : "two"; + return n100 >= 3 && n100 <= 10 ? "few" : n100 >= 11 ? "many" : "other"; + } + if (code == "he") return n == 1 ? "one" : n == 2 ? "two" : "other"; + if (code == "ga") return n == 1 ? "one" : n == 2 ? "two" : n >= 3 && n <= 6 ? "few" : n >= 7 && n <= 10 ? "many" : "other"; + return n == 1 ? "one" : "other"; +} + +// The locale Omarchy formats this language with, from its registry, so the +// app's numbers and dates match the desktop's (Arabic there uses Western +// digits); without Omarchy, Qt's own locale for the code. +QLocale Translator::formatLocale(const QString &language) { + QFile registry(qEnvironmentVariable("OMARCHY_PATH") + "/default/i18n/locales.json"); + if (registry.open(QIODevice::ReadOnly)) { + const QString name = QJsonDocument::fromJson(registry.readAll()).object() + .value(language).toObject().value("formatLocale").toString(); + if (!name.isEmpty()) + return QLocale(name); + } + return QLocale(language); +} + +QString Translator::translate(const char *, const char *sourceText, const char *, int n) const { + // A null string tells Qt there is no translation, so it shows the English. + QReadLocker locker(&m_lock); + const Entry entry = m_strings.value(QString::fromUtf8(sourceText)); + const QJsonValue &value = entry.value; + if (value.isString()) + return value.toString(); + if (value.isObject()) { + const QJsonObject forms = value.toObject(); + const QString form = forms.value(n < 0 ? "other" : pluralCategory(entry.language, n)).toString(); + return form.isEmpty() ? forms.value("other").toString() : form; + } + return {}; +} + +void Translator::reload() { + const auto paths = m_watcher.files() + m_watcher.directories(); + if (!paths.isEmpty()) + m_watcher.removePaths(paths); + + // omarchy-language replaces the file, which drops it from the watch, and a + // first pick creates it, and maybe its directory; watch the nearest + // existing directory too and re-arm every time. + QString directory = QFileInfo(m_languageFile).absolutePath(); + while (!QFileInfo::exists(directory) && directory != "/") + directory = QFileInfo(directory).absolutePath(); + m_watcher.addPath(directory); + if (QFileInfo::exists(m_languageFile)) + m_watcher.addPath(m_languageFile); + + // Catalogs are compiled in, so only a different language needs a reload. + const QString language = readLanguage(m_languageFile); + if (language == this->language()) + return; + + // English first (it carries the plural forms of counted strings), then + // the base language and the regional file over it (pt, then pt-BR), so a + // missing string falls back toward English one step at a time. + QHash strings; + QStringList codes{"en", language.section('-', 0, 0), language}; + codes.removeDuplicates(); + for (const auto &code : codes) { + QFile catalog(m_catalogDirectory + "/" + code + ".json"); + if (!catalog.open(QIODevice::ReadOnly)) + continue; + const QJsonObject object = QJsonDocument::fromJson(catalog.readAll()).object(); + for (auto it = object.begin(); it != object.end(); ++it) + if ((it.value().isString() && !it.value().toString().isEmpty()) || it.value().isObject()) + strings.insert(it.key(), {it.value(), code}); + } + + { + QWriteLocker locker(&m_lock); + m_language = language; + m_strings = strings; + } + // Dates, numbers, and Qt's own day and month names follow the language + // too, and right-to-left languages mirror the window. + const QLocale locale = formatLocale(language); + QLocale::setDefault(locale); + QGuiApplication::setLayoutDirection(locale.textDirection()); + emit changed(); +} diff --git a/src/translator.h b/src/translator.h new file mode 100644 index 0000000..e199412 --- /dev/null +++ b/src/translator.h @@ -0,0 +1,57 @@ +#pragma once + +#include +#include +#include +#include +#include +#include +#include + +// Follows the language picked under Omarchy's Setup > Language. Catalogs are +// flat JSON objects from English source text to translation, one per Omarchy +// language code (i18n/da.json, i18n/pt-BR.json), so QML keeps plain +// qsTr("Save") and C++ keeps tr("Save"). A counted string, +// qsTr("%n clips", "", count), maps to an object of plural forms keyed by +// CLDR category ({"one": "%n klip", "other": "%n klip"}). +class Translator : public QTranslator { + Q_OBJECT + Q_PROPERTY(QString language READ language NOTIFY changed) + +public: + explicit Translator(const QString &languageFile = {}, const QString &catalogDirectory = ":/i18n", + QObject *parent = nullptr); + ~Translator() override; + + QString language() const; + bool isEmpty() const override; + QString translate(const char *context, const char *sourceText, const char *disambiguation = nullptr, + int n = -1) const override; + + static QString readLanguage(const QString &path); + static QString pluralCategory(const QString &language, long long count); + static QLocale formatLocale(const QString &language); + +signals: + void changed(); + +private: + void reload(); + + QString m_languageFile; + QString m_catalogDirectory; + // A translation, and the language whose catalog it came from, so a + // counted string falling back to English takes English plural rules. + struct Entry { + QJsonValue value; + QString language; + }; + + // translate() also runs on worker threads (an app's background errors), + // while a language switch replaces the catalog on the GUI thread. + mutable QReadWriteLock m_lock; + QString m_language; + QHash m_strings; + QFileSystemWatcher m_watcher; + QTimer m_debounce; +}; diff --git a/tests/tests.cpp b/tests/tests.cpp index c8f6f05..6525861 100644 --- a/tests/tests.cpp +++ b/tests/tests.cpp @@ -5,6 +5,7 @@ #include "renderer.h" #include "images.h" #include "syntax.h" +#include "translator.h" #include #include #include @@ -47,6 +48,11 @@ #include #include #include +#include +#include +#include +#include +#include class TestFilePortal : public QDBusVirtualObject { public: @@ -85,6 +91,227 @@ class TestFilePortal : public QDBusVirtualObject { } }; +namespace { + +void writeFile(const QString &path, const QByteArray &contents) { + QFile file(path); + QVERIFY(file.open(QIODevice::WriteOnly)); + file.write(contents); +} + +// The folder of the app's sources, where its catalogs live. +QString sourceFolder() { + return QFileInfo(QFINDTESTDATA("../src/main.cpp")).absolutePath(); +} + +// A source file with its comments left out (their examples aren't calls) +// and its strings kept whole, so neither hides the other. +QString withoutComments(const QString &text, bool cpp) { + QString out; + for (qsizetype i = 0; i < text.size();) { + const QChar c = text.at(i); + if (text.mid(i, 2) == "//") { + const qsizetype end = text.indexOf('\n', i); + i = end < 0 ? text.size() : end; + } else if (text.mid(i, 2) == "/*") { + const qsizetype end = text.indexOf("*/", i + 2); + i = end < 0 ? text.size() : end + 2; + } else if (cpp && c == '"' && i > 0 && text.at(i - 1) == 'R') { + // A raw string holds quotes of its own; it's no translation, so it's left out whole. + const qsizetype open = text.indexOf('(', i); + const QString close = ')' + text.mid(i + 1, open - i - 1) + '"'; + out += "\"\""; + i = text.indexOf(close, open) + close.size(); + } else if (c == '"' || c == '\'' || c == '`') { + qsizetype end = i + 1; + while (end < text.size() && text.at(end) != c) + end += text.at(end) == '\\' ? 2 : 1; + out += text.mid(i, end + 1 - i); + i = end + 1; + } else { + out += c; + ++i; + } + } + return out; +} + +// A literal's text as the language reads it. +QString unescaped(const QString &literal) { + QString out; + for (qsizetype i = 0; i < literal.size(); ++i) { + QChar c = literal.at(i); + if (c == '\\' && i + 1 < literal.size()) { + c = literal.at(++i); + c = c == 'n' ? QChar('\n') : c == 't' ? QChar('\t') : c; + } + out += c; + } + return out; +} + +// Every text the sources hand to qsTr(), tr() or QT_TR_NOOP(), and whether +// any call also passes it a count (its third argument). C++'s adjacent +// literals are one text. A call whose text isn't a literal can't be in a +// catalog, and is reported in `problems`; the sources' own +// QString tr(const char *) helpers are definitions, not calls. +QMap translatables(const QString &folder, QStringList *problems) { + static const QRegularExpression call(R"((? found; + for (const QFileInfo &info : QDir(folder).entryInfoList({"*.qml", "*.js", "*.cpp", "*.h"}, QDir::Files)) { + QFile file(info.filePath()); + if (!file.open(QIODevice::ReadOnly)) + continue; + const bool cpp = info.suffix() == "cpp" || info.suffix() == "h"; + const QString code = withoutComments(QString::fromUtf8(file.readAll()), cpp); + for (auto calls = call.globalMatch(code); calls.hasNext();) { + const auto match = calls.next(); + qsizetype at = match.capturedEnd(); + QString text; + bool isLiteral = false; + for (auto part = literal.match(code.mid(at)); part.hasMatch(); part = literal.match(code.mid(at))) { + text += unescaped(part.captured(2)); + at += part.capturedEnd(); + isLiteral = true; + if (!cpp) + break; + } + if (!isLiteral) { + *problems << info.fileName() + ": not a literal: " + code.mid(match.capturedStart(), 60); + continue; + } + // The arguments after the text, up to the call's closing parenthesis. + int depth = 0, commas = 0; + for (; at < code.size(); ++at) { + const QChar c = code.at(at); + if (c == '"' || c == '\'') { + for (++at; at < code.size() && code.at(at) != c; at += code.at(at) == '\\' ? 2 : 1) { } + } else if (c == '(' || c == '[' || c == '{') { + ++depth; + } else if (c == ')' || c == ']' || c == '}') { + if (depth-- == 0) + break; + } else if (c == ',' && depth == 0) { + ++commas; + } + } + found[text] = found.value(text) || commas >= 2; + } + } + return found; +} + +QJsonObject readCatalog(const QString &path, QStringList *problems) { + QFile file(path); + if (!file.open(QIODevice::ReadOnly)) { + *problems << path + ": can't be read"; + return {}; + } + QJsonParseError error; + const QJsonDocument document = QJsonDocument::fromJson(file.readAll(), &error); + if (!document.isObject()) + *problems << path + ": not a JSON object: " + error.errorString(); + return document.object(); +} + +// The placeholders in a text, in order: %1 to %9, and the count (%n, %Ln). +QStringList placeholders(const QString &text) { + static const QRegularExpression placeholder("%L?[1-9n]"); + QStringList found; + for (auto it = placeholder.globalMatch(text); it.hasNext();) + found << it.next().captured(); + found.sort(); + return found; +} + +// Omarchy's 49 translations (default/i18n/locales.json), as the sync's LANGUAGES has them. +const QStringList &languageCodes() { + static const QStringList codes{"ar", "bg", "bn", "ca", "cs", "da", "de", "el", "es-MX", "et", "fa", "fi", "fil", + "fr", "ga", "he", "hi", "hr", "hu", "id", "is", "it", "ja", "ko", "lt", "lv", "ms", + "nl", "no", "pl", "pt", "pt-BR", "ro", "ru", "si", "sk", "sl", "sr", "sv", "sw", + "ta", "th", "tr", "uk", "ur", "uz", "vi", "zh-CN", "zh-TW"}; + return codes; +} + +// What's wrong with the translations in `folder`, measured against its +// en.json: an unknown language, empty or broken translations, and plural +// forms that don't fit the language's rule. A string a catalog lacks, or one +// en.json no longer has, is work for the translation sync +// (scripts/i18n-sync.py), not a problem: the window shows the English +// meanwhile, so a change to the English never waits on 49 languages. +QStringList catalogProblems(const QString &folder) { + const QStringList &codes = languageCodes(); + QStringList problems; + const QJsonObject english = readCatalog(folder + "/en.json", &problems); + for (const QFileInfo &file : QDir(folder).entryInfoList({"*.json"}, QDir::Files)) { + const QString code = file.completeBaseName(); + if (code == "en") + continue; + if (!codes.contains(code)) { + problems << file.fileName() + ": not one of Omarchy's language codes"; + continue; + } + const QJsonObject catalog = readCatalog(file.filePath(), &problems); + + // The categories the language's rule reaches, and "other" always. + QSet categories{"other", Translator::pluralCategory(code, 1000000)}; + for (long long n = 0; n <= 1000; ++n) + categories << Translator::pluralCategory(code, n); + + for (auto it = english.begin(); it != english.end(); ++it) { + const QJsonValue translated = catalog.value(it.key()); + const QString where = code + ": " + it.key() + ": "; + if (translated.isUndefined()) + continue; + if (it.value().isString()) { + if (!translated.isString() || translated.toString().trimmed().isEmpty()) + problems << where + "needs a translation"; + else if (placeholders(translated.toString()) != placeholders(it.key())) + problems << where + "has other placeholders than the English"; + continue; + } + const QJsonObject forms = translated.toObject(); + const QStringList given = forms.keys(); + if (!translated.isObject() || QSet(given.begin(), given.end()) != categories) { + QStringList wanted(categories.begin(), categories.end()); + wanted.sort(); + problems << where + "needs exactly the plural forms " + wanted.join(", "); + continue; + } + // Every form says every placeholder; one that isn't "other" may + // say the number in words instead of the count. + const QStringList all = placeholders(it.value().toObject().value("other").toString()); + const QSet needed(all.begin(), all.end()); + QSet fixed = needed; + fixed.remove("%n"); + fixed.remove("%Ln"); + for (auto form = forms.begin(); form != forms.end(); ++form) { + const QStringList has = placeholders(form.value().toString()); + const QSet present(has.begin(), has.end()); + if (form.value().toString().trimmed().isEmpty()) + problems << where + form.key() + " needs a translation"; + else if (!(form.key() == "other" ? present == needed : present.contains(fixed) && needed.contains(present))) + problems << where + form.key() + " has other placeholders than the English"; + } + } + } + return problems; +} + +// A Translator sets the application's default locale and layout direction, so a test that makes one puts both back. +struct LanguageGuard { + QLocale locale; + Qt::LayoutDirection direction = QGuiApplication::layoutDirection(); + ~LanguageGuard() { + QLocale::setDefault(locale); + QGuiApplication::setLayoutDirection(direction); + } +}; + +} + class HypeTests : public QObject { Q_OBJECT QTemporaryDir settingsDirectory; @@ -4419,6 +4646,206 @@ static void write(const QString &path, const QString &content) { QVERIFY(f.open(QIODevice::ReadOnly)); QCOMPARE(f.readAll(), QByteArray("existing")); } + void translatorFallsBackToEnglish() { + LanguageGuard guard; + QTemporaryDir dir; + Translator translator(dir.path() + "/language", dir.path()); + QCOMPARE(translator.language(), QString("en")); + QVERIFY(translator.translate("Main", "Save").isNull()); + } + + void translatorFollowsTheLanguageFile() { + LanguageGuard guard; + QTemporaryDir dir; + writeFile(dir.path() + "/language", "pt-BR\n"); + writeFile(dir.path() + "/pt.json", R"({"Save": "Guardar", "Open": "Abrir"})"); + writeFile(dir.path() + "/pt-BR.json", R"({"Save": "Salvar"})"); + + Translator translator(dir.path() + "/language", dir.path()); + QCOMPARE(translator.language(), QString("pt-BR")); + QCOMPARE(translator.translate("Main", "Save"), QString("Salvar")); + QCOMPARE(translator.translate("Main", "Open"), QString("Abrir")); + QVERIFY(translator.translate("Main", "Quit").isNull()); + } + + void translatorFollowsAFirstPick() { + LanguageGuard guard; + QTemporaryDir dir; + Translator translator(dir.path() + "/omarchy/language", dir.path()); + QCOMPARE(translator.language(), QString("en")); + // Omarchy may create the file's directory only when a language is first picked. + QVERIFY(QDir(dir.path()).mkpath("omarchy")); + writeFile(dir.path() + "/omarchy/language", "da\n"); + QTRY_COMPARE(translator.language(), QString("da")); + } + + void translatorPicksPluralForms() { + LanguageGuard guard; + QTemporaryDir dir; + writeFile(dir.path() + "/language", "ru\n"); + writeFile(dir.path() + "/ru.json", R"({"%n items": {"one": "%n элемент", "few": "%n элемента", "many": "%n элементов", "other": "%n элемента"}})"); + + Translator translator(dir.path() + "/language", dir.path()); + QCOMPARE(translator.translate("Main", "%n items", nullptr, 21), QString("%n элемент")); + QCOMPARE(translator.translate("Main", "%n items", nullptr, 22), QString("%n элемента")); + QCOMPARE(translator.translate("Main", "%n items", nullptr, 25), QString("%n элементов")); + QCOMPARE(Translator::pluralCategory("ar", 11), QString("many")); + + // A language without the string counts with English's rules, not its own. + writeFile(dir.path() + "/language", "ja\n"); + writeFile(dir.path() + "/en.json", R"({"%n items": {"one": "%n item", "other": "%n items"}})"); + Translator japanese(dir.path() + "/language", dir.path()); + QCOMPARE(japanese.translate("Main", "%n items", nullptr, 1), QString("%n item")); + QCOMPARE(Translator::pluralCategory("ja", 1), QString("other")); + } + + void englishCatalogMatchesTheSources() { + // en.json is the source translators work from: every text the + // sources translate is in it, as itself or (when a count is passed) + // as its English plural forms, and nothing else is. + QStringList problems; + const QMap used = translatables(sourceFolder(), &problems); + QVERIFY(used.size() > 100); + QVERIFY(used.value("%Ln slides selected")); + const QJsonObject english = readCatalog(sourceFolder() + "/i18n/en.json", &problems); + for (auto it = used.begin(); it != used.end(); ++it) { + const QJsonValue value = english.value(it.key()); + if (value.isUndefined()) + problems << "missing from en.json: " + it.key(); + else if (it.value() && (value.toObject().keys() != QStringList{"one", "other"} + || value.toObject().value("other").toString() != it.key())) + problems << "counted, so needs its one and other forms: " + it.key(); + else if (!it.value() && value.toString() != it.key()) + problems << "should be itself: " + it.key(); + } + for (const QString &key : english.keys()) + if (!used.contains(key)) + problems << "in en.json but no source translates it: " + key; + QVERIFY2(problems.isEmpty(), qPrintable(problems.join('\n'))); + } + + void catalogsMatchTheEnglishOne() { + QStringList problems = catalogProblems(sourceFolder() + "/i18n"); + // Every language has its catalog, empty until the sync fills it: the + // sync only changes catalogs that exist, and only these are compiled in. + for (const QString &code : languageCodes()) + if (!QFileInfo::exists(sourceFolder() + "/i18n/" + code + ".json")) + problems << code + ".json: missing"; + QVERIFY2(problems.isEmpty(), qPrintable(problems.join('\n'))); + } + + void catalogChecksCatchBrokenTranslations() { + QTemporaryDir dir; + writeFile(dir.filePath("en.json"), R"({"Open": "Open", "Open %1": "Open %1", + "%Ln items": {"one": "%Ln item", "other": "%Ln items"}, + "%Ln items in %1": {"one": "%Ln item in %1", "other": "%Ln items in %1"}})"); + // Polish needs one, few, many and other; a form may say "one" in + // words, but not drop the document. + writeFile(dir.filePath("pl.json"), R"({"Open": "Otwórz", "Open %1": "Otwórz", + "%Ln items": {"one": "jeden element", "few": "%Ln elementy", "other": "%Ln elementu"}, + "%Ln items in %1": {"one": "jeden element", "few": "%Ln elementy w %1", + "many": "%Ln elementów w %1", "other": "%Ln elementu w %1"}})"); + writeFile(dir.filePath("da.json"), R"({"Open": " ", "Open %1": "Åbn %1", + "%Ln items": {"one": "ét element", "other": " "}, + "%Ln items in %1": {"one": "%Ln element i %1", "other": "%Ln elementer i %1"}})"); + // German hasn't caught up yet: one string still to translate and one + // the English has since dropped. + writeFile(dir.filePath("de.json"), R"({"Open": "Öffnen", "Opened": "Geöffnet"})"); + writeFile(dir.filePath("xx.json"), "{}"); + QStringList problems = catalogProblems(dir.path()); + problems.sort(); + QCOMPARE(problems, QStringList({"da: %Ln items: other needs a translation", + "da: Open: needs a translation", + "pl: %Ln items in %1: one has other placeholders than the English", + "pl: %Ln items: needs exactly the plural forms few, many, one, other", + "pl: Open %1: has other placeholders than the English", + "xx.json: not one of Omarchy's language codes"})); + } + + void everyCatalogIsCompiledIn() { + QFile resources(sourceFolder() + "/resources.qrc"); + QVERIFY(resources.open(QIODevice::ReadOnly)); + const QString listed = QString::fromUtf8(resources.readAll()); + QStringList left; + for (const QString &name : QDir(sourceFolder() + "/i18n").entryList({"*.json"}, QDir::Files)) + if (!listed.contains("i18n/" + name + "")) + left << name; + QVERIFY2(left.isEmpty(), qPrintable("not in resources.qrc: " + left.join(", "))); + } + + void slidesRenderTheSameRightToLeft() { + // An Arabic or Hebrew desktop turns the application right to left; a slide is the author's, and stays as written. + QTemporaryDir tmp; + QDir().mkpath(tmp.filePath("images")); + QImage logo(40, 20, QImage::Format_RGB32); + logo.fill(Qt::red); + QVERIFY(logo.save(tmp.filePath("images/logo.png"))); + Deck deck; + const QStringList slides{ + "# A headline\n\nWith a line below it", + "- One point\n- Another point\n- A third", + "| Left | Right |\n|:-----|------:|\n| a | 1 |\n| bb | 22 |\n\nText beside the table", + "```\nint main() { return 0; }\n```", + "> A quote, left as it was written", + "# Placed\n\n![top-left 20%](images/logo.png)", + }; + const auto guard = qScopeGuard([direction = QGuiApplication::layoutDirection()] { + QGuiApplication::setLayoutDirection(direction); + }); + for (const QString &source : slides) { + QImage pictures[2]; + for (int rtl = 0; rtl < 2; ++rtl) { + QGuiApplication::setLayoutDirection(rtl ? Qt::RightToLeft : Qt::LeftToRight); + pictures[rtl] = QImage(960, 540, QImage::Format_ARGB32_Premultiplied); + pictures[rtl].fill(Qt::transparent); + QPainter painter(&pictures[rtl]); + QString warning; + paintSlide(&painter, pictures[rtl].rect(), source, tmp.path(), deck.palette(), &warning); + QVERIFY2(warning.isEmpty(), qPrintable(warning)); + } + QVERIFY2(pictures[0] == pictures[1], qPrintable("drawn differently right to left: " + source)); + } + } + void windowFollowsTheLanguage() { + if (qEnvironmentVariable("HYPE_GUI_TESTS") == "0") QSKIP("HYPE_GUI_TESTS=0 skips the window-level tests"); + LanguageGuard guard; + QTemporaryDir dir; + writeFile(dir.filePath("language"), "da\n"); + writeFile(dir.filePath("da.json"), R"({"Bold": "Fed", "Top left": "Øverst til venstre", "%Ln slides selected": {"one": "%Ln dias valgt", "other": "%Ln dias valgt"}})"); + Translator translator(dir.filePath("language"), dir.path()); + QCoreApplication::installTranslator(&translator); + const auto uninstall = qScopeGuard([&] { QCoreApplication::removeTranslator(&translator); }); + Deck deck; + deck.editSource("# First\n---\n# Last\n"); + QQuickStyle::setStyle("Basic"); + qmlRegisterType("Hype", 1, 0, "SlideCanvas"); + qmlRegisterType("Hype", 1, 0, "AppTheme"); + QQmlApplicationEngine engine; + QObject::connect(&translator, &Translator::changed, &engine, &QQmlEngine::retranslate); + engine.rootContext()->setContextProperty("deck", &deck); + engine.addImageProvider("slides", new Thumbnails(&deck)); + engine.load(QUrl("qrc:/Main.qml")); + QVERIFY(!engine.rootObjects().isEmpty()); + auto window = qobject_cast(engine.rootObjects().first()); + const auto close = qScopeGuard([&] { + window->setProperty("allowClose", true); + window->close(); + }); + auto bold = window->findChild("boldButton"); + QVERIFY(bold); + QCOMPARE(bold->property("label").toString(), QString("Fed")); + QCOMPARE(bold->property("description").toString(), QString("Fed (Ctrl+B)")); + QVariant place; + QVERIFY(QMetaObject::invokeMethod(window, "positionName", Q_RETURN_ARG(QVariant, place), Q_ARG(QVariant, "top-left"))); + QCOMPARE(place.toString(), QString("Øverst til venstre")); + // A string Danish doesn't have yet shows in English. + QCOMPARE(window->findChild("italicButton")->property("label").toString(), QString("Italic")); + + // Picking another language under Setup > Language changes the open window. + writeFile(dir.filePath("language"), "en\n"); + QTRY_COMPARE(bold->property("label").toString(), QString("Bold")); + QCOMPARE(bold->property("description").toString(), QString("Bold (Ctrl+B)")); + } }; QTEST_MAIN(HypeTests) #include "tests.moc" From a197b9ee898d77bdb6b5b3ed199236703360506c Mon Sep 17 00:00:00 2001 From: Omarchybot <317366263+omarchybot@users.noreply.github.com> Date: Thu, 12 Nov 2026 12:20:39 +0100 Subject: [PATCH 2/4] Make cached and C++-made text follow a language switch Codex found three messages still glued in English, parse errors cached by source alone so they kept the old language, and an untitled title that QML's retranslation never re-reads. The parse caches and slide render ids now carry a translation generation, Deck::retranslate redoes the deck's error, title and banners on a switch, and the starter headline of a new presentation is translated too. Co-Authored-By: Codex XHigh Co-Authored-By: Claude Opus 5.5 --- docs/i18n.md | 2 +- src/deck.cpp | 73 +++++++++++++++++++++++++++++++----------------- src/deck.h | 2 ++ src/i18n/en.json | 6 ++++ src/main.cpp | 1 + src/pptx.cpp | 2 +- src/renderer.cpp | 11 ++++++-- src/renderer.h | 3 ++ tests/tests.cpp | 24 ++++++++++++++++ 9 files changed, 93 insertions(+), 31 deletions(-) diff --git a/docs/i18n.md b/docs/i18n.md index db1ea1d..271b828 100644 --- a/docs/i18n.md +++ b/docs/i18n.md @@ -8,7 +8,7 @@ The window and the export worker it starts are translated, so an export's progre ## Adding or changing a string -Pull requests only ever touch English: wrap the text in `qsTr()` (QML) or `tr()` (C++), with `%1` placeholders filled by `.arg()` rather than a sentence glued together, and add it to `src/i18n/en.json` as itself, or with its `one` and `other` forms when it's counted. A free function in C++ uses its file's `tr()` helper. The `englishCatalogMatchesTheSources` test keeps `en.json` exactly in step with the sources. Leave the other catalogs alone. Since the English is the key, rewording a string makes a new key; its translations become pending, and the old key is dropped by the next sync. The catalog tests check the translations that are there (placeholders, plural forms, language codes, every catalog listed in `resources.qrc`), but never require them to be complete, so English is never blocked. +Pull requests only ever touch English: wrap the text in `qsTr()` (QML) or `tr()` (C++), with `%1` placeholders filled by `.arg()` rather than a sentence glued together, and add it to `src/i18n/en.json` as itself, or with its `one` and `other` forms when it's counted. A free function in C++ uses its file's `tr()` helper. QML redoes every `qsTr()` binding on a language switch, but text C++ makes and keeps is not: parse errors are cached by translation generation, and `Deck::retranslate` makes the deck's error, title and slide banners again, so a new cache of translated text needs the same. The `englishCatalogMatchesTheSources` test keeps `en.json` exactly in step with the sources. Leave the other catalogs alone. Since the English is the key, rewording a string makes a new key; its translations become pending, and the old key is dropped by the next sync. The catalog tests check the translations that are there (placeholders, plural forms, language codes, every catalog listed in `resources.qrc`), but never require them to be complete, so English is never blocked. ## Keeping translations in sync diff --git a/src/deck.cpp b/src/deck.cpp index 5a91650..527b626 100644 --- a/src/deck.cpp +++ b/src/deck.cpp @@ -140,10 +140,32 @@ QString setScalar(QString header, const QString &key, const QString &value) { } return header; } +// The first slide's problem, for a structure whose boundaries are already known. +static QString slidesError(const ParsedDeck &parsed) { + for (const auto &slide : parsed.slides) { + // A slide body cannot contain front matter. Prefix a plain line so + // a leading --- is interpreted as a slide break instead. + static thread_local QCache errors(2 * 1024 * 1024); + // Errors are in the window's language, so a language switch starts the cache over. + const QString key = QString::number(translationGeneration()) + QChar(0) + slide.source; + auto error = errors.object(key); + if (!error) { + error = new QString(parseDeck("Slide\n" + slide.source).error); + errors.insert(key, error, qMax(1, int(key.size() * 2))); + error = errors.object(key); + } + const QString problem = error ? *error : parseDeck("Slide\n" + slide.source).error; + if (!problem.isEmpty()) + return problem; + } + return {}; +} +// A new presentation, whose headline the window selects so typing replaces it. +static QString starterSource() { return "---\ntheme: tokyo-night\n---\n\n# " + tr("Your next idea") + "\n"; } Deck::Deck(QObject *parent, const QString &exportProgram) : QAbstractListModel(parent), m_exportProgram(exportProgram.isEmpty() ? QCoreApplication::applicationFilePath() : exportProgram) { discoverThemes(); - m_source = "---\ntheme: tokyo-night\n---\n\n# Your next idea\n"; + m_source = starterSource(); m_parsed = parseDeck(m_source); m_saved = m_source; // Writers may truncate, or remove and recreate, the file; read it once they settle. @@ -259,6 +281,21 @@ QString Deck::title() const { return scalar(m_parsed.header, "title", m_path.isEmpty() ? tr("Untitled") : QFileInfo(m_path).completeBaseName()); } +void Deck::retranslate() { + // Parse errors, problem banners and the untitled name were made in the old language. + retranslateSlides(); + m_mediaCache.clear(); + m_renderIds.clear(); + const QString old = m_parsed.error; + if (!old.isEmpty()) { + const QString document = parseDeck(m_source).error; + m_parsed.error = document.isEmpty() ? slidesError(m_parsed) : document; + if (m_status == old) + setStatus(m_parsed.error); + } + ++m_revision; + notifyChanged(); +} void Deck::setStatus(const QString &s) { m_status = s; if (!m_exporting && !m_exportStatus.isEmpty()) { @@ -283,25 +320,8 @@ void Deck::apply(const QString &source, int selected, bool history, int anchor, m_redo.clear(); } auto parsed = structure ? *structure : parseDeck(source); - if (structure) { - parsed.error.clear(); - for (const auto &slide : parsed.slides) { - // A slide body cannot contain front matter. Prefix a plain line so - // a leading --- is interpreted as a slide break instead. - static thread_local QCache errors(2 * 1024 * 1024); - auto error = errors.object(slide.source); - if (!error) { - error = new QString(parseDeck("Slide\n" + slide.source).error); - errors.insert(slide.source, error, qMax(1, int(slide.source.size() * 2))); - error = errors.object(slide.source); - } - const QString problem = error ? *error : parseDeck("Slide\n" + slide.source).error; - if (!problem.isEmpty()) { - parsed.error = problem; - break; - } - } - } + if (structure) + parsed.error = slidesError(parsed); const bool reset = parsed.slides.size() != count(); QVector modified; if (!reset) @@ -944,7 +964,7 @@ void Deck::newDeck() { m_path.clear(); m_saved.clear(); m_externalChange = false; - apply("---\ntheme: tokyo-night\n---\n\n# Your next idea\n", 0); + apply(starterSource(), 0); m_undo.clear(); m_redo.clear(); watch(); @@ -1020,7 +1040,7 @@ bool Deck::importMedia(const QUrl &url, bool newSlide) { if (newSlide) addSlide(); editSlide(withReplacedMedia(slideSource(), name)); - setStatus("Added " + name); + setStatus(tr("Added %1").arg(name)); return true; } bool Deck::pasteMedia() { @@ -1172,7 +1192,7 @@ QString Deck::savePastedMedia(const QString &value) { const QString directory = QDir(baseDir()).filePath(m_paste.video ? "videos" : "images"); const QString destination = QDir(directory).filePath(name); if (QFile::exists(destination)) - return name + " already exists. Choose another name."; + return tr("%1 already exists. Choose another name.").arg(name); if (!QDir().mkpath(directory)) return tr("Could not create %1").arg(directory); bool saved = false; @@ -1192,7 +1212,7 @@ QString Deck::savePastedMedia(const QString &value) { return tr("Could not save %1").arg(name); cancelPaste(); editSlide(withReplacedMedia(slideSource(), name)); - setStatus("Added " + name); + setStatus(tr("Added %1").arg(name)); return {}; } QString Deck::renderId(int index) const { @@ -1204,7 +1224,8 @@ QString Deck::renderId(int index) const { return cached.id; QByteArray bytes; QDataStream stream(&bytes, QIODevice::WriteOnly); - stream << slide(index) << baseDir() << palette(); + // A slide with problems shows them on a banner, in the window's language. + stream << slide(index) << baseDir() << palette() << translationGeneration(); auto media = parseMedia(slide(index), baseDir()); for (const QString &path : {media.path, media.poster}) { QFileInfo file(path); @@ -1634,7 +1655,7 @@ bool Deck::exportPptx(const QString &path) { emit exportAdvanced(0.8, tr("Packaging PowerPoint…")); if (!writePptx(temp.path() + "/slides.json", path, &error, [this](double fraction) { emit exportAdvanced(0.8 + 0.2 * fraction, tr("Packaging PowerPoint…")); })) { - setStatus("PowerPoint export failed: " + error); + setStatus(tr("PowerPoint export failed: %1").arg(error)); return false; } setStatus(tr("Exported %1").arg(path)); diff --git a/src/deck.h b/src/deck.h index 5a283da..00febb8 100644 --- a/src/deck.h +++ b/src/deck.h @@ -113,6 +113,8 @@ class Deck : public QAbstractListModel { // For PowerPoint, animations become videos and opaque slides are stored as JPEG. bool renderImages(const QString &directory, int width = 1920, bool powerPoint = false); Q_INVOKABLE void select(int index); + // After a language switch, so what the window shows is made again in the new language. + void retranslate(); Q_INVOKABLE void extendSelection(int index); Q_INVOKABLE void moveSelection(int direction); Q_INVOKABLE void dropSelection(int slot); diff --git a/src/i18n/en.json b/src/i18n/en.json index d197dab..cff5a65 100644 --- a/src/i18n/en.json +++ b/src/i18n/en.json @@ -1,11 +1,14 @@ { + "%1 already exists. Choose another name.": "%1 already exists. Choose another name.", "%1 — Presenter View": "%1 — Presenter View", "%Ln slides selected": { "one": "%Ln slide selected", "other": "%Ln slides selected" }, + "A placed image cannot use fit, span, background, or overlay": "A placed image cannot use fit, span, background, or overlay", "Add a slide": "Add a slide", "Add image / video": "Add image / video", + "Added %1": "Added %1", "An svg block holds one element": "An svg block holds one element", "Animation conversion failed: %1": "Animation conversion failed: %1", "Black": "Black", @@ -165,6 +168,8 @@ "Play": "Play", "Play or pause video while presenting": "Play or pause video while presenting", "PowerPoint export exceeds the 4 GiB ZIP limit.": "PowerPoint export exceeds the 4 GiB ZIP limit.", + "PowerPoint export failed: %1": "PowerPoint export failed: %1", + "PowerPoint video requires H.264/AAC MP4: %1": "PowerPoint video requires H.264/AAC MP4: %1", "Preparing %1 export…": "Preparing %1 export…", "Present": "Present", "Present from first slide": "Present from first slide", @@ -240,5 +245,6 @@ "Visual · Switch to Markdown": "Visual · Switch to Markdown", "White": "White", "Your headline": "Your headline", + "Your next idea": "Your next idea", "←/→ change slide · Space plays media · Esc ends the show": "←/→ change slide · Space plays media · Esc ends the show" } diff --git a/src/main.cpp b/src/main.cpp index 59ab220..829c925 100644 --- a/src/main.cpp +++ b/src/main.cpp @@ -148,6 +148,7 @@ int main(int argc, char **argv) { qmlRegisterType("Hype", 1, 0, "SlideCanvas"); qmlRegisterType("Hype", 1, 0, "AppTheme"); QQmlApplicationEngine engine; + QObject::connect(&*translator, &Translator::changed, &deck, &Deck::retranslate); QObject::connect(&*translator, &Translator::changed, &engine, &QQmlEngine::retranslate); QObject::connect(&engine, &QQmlEngine::warnings, [](const QList &errors) { for (const auto &error : errors) diff --git a/src/pptx.cpp b/src/pptx.cpp index f06316d..07e1cba 100644 --- a/src/pptx.cpp +++ b/src/pptx.cpp @@ -387,7 +387,7 @@ bool readSlide(const QJsonObject &entry, const QDir &base, PowerPointSlide &slid QFileInfo(slide.video).suffix().toLower() != "mp4" || video["codec_name"] != "h264" || (!audio.isEmpty() && audio["codec_name"] != "aac") || video["width"].toInt() <= 0 || video["height"].toInt() <= 0) { - error = "PowerPoint video requires H.264/AAC MP4: " + QFileInfo(slide.video).fileName(); + error = tr("PowerPoint video requires H.264/AAC MP4: %1").arg(QFileInfo(slide.video).fileName()); return false; } const double ratio = double(video["width"].toInt()) / video["height"].toInt(); diff --git a/src/renderer.cpp b/src/renderer.cpp index 0eaa307..c6e950f 100644 --- a/src/renderer.cpp +++ b/src/renderer.cpp @@ -2,6 +2,7 @@ #include "budget.h" #include "images.h" #include "syntax.h" +#include #include #include #include @@ -288,7 +289,7 @@ static Media readMedia(const QString &source, const QString &base) { if (result.video) result.error = tr("Only images can be placed"); else if (fit || span || !result.background.isEmpty() || !explicitOverlay.isEmpty()) - result.error = "A placed image cannot use fit, span, background, or overlay"; + result.error = tr("A placed image cannot use fit, span, background, or overlay"); if (result.size == 0) result.size = defaultPlacedSize; for (const auto &[position, alignment] : placements()) @@ -407,10 +408,14 @@ static QString svgProblem(const QString &svg) { return tr("Give the SVG a viewBox, or a width and height"); return {}; } +static std::atomic generation{0}; +int translationGeneration() { return generation.load(); } +void retranslateSlides() { ++generation; } Media parseMedia(const QString &source, const QString &base) { - // Parsing is pure: file existence and modification checks remain at call sites. + // Parsing is pure: file existence and modification checks remain at call sites. Its + // errors are in the window's language, so a language switch starts the cache over. static thread_local QCache cache(8 * 1024 * 1024); - const QString key = base + QChar(0) + source; + const QString key = QString::number(translationGeneration()) + QChar(0) + base + QChar(0) + source; if (const auto result = cache.object(key)) return *result; auto result = readMedia(source, base); diff --git a/src/renderer.h b/src/renderer.h index 78c4d82..3ceef7d 100644 --- a/src/renderer.h +++ b/src/renderer.h @@ -31,6 +31,9 @@ QString withMediaDirectives(const QString &source, const QStringList &remove, const QStringList &add); QString speakerNotes(const QString &source); Media parseMedia(const QString &source, const QString &base); +// Parse errors are cached in the language they were made in; a language switch moves to a new generation. +int translationGeneration(); +void retranslateSlides(); QString ensurePoster(const QString &video, const QString &base); QStringList slideProblems(const QString &source, const QString &base); void layoutSlideText(QTextDocument &document, const QString &markdown, const QVariantMap &palette, diff --git a/tests/tests.cpp b/tests/tests.cpp index 6525861..04590a6 100644 --- a/tests/tests.cpp +++ b/tests/tests.cpp @@ -4806,6 +4806,30 @@ static void write(const QString &path, const QString &content) { QVERIFY2(pictures[0] == pictures[1], qPrintable("drawn differently right to left: " + source)); } } + void cachedTextFollowsTheLanguage() { + // Parse errors are cached and the untitled name is made in C++, so neither is redone by QML's retranslation. + LanguageGuard guard; + QTemporaryDir dir; + writeFile(dir.filePath("language"), "en\n"); + writeFile(dir.filePath("da.json"), R"({"Unknown position": "Ukendt placering", "Untitled": "Uden titel", "Unclosed code fence": "Uafsluttet kodeblok"})"); + Translator translator(dir.filePath("language"), dir.path()); + QCoreApplication::installTranslator(&translator); + const auto uninstall = qScopeGuard([&] { QCoreApplication::removeTranslator(&translator); }); + Deck deck; + QObject::connect(&translator, &Translator::changed, &deck, &Deck::retranslate); + const QString slide = "![position=middle](images/x.png)"; + QCOMPARE(parseMedia(slide, dir.path()).error, QString("Unknown position")); + deck.editSource("# One\n\n```\nunclosed\n"); + QCOMPARE(deck.title(), QString("Untitled")); + QCOMPARE(deck.status(), QString("Unclosed code fence")); + QSignalSpy changes(&deck, &Deck::changed); + + writeFile(dir.filePath("language"), "da\n"); + QTRY_COMPARE(deck.title(), QString("Uden titel")); + QVERIFY(changes.count() > 0); + QCOMPARE(deck.status(), QString("Uafsluttet kodeblok")); + QCOMPARE(parseMedia(slide, dir.path()).error, QString("Ukendt placering")); + } void windowFollowsTheLanguage() { if (qEnvironmentVariable("HYPE_GUI_TESTS") == "0") QSKIP("HYPE_GUI_TESTS=0 skips the window-level tests"); LanguageGuard guard; From 341969ebbab14cf0ee8bfbadc9388481d809fb8d Mon Sep 17 00:00:00 2001 From: Omarchybot <317366263+omarchybot@users.noreply.github.com> Date: Thu, 12 Nov 2026 12:25:39 +0100 Subject: [PATCH 3/4] Redo the check that found a deck's error, and leave the status flash alone A slide edited within known boundaries may begin with --- that only those boundaries explain, so reparsing the whole document on a language switch turned "Unclosed code fence" into "Front matter needs a closing ---". The deck now remembers which check produced its error and repeats that one. It no longer re-sets the status on a switch: the status line is a flash of a few seconds, and setting it again would show an error that had already gone. The test now reaches the per-slide cache through slide editing and undo, and the thumbnail's render id. Co-Authored-By: Codex XHigh Co-Authored-By: Claude Opus 5.5 --- src/deck.cpp | 12 +++++------- src/deck.h | 2 ++ tests/tests.cpp | 17 ++++++++++++++--- 3 files changed, 21 insertions(+), 10 deletions(-) diff --git a/src/deck.cpp b/src/deck.cpp index 527b626..8273ac4 100644 --- a/src/deck.cpp +++ b/src/deck.cpp @@ -286,13 +286,10 @@ void Deck::retranslate() { retranslateSlides(); m_mediaCache.clear(); m_renderIds.clear(); - const QString old = m_parsed.error; - if (!old.isEmpty()) { - const QString document = parseDeck(m_source).error; - m_parsed.error = document.isEmpty() ? slidesError(m_parsed) : document; - if (m_status == old) - setStatus(m_parsed.error); - } + // The same check that found the error, since a slide may begin with --- that only its boundaries explain. The + // status line is a flash of a few seconds, so it is left to run out rather than shown again. + if (!m_parsed.error.isEmpty()) + m_parsed.error = m_slideChecked ? slidesError(m_parsed) : parseDeck(m_source).error; ++m_revision; notifyChanged(); } @@ -334,6 +331,7 @@ void Deck::apply(const QString &source, int selected, bool history, int anchor, m_renderIds.clear(); m_source = source; m_parsed = parsed; + m_slideChecked = structure; m_selected = qBound(0, selected, count() - 1); m_anchor = qBound(0, anchor < 0 ? selected : anchor, count() - 1); ++m_revision; diff --git a/src/deck.h b/src/deck.h index 00febb8..3063b26 100644 --- a/src/deck.h +++ b/src/deck.h @@ -181,6 +181,8 @@ class Deck : public QAbstractListModel { mutable QVariantMap m_paletteCache; QString m_source, m_saved, m_path, m_status; ParsedDeck m_parsed; + // Whether m_parsed.error came from checking known slide boundaries rather than parsing the whole document. + bool m_slideChecked = false; int m_selected = 0, m_anchor = 0, m_revision = 0; QVector m_undo, m_redo; QMap m_themes; diff --git a/tests/tests.cpp b/tests/tests.cpp index 04590a6..a7f3b34 100644 --- a/tests/tests.cpp +++ b/tests/tests.cpp @@ -4819,16 +4819,27 @@ static void write(const QString &path, const QString &content) { QObject::connect(&translator, &Translator::changed, &deck, &Deck::retranslate); const QString slide = "![position=middle](images/x.png)"; QCOMPARE(parseMedia(slide, dir.path()).error, QString("Unknown position")); - deck.editSource("# One\n\n```\nunclosed\n"); - QCOMPARE(deck.title(), QString("Untitled")); + // Edited within known boundaries, so the slide's leading --- is a rule, not front matter. + deck.editSource("# One\n"); + deck.editSlide("---\n```\nunclosed"); QCOMPARE(deck.status(), QString("Unclosed code fence")); + QCOMPARE(deck.title(), QString("Untitled")); + const QString renderId = deck.renderId(0); QSignalSpy changes(&deck, &Deck::changed); writeFile(dir.filePath("language"), "da\n"); QTRY_COMPARE(deck.title(), QString("Uden titel")); QVERIFY(changes.count() > 0); - QCOMPARE(deck.status(), QString("Uafsluttet kodeblok")); QCOMPARE(parseMedia(slide, dir.path()).error, QString("Ukendt placering")); + // A thumbnail's problem banner is drawn again, in Danish. + QVERIFY(deck.renderId(0) != renderId); + // The deck's own error, which an attempt to save names, is the same problem in the new language. + QVERIFY(!deck.savePath(dir.filePath("talk.md"))); + QVERIFY2(deck.status().contains("Uafsluttet kodeblok"), qPrintable(deck.status())); + // Undo checks known boundaries again, through the same cache. + deck.undo(); + deck.redo(); + QCOMPARE(deck.status(), QString("Uafsluttet kodeblok")); } void windowFollowsTheLanguage() { if (qEnvironmentVariable("HYPE_GUI_TESTS") == "0") QSKIP("HYPE_GUI_TESTS=0 skips the window-level tests"); From 4070cc07c57e5c91aa17ab1088ba49479296d803 Mon Sep 17 00:00:00 2001 From: Omarchybot <317366263+omarchybot@users.noreply.github.com> Date: Thu, 12 Nov 2026 12:36:30 +0100 Subject: [PATCH 4/4] Translate the close dialog's buttons and Qt's text menu The close dialog took Qt's standard Discard and Cancel, whose text Qt sets once from its own catalogs: about twenty of Omarchy's languages have none, and a live switch left the old words behind. The dialog now has its own buttons, translated like the rest of the window. Qt's right-click menu on the text fields asks for Cut, Copy, Paste and Select All through qsTr, so they are listed for the catalogs too, as folio does. Co-Authored-By: Claude Opus 5.5 --- src/Main.qml | 8 ++++++-- src/i18n/en.json | 5 +++++ src/main.cpp | 4 ++++ tests/tests.cpp | 27 ++++++++++++++++++++++++++- 4 files changed, 41 insertions(+), 3 deletions(-) diff --git a/src/Main.qml b/src/Main.qml index eb61875..38fe2d2 100644 --- a/src/Main.qml +++ b/src/Main.qml @@ -545,8 +545,12 @@ ApplicationWindow { } } Dialog { - id: closeDialog; title: qsTr("Unsaved changes"); modal: true; anchors.centerIn: parent - standardButtons: Dialog.Discard | Dialog.Cancel + id: closeDialog; objectName: "closeDialog"; title: qsTr("Unsaved changes"); modal: true; anchors.centerIn: parent + // Its own buttons rather than Qt's standard ones, whose text Qt sets once and never retranslates. + footer: DialogButtonBox { + Button { text: qsTr("Discard"); DialogButtonBox.buttonRole: DialogButtonBox.DestructiveRole } + Button { text: qsTr("Cancel"); DialogButtonBox.buttonRole: DialogButtonBox.RejectRole } + } Label { text: qsTr("Changes could not be backed up. Discard them and quit?") } onDiscarded: { win.allowClose = true; win.close() } } diff --git a/src/i18n/en.json b/src/i18n/en.json index cff5a65..5902b89 100644 --- a/src/i18n/en.json +++ b/src/i18n/en.json @@ -54,6 +54,7 @@ "Compressing image…": "Compressing image…", "Converting the animation on slide %1 of %2": "Converting the animation on slide %1 of %2", "Converting the video on slide %1 of %2": "Converting the video on slide %1 of %2", + "Copy": "Copy", "Could not back up this version. Changes are still in the editor.": "Could not back up this version. Changes are still in the editor.", "Could not compress the pasted image.": "Could not compress the pasted image.", "Could not connect to the desktop file chooser.": "Could not connect to the desktop file chooser.", @@ -82,9 +83,11 @@ "Could not save the recovery draft. Changes are still in the editor.": "Could not save the recovery draft. Changes are still in the editor.", "Could not save video overlay": "Could not save video overlay", "Current": "Current", + "Cut": "Cut", "Delete": "Delete", "Delete slide": "Delete slide", "Delete slides": "Delete slides", + "Discard": "Discard", "Draft backed up · Ctrl+S to choose a file": "Draft backed up · Ctrl+S to choose a file", "Draft backed up · file changed outside Hype; use Save As to keep both": "Draft backed up · file changed outside Hype; use Save As to keep both", "Draft backed up · finish the Markdown to save the presentation": "Draft backed up · finish the Markdown to save the presentation", @@ -159,6 +162,7 @@ "Overview": "Overview", "Overview on or off": "Overview on or off", "Packaging PowerPoint…": "Packaging PowerPoint…", + "Paste": "Paste", "Paste an image or video first.": "Paste an image or video first.", "Paste image": "Paste image", "Paste text, or add and name media": "Paste text, or add and name media", @@ -198,6 +202,7 @@ "Save to %1": "Save to %1", "Save video": "Save video", "Saved": "Saved", + "Select All": "Select All", "Show these shortcuts": "Show these shortcuts", "Size": "Size", "Size must be a percentage from 1% to 100%": "Size must be a percentage from 1% to 100%", diff --git a/src/main.cpp b/src/main.cpp index 829c925..2a0c299 100644 --- a/src/main.cpp +++ b/src/main.cpp @@ -20,6 +20,10 @@ #include #include #include +// Qt's own words in the window, the text fields' right-click menu, which reach the Translator because it ignores the +// context. Qt translates them itself only for the languages it ships a catalog for; Undo, Redo and Delete are Hype's too. +[[maybe_unused]] static const char *const qtStrings[] = {QT_TR_NOOP("Cut"), QT_TR_NOOP("Copy"), QT_TR_NOOP("Paste"), + QT_TR_NOOP("Select All")}; // The desktop's interface font, e.g. "Adwaita Sans 11", which the gtk3 platform // theme used to supply. Without a settings portal Qt's default font stays. static void adoptDesktopFont() { diff --git a/tests/tests.cpp b/tests/tests.cpp index a7f3b34..5a387c3 100644 --- a/tests/tests.cpp +++ b/tests/tests.cpp @@ -4846,7 +4846,9 @@ static void write(const QString &path, const QString &content) { LanguageGuard guard; QTemporaryDir dir; writeFile(dir.filePath("language"), "da\n"); - writeFile(dir.filePath("da.json"), R"({"Bold": "Fed", "Top left": "Øverst til venstre", "%Ln slides selected": {"one": "%Ln dias valgt", "other": "%Ln dias valgt"}})"); + writeFile(dir.filePath("da.json"), R"({"Bold": "Fed", "Top left": "Øverst til venstre", "Cancel": "Annuller", "Discard": "Kassér", + "%Ln slides selected": {"one": "%Ln dias valgt", "other": "%Ln dias valgt"}})"); + writeFile(dir.filePath("vi.json"), R"({"Bold": "Đậm", "Discard": "Hủy bỏ", "Cancel": "Hủy"})"); Translator translator(dir.filePath("language"), dir.path()); QCoreApplication::installTranslator(&translator); const auto uninstall = qScopeGuard([&] { QCoreApplication::removeTranslator(&translator); }); @@ -4875,6 +4877,29 @@ static void write(const QString &path, const QString &content) { QCOMPARE(place.toString(), QString("Øverst til venstre")); // A string Danish doesn't have yet shows in English. QCOMPARE(window->findChild("italicButton")->property("label").toString(), QString("Italic")); + // The close dialog's buttons follow a live switch too, including to a language Qt has no catalog for. + auto closeDialog = window->findChild("closeDialog"); + QVERIFY(closeDialog); + auto buttons = [&] { + QStringList texts; + auto footer = closeDialog->property("footer").value(); + for (auto *button : footer ? footer->findChildren() : QList()) + if (button->inherits("QQuickAbstractButton") && button->isVisible()) + texts << button->property("text").toString(); + texts.sort(); + return texts; + }; + QVERIFY(QMetaObject::invokeMethod(closeDialog, "open")); + QTRY_COMPARE(buttons().size(), 2); + QCOMPARE(buttons(), QStringList({"Annuller", "Kassér"})); + writeFile(dir.filePath("language"), "vi\n"); + QTRY_COMPARE(buttons(), QStringList({"Hủy", "Hủy bỏ"})); + // Discard still lets the window close. + QVERIFY(!window->property("allowClose").toBool()); + for (auto *button : closeDialog->property("footer").value()->findChildren()) + if (button->inherits("QQuickAbstractButton") && button->property("text").toString() == "Hủy bỏ") + QVERIFY(QMetaObject::invokeMethod(button, "click")); + QTRY_VERIFY(window->property("allowClose").toBool()); // Picking another language under Setup > Language changes the open window. writeFile(dir.filePath("language"), "en\n");