diff --git a/.claude/skills/install-locally/SKILL.md b/.claude/skills/install-locally/SKILL.md new file mode 100644 index 0000000..afad5bb --- /dev/null +++ b/.claude/skills/install-locally/SKILL.md @@ -0,0 +1,46 @@ +--- +name: install-locally +description: Update the maintainer's installed copy of Quick Video Transcoder (the folder their Send to shortcut points at) from a published release with its GitHub attestation verified, or from a build of main. Use when the maintainer asks to update, reinstall or refresh the installed or "release" copy, or to test a published release locally. +--- + +# Updating the installed copy + +The install folder and the shortcut are machine-specific: read them from `CLAUDE.local.md` (never write them +in a tracked file). The folder holds **only** `quick-video-transcoder.exe`; its *Send to* shortcut points at +that exe, so replacing the file in place keeps it working. + +## Rules + +- Never overwrite while the application runs: `Get-Process quick-video-transcoder`. If one runs, ask the + maintainer to close it — never kill their window. Check the *path* of a running process: a test build of + yours may be the one running. +- A windowed exe: PowerShell does not wait for it when capturing output. Ask it for its version with + `Start-Process -ArgumentList '--version' -RedirectStandardOutput -NoNewWindow -Wait`. +- Any script with a backslash goes through a file written with the Write tool. Assert every path before + writing or deleting, and compare hashes after copying. +- Deleting anything else in the install folder needs the maintainer's yes. + +## From a published release (preferred) + +1. `gh release download vX.Y.Z --repo geeooff/quick-video-transcoder --dir `. +2. The SHA-256 of the exe equals the line in `SHA256SUMS.txt`. +3. `gh attestation verify --repo geeooff/quick-video-transcoder --signer-workflow geeooff/quick-video-transcoder/.github/workflows/release.yml --source-ref refs/tags/vX.Y.Z` + — restricted to that workflow and tag; `--format json` shows the commit. Any failure: do not install. +4. `--version` prints `X.Y.Z` and the tag's commit. +5. Copy over the installed exe, re-check the hash, show the folder and the file's version block. + +## From main (between releases, to try what is merged) + +`git worktree add --detach /main-tree origin/main`, `.\scripts\build.ps1 release` there (the +published profile), install `dist\quick-video-transcoder.exe` as above (hash, `--version` naming that +commit), then remove the worktree (`Remove-Item -LiteralPath ('\\?\' + )` for long paths, then +`git worktree prune`). Say plainly that it is not a release (About shows the last version number). + +## Windows details + +- *Open with* / *Send to* names come from the exe's `FileDescription`, cached per path in + `HKCU\Software\Classes\Local Settings\Software\Microsoft\Windows\Shell\MuiCache` + (`.FriendlyAppName`, `.ApplicationCompany`). A stale name (an exe once run without a version block) + is fixed by deleting those two values for that path — with the maintainer's yes. +- A shell started by the Claude desktop app may see `%APPDATA%` through the package's private copy: check + the shortcut where Explorer reads it before concluding it is missing. diff --git a/.claude/skills/localize/SKILL.md b/.claude/skills/localize/SKILL.md new file mode 100644 index 0000000..66b22a7 --- /dev/null +++ b/.claude/skills/localize/SKILL.md @@ -0,0 +1,52 @@ +--- +name: localize +description: Translate Quick Video Transcoder — new or changed English messages into French and its regional variants, or a whole new language — with persona-briefed subagents (translator, cold reviewer, regional localizers), screenshots and the project's Fluent rules. Use when messages were added or changed, when the maintainer asks for a new language or variant, or to review a translation. +--- + +# Localizing + +Rules live in `docs/localization.md` (conventions, typography, glossary, regional decisions) and the doc +comment of `src/i18n.rs`. Read both first. The maintainer has no native reviewers: quality comes from the +briefs, context and a cold review — never from literal translation. + +## When code adds or changes texts + +- Every user-facing text is `crate::tr!("area-element", var = value)` with the English message in its source + area of `i18n/en/quick_video_transcoder.ftl`, a `#` comment when the meaning is not obvious (where it + shows, what each variable holds). Numbers through `{ NUM($x, decimals: N) }`, plurals as multi-line + selectors, data (names, codecs, time codes) as string variables, logs stay English. +- `french_is_complete` fails until French has the new ids: translate them in the same change. When a French + message changes, update the same message in regional files (`fr-CA`…). +- Check the layout in the longest languages: debug build, then + `QVT_LANGUAGE=fr-FR` or `QVT_PSEUDO=1` with `QVT_SCREENSHOT=` on a synthetic clip in a scratch + folder (one app instance at a time: a second launch hands its files to the first). + +## Translating with subagents + +A few messages: do it inline with the same rules. Many, or a new language — orchestrate: + +1. **Brief** (one file in scratch, read by every agent): the app and its users (gamers sharing clips in + size-limited chats), `README.md`, `docs/localization.md`, the English file with comments, a screenshot of + the window in English, the Fluent rules (keep ids/variables/selectors, literal U+00A0/U+202F, CLDR plural + categories), the checks (`cargo test --locked --lib i18n`, a screenshot in their language), "edit only your + file, never commit". Only one agent at a time takes screenshots. +2. **Translator** with a strong native persona (a seasoned localizer of games and consumer software from a + precise city, who uses the platform's own terms and hates translated-sounding text). Writes the complete + base file. +3. **Cold reviewer**, another persona (UX writer) who did not write it: contresens against the code, + calques, register, consistency, typography, length on the screenshot. Edits the file, reports + before → after. +4. **Regional localizers**, one persona per variant, in parallel: keep only real differences (vocabulary, + typography conventions applied to every message concerned, keyboard names). An empty result is valid — + then no file; record the decision in `docs/localization.md`. +5. **Orchestrator** (you): read every report, fix what they found in the English source or the code, check + the screenshots yourself, run `.\scripts\build.ps1`, commit per step. + +Use the strongest model for the base translator and the reviewer; a lighter one is fine for variants with +few expected differences. Agents hit by a usage limit are resumed with SendMessage, not restarted. + +## A new language + +`LANGUAGES` in `src/i18n.rs` (variants named in their own language), a complete base file, regional files, +a completeness test if the project commits to it, egui font coverage (Latin, Greek, Cyrillic built in; CJK +via the system font fallback; no right-to-left layout in egui), and a row in the regional decisions table. diff --git a/.claude/skills/release/SKILL.md b/.claude/skills/release/SKILL.md new file mode 100644 index 0000000..16517a6 --- /dev/null +++ b/.claude/skills/release/SKILL.md @@ -0,0 +1,51 @@ +--- +name: release +description: Prepare and publish a Quick Video Transcoder release (vX.Y.Z), from the release commit to the published, attested executable and the maintainer's installed copy. Use when the maintainer asks to prepare, cut, tag or publish a release. +--- + +# Releasing Quick Video Transcoder + +A release is one file, `quick-video-transcoder.exe`, built by `release.yml` from a tag. Pushing the release +branch and the tag need the maintainer's go-ahead (a pull request merges by itself once CI is green: that +approval stands). + +## 1. Ready? + +- `main` holds everything meant for the release; open PRs are merged or deliberately left out. +- `CHANGELOG.md` `[Unreleased]` lists what the user sees, under *Added*, *Changed*, *Fixed*, *Removed*. For a + first release of a feature, fixes made before it shipped are not *Fixed*: fold them into the *Added* line. +- The docs describe this version: the release links them at its commit forever (`AGENTS.md`). +- Version (semver): patch for fixes only, minor for a feature, major for a breaking change of what the user + relies on (profiles file, behaviour). Propose it; the maintainer decides. + +## 2. The release commit + +On `release/vX.Y.Z` from an up-to-date `main`: + +1. `version = "X.Y.Z"` in `Cargo.toml`, then `cargo update -p quick-video-transcoder --offline` for the lock. +2. `CHANGELOG.md`: a new empty `## [Unreleased]`, then `## [X.Y.Z] - YYYY-MM-DD` (today) with what was under + it; at the bottom, `[Unreleased]: …/compare/vX.Y.Z...HEAD` and `[X.Y.Z]: …/releases/tag/vX.Y.Z` (and fix + the previous version's link to compare with its predecessor). +3. Commit `Release X.Y.Z` (body: what it brings, why this bump). +4. `.\scripts\build.ps1 release` from that clean commit: the published fat LTO profile, never `-Fast`. + Read the whole output: `notes.md from the changelog`, the notices, `release OK`. + +## 3. Publish + +1. Push the branch, open the PR (`Release X.Y.Z`), `gh pr merge --auto --merge`. +2. Once merged: `git switch main && git pull --ff-only`, check `version` and the dated section, then tag the + **merge commit** and push the tag alone: + `git tag -a vX.Y.Z -m "Quick Video Transcoder X.Y.Z"`, `git push origin vX.Y.Z`. +3. Follow the run: `gh run list --workflow release.yml -L 1`, then + `gh run watch --exit-status` in the background. On failure read `gh run view --log-failed`, + fix on a branch, and re-tag only with the maintainer (a pushed tag is not moved silently). +4. Check the page: `gh release view vX.Y.Z` — `quick-video-transcoder.exe`, `SHA256SUMS.txt`, notes from the + changelog, not a draft. + +## 4. After + +- From 1.2.0 on, update this machine **as a user would**: *Help → Check for updates* in the installed + previous version, *Download and install*, *Restart now*; then the new version must show *Updated to X.Y.Z* + and `--version` the tag's commit (docs/updating.md, "Measured"). Record the timings there. Otherwise, or + if it fails, install with the **install-locally** skill (from the release, attestation verified). +- Report to the maintainer: the release URL, what it contains, what was not verified (other GPUs, Linux). diff --git a/.claude/skills/upgrade-dependencies/SKILL.md b/.claude/skills/upgrade-dependencies/SKILL.md new file mode 100644 index 0000000..3081026 --- /dev/null +++ b/.claude/skills/upgrade-dependencies/SKILL.md @@ -0,0 +1,45 @@ +--- +name: upgrade-dependencies +description: Upgrade Quick Video Transcoder's dependencies across breaking versions — crate 0.x minors and majors (eframe/egui, wgpu, cpal, rfd, ICU4X, i18n-embed…), GitHub Actions majors, a new stable toolchain — following each upgrade guide, without workarounds, and explain a Dependabot PR that did not merge by itself. Use when the maintainer asks to update dependencies or why a Dependabot PR is waiting or failing. +--- + +# Upgrading the dependencies + +Dependabot merges by itself what Cargo calls compatible (patches, minors of crates ≥ 1.0) once the `build` +check passes. A 0.x minor (`rfd` 0.17 → 0.18), a major, or an action major waits — by design of +`dependabot-automerge.yml`. With CI green, such a PR may be merged (standing approval); otherwise the work is +done here. + +## Why a Dependabot PR is waiting or red + +- Waiting with CI green: a 0.x minor or a major — the workflow skipped its merge step on purpose. Say so, + then merge it if the maintainer's standing approval applies. +- Red: read `gh pr checks ` and `gh run view --log-failed`; usually an API break (follow §2) or a new + `rust-version` requirement. + +## What is behind + +`cargo info ` for each direct dependency (`latest` shows the newest), each `uses:` against +`gh api repos///releases/latest --jq .tag_name`, `gh pr list --author app/dependabot`. Show the +list (locked, latest, kind of change) and agree on what to take. + +## One dependency (or family) at a time + +On `deps/-` from `main`: + +1. **Read the upgrade path**: changelog / migration guide of every version between, from the publisher. Note + each break this code meets. +2. Raise `Cargo.toml`, `cargo update -p `. A newer required Rust raises `rust-version` (comment why). +3. Fix each break **the way the guide says**. Never: a silenced lint, a `[patch]` or fork, a held-back + version, a feature turned off to dodge a change. +4. Families that move together, in one commit and one Dependabot group (`.github/dependabot.yml`): + - `eframe` + `egui`: egui is a direct dependency only for `monochrome_emoji_fonts`; a lone eframe bump + builds two eguis and silently drops it. `app::tests::symbols_are_in_the_embedded_fonts` catches it. + - The ICU4X crates (`icu_decimal`, `icu_locale_core`, `icu_provider`, `fixed_decimal`) on one 2.x line; + `i18n-embed` + `i18n-embed-fl`. Check `i18n::tests` and a French screenshot (`25,0 Mo`). +5. egui upgrades: check the window — `QVT_SCREENSHOT` on a synthetic clip, and the pseudo-locale + (`QVT_PSEUDO=1`) for layout regressions. Glyphs can change between versions. +6. `.\scripts\build.ps1` (and `build` for anything that changes the exe), read the whole output. +7. Changelog only for what a user notices. Push, PR, auto-merge (push needs the maintainer's go-ahead). + +An upgrade that cannot be done properly (upstream bug, no replacement) is not forced: stop, write why, ask. diff --git a/.gitignore b/.gitignore index 62409f0..5d5590c 100644 --- a/.gitignore +++ b/.gitignore @@ -20,3 +20,6 @@ *.ts *.m2ts *.qvt-partial + +# Worktrees of Claude Code subagents. +/.claude/worktrees/ diff --git a/AGENTS.md b/AGENTS.md index b646b6f..cd6af01 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -54,12 +54,18 @@ tests/pipeline.rs end to end on synthetic clips examples/transcode.rs - Spawn FFmpeg with `ffmpeg::tool()` or `background_tool()` (no console window); collect stderr with `StderrTail::finish()` after exit; stop with `kill_tree` (Chocolatey and Scoop shims). - Never hard-code an encoder: go through `Capabilities::encoder`. H.265 stays the default codec. +- The network is used only when the user clicks *Check for updates* (docs/updating.md): never a + background check. Updater tests never call GitHub (scripted feed, local listener). +- Every text a user reads is a Fluent message: `crate::tr!("id")`, numbers through `NUM` in the message + (docs/localization.md). Logs and technical details stay in English. - Qualities are H.265 QPs everywhere; `EncoderSpec::qp` converts for AV1 scales. - Module doc comments carry the rules a module is shaped by: read them first, update them with the rule. - The cpal callback is real time: short locks, no I/O, never wait on a decoder. - egui: `lost_focus()` lasts two frames, apply a text field only if the user typed in it (`time_edit`); sliders use `SliderClamping::Edits`. Some symbols are missing from egui's fonts (arrows, most emoji): check a screenshot after adding one. +- `QVT_PSEUDO=1` and `QVT_LANGUAGE=fr-CA` (debug builds) pseudo-localize or force a language for + screenshots (docs/localization.md). - `QVT_PRETEND_NO_FFMPEG=1` (debug builds) shows the *FFmpeg is needed* window without uninstalling FFmpeg. Never click *Install FFmpeg for me* while testing: it really runs winget. - Checking the UI without driving it: `QVT_SCREENSHOT=` saves the window once the queue is @@ -67,6 +73,10 @@ tests/pipeline.rs end to end on synthetic clips examples/transcode.rs ## Workflow +Project skills in `.claude/skills/`: **release**, **install-locally**, **upgrade-dependencies**, **localize** — +the procedures this repository repeats, with their pitfalls. Use them; update them when a procedure changes. + + ```powershell .\scripts\build.ps1 # fmt, clippy -D warnings, rustdoc -D warnings, tests, doc links, no video / personal path .\scripts\build.ps1 build # + optimized build, release-fast profile (thin LTO, ~20 s) diff --git a/CHANGELOG.md b/CHANGELOG.md index 3c5dddc..50cb701 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -7,6 +7,17 @@ refuses a tag without one. ## [Unreleased] +### Added + +- The application speaks French: *View → Language* offers Automatic (the system's language), English + (United States, United Kingdom) and French (France, Canada, Belgium, Switzerland). It switches at once, + without restarting. +- Numbers follow the chosen language and region: `25,0 Mo` in French, the Canadian and Swiss groupings, + `25.0 MB` in English. The size limit box accepts a comma or a point. +- *Help → Check for updates*: shows the latest version and what changed, downloads it, checks it against + the published checksums, and restarts on it — the previous version comes back if anything fails. The + application connects only when you click. + ### Fixed - *Encodes at once* is measured from 1 to 4 encodes and takes the fewest that reach the best speed: the diff --git a/Cargo.lock b/Cargo.lock index a34debe..e95e345 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -296,6 +296,15 @@ dependencies = [ "x11rb", ] +[[package]] +name = "arc-swap" +version = "1.9.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "84a22b5d51209f6de83d37a0b33d320acb8da88823e42a94c075140708f032a5" +dependencies = [ + "rustversion", +] + [[package]] name = "arrayref" version = "0.3.9" @@ -503,6 +512,21 @@ version = "1.5.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "f2032f911046de80f0a198e0901378627c33f59ea0ac00e363d481118bd70a53" +[[package]] +name = "base64" +version = "0.23.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ac07cdecf99051d9a5238b80f35af32cdeba5b336e55d957b318b50137e18da5" + +[[package]] +name = "basic-toml" +version = "0.1.10" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ba62675e8242a4c4e806d12f11d136e626e6c8361d6b829310732241652a178a" +dependencies = [ + "serde", +] + [[package]] name = "bit-set" version = "0.10.0" @@ -533,6 +557,15 @@ dependencies = [ "serde_core", ] +[[package]] +name = "block-buffer" +version = "0.12.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d2f6c7dbe95a6ed67ad9f18e57daf93a2f034c524b99fd2b76d18fdfeb6660aa" +dependencies = [ + "hybrid-array", +] + [[package]] name = "block2" version = "0.5.1" @@ -739,6 +772,12 @@ dependencies = [ "crossbeam-utils", ] +[[package]] +name = "const-oid" +version = "0.10.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "be95d4a884358a21a199689323c29e9256b4a1b315e22f183d155422041d3a9a" + [[package]] name = "core-foundation" version = "0.9.4" @@ -749,6 +788,16 @@ dependencies = [ "libc", ] +[[package]] +name = "core-foundation" +version = "0.10.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b2a6cd9ae233e7f62ba4e9353e81a88df7fc8a5987b8d445b4d90c879bd156f6" +dependencies = [ + "core-foundation-sys", + "libc", +] + [[package]] name = "core-foundation-sys" version = "0.8.7" @@ -762,7 +811,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "c07782be35f9e1140080c6b96f0d44b739e2278479f64e02fdab4e32dfd8b081" dependencies = [ "bitflags 1.3.2", - "core-foundation", + "core-foundation 0.9.4", "core-graphics-types", "foreign-types", "libc", @@ -775,7 +824,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "45390e6114f68f718cc7a830514a96f903cccd70d02a8f6d9f643ac4ba45afaf" dependencies = [ "bitflags 1.3.2", - "core-foundation", + "core-foundation 0.9.4", "libc", ] @@ -823,6 +872,15 @@ dependencies = [ "windows-core", ] +[[package]] +name = "cpufeatures" +version = "0.3.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "5ca28b0ae3115b884660db4118d803791fd6756b6e88f39c0f3f7859060d7566" +dependencies = [ + "libc", +] + [[package]] name = "crc32fast" version = "1.5.5" @@ -853,6 +911,15 @@ version = "0.2.4" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "460fbee9c2c2f33933d720630a6a0bac33ba7053db5344fac858d4b8952d77d5" +[[package]] +name = "crypto-common" +version = "0.2.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ce6e4c961d6cd6c9a86db418387425e8bdeaf05b3c8bc1411e6dca4c252f1453" +dependencies = [ + "hybrid-array", +] + [[package]] name = "cursor-icon" version = "1.2.0" @@ -865,6 +932,17 @@ version = "0.11.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "0c87e182de0887fd5361989c677c4e8f5000cd9491d6d563161a8f3a5519fc7f" +[[package]] +name = "digest" +version = "0.11.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f1dd6dbb5841937940781866fa1281a1ff7bd3bf827091440879f9994983d5c2" +dependencies = [ + "block-buffer", + "const-oid", + "crypto-common", +] + [[package]] name = "dispatch" version = "0.2.0" @@ -1259,12 +1337,33 @@ version = "0.4.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "b97b65636e5b9ef369943878ac74335ba1c55c1cb6adbf1e2c293c624248d693" +[[package]] +name = "find-crate" +version = "0.6.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "59a98bbaacea1c0eb6a0876280051b892eb73594fd90cf3b20e9c817029c57d2" +dependencies = [ + "toml 0.5.11", +] + [[package]] name = "find-msvc-tools" version = "0.1.15" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "1c66915cc5391097de7a2b0b972e8505aa33c0df401fd3a6811dbdb32881ba48" +[[package]] +name = "fixed_decimal" +version = "0.7.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "2214fb00f669ee96bee5bb29dfb1ddabe058b2bc426817efc79afa03c9bc55ae" +dependencies = [ + "displaydoc", + "ryu", + "smallvec", + "writeable", +] + [[package]] name = "fixedbitset" version = "0.5.9" @@ -1282,6 +1381,61 @@ dependencies = [ "zlib-rs", ] +[[package]] +name = "fluent" +version = "0.17.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8137a6d5a2c50d6b0ebfcb9aaa91a28154e0a70605f112d30cb0cd4a78670477" +dependencies = [ + "fluent-bundle", + "unic-langid", +] + +[[package]] +name = "fluent-bundle" +version = "0.16.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "01203cb8918f5711e73891b347816d932046f95f54207710bda99beaeb423bf4" +dependencies = [ + "fluent-langneg", + "fluent-syntax", + "intl-memoizer", + "intl_pluralrules", + "rustc-hash 2.1.3", + "self_cell", + "smallvec", + "unic-langid", +] + +[[package]] +name = "fluent-langneg" +version = "0.13.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7eebbe59450baee8282d71676f3bfed5689aeab00b27545e83e5f14b1195e8b0" +dependencies = [ + "unic-langid", +] + +[[package]] +name = "fluent-pseudo" +version = "0.3.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "86f1b5259b7f28e4f6a03e826c8305e15309cd90fc3a786447407c001786bf2e" +dependencies = [ + "once_cell", + "regex", +] + +[[package]] +name = "fluent-syntax" +version = "0.12.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "54f0d287c53ffd184d04d8677f590f4ac5379785529e5e08b1c8083acdd5c198" +dependencies = [ + "memchr", + "thiserror 2.0.21", +] + [[package]] name = "foldhash" version = "0.1.5" @@ -1427,6 +1581,17 @@ dependencies = [ "windows-link", ] +[[package]] +name = "getrandom" +version = "0.2.17" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ff2abc00be7fca6ebc474524697ae276ad847ad0a6b3faa4bcb027e9a4614ad0" +dependencies = [ + "cfg-if", + "libc", + "wasi", +] + [[package]] name = "getrandom" version = "0.3.4" @@ -1644,6 +1809,98 @@ version = "0.4.3" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "7f24254aa9a54b5c858eaee2f5bccdb46aaf0e486a595ed5fd8f86ba55232a70" +[[package]] +name = "http" +version = "1.5.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "918d3568bebf352712bc2ef3d46a8bcf1a75b373be6539de198e9105cbbf9ce0" +dependencies = [ + "bytes", + "itoa", +] + +[[package]] +name = "httparse" +version = "1.10.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6dbf3de79e51f3d586ab4cb9d5c3e2c14aa28ed23d180cf89b4df0454a69cc87" + +[[package]] +name = "hybrid-array" +version = "0.4.15" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "27f864f10dfb56725ce5ce5472bc52252c8f93a4ab86327122cebf62c5f59a17" +dependencies = [ + "typenum", +] + +[[package]] +name = "i18n-config" +version = "0.4.8" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3e06b90c8a0d252e203c94344b21e35a30f3a3a85dc7db5af8f8df9f3e0c63ef" +dependencies = [ + "basic-toml", + "log", + "serde", + "serde_derive", + "thiserror 1.0.69", + "unic-langid", +] + +[[package]] +name = "i18n-embed" +version = "0.16.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a217bbb075dcaefb292efa78897fc0678245ca67f265d12c351e42268fcb0305" +dependencies = [ + "arc-swap", + "fluent", + "fluent-langneg", + "fluent-syntax", + "i18n-embed-impl", + "intl-memoizer", + "log", + "parking_lot", + "rust-embed", + "sys-locale", + "thiserror 1.0.69", + "unic-langid", + "walkdir", +] + +[[package]] +name = "i18n-embed-fl" +version = "0.10.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "602e6bd30c3db2749e13e38b363a3d98d9d41de1d8de7a79c31bb69e45b47cda" +dependencies = [ + "find-crate", + "fluent", + "fluent-syntax", + "i18n-config", + "i18n-embed", + "proc-macro-error3", + "proc-macro2", + "quote", + "strsim", + "syn 2.0.119", + "unic-langid", +] + +[[package]] +name = "i18n-embed-impl" +version = "0.8.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0f2cc0e0523d1fe6fc2c6f66e5038624ea8091b3e7748b5e8e0c84b1698db6c2" +dependencies = [ + "find-crate", + "i18n-config", + "proc-macro2", + "quote", + "syn 2.0.119", +] + [[package]] name = "icu_collections" version = "2.4.0" @@ -1658,6 +1915,29 @@ dependencies = [ "zerovec", ] +[[package]] +name = "icu_decimal" +version = "2.4.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1150ad5e272740670464934ee76facda43ef2e11f85c27b7ba76ccb33edf2d05" +dependencies = [ + "displaydoc", + "fixed_decimal", + "icu_decimal_data", + "icu_locale_core", + "icu_locale_fallback", + "icu_plurals", + "icu_provider", + "writeable", + "zerovec", +] + +[[package]] +name = "icu_decimal_data" +version = "2.4.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "5595ab78370d48abd24a062f3db115d5108dd0b65634352036cae532aebb0df8" + [[package]] name = "icu_locale_core" version = "2.4.0" @@ -1666,11 +1946,32 @@ checksum = "25d29b57c17c6528d0dc4c2141cfa2d08200465acb537a3909c8b9b8a4a984c0" dependencies = [ "displaydoc", "litemap", + "serde", "tinystr", "writeable", "zerovec", ] +[[package]] +name = "icu_locale_fallback" +version = "2.4.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "406e9ae5b95d8aa37db6293405931b766a6172d1848daee22d70eb44aa78a43c" +dependencies = [ + "icu_locale_core", + "icu_locale_fallback_data", + "icu_provider", + "potential_utf", + "tinystr", + "zerovec", +] + +[[package]] +name = "icu_locale_fallback_data" +version = "2.4.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3632ebbd0c5c3637ba1a40bdf8288f2cb9d2268e73441a69d5fc73d7cfbaa87c" + [[package]] name = "icu_normalizer" version = "2.4.0" @@ -1691,6 +1992,25 @@ version = "2.4.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "20f0088bfb7441f7a37fa0c9e20cb1e9cba1cac6b9ce8cd2a6dc44294f8e8cbc" +[[package]] +name = "icu_plurals" +version = "2.4.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "2ef046647b445acf95ce0f8083fa292467d3df649959fa9a20f3f8abfd957c5d" +dependencies = [ + "fixed_decimal", + "icu_locale_fallback", + "icu_plurals_data", + "icu_provider", + "zerovec", +] + +[[package]] +name = "icu_plurals_data" +version = "2.4.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d43ff7df2c1a1d41588a6ddcba354d513d4a3e10eec22c06fe56d13c12a848ea" + [[package]] name = "icu_properties" version = "2.4.0" @@ -1720,6 +2040,8 @@ checksum = "413099315636c588ee8f011190b329b971a09a8fae9d157e01dcae8379468514" dependencies = [ "displaydoc", "icu_locale_core", + "serde", + "stable_deref_trait", "writeable", "yoke", "zerofrom", @@ -1772,6 +2094,25 @@ dependencies = [ "hashbrown 0.17.1", ] +[[package]] +name = "intl-memoizer" +version = "0.5.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "310da2e345f5eb861e7a07ee182262e94975051db9e4223e909ba90f392f163f" +dependencies = [ + "type-map", + "unic-langid", +] + +[[package]] +name = "intl_pluralrules" +version = "7.0.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "078ea7b7c29a2b4df841a7f6ac8775ff6074020c6776d48491ce2268e068f972" +dependencies = [ + "unic-langid", +] + [[package]] name = "is_terminal_polyfill" version = "1.70.2" @@ -2045,6 +2386,22 @@ dependencies = [ "autocfg", ] +[[package]] +name = "mime" +version = "0.3.18" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d5848f5a9e8117cf94f2f90faac24a87ff81600ff8628c1e3deaab572e76bfa1" + +[[package]] +name = "mime_guess" +version = "2.0.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f7c44f8e672c00fe5308fa235f821cb4198414e1c77935c1ab6948d3fd78550e" +dependencies = [ + "mime", + "unicase", +] + [[package]] name = "miniz_oxide" version = "0.8.9" @@ -2597,6 +2954,12 @@ version = "1.70.2" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "384b8ab6d37215f3c5301a95a4accb5d64aa607f1fcb26a11b5303878451b4fe" +[[package]] +name = "openssl-probe" +version = "0.2.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7e036b411754132fd6b74e94b74e9a13c5cf606fa93d1885c35860d3060820b1" + [[package]] name = "orbclient" version = "0.3.55" @@ -2875,6 +3238,8 @@ version = "0.1.6" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "d83eb9bc6d8e5cf568e7a1101d60ee05e81ed50ea106026f3d18deeb046d7661" dependencies = [ + "serde_core", + "writeable", "zerovec", ] @@ -2893,6 +3258,28 @@ dependencies = [ "toml_edit", ] +[[package]] +name = "proc-macro-error-attr3" +version = "3.1.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9e564d14133360e1ae169ffde5da25881b5fa47261665b8e5713c212c27799da" +dependencies = [ + "proc-macro2", + "quote", +] + +[[package]] +name = "proc-macro-error3" +version = "3.1.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8f0d4471b3436c22106b21913b1dda531558918ae9b7ec55d58aa84b43552233" +dependencies = [ + "proc-macro-error-attr3", + "proc-macro2", + "quote", + "syn 3.0.10", +] + [[package]] name = "proc-macro2" version = "1.0.107" @@ -2931,12 +3318,25 @@ dependencies = [ "eframe", "egui", "env_logger", + "fixed_decimal", + "fluent-bundle", + "fluent-pseudo", + "fluent-syntax", + "i18n-embed", + "i18n-embed-fl", + "icu_decimal", + "icu_locale_core", + "icu_provider", "log", "rfd", + "rust-embed", "serde", "serde_json", + "sha2", "tempfile", - "toml", + "toml 1.2.1+spec-1.1.0", + "unic-langid", + "ureq", ] [[package]] @@ -3094,6 +3494,20 @@ dependencies = [ "windows-sys 0.61.2", ] +[[package]] +name = "ring" +version = "0.17.14" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a4689e6c2294d81e88dc6261c768b63bc4fcdb852be6d1352498b114f61383b7" +dependencies = [ + "cc", + "cfg-if", + "getrandom 0.2.17", + "libc", + "untrusted", + "windows-sys 0.52.0", +] + [[package]] name = "ron" version = "0.12.3" @@ -3116,6 +3530,41 @@ dependencies = [ "memchr", ] +[[package]] +name = "rust-embed" +version = "8.14.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e98f580cf7a2863aeb6827800283f52cbe6fb3f3bb7c1843783f903c16dcb8ad" +dependencies = [ + "rust-embed-impl", + "rust-embed-utils", + "walkdir", +] + +[[package]] +name = "rust-embed-impl" +version = "8.14.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a93e2f69cf224a6c7df7509aa5ba4a23f56828ee41b040e92ac8762371eb9ba7" +dependencies = [ + "mime_guess", + "proc-macro2", + "quote", + "rust-embed-utils", + "syn 2.0.119", + "walkdir", +] + +[[package]] +name = "rust-embed-utils" +version = "8.14.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "915e33dccbe7deb2b8a342dc4c517503fe85e0230ddbae40a4fb0220493dad9b" +dependencies = [ + "sha2", + "walkdir", +] + [[package]] name = "rustc-hash" version = "1.1.0" @@ -3163,12 +3612,92 @@ dependencies = [ "windows-sys 0.61.2", ] +[[package]] +name = "rustls" +version = "0.23.46" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "48e13bd8c0e9365c43cfa5c9e8f9ad49d3c8444926c9aac819e0e4dc503c8fdf" +dependencies = [ + "log", + "once_cell", + "ring", + "rustls-pki-types", + "rustls-webpki", + "subtle", + "zeroize", +] + +[[package]] +name = "rustls-native-certs" +version = "0.8.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4a073f5dc7469f984c52ad2752b63b0807745133b6de880b7b64c1ac4c48aec4" +dependencies = [ + "openssl-probe", + "rustls-pki-types", + "schannel", + "security-framework", +] + +[[package]] +name = "rustls-pki-types" +version = "1.16.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "102f35f7de7b06d8c61f1cff6592f5253e0dea431c74867aad5dfd70f44663fb" +dependencies = [ + "zeroize", +] + +[[package]] +name = "rustls-platform-verifier" +version = "0.7.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1167586491e2b18b8bfbb293e8180ec17c201c4f076d7cb3070ca964e7598f98" +dependencies = [ + "core-foundation 0.10.1", + "core-foundation-sys", + "jni", + "log", + "once_cell", + "rustls", + "rustls-native-certs", + "rustls-platform-verifier-android", + "rustls-webpki", + "security-framework", + "security-framework-sys", + "webpki-root-certs", + "windows-sys 0.61.2", +] + +[[package]] +name = "rustls-platform-verifier-android" +version = "0.2.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "eec689c0bc40ff2458a5977b6619cb718087084a18e02a131c599b62d05e1a5f" + +[[package]] +name = "rustls-webpki" +version = "0.103.17" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e3a0760a887c14823fca5a1c970b01d47c328c696c0c64829d1df50e8f853fd5" +dependencies = [ + "ring", + "rustls-pki-types", + "untrusted", +] + [[package]] name = "rustversion" version = "1.0.23" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "cf54715a573b99ac80df0bc206da022bcd442c974952c7b9720069370852e21f" +[[package]] +name = "ryu" +version = "1.0.23" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9774ba4a74de5f7b1c1451ed6cd5285a32eddb5cccb8cc655a4e50009e06477f" + [[package]] name = "same-file" version = "1.0.6" @@ -3178,6 +3707,15 @@ dependencies = [ "winapi-util", ] +[[package]] +name = "schannel" +version = "0.1.30" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9cb23c424d8ee841bb4d813677ca237e2a610067d594fec130f87d6093495ab5" +dependencies = [ + "windows-sys 0.61.2", +] + [[package]] name = "scoped-tls" version = "1.0.1" @@ -3203,6 +3741,29 @@ dependencies = [ "tiny-skia", ] +[[package]] +name = "security-framework" +version = "3.7.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b7f4bc775c73d9a02cde8bf7b2ec4c9d12743edf609006c7facc23998404cd1d" +dependencies = [ + "bitflags 2.13.2", + "core-foundation 0.10.1", + "core-foundation-sys", + "libc", + "security-framework-sys", +] + +[[package]] +name = "security-framework-sys" +version = "2.17.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6ce2691df843ecc5d231c0b14ece2acc3efb62c0a398c7e1d875f3983ce020e3" +dependencies = [ + "core-foundation-sys", + "libc", +] + [[package]] name = "self_cell" version = "1.3.0" @@ -3284,6 +3845,17 @@ dependencies = [ "serde_core", ] +[[package]] +name = "sha2" +version = "0.11.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "47d7069beb7d6ac7b9acd1039986e73443f24234f41074da099d6f994ac9ad19" +dependencies = [ + "cfg-if", + "cpufeatures", + "digest", +] + [[package]] name = "shlex" version = "2.0.1" @@ -3461,6 +4033,18 @@ version = "0.1.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "6637bab7722d379c8b41ba849228d680cc12d0a45ba1fa2b48f2a30577a06731" +[[package]] +name = "strsim" +version = "0.11.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7da8b5736845d9f2fcb837ea5d9e2628564b3b043a70948a3f0b778838c5fb4f" + +[[package]] +name = "subtle" +version = "2.6.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "13c2bddecc57b384dee18652358fb23172facb8a2c51ccc10d74c157bdea3292" + [[package]] name = "syn" version = "2.0.119" @@ -3611,6 +4195,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "abc840c238154d58f9e86b2792261edfde565a17696e1cda1a449de27979801a" dependencies = [ "displaydoc", + "serde_core", "zerovec", ] @@ -3623,6 +4208,15 @@ dependencies = [ "pin-project-lite", ] +[[package]] +name = "toml" +version = "0.5.11" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f4f7f0dd8d50a853a531c426359045b1998f04219d88799810762cd4ad314234" +dependencies = [ + "serde", +] + [[package]] name = "toml" version = "1.2.1+spec-1.1.0" @@ -3738,6 +4332,12 @@ version = "1.0.3" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "bc7d623258602320d5c55d1bc22793b57daff0ec7efc270ea7d55ce1d5f5471c" +[[package]] +name = "typenum" +version = "1.20.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b6f5e870be6c3b371b77fe0ee0bafb859fa4964b4404c27de1d380043c4dda20" + [[package]] name = "uds_windows" version = "1.2.1" @@ -3749,6 +4349,31 @@ dependencies = [ "windows-sys 0.61.2", ] +[[package]] +name = "unic-langid" +version = "0.9.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a28ba52c9b05311f4f6e62d5d9d46f094bd6e84cb8df7b3ef952748d752a7d05" +dependencies = [ + "unic-langid-impl", +] + +[[package]] +name = "unic-langid-impl" +version = "0.9.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "dce1bf08044d4b7a94028c93786f8566047edc11110595914de93362559bc658" +dependencies = [ + "serde", + "tinystr", +] + +[[package]] +name = "unicase" +version = "2.10.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "357cc3acc6a036009fd6c973ed009037c732d60d0b4f6c673e9041497482a28f" + [[package]] name = "unicode-general-category" version = "1.1.0" @@ -3785,6 +4410,43 @@ version = "0.2.3" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "ca718471876992059f251e33aafc334346ada08042b7661dd1fe313a9bced557" +[[package]] +name = "untrusted" +version = "0.9.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8ecb6da28b8a351d773b68d5825ac39017e680750f980f3a1a85cd8dd28a47c1" + +[[package]] +name = "ureq" +version = "3.5.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3ac5cecf619ca81f66a96482db09687c9f7465af65f4300a8c30cca05bd5a59d" +dependencies = [ + "base64", + "flate2", + "log", + "percent-encoding", + "rustls", + "rustls-pki-types", + "rustls-platform-verifier", + "ureq-proto", + "utf8-zero", + "webpki-roots", + "winreg", +] + +[[package]] +name = "ureq-proto" +version = "0.7.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "622dce33c252115466d83f63e9744a18f12b4406aae51a01c15ad8fcf1185eb3" +dependencies = [ + "base64", + "http", + "httparse", + "log", +] + [[package]] name = "url" version = "2.5.8" @@ -3797,6 +4459,12 @@ dependencies = [ "serde", ] +[[package]] +name = "utf8-zero" +version = "0.8.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b8c0a043c9540bae7c578c88f91dda8bd82e59ae27c21baca69c8b191aaf5a6e" + [[package]] name = "utf8_iter" version = "1.1.0" @@ -3874,6 +4542,12 @@ dependencies = [ "winapi-util", ] +[[package]] +name = "wasi" +version = "0.11.1+wasi-snapshot-preview1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ccf3ec651a847eb01de73ccad15eb7d99f80485de043efb2f370cd654f4ea44b" + [[package]] name = "wasip2" version = "1.0.4+wasi-0.2.12" @@ -4109,6 +4783,24 @@ dependencies = [ "web-sys", ] +[[package]] +name = "webpki-root-certs" +version = "1.0.12" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "293198dcebfb821155b5092ab94b5a82ff180eddd7241df3bd6e66a4ffd1a585" +dependencies = [ + "rustls-pki-types", +] + +[[package]] +name = "webpki-roots" +version = "1.0.12" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7265c9301c16a8711c992c2d8da90ee77ef54b1ed51482d6dfeb00dc756b1297" +dependencies = [ + "rustls-pki-types", +] + [[package]] name = "weezl" version = "0.1.12" @@ -4523,7 +5215,7 @@ dependencies = [ "calloop 0.13.0", "cfg_aliases", "concurrent-queue", - "core-foundation", + "core-foundation 0.9.4", "core-graphics", "cursor-icon", "dpi", @@ -4569,6 +5261,16 @@ dependencies = [ "memchr", ] +[[package]] +name = "winreg" +version = "0.56.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7d6f32a0ff4a9f6f01231eb2059cc85479330739333e0e58cadf03b6af2cca10" +dependencies = [ + "cfg-if", + "windows-sys 0.61.2", +] + [[package]] name = "wit-bindgen" version = "0.57.1" @@ -4843,6 +5545,12 @@ dependencies = [ "synstructure", ] +[[package]] +name = "zeroize" +version = "1.9.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "85ccff8a4805aba1eaa4cd4afcd49f7557dd2cf5fd79ffc37f8959466effc5aa" + [[package]] name = "zerotrie" version = "0.2.5" @@ -4852,6 +5560,7 @@ dependencies = [ "displaydoc", "yoke", "zerofrom", + "zerovec", ] [[package]] @@ -4860,6 +5569,7 @@ version = "0.11.9" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "f58a2799cfe9a1670c7ea8edbd52ef8edb93cb37a7f83bf31ba9e35d9dae6a40" dependencies = [ + "serde", "yoke", "zerofrom", "zerovec-derive", diff --git a/Cargo.toml b/Cargo.toml index ef138db..536d9a0 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -28,17 +28,39 @@ eframe = { version = "0.37.0", features = ["persistence"] } # eframe; Dependabot bumps both together. egui = { version = "0.37.0", features = ["monochrome_emoji_fonts"] } env_logger = "0.11.11" +# Localization: Project Fluent through i18n-embed (the .ftl files are embedded in the executable, and +# `fl!` checks every message id against the English file at compile time), numbers formatted by ICU4X +# with CLDR data compiled in, so a French "25,0 Mo" is the same on every OS. See src/i18n.rs. +fixed_decimal = { version = "0.7.3", features = ["ryu"] } +fluent-bundle = "0.16.0" +i18n-embed = { version = "0.16.0", features = ["fluent-system", "desktop-requester"] } +i18n-embed-fl = "0.10.1" +icu_decimal = "2.4.0" +icu_locale_core = { version = "2.4.0", features = ["alloc"] } +# `sync`: the formatter must be Send + Sync to live in a Fluent function. +icu_provider = { version = "2.4.0", features = ["sync"] } +rust-embed = "8.14.0" +unic-langid = "0.9.6" log = "0.4.34" rfd = "0.18.0" serde = { version = "1.0.229", features = ["derive"] } serde_json = "1.0.154" +# The updater (src/update/): SHA-256 of the downloaded executable. +sha2 = "0.11.1" +# The updater's HTTPS client: rustls, certificates checked against the OS's trust store (so a corporate +# proxy's own root works), Windows' proxy settings read like a browser would. +ureq = { version = "3.5.2", features = ["platform-verifier", "win-system-proxy"] } toml = "1.2.1" +# Pseudo-localization (debug builds, QVT_PSEUDO=1): every text elongated and bracketed, to spot a text left +# in code and a layout that cannot take a longer language. +fluent-pseudo = "0.3.3" [target.'cfg(windows)'.dependencies] # Copies the encoded files to the clipboard as a file list (CF_HDROP), so they paste straight into a chat. clipboard-win = "5.4.1" [dev-dependencies] +fluent-syntax = "0.12.0" tempfile = "3.27.0" [profile.dev] diff --git a/README.md b/README.md index 8303fd1..99a6209 100644 --- a/README.md +++ b/README.md @@ -25,6 +25,9 @@ and any video FFmpeg reads. - **HDR to SDR done right.** An HDR capture is tone mapped on the GPU by libplacebo, with peak detection and gamut mapping, and the preview shows it exactly as it will be encoded. - **Ready to paste.** *Copy* puts the encoded file on the clipboard: paste it into the conversation. +- **English and French.** It follows the system's language, or the one chosen in *View → Language*, + regional variants included (French of France, Canada, Belgium, Switzerland; US and UK English), numbers + formatted as that region writes them. Nothing is ever overwritten: an output name that exists gets ` (2)`, and the source is only read. @@ -73,6 +76,14 @@ window opens: videos sent while it is open join its queue. Keyboard shortcuts are under *Help*, with *About* (the version, and this documentation as it was for that version). +## Updating + +*Help → Check for updates* looks for a newer version on GitHub (the only time the application +connects), shows what changed, and on request downloads it, checks it against the release's published +checksums and restarts on it; if the new file cannot be put in place, the previous version comes back. +The program's folder must be writable (not Program Files): otherwise download the new file from the +release page and replace it by hand. How it works: [Updating](docs/updating.md). + ## When something goes wrong The application keeps a log of its last two runs in its data folder (*Profiles → Open profiles.toml @@ -121,6 +132,8 @@ for what is documented and how to measure it. | --- | --- | | [Messenger's limits](docs/messenger.md) | What Meta documents, and how to measure the rest. | | [Discord's limits](docs/discord.md) | Upload limits with and without Nitro, formats, the Discord profiles. | +| [Localization](docs/localization.md) | How texts are translated, the glossary, adding a language. | +| [Updating](docs/updating.md) | How the application updates itself, what it trusts, the measurements. | | [Architecture](docs/architecture.md) | How the size fitting, the filters and the preview work, with measurements. | | [Changelog](CHANGELOG.md) | What each release changed. | | [Contributing](CONTRIBUTING.md) | Building, testing, rules. | diff --git a/about.toml b/about.toml index e144f8c..90bbc71 100644 --- a/about.toml +++ b/about.toml @@ -16,6 +16,8 @@ accepted = [ "MPL-2.0", "CC0-1.0", "MIT-0", + # webpki-roots (through ureq): Mozilla's list of certificate authorities, a permissive data licence. + "CDLA-Permissive-2.0", ] targets = ["x86_64-pc-windows-msvc"] ignore-build-dependencies = true diff --git a/build.rs b/build.rs index cadb3e4..5dd86b3 100644 --- a/build.rs +++ b/build.rs @@ -18,6 +18,9 @@ fn main() { watch_head(); println!("cargo:rerun-if-changed=src"); println!("cargo:rerun-if-changed=Cargo.toml"); + // The messages are embedded and checked by `fl!` at compile time: an edited .ftl rebuilds. + println!("cargo:rerun-if-changed=i18n"); + println!("cargo:rerun-if-changed=i18n.toml"); let commit = git(&["rev-parse", "HEAD"]).unwrap_or_else(|| "unknown".to_owned()); let known = commit != "unknown"; diff --git a/docs/architecture.md b/docs/architecture.md index 8607993..1c8e91a 100644 --- a/docs/architecture.md +++ b/docs/architecture.md @@ -19,6 +19,7 @@ on the GPU by libplacebo. | `src/ffmpeg/` | Probe, encoders, filters, hardware detection, preview decoder, audio decoder. | | `src/player.rs`, `src/audio.rs` | Preview playback with the sound as master clock (`cpal`). | | `src/thumbnails.rs` | The thumbnail strip, by parallel seeks. | +| `src/update/`, `src/app/update_window.rs` | *Check for updates*: the release feed, the state machine, the download and the swap at exit. | | `src/instance.rs` | One window: a second launch hands its files to the open one. | | `src/sendto.rs` | The *Send to* shortcut. | | `src/build_info.rs`, `build.rs` | The version, the commit, links to the documentation of that commit; the icon and version block. | @@ -120,7 +121,8 @@ out 0.03 % over the limit and was re-encoded once, to 97.4 % of it. ## Files written -Next to the videos, only the output and its partial file. FFmpeg writes `.qvt-partial`, checked by +Beside the executable, only during an update the user asked for: `.new` and `.old` +([Updating](updating.md)). Next to the videos, only the output and its partial file. FFmpeg writes `.qvt-partial`, checked by `naming::check_partial` (same folder, marker extension, not the source) before every run; it is renamed once the size is checked, deleted otherwise. An output name that exists gets ` (2)`, ` (3)`…: nothing is ever overwritten. Source metadata (titles, encoder tags, chapters) is not copied. diff --git a/docs/localization.md b/docs/localization.md new file mode 100644 index 0000000..47a526a --- /dev/null +++ b/docs/localization.md @@ -0,0 +1,123 @@ +# Localization + +**TL;DR** — Texts are [Project Fluent](https://projectfluent.org/) messages in `i18n//quick_video_transcoder.ftl`, +embedded in the executable and read with `tr!("id")`. English is the reference and the fallback; regional +files (`fr-CA`, `en-GB`…) hold only what differs from their language. Numbers are formatted by the `NUM` +function (ICU4X, CLDR data compiled in). *View → Language* picks *Automatic* or a regional variant. + +Design and rules: the doc comment of [`src/i18n.rs`](../src/i18n.rs). Spikes behind the choices (2026-11-23): +ICU4X adds about 93 KB with every locale's number data; OS regional customizations are not followed (as +Firefox does by default), the chosen variant's CLDR formats are. + +## Writing code + +- Every text a user reads: `crate::tr!("area-element", name = value)`. Never a literal, never `format!` to + build a sentence, never two messages glued together: word order differs between languages. +- Numbers are passed as numbers (`mb = 25.0`), formatted in the message: `{ NUM($mb, decimals: 1) } MB`. + Counts too, so plurals work: `{ $count -> [one] 1 video *[other] { NUM($count) } videos }`. +- Names (files, codecs, encoder names, profile names) are passed as variables and never translated: they are + data. The built-in profile names stay as they are in every language (they are stored in `profiles.toml`). +- Symbols-only labels (`⏮`, `▶`) stay in code; their tooltip is a message. +- Logs (`log::info!`…) and technical details (FFmpeg's stderr, `anyhow` chains) stay in English: they are + for support. A message shown to the user wraps them: `encode-failed = Encoding failed: { $detail }`. +- Time codes (`00:01:02.500`) and technical units that are identifiers (`kbit/s`, `fps` in a codec label) + are formatted by `timecode` and passed as variables when they are data; a unit in a sentence belongs to the + message, so a translator can write `i/s`. +- One message per sentence or label, with an id `area-element[-detail]` (`-tooltip` for hover texts), in + the section of its source file in the English file. A comment above a message explains it when the + English alone is ambiguous (where it shows, what a variable holds). +- `cargo test` checks that every file parses, that translations use only English ids and variables, and + that every English message is used. +- Debug builds: `QVT_PSEUDO=1` elongates and brackets every text (`[Ŝţàŕţ ĥéŕé~~~]`): a text left in code + shows unbracketed, a layout that cannot take a longer language shows clipped. + +## Translating + +The application is for people who share game captures in chats (Messenger, Discord): gamers, not video +engineers. It should read like a well-made native app of that language, never like a translation: + +- **Translate the meaning in this context, not the words.** Read the code around a message when the id and + comment are not enough. Prefer the term the platform and well-known apps of that language use (Windows, + Explorer, Discord, OBS, HandBrake, VLC in that language). +- **Short.** Buttons and menu items are commands; tooltips are one line. French runs about 20 % longer than + English: when a label would not fit, rephrase rather than abbreviate. +- **Consistent.** One concept, one word, everywhere (glossary below). +- **Keep variables and markup** exactly: `{ $name }`, `{ NUM(...) }`, selectors; reorder them freely. +- **Keyboard keys** are named as that language's keyboards and Windows name them (`Début`, `Fin`, `Espace`, + `Gauche`…); letter shortcuts (`I`, `O`, `M`) do not change. + +### French (`fr`, and what differs in `fr-CA`, `fr-BE`, `fr-CH`) + +- Typography: a no-break space (U+00A0) before `:`, `;`, `!`, `?`, `%` and inside `« »`; a narrow no-break + space (U+202F) is also correct before `;` `!` `?` (fr-FR). Ellipsis `…`. Apostrophe `’`. Capital only on + the first word of a label (`Ajouter des vidéos`, not `Ajouter Des Vidéos`). +- Units: `Mo`, `Go`, `kbit/s`, `i/s` (images par seconde), `Hz`. A no-break space between a number and its unit. +- Commands in the infinitive (`Encoder`, `Ajouter des vidéos…`), not the imperative. +- `fr-CA`: Québec usage, Office québécois de la langue française terminology where it is what people + actually say and what Windows in Canadian French shows (`courriel`, `clavarder` are not needed here). + Only messages that really differ go in `i18n/fr-CA/`. +- `fr-BE`, `fr-CH`: same texts as `fr` unless a term really differs; their number formats differ anyway (CLDR). + +### Regional decisions (2026-11-23) + +Each variant was reviewed message by message by a translator briefed as a native professional of that +region, who kept only real differences: + +| Variant | File | What differs from its base | +| --- | --- | --- | +| `fr-CA` | `i18n/fr-CA/` | Canadian French keyboard names (`Origine`, `Pg préc` / `Pg suiv`); Québec typography: no space before `; ? !` (still a no-break space before `:` and `%`, inside `« »`). Vocabulary: none — the base already reads naturally in Québec. | +| `fr-BE` | none | Nothing: Windows and software in Belgium use the same terms and Microsoft's typography. | +| `fr-CH` | none | Nothing for now: same terms; Swiss usage before `; ! ?` is mixed, so the base is kept until a reliable source says otherwise. | +| `en-GB` | `i18n/en-GB/` | *colour*, *licence*. | + +Numbers differ in every region anyway, from CLDR (`fr-CA` and `fr-CH` group with a no-break space, `fr` with +a narrow one). A regional file copies whole messages from its base: **when a base message changes, update the +same message in the regional files** (they hold few). + +### Process + +Translations are made by subagents with a strong native persona each (a translator writes, another reviews +cold, a regional localizer per variant), working from this guide, the English comments, the code around each +message and a screenshot of the window in their language (`shot-lang.ps1`-style: `QVT_LANGUAGE=fr-CA` and +`QVT_SCREENSHOT`). The orchestrator merges, checks the screenshots and fixes what the translators report +about the English source or the code. + +### Adding a language + +1. Add its regional variants to `LANGUAGES` in `src/i18n.rs` (named in that language). +2. Write `i18n//quick_video_transcoder.ftl` (complete), then regional files with only what + differs. Check the script is covered by egui's fonts (Latin, Greek, Cyrillic are; CJK falls back to the + system's fonts; right-to-left scripts are not laid out by egui). +3. A completeness test like `french_is_complete` for a language the project commits to keep complete. + +### English (`en`, `en-GB`) + +- `en` is US English. `en-GB` holds only British spellings and terms that differ (*licence* as a noun, + *colour*, *optimise*…), nothing else. + +## Glossary + +| English | French (`fr`) | Notes | +| --- | --- | --- | +| video (a queued file) | vidéo | | +| queue | file d’attente | « la file » once the context is clear | +| kept part (trimmed range) | partie conservée | the range between the two handles | +| trim / trim handle | découper / poignée | | +| start / end (of the kept part) | début / fin | | +| frame (a picture) | image | « trame » is interlaced fields: never | +| frame rate | fréquence d’images | `30 i/s` in values | +| resolution | résolution | | +| size limit | taille maximale | | +| bitrate | débit | | +| estimate (noun) | estimation | | +| encode (verb) / encoding | encoder / encodage | | +| encoder (NVENC, x265…) | encodeur | | +| profile | profil | | +| preview | aperçu | | +| tone mapping | mappage tonal | HDR → SDR | +| sound / audio track | son / piste audio | | +| microphone | micro | | +| quality bounds | limites de qualité | | +| Send to (Explorer menu) | Envoyer vers | Windows’ own French name | +| log | journal | | +| output folder | dossier de sortie | | diff --git a/docs/updating.md b/docs/updating.md new file mode 100644 index 0000000..9cf86e7 --- /dev/null +++ b/docs/updating.md @@ -0,0 +1,94 @@ +# Updating + +**TL;DR** — *Help → Check for updates* opens a window that reads the latest GitHub release, shows its notes, +downloads `quick-video-transcoder.exe` beside the running one, checks its SHA-256 against two witnesses, +and on *Restart now* swaps the executable and restarts. The application connects only when the user clicks. +The swap is GameModeExecutor's (lot 13), measured there and here. + +Code: `src/update/` (the rules, the feed, the swap), `src/app/update_window.rs` (the window). Its module doc +comments carry the rules. + +## The window + +| Phase | The window shows | +| --- | --- | +| Checking | a spinner | +| Up to date | *1.1.0 is the latest version*, *Check again* | +| Available | *Version 1.2.0 is available*, the release notes (the changelog section, English), *Download and install (18.9 MB)*, *See it on GitHub* | +| Downloading | a progress bar | +| Ready | *Restart now* — disabled while videos are encoding (a restart would stop them) | +| Updated | *Updated to 1.2.0*, at the first start of the new version | +| Failed | the reason in a sentence, *Details are in the log*, *Try again* or *Check again*, the release page | + +Closing the window hides it: a download goes on and is found again on reopening. All rules live in +`update::Machine` (pure, tested whole); the window draws its phase and sends events. + +## The release, and what is trusted + +One `GET api.github.com/repos/{owner}/{repo}/releases/latest` (60 an hour per IP without a token): the tag +(exactly `vX.Y.Z`, else "an answer this version does not understand"), the notes, and per asset its URL, +size and `digest: sha256:…`. Drafts and pre-releases are refused; a release not newer than the running +version is never offered (no downgrade). The download uses that release's own URLs. + +Two witnesses to the file, both over TLS: the workflow's `SHA256SUMS.txt` and GitHub's digest computed on +upload. They must agree with each other and with the downloaded bytes, else the file is deleted. **What this +does not defend against:** a compromised account or workflow — the hash proves the file is the one +published, not that it is honest. Verifying the build attestation (Sigstore) inside the application was +weighed on 2026-11-23 and left out: the Rust Sigstore crates are heavy and not yet stable; `gh attestation +verify` remains the way to check a download by hand (README). A file fetched by a library carries no Mark of +the Web, so SmartScreen does not see it: the hash is what vouches for it. + +TLS: rustls (through `ureq`), certificates checked against the OS's trust store (`rustls-platform-verifier`: +a corporate proxy's own root is accepted like in a browser), Windows' proxy settings read +(`win-system-proxy`). A generic `User-Agent` with the version, nothing about the user. + +## The swap + +The running executable is never written. Windows refuses to overwrite or delete an executable that runs, but +a separate process can rename it once it has exited: + +1. The download goes to `.new`, beside the executable: the swap is a rename on the same folder, not a + copy. Creating it is also the test that the folder can be written; a read-only folder (Program Files) + fails here and the window offers the release page. +2. *Restart now* writes `updates\pending.txt` (the version being installed) in the data folder, starts a + hidden Windows PowerShell (`-NoProfile -NonInteractive -WindowStyle Hidden`, `CREATE_NO_WINDOW`) and + closes the window the normal way. +3. The script waits for this exact process (`Wait-Process -Id -Timeout 30`), removes an older `.old`, + renames `` to `.old` and `.new` to `` — each step retried up to 10 times, 0.5 s + apart, because OneDrive or an antivirus may hold a file just written — then starts ``. +4. On any failure, it writes the reason to `updates\result.txt`, puts `.old` back if `` is gone, + and starts the executable again. +5. The next start compares `pending.txt` with its own version: equal, *Updated to X* and the `.old` goes; + different, the failure and `result.txt`'s reason, and the unused `.new` goes. A `.new` left without a + pending update (a download never installed) is deleted at start. + +Paths reach the script only as PowerShell single-quoted literals (`'` doubled) through `-LiteralPath`: spaces, +apostrophes and brackets cannot change the command (GameModeExecutor lost a delete to double quotes on +2026-09-17). Why PowerShell: `Wait-Process` waits for one process id, where a batch file could only guess +with a delay. Why not the `self-replace` crate (renaming the running image from inside): never measured +here, and it has no way back when the new file cannot be put in place. + +The protocol proves itself from the second release that carries it: 1.1.0 is the first; the first real +update through it is 1.1.0 → 1.2.0. + +## Measured, 2026-11-23, on the maintainer's machine + +A debug build of the branch, copied to a scratch folder named with a space, an apostrophe and brackets +(`update test [it's]`), run with `QVT_UPDATE_AS=0.9.0` (debug builds only) so the published 1.0.0 counts as +newer: + +| Step | Result | +| --- | --- | +| *Check for updates* | `releases/latest` answered, *Version 1.0.0 is available* with its notes, under a second | +| *Download and install* | 18,912,256 bytes in about a second, both witnesses agreed, *downloaded and verified* | +| *Restart now* | the window closed; the swap left `quick-video-transcoder.exe` with the published 1.0.0's SHA-256 (`a55a5f19…05ee02`) and the debug build as `.old`; 1.0.0 started and came to the foreground | +| Rollback | the same, with `.old` held open by another process: the removal failed ten times, the catch wrote *The process cannot access the file…* to `result.txt`, the executable stayed in place and restarted, and its next start showed the failure and the reason | + +Not measured: behind a proxy; the *Updated to* message from a real release pair (1.0.0 does not read +`pending.txt` — it waits for 1.1.0 → 1.2.0); OneDrive's locks (the retries are there for them). + +## Files written + +Beside the executable: `.new` (the download) and `.old` (the previous version, until the next +start). In the data folder: `updates\pending.txt` and `updates\result.txt`. Nothing else, and only after a +click. diff --git a/i18n.toml b/i18n.toml new file mode 100644 index 0000000..fcf0ab5 --- /dev/null +++ b/i18n.toml @@ -0,0 +1,5 @@ +# i18n-embed's configuration: English is the reference language, every other falls back to it. +fallback_language = "en" + +[fluent] +assets_dir = "i18n" diff --git a/i18n/en-GB/quick_video_transcoder.ftl b/i18n/en-GB/quick_video_transcoder.ftl new file mode 100644 index 0000000..6b3e3f5 --- /dev/null +++ b/i18n/en-GB/quick_video_transcoder.ftl @@ -0,0 +1,11 @@ +# British English: only the messages that differ from en (US English). + +queue-probed = + { $name }: { $summary }, { $duration }, { $tracks -> + [one] { NUM($tracks) } audio track + *[other] { NUM($tracks) } audio tracks + }, colour { $color }; { $engine } + +about-licence = Licence +about-third-party-link = third-party libraries and their licences +ffmpeg-licence-note = Installing accepts the package's licence (GPL) and the winget source's terms. diff --git a/i18n/en/quick_video_transcoder.ftl b/i18n/en/quick_video_transcoder.ftl new file mode 100644 index 0000000..0f03db9 --- /dev/null +++ b/i18n/en/quick_video_transcoder.ftl @@ -0,0 +1,635 @@ +# Quick Video Transcoder — English messages: the reference every other language falls back to. +# +# Conventions (see docs/localization.md): +# - Ids are `area-element[-detail]`, lower case with hyphens; `-tooltip` for hover texts. +# - Numbers always go through NUM: { NUM($mb, decimals: 1) } MB. Never format a number in Rust. +# - Variables are named for what they hold ($name, $count, $mb…); plurals use selectors on $count. +# - Keyboard keys are written as the user's keyboard names them (Home, Space…) and translated with the text. +# - Each section below belongs to one source area; keep new messages in their area. + +## Language menu (src/app/mod.rs) + +menu-language = Language +language-automatic = Automatic (system language) + +## Timeline and transport (src/app/timeline.rs) + +timeline-first-tooltip = Start of the kept part (Home) +timeline-previous-tooltip = Previous frame (Left) +timeline-play-tooltip = Play / pause the kept part (Space) +timeline-next-tooltip = Next frame (Right) +timeline-last-tooltip = End of the kept part (End) +timeline-start-here = [ Start here +timeline-start-here-tooltip = Start the kept part at the current frame (I) +timeline-end-here = End here ] +timeline-end-here-tooltip = End the kept part after the current frame (O) +timeline-volume-tooltip = Volume { NUM($percent) }% +timeline-mute-tooltip = Mute / unmute (M) +timeline-no-sound = No sound + +## Settings panel (src/app/settings.rs) + +# Heading of the settings panel when several videos are selected. $count is the number of videos (always 2 or more). +settings-heading-selected = + { $count -> + [one] { NUM($count) } video selected + *[other] { NUM($count) } videos selected + } +# Grey note under the heading when several videos are selected. +settings-change-applies-to-all = A change applies to each of them +# Heading of the settings panel when the queue has no selected video. +settings-no-video = No video selected + +# Section headings of the settings panel. +settings-section-profile = Profile +settings-section-kept-part = Kept part +settings-section-estimate = Estimate +settings-section-output = Output + +# Profile picker text when the video's settings were edited after choosing the profile. $name is the profile name. +settings-profile-changed = { $name } (changed) +# Button next to the profile picker: puts back the settings of the chosen profile. +settings-profile-reset = Reset +settings-profile-reset-tooltip = Back to the profile's settings +# Placeholder of the text field where the user names a profile to save. +settings-profile-name-hint = Profile name +# Button that saves the current settings as a profile; the "update" form shows when the typed name already exists. +settings-profile-save = Save as profile +settings-profile-update = Update profile +settings-profile-save-tooltip = Keep these settings as a profile for later videos + +# Row labels of the settings grid. +settings-size-limit = Size limit +settings-size-limit-tooltip = Megabytes of 1,000,000 bytes +# The size limit in its number box ("25.0 MB"); megabytes of 1,000,000 bytes. +settings-size-value = { NUM($mb, decimals: 1) } MB +settings-resolution = Resolution +# Picker text for the resolution ceiling. $short is the short side of the picture in pixels, e.g. 720 (shown as 720p). +settings-resolution-up-to = up to { $short }p +settings-frame-rate = Frame rate +# Picker text for the frame rate ceiling. $fps is a number of frames per second. +settings-frame-rate-up-to = up to { NUM($fps) } fps +# A frame rate in a list of choices. $fps is a number of frames per second. +settings-fps-value = { NUM($fps) } fps +settings-codec = Codec +# Picker text for a codec list made of one codec. $codec is the codec name, e.g. "H.264". +settings-codec-only = { $codec } only +# Shown after the arrow in the codec picker when no installed encoder can encode the codec list. +settings-codec-no-encoder = no encoder +settings-codec-tooltip = The codecs the destination plays, preferred first: the first one your GPU encodes is used, else the first one the CPU encodes +settings-hdr = HDR +# Checkbox: converts HDR videos to SDR when encoding. +settings-hdr-convert = Convert to SDR +settings-hdr-convert-tooltip = Off: an HDR video stays HDR (10-bit); phones without HDR show it washed out +# Shown when the checkbox is disabled because the chosen codecs cannot carry HDR. +settings-hdr-convert-disabled-tooltip = H.264 cannot carry HDR +settings-tone-mapping = Tone mapping +settings-tone-mapping-disabled-tooltip = This video is SDR +settings-sound = Sound +settings-sound-auto-tooltip = The game's track: the first one whose name is not a microphone or a voice chat +# Sound choices. "Every track mixed" mixes all the audio tracks of the capture into one. +settings-sound-mix-all = Every track mixed +settings-sound-none = No sound +# The automatic choice when it picks a track that has a name. $title is the track's name, as written in the file. +settings-sound-auto-titled = Automatic: { $title } +# The automatic choice when the picked track has no name. $number is the track's position, starting at 1. +settings-sound-auto-numbered = Automatic: track { $number } +# The automatic choice when no track can be identified yet (no video analysed, or no audio). +settings-sound-auto-default = Automatic (the game's track) +# A track without a name in the sound picker. $number is its position, starting at 1. +settings-sound-track = Track { $number } +settings-sound-bitrate = Sound bitrate +# A bitrate of the sound or the video. $kbps is a number of kilobits per second. +settings-kbps-value = { NUM($kbps) } kbit/s + +# Collapsible group of the settings grid. +settings-quality-bounds = Quality bounds +settings-best-worth-it = Best worth it +settings-best-worth-it-tooltip = Past this quality the extra bytes are not visible: an easy clip ends up smaller than the limit +settings-worst-accepted = Worst accepted +settings-worst-accepted-tooltip = Below this quality the frame rate, then the resolution, are lowered +# Value of a quality slider. QP is the quantization parameter (lower is better). $qp is its number, $word a short +# description of that quality, such as "good" (one of the estimate-quality-* messages, already translated). +settings-quality-value = QP { NUM($qp) } ({ $word }) +settings-lowest-resolution = Lowest resolution +settings-lowest-frame-rate = Lowest frame rate +# Text added to the name of each output file. +settings-file-name-suffix = File name suffix + +# Kept part (trim) section. +settings-kept-part-multi-note = The kept part is set video by video, on the timeline +settings-trim-start = Start +settings-trim-end = End +settings-trim-duration = Duration +settings-keep-everything = Keep everything +# Message in the log when the user typed something that is not a time in the start or end field. $text is what was typed. +settings-not-a-time = not a time: { $text } + +# Estimate section: a sentence above the details, depending on how the encode will fit. +settings-verdict-best-quality = Fits at the best quality worth it: the file will be smaller than the limit +settings-verdict-fitted = Fills the size limit +settings-verdict-below-floor = Below the worst accepted quality even at the lowest settings: shorten the kept part +settings-estimate-output = Output +# Planned output. $size is the picture size like "1280x720", $fps a frame rate number, $target a short description of the planned settings. +settings-estimate-output-value = { $size } at { $fps } fps ({ $target }) +settings-estimate-video-bitrate = Video bitrate +settings-estimate-quality = Quality +# $word is a short description of the quality, $qp the quantization parameter (lower is better). +settings-estimate-quality-value = { $word } (QP { NUM($qp, decimals: 1) }) +settings-estimate-size = Size +# $predicted is the expected size of the file and $limit the size limit, both in megabytes. +settings-estimate-size-value = ≈ { NUM($predicted, decimals: 1) } MB of { NUM($limit, decimals: 1) } MB +# Label of the number of short test encodes the estimate is based on. +settings-estimate-measured = Measured +settings-estimate-measured-value = + { $count -> + [one] { NUM($count) } sample encode + *[other] { NUM($count) } sample encodes + } +settings-estimating = Estimating… +# Shown while estimating: the video bitrate available, in kilobits per second. +settings-estimate-budget = Budget: { NUM($kbps) } kbit/s of video +# Small grey line. $engine is the name of the filter engine (data, not translated). +settings-estimate-filters = Filters: { $engine } + +# Output section: where the files go, and the encoder settings. +# Shown in place of the output folder when there is none: each output goes in its source's folder. +settings-output-next-to-video = Next to each video +# Button that goes back to writing each output next to its source (enabled when a folder is chosen). +settings-output-use-next-to-video = Next to each video +settings-output-choose-folder = Choose folder… +settings-output-folder-dialog-title = Output folder +settings-encoder = Encoder +settings-encoder-automatic = Automatic +settings-parallel-encodes = Encodes at once +# $count is the number of encodes the GPU runs at once before they slow each other down. +settings-parallel-measured-tooltip = Measured on this GPU: { $count } at once before encodes slow each other down (an RTX 4090 has two NVENC engines, an RTX 3080 one) +settings-parallel-not-measured-tooltip = Not measured yet +# Small grey status under the "Encodes at once" slider, in lower case on purpose. +settings-parallel-measuring = measuring… +# $count is the measured number of simultaneous encodes. +settings-parallel-measured = measured: { $count } +settings-parallel-not-measured = not measured +# Small button: sets the slider back to the measured number. +settings-parallel-use-measured = Use it +settings-parallel-measure-again = Measure again +settings-parallel-measure-again-tooltip = A few seconds; new estimates and encodes wait meanwhile + +# Profiles window (also in src/app/settings.rs). +profiles-title = Profiles +profiles-intro = The first profile is given to new videos. A profile is changed by saving a video's settings under its name. +# One line summarizing a profile in the list. $mb is the size limit in megabytes, $short the short side in pixels +# (720 gives 720p), $fps the highest frame rate (written right after the "p"), $codecs the codec list (data). +profiles-summary = { NUM($mb) } MB · { $short }p{ NUM($fps) } · { $codecs } +# Same as profiles-summary for a profile that converts HDR videos to SDR. +profiles-summary-sdr = { NUM($mb) } MB · { $short }p{ NUM($fps) } · { $codecs } · SDR +profiles-move-up-tooltip = Move up +profiles-delete-tooltip = Delete +# Menu button listing the profiles that came with the application and were deleted from the list. +profiles-add-built-in = Add a built-in profile + +## Preview (src/app/preview.rs) + +# Overlay on the preview. $size is the preview picture size like "1280x720", $width and $height the source size in +# pixels, $codec the source codec name (data). +preview-info = Preview { $size } · source { $width }x{ $height } { $codec } +# Same for an HDR source encoded to SDR. $dynamic is the HDR format name (data). +preview-info-hdr-encoded = Preview { $size } · source { $width }x{ $height } { $codec } · { $dynamic } tone mapped as encoded +# Same for an HDR source kept as HDR in the output: the preview cannot show HDR, so it is tone mapped. +preview-info-hdr-kept = Preview { $size } · source { $width }x{ $height } { $codec } · { $dynamic } kept HDR, shown tone mapped +preview-seeking = Seeking… +# $detail is the technical error of the video decoder (English). +preview-decoder-error = Decoder: { $detail } +# Centered texts of the preview when there is no picture. +preview-empty-queue = Drop game captures here, or add them with Ctrl+O +preview-decoding = Decoding… +preview-select-video = Select a video + +## Queue panel (src/app/queue_panel.rs) + +# Heading of the left panel. +queue-panel-heading = Queue +# Button at the top of the queue; a "➕ " symbol is put before this text. +queue-panel-add = Add… +queue-panel-add-tooltip = Add videos (Ctrl+O), or drop them here +# Shown in the empty queue, in two lines (this one is the larger). +queue-panel-empty-title = Drop videos here +queue-panel-empty-hint = or use Explorer's Send to menu +# Details line of a queue row: video summary (resolution, frame rate…), kept duration, profile name. +queue-panel-row-details = { $summary } · { $duration } · { $profile } +# Kept duration of a trimmed video: both are time codes (e.g. "0:12" of "1:05"). +queue-panel-duration-trimmed = { $kept } of { $total } +queue-panel-reading = Reading… +queue-panel-estimating = Estimating the size… +queue-panel-waiting = Waiting for an encoder… +# Small button in a row that waits or encodes: stops that video. +queue-panel-cancel = Cancel +# Progress text in a row while encoding. $percent is 0 to 100; $speed is the encoding speed relative to +# the video's duration (2.5 means 2.5 times faster than playback), 0 when unknown; $retry is the number of +# retries so far, 0 for the first attempt. +queue-panel-progress = + { NUM($percent) } %{ $speed -> + [0] { "" } + *[other] { " · " }{ NUM($speed, decimals: 1) }x + }{ $retry -> + [0] { "" } + *[other] { " · " }retry { NUM($retry) } + } +# Size of an encoded video in a row; a "✔ " symbol is put before this text. +queue-panel-done-size = { NUM($mb, decimals: 2) } MB +# Small button in a row of an encoded video: copies the file to the clipboard. +queue-panel-copy = Copy +queue-panel-copy-tooltip = Copy the file, to paste it into the conversation +# Small button in a row of an encoded video: opens its folder in Explorer. +queue-panel-show = Show +queue-panel-show-tooltip = Show in Explorer +# Estimate of a video's output. $target is the size and frame rate it will be encoded at, $mb the +# predicted file size, $quality a word for the quality, $queued is "yes" when the video is already queued +# for encoding, else "no". +queue-panel-estimate = + { $target } · ≈ { NUM($mb, decimals: 1) } MB · { $quality }{ $queued -> + [yes] { " · " }queued + *[other] { "" } + } +# Shown in a row while the estimate is being recomputed after a change of settings. +queue-panel-settings-changed = Settings changed… +# Button below the queue; a "▶ " symbol is put before this text. $count: how many selected videos can be encoded. +queue-panel-encode-selected = Encode selected ({ NUM($count) }) +queue-panel-encode-selected-tooltip = Encode the selected videos with their estimate (Ctrl+E) +# Button below the queue. $count: how many videos can be encoded. +queue-panel-encode-all = Encode all ({ NUM($count) }) +# Button below the queue; a "⏹ " symbol is put before this text. Stops every queued and running encode. +queue-panel-stop-all = Stop all +# Button below the queue. $count: how many videos are encoded. +queue-panel-copy-encoded = Copy encoded ({ NUM($count) }) +queue-panel-copy-encoded-tooltip = Copy every encoded file, to paste them into a conversation + +## Main window: menus, status bar, log, shortcuts, dialogs (src/app/mod.rs) + +# Menu bar. Shortcuts written in a label (Ctrl+O, Del) use the key names of the language's keyboards. +menu-file = File +menu-file-add-videos = Add videos… (Ctrl+O) +menu-file-remove-selected = Remove selected (Del) +menu-file-remove-encoded = Remove encoded videos +menu-file-quit = Quit +menu-profiles = Profiles +menu-profiles-edit = Edit profiles… +# Opens the folder that holds the profiles file, named profiles.toml, in Explorer. +menu-profiles-open-folder = Open profiles.toml folder +menu-view = View +# Checkbox that shows or hides the log panel. +menu-view-log = Log +menu-help = Help +menu-help-shortcuts = Keyboard shortcuts +menu-help-documentation = Documentation +menu-help-about = About Quick Video Transcoder + +# Bottom status bar. $total is the number of videos in the queue; the other counts are how many of them +# are being encoded (or wait for an encoder), being estimated, and encoded. +status-summary = + { $total -> + [one] { NUM($total) } video + *[other] { NUM($total) } videos + } · { NUM($encoding) } encoding · { NUM($estimating) } estimating · { NUM($done) } done +# Next to a spinner, while FFmpeg's encoders are being detected at start. +status-detecting = Detecting the encoders… + +# Window with the list of keyboard shortcuts: a title, then one line per shortcut made of the keys (left) +# and what they do (right). Key names follow the language's keyboards (Space, Home, Page Up / Down…); +# letters (I, O, M) do not change. +shortcuts-title = Keyboard shortcuts +shortcuts-play-keys = Space +shortcuts-play-action = Play / pause the kept part +shortcuts-step-keys = Left / Right +shortcuts-step-action = Previous / next frame +shortcuts-second-keys = Shift + Left / Right +shortcuts-second-action = -1 s / +1 s +shortcuts-ten-seconds-keys = Page Up / Down +shortcuts-ten-seconds-action = -10 s / +10 s +shortcuts-trim-keys = I / O +shortcuts-trim-action = Start / end of the kept part at the current frame +shortcuts-goto-keys = Home / End +shortcuts-goto-action = Go to the start / end of the kept part +shortcuts-mute-keys = M +shortcuts-mute-action = Mute / unmute +shortcuts-add-keys = Ctrl + O +shortcuts-add-action = Add videos +shortcuts-select-all-keys = Ctrl + A +shortcuts-select-all-action = Select every video +shortcuts-encode-keys = Ctrl + E +shortcuts-encode-action = Encode the selected videos +shortcuts-delete-keys = Delete +shortcuts-delete-action = Remove the selected videos +shortcuts-handle-keys = Drag a handle +shortcuts-handle-action = Move the start or end of the kept part +shortcuts-shift-drag-keys = Shift + drag +shortcuts-shift-drag-action = Move the kept part as a whole + +# Title of the window. $total is the number of videos in the queue. +title-idle = + Quick Video Transcoder — { $total -> + [one] { NUM($total) } video + *[other] { NUM($total) } videos + } +# Title of the window while encoding. $count: videos being encoded; $percent: their average progress. +title-encoding = Quick Video Transcoder — encoding { NUM($count) } ({ NUM($percent) } %) + +# File dialog opened by "Add videos": its title and the names of its two file filters. +dialog-add-title = Add videos +dialog-add-filter-videos = Videos +dialog-add-filter-all = All files +# Question asked when the window is closed while videos are being encoded (Yes / No buttons). +dialog-close-title = Encodes running +dialog-close-description = Closing stops the running encodes and deletes their partial files. Close anyway? + +# Lines of the log panel (and of the status bar). $detail is a technical error text, kept in English. +# $path: a file or folder path; $program: the name of a program (ffmpeg, ffprobe); $version: FFmpeg's version. +app-profiles-load-failed = { $detail }; using the built-in profile +app-folder-not-video = { $path } is a folder, not a video +app-files-copied = + { $count -> + [one] { NUM($count) } file + *[other] { NUM($count) } files + } copied: paste them into the conversation +app-profiles-no-folder = no data folder: the profiles cannot be saved +app-profiles-saved = profiles saved to { $path } +app-ffmpeg-missing = { $program } is not on the PATH +# $required: the oldest FFmpeg major version that works. +app-ffmpeg-too-old = { $version }: FFmpeg { NUM($required) } or later is needed +# $summary: the detected encoders, as a technical list. +app-hardware = hardware: { $summary } +app-no-encoder = FFmpeg runs, but none of its video encoders works on this computer +# $encoder: an encoder's name, for example "H.265 (NVENC)". +app-measuring = measuring how many encodes { $encoder } runs at once… +app-measure-failed = the encoder failed while measuring its parallel encodes +# $key: the graphics card, its driver and the encoder; $count: the number of encodes at once. +app-measured = + { $key }: { $count -> + [one] { NUM($count) } encode + *[other] { NUM($count) } encodes + } at once + +## Help windows: About, FFmpeg, Send to (src/app/help.rs) + +# Log line when a later launch of the application (Explorer's Send to) hands over files. +app-files-received = + { $count -> + [one] { NUM($count) } file + *[other] { NUM($count) } files + } received from Send to + +# File menu items that add the application to Explorer's "Send to" menu (the shortcut lives in the +# user's SendTo folder). +sendto-menu-add = Add to Explorer's Send to menu +sendto-menu-update = Update the Send to shortcut +sendto-menu-tooltip = Select videos in Explorer, right-click, Send to, Quick Video Transcoder +sendto-menu-remove = Remove from Explorer's Send to menu +# $path: where the shortcut was written. +sendto-menu-written = Send to shortcut written: { $path } +sendto-menu-removed = Send to shortcut removed + +# About window. +about-title = About Quick Video Transcoder +# $version: the version number. +about-heading = Quick Video Transcoder { $version } +about-summary = Trims game captures and re-encodes them to fit a size limit. +# Label of a row; its value is the short code of the build's source commit. +about-commit = Commit +about-documentation = Documentation +# Link text, after the "Documentation" label. +about-documentation-link = for this version +# Label of a row; its value is a link to the change history file (CHANGELOG.md). +about-changes = Changes +about-licence = License +about-built-with = Built with +about-third-party-link = third-party libraries and their licenses +about-notices-no-folder = no data folder to open the third-party notices from +# $path: the file that could not be written; $detail: the technical reason. +about-notices-failed = cannot write { $path }: { $detail } + +# Window shown when FFmpeg (the free program that reads and encodes videos) is missing or too old. +ffmpeg-title = FFmpeg is needed +# $program: the name of the program that was not found (ffmpeg or ffprobe). +ffmpeg-missing = Quick Video Transcoder reads and encodes videos with FFmpeg, a free program it does not include, and { $program } cannot be found on this computer. +# $version: the version found; $required: the oldest major version that works. +ffmpeg-too-old = The FFmpeg found is too old ({ $version }). Version { NUM($required) } or later is needed. +ffmpeg-installing = Installing FFmpeg with winget: a minute or two… +# winget is Windows' package manager. $package: the winget package identifier. +ffmpeg-winget-offer = It can be installed for you with winget, Windows' package manager: the { $package } package (gyan.dev's full build, about 100 MB, for your account only). +ffmpeg-install-button = Install FFmpeg for me +ffmpeg-licence-note = Installing accepts the package's license (GPL) and the winget source's terms. +# Introduces the manual steps below it. +ffmpeg-or-yourself = Or install it yourself: +ffmpeg-looking-for-winget = Looking for winget… +# Before a command to type in Windows Terminal; the command follows, then a "Copy" button. +ffmpeg-in-terminal = In Terminal: +ffmpeg-copy = Copy +# Followed by a link to the download page, on the same line. "release full" is the name of a build on +# that page. +ffmpeg-download = Or download the "release full" build from +ffmpeg-unzip = unzip it, and add its bin folder to the Path environment variable. +ffmpeg-check-again = Check again +# Log line. $package: the winget package identifier. +ffmpeg-install-log = installing FFmpeg with winget ({ $package })… + +## Queue, estimate and encode messages (src/queue.rs, src/estimate.rs, src/encode.rs) + +# Log line when a video has been read. $name: file name. $summary: one line such as "3840x2160 60 fps AV1 +# HDR10". $duration: a time code. $tracks: number of audio tracks. $color: the file's color tags as FFmpeg +# names them (data). $engine: how the filters run (a media-engine-* text). +queue-probed = + { $name }: { $summary }, { $duration }, { $tracks -> + [one] { NUM($tracks) } audio track + *[other] { NUM($tracks) } audio tracks + }, color { $color }; { $engine } +# Log line when a video cannot be used. $name: file name. $detail: why (already a sentence or a technical text). +queue-job-error = { $name }: { $detail } +# Log line when a size estimate failed. $detail: the technical cause. +queue-estimate-failed = { $name }: estimate failed: { $detail } +# Log line when the filters of a video fall back to another engine. $engine: a media-engine-* text. +queue-engine-changed = { $name }: now using { $engine } +# Log line when an encode finished. $path: the output file. $mb: its size in megabytes. $seconds: how long it took. +queue-encoded = { $name }: encoded to { $path } ({ NUM($mb, decimals: 2) } MB in { NUM($seconds, decimals: 1) } s) +# Log line when an encode failed. $detail: the technical cause. +queue-encode-failed = { $name }: encode failed: { $detail } +# Shown in the queue row when the user asked to encode a video whose estimate failed. $detail: the cause. +queue-no-estimate = cannot encode without an estimate: { $detail } + +# Words describing the predicted quality of a video, shown in the queue row and the settings, next to the +# size: "720p30 · ≈ 24.5 MB · good". Lowercase, one word or two. +estimate-quality-excellent = excellent +estimate-quality-very-good = very good +estimate-quality-good = good +estimate-quality-fair = fair +estimate-quality-poor = poor +# Estimate errors, shown in the queue row. +estimate-no-size = no output size to try +estimate-empty-range = the trimmed range is empty +# $mb: the size limit in megabytes. $duration: the kept part's length as a time code. +estimate-too-small = { NUM($mb, decimals: 0) } MB cannot even hold the sound of { $duration }: shorten the kept part +# $status: FFmpeg's exit status (data). $detail: FFmpeg's own message (technical, English). +estimate-sample-failed = sample encode failed ({ $status }): { $detail } +estimate-sample-failed-silent = sample encode failed ({ $status }): no output + +# Encode errors, shown in the queue row. $path: a file path. $status: FFmpeg's exit status (data). +# $detail: FFmpeg's own message (technical, English). +encode-output-exists = { $path } already exists +encode-cannot-read = cannot read { $path } +encode-cannot-rename = cannot rename the encode to { $path } +# $mb: the size limit in megabytes. $count: how many times the encode was tried. +encode-overshoot = + the encoder overshot { NUM($mb, decimals: 1) } MB { $count -> + [one] { NUM($count) } time + *[other] { NUM($count) } times + }: lower the quality floor or shorten the kept part +encode-ffmpeg-failed = ffmpeg failed ({ $status }): { $detail } +encode-ffmpeg-failed-silent = ffmpeg failed ({ $status }): no message +# Safety checks: the encode only writes its own partial file and never the source. +encode-refuse-partial = refusing to write { $path }: not a partial file +encode-refuse-source = refusing to write over the source { $path } + +## Profiles and settings values (src/profile.rs, src/plan.rs) + +# Tone mapping curves (HDR to SDR conversion), in the Tone mapping menu. Curve names are technical terms. +profile-tone-auto = Automatic (libplacebo) +profile-tone-bt2390 = BT.2390 +profile-tone-spline = Spline +profile-tone-hable = Hable (filmic) +profile-tone-mobius = Möbius +# Errors reading or writing the profiles file. $path: the file's path. +profile-invalid-file = invalid profiles file +profile-cannot-read = cannot read { $path } +profile-cannot-create = cannot create { $path } +profile-cannot-write = cannot write { $path } +profile-cannot-replace = cannot replace { $path } + +# A frame rate as a number, without the unit: a whole rate (60) or a fraction rounded to two decimals (29.97). +plan-rate-whole = { NUM($fps, decimals: 0) } +plan-rate-fraction = { NUM($fps, decimals: 2) } + +## Media details (src/ffmpeg/) + +# Errors about the FFmpeg tools, shown in the queue row or the log. +media-ffmpeg-start-failed = cannot start ffmpeg (is FFmpeg on the PATH?) +media-ffprobe-start-failed = cannot run ffprobe (is FFmpeg on the PATH?) +# $detail: ffprobe's own message (technical, English). +media-ffprobe-failed = ffprobe failed: { $detail } +media-probe-invalid = invalid ffprobe output +media-no-video = no video stream +media-no-dimensions = video stream without dimensions +# $status: FFmpeg's exit status (data). $detail: FFmpeg's own message (technical, English). +media-no-frame = no frame ({ $status }): { $detail } + +# How the filters run, shown as "Filters: ..." in the settings and in the log. Vulkan and libplacebo are +# technical names. +media-engine-vulkan = Vulkan decode + libplacebo +media-engine-placebo = libplacebo +media-engine-software = software filters + +# Dynamic range of a video, in the preview line and the queue row. Standard names; usually kept as is. +media-dynamic-sdr = SDR +media-dynamic-pq = HDR10 +media-dynamic-hlg = HLG + +# Channel layout of an audio track. $channels: the channel count. +media-audio-layout = + { $channels -> + [1] mono + [2] stereo + [6] 5.1 + [8] 7.1 + *[other] { NUM($channels) } channels + } +# An audio track in a menu, without and with the title the file gives it ("Microphone"). $number: its +# position (1, 2…). $codec: codec name (data). $layout: a media-audio-layout text. $title: the file's text (data). +media-audio-track = { NUM($number) } · { $codec }, { $layout } +media-audio-track-titled = { NUM($number) } · { $title } ({ $codec }, { $layout }) + +# One line describing a source video in the log and the queue. $width, $height: picture size in pixels +# (text, no digit grouping). $fps: frame rate text such as "60" or "29.97". $codec: codec name (data). +# $dynamic: a media-dynamic-* text. +media-summary = { $width }x{ $height } { $fps } fps { $codec } { $dynamic } + +# Log line listing what this computer can encode with. $encoders: such as "NVENC H.265/H.264, CPU H.265", +# or media-hardware-none. $placebo: "yes" or "no", whether GPU tone mapping works. +media-hardware-summary = + encoders: { $encoders }; GPU tone mapping (libplacebo): { $placebo -> + [yes] yes + *[no] no + } +media-hardware-none = none + +# Errors installing FFmpeg with winget, shown in the FFmpeg window. $status: exit status (data). $detail: winget's last lines. +media-winget-start-failed = cannot start winget +media-winget-failed = winget failed ({ $status }): { $detail } + +## Startup, Send to, clipboard (src/main.rs, src/sendto.rs, src/clipboard.rs) + +# Message box when the window cannot open: title, then body. $detail: the technical cause (English). +startup-window-failed-title = Quick Video Transcoder cannot open its window +startup-window-failed = + { $detail } + + The window needs a graphics driver with DirectX 12 or Vulkan. Updating the graphics driver usually fixes this. +# Message box after a crash: title, then body. $detail: the panic message (English). +startup-stopped-title = Quick Video Transcoder has stopped +startup-stopped = + Something went wrong: { $detail } + + Encodes that were running did not finish. +# Last paragraph of those message boxes. $path: the log file. +startup-log-hint = Details are in { $path } + +# Errors of the Explorer "Send to" shortcut. $path: the shortcut's path. $detail: PowerShell's message (technical). +sendto-no-folder = no Send to folder on this system +sendto-no-executable = cannot find this executable +sendto-no-exe-folder = the executable has no folder +sendto-start-failed = cannot start PowerShell +sendto-create-failed = cannot create { $path }: { $detail } +sendto-delete-failed = cannot delete { $path } +# The description stored in the shortcut (Explorer shows it in the shortcut's properties). +sendto-shortcut-description = Trim and re-encode videos to fit a size limit + +# Errors copying files to the clipboard. $detail: the system's message (technical). +clipboard-copy-failed = cannot copy to the clipboard: { $detail } +clipboard-unsupported = copying files to the clipboard is only supported on Windows + +## Updates window (src/app/update_window.rs) + +# Help menu item: opens the updates window and checks GitHub at once (the only time the app connects). +menu-help-updates = Check for updates… +# Title of the updates window. +update-title = Updates +# First line of the window. $version: the running version, like 1.0.0 (data). +update-running = This is Quick Video Transcoder { $version }. +update-check = Check for updates +update-check-again = Check again +update-checking = Checking for updates… +# $version: the running version, which is the latest. +update-up-to-date = { $version } is the latest version. +# $version: the newer version found. Above the release notes (shown in English, from the changelog). +update-available = Version { $version } is available +# Button. $mb: the executable's size in megabytes. +update-download = Download and install ({ NUM($mb, decimals: 1) } MB) +# Link to the release on GitHub, in the browser. +update-release-page = See it on GitHub +update-downloading = Downloading { $version }… +# Shown once the file is downloaded and its SHA-256 checked against the release's. +update-ready = { $version } is downloaded and verified. Restarting installs it. +update-restart = Restart now +# Under the disabled restart button while videos are encoding (a restart would stop them). +update-wait-for-encodes = Available once the encodes are finished or stopped. +update-restarting = Installing { $version }: the application closes and comes back… +# Shown at the first start after an update. $version: the new version. +update-updated = Updated to { $version }. +update-see-log = Details are in the log (View → Log). +update-retry = Try again +update-fault-connection = Could not reach GitHub: no connection, or it did not answer. +# $status: the HTTP status GitHub answered with, like 503 (data). +update-fault-status = GitHub answered with an error ({ $status }). Try again later. +update-fault-unexpected = GitHub's answer was not what this version expects. See the release page. +update-fault-not-verified = The downloaded file does not match the published one: it was deleted. Try again. +# The executable's folder is read-only (for instance under Program Files): the user can download it by hand. +update-fault-cannot-write = This copy's folder cannot be written. Download the new version from the release page instead. +# $detail: why the install failed (technical, English: a Windows or PowerShell message). +update-fault-install = The update could not be installed: { $detail } diff --git a/i18n/fr-CA/quick_video_transcoder.ftl b/i18n/fr-CA/quick_video_transcoder.ftl new file mode 100644 index 0000000..7967fbb --- /dev/null +++ b/i18n/fr-CA/quick_video_transcoder.ftl @@ -0,0 +1,25 @@ +# French (Canada): only the messages that differ from fr. + +# Keyboard keys as Canadian French keyboards and Windows name them. + +timeline-first-tooltip = Début de la partie conservée (Origine) +shortcuts-ten-seconds-keys = Pg préc / Pg suiv +shortcuts-goto-keys = Origine / Fin + +# Québec typography: no space before ; ! ? (a no-break space stays before :). + +settings-hdr-convert-tooltip = Décoché : une vidéo HDR reste en HDR (10 bits); les téléphones sans HDR l’affichent délavée +dialog-close-description = Fermer arrête les encodages en cours et supprime leurs fichiers partiels. Fermer quand même? +app-profiles-load-failed = { $detail }; utilisation du profil intégré +queue-probed = + { $name } : { $summary }, { $duration }, { $tracks -> + [one] { NUM($tracks) } piste audio + *[other] { NUM($tracks) } pistes audio + }, couleur { $color }; { $engine } +media-ffmpeg-start-failed = impossible de démarrer ffmpeg (FFmpeg est-il dans le PATH?) +media-ffprobe-start-failed = impossible d’exécuter ffprobe (FFmpeg est-il dans le PATH?) +media-hardware-summary = + encodeurs : { $encoders }; mappage tonal GPU (libplacebo) : { $placebo -> + [yes] oui + *[no] non + } diff --git a/i18n/fr/quick_video_transcoder.ftl b/i18n/fr/quick_video_transcoder.ftl new file mode 100644 index 0000000..d7eecd1 --- /dev/null +++ b/i18n/fr/quick_video_transcoder.ftl @@ -0,0 +1,469 @@ +# Quick Video Transcoder — French messages (fr). Regional files (fr-CA…) hold only what differs. +# Missing messages fall back to English. See docs/localization.md for the glossary and typography. + +## Language menu (src/app/mod.rs) + +menu-language = Langue +language-automatic = Automatique (langue du système) + +## Timeline and transport (src/app/timeline.rs) + +timeline-first-tooltip = Début de la partie conservée (Début) +timeline-previous-tooltip = Image précédente (Gauche) +timeline-play-tooltip = Lire / mettre en pause la partie conservée (Espace) +timeline-next-tooltip = Image suivante (Droite) +timeline-last-tooltip = Fin de la partie conservée (Fin) +timeline-start-here = [ Début ici +timeline-start-here-tooltip = Placer le début de la partie conservée sur l’image actuelle (I) +timeline-end-here = Fin ici ] +timeline-end-here-tooltip = Placer la fin de la partie conservée après l’image actuelle (O) +timeline-volume-tooltip = Volume : { NUM($percent) } % +timeline-mute-tooltip = Couper / rétablir le son (M) +timeline-no-sound = Cette vidéo n’a pas de son + +## Settings panel (src/app/settings.rs) + +settings-heading-selected = + { $count -> + [one] { NUM($count) } vidéo sélectionnée + *[other] { NUM($count) } vidéos sélectionnées + } +settings-change-applies-to-all = Toute modification s’applique à chacune +settings-no-video = Aucune vidéo sélectionnée + +settings-section-profile = Profil +settings-section-kept-part = Partie conservée +settings-section-estimate = Estimation +settings-section-output = Sortie + +settings-profile-changed = { $name } (modifié) +settings-profile-reset = Rétablir +settings-profile-reset-tooltip = Revenir aux réglages du profil +settings-profile-name-hint = Nom du profil +settings-profile-save = Enregistrer le profil +settings-profile-update = Mettre à jour le profil +settings-profile-save-tooltip = Garder ces réglages dans un profil pour les prochaines vidéos + +settings-size-limit = Taille maximale +settings-size-limit-tooltip = En mégaoctets de 1 000 000 d’octets +settings-size-value = { NUM($mb, decimals: 1) } Mo +settings-resolution = Résolution +settings-resolution-up-to = jusqu’à { $short }p +settings-frame-rate = Fréquence d’images +settings-frame-rate-up-to = jusqu’à { NUM($fps) } i/s +settings-fps-value = { NUM($fps) } i/s +settings-codec = Codec +settings-codec-only = { $codec } uniquement +settings-codec-no-encoder = aucun encodeur +settings-codec-tooltip = Les codecs que la destination sait lire, par ordre de préférence : le premier que votre GPU sait encoder est utilisé, sinon le premier que le processeur sait encoder +settings-hdr = HDR +settings-hdr-convert = Convertir en SDR +settings-hdr-convert-tooltip = Décoché : une vidéo HDR reste en HDR (10 bits) ; les téléphones sans HDR l’affichent délavée +settings-hdr-convert-disabled-tooltip = H.264 ne prend pas en charge le HDR +settings-tone-mapping = Mappage tonal +settings-tone-mapping-disabled-tooltip = Cette vidéo est en SDR +settings-sound = Son +settings-sound-auto-tooltip = La piste du jeu : la première dont le nom n’indique ni un micro ni un chat vocal +settings-sound-mix-all = Toutes les pistes mixées +settings-sound-none = Sans son +settings-sound-auto-titled = Automatique : { $title } +settings-sound-auto-numbered = Automatique : piste { $number } +settings-sound-auto-default = Automatique (la piste du jeu) +settings-sound-track = Piste { $number } +settings-sound-bitrate = Débit audio +settings-kbps-value = { NUM($kbps) } kbit/s + +settings-quality-bounds = Limites de qualité +settings-best-worth-it = Maximum utile +settings-best-worth-it-tooltip = Au-delà de cette qualité, les octets en plus ne se voient pas : un clip facile donne un fichier plus petit que la limite +settings-worst-accepted = Minimum accepté +settings-worst-accepted-tooltip = En dessous de cette qualité, la fréquence d’images, puis la résolution, sont réduites +settings-quality-value = QP { NUM($qp) } ({ $word }) +settings-lowest-resolution = Résolution minimale +settings-lowest-frame-rate = Fréquence minimale +settings-file-name-suffix = Suffixe du nom + +settings-kept-part-multi-note = La partie conservée se règle vidéo par vidéo, sur la chronologie +settings-trim-start = Début +settings-trim-end = Fin +settings-trim-duration = Durée +settings-keep-everything = Tout garder +settings-not-a-time = « { $text } » n’est pas un temps valide + +settings-verdict-best-quality = Tient à la qualité maximale utile : le fichier sera plus petit que la limite +settings-verdict-fitted = Utilise toute la taille maximale +settings-verdict-below-floor = Sous la qualité minimale acceptée, même aux réglages les plus bas : raccourcissez la partie conservée +settings-estimate-output = Sortie +settings-estimate-output-value = { $size } à { $fps } i/s ({ $target }) +settings-estimate-video-bitrate = Débit vidéo +settings-estimate-quality = Qualité +settings-estimate-quality-value = { $word } (QP { NUM($qp, decimals: 1) }) +settings-estimate-size = Taille +settings-estimate-size-value = ≈ { NUM($predicted, decimals: 1) } Mo sur { NUM($limit, decimals: 1) } Mo +settings-estimate-measured = Mesurée sur +settings-estimate-measured-value = + { $count -> + [one] { NUM($count) } encodage d’essai + *[other] { NUM($count) } encodages d’essai + } +settings-estimating = Estimation… +settings-estimate-budget = Budget : { NUM($kbps) } kbit/s pour la vidéo +settings-estimate-filters = Filtres : { $engine } + +settings-output-next-to-video = À côté de chaque vidéo +settings-output-use-next-to-video = À côté de chaque vidéo +settings-output-choose-folder = Choisir un dossier… +settings-output-folder-dialog-title = Dossier de sortie +settings-encoder = Encodeur +settings-encoder-automatic = Automatique +settings-parallel-encodes = Encodages simultanés +settings-parallel-measured-tooltip = Mesuré sur ce GPU : { $count } à la fois avant que les encodages ne se ralentissent entre eux (une RTX 4090 a deux moteurs NVENC, une RTX 3080 un seul) +settings-parallel-not-measured-tooltip = Pas encore mesuré +settings-parallel-measuring = mesure… +settings-parallel-measured = mesuré : { $count } +settings-parallel-not-measured = non mesuré +settings-parallel-use-measured = Appliquer +settings-parallel-measure-again = Mesurer à nouveau +settings-parallel-measure-again-tooltip = Quelques secondes, pendant lesquelles les nouvelles estimations et les encodages patientent + +profiles-title = Profils +profiles-intro = Les nouvelles vidéos reçoivent le premier profil. Pour modifier un profil, enregistrez sous son nom les réglages d’une vidéo. +profiles-summary = { NUM($mb) } Mo · { $short }p{ NUM($fps) } · { $codecs } +profiles-summary-sdr = { NUM($mb) } Mo · { $short }p{ NUM($fps) } · { $codecs } · SDR +profiles-move-up-tooltip = Monter +profiles-delete-tooltip = Supprimer +profiles-add-built-in = Ajouter un profil intégré + +## Preview (src/app/preview.rs) + +preview-info = Aperçu { $size } · source { $width }x{ $height } { $codec } +preview-info-hdr-encoded = Aperçu { $size } · source { $width }x{ $height } { $codec } · { $dynamic } converti en SDR, comme à l’encodage +preview-info-hdr-kept = Aperçu { $size } · source { $width }x{ $height } { $codec } · { $dynamic } conservé, affiché en SDR +preview-seeking = Recherche… +preview-decoder-error = Décodeur : { $detail } +preview-empty-queue = Déposez vos captures de jeu ici, ou ajoutez-les avec Ctrl+O +preview-decoding = Décodage… +preview-select-video = Sélectionnez une vidéo + +## Queue panel (src/app/queue_panel.rs) + +queue-panel-heading = File d’attente +queue-panel-add = Ajouter… +queue-panel-add-tooltip = Ajouter des vidéos (Ctrl+O), ou les déposer ici +queue-panel-empty-title = Déposez des vidéos ici +queue-panel-empty-hint = ou passez par le menu Envoyer vers de l’Explorateur +queue-panel-row-details = { $summary } · { $duration } · { $profile } +queue-panel-duration-trimmed = { $kept } sur { $total } +queue-panel-reading = Analyse… +queue-panel-estimating = Estimation de la taille… +queue-panel-waiting = En attente d’un encodeur… +queue-panel-cancel = Annuler +queue-panel-progress = + { NUM($percent) } %{ $speed -> + [0] { "" } + *[other] { " · " }{ NUM($speed, decimals: 1) }x + }{ $retry -> + [0] { "" } + *[other] { " · " }reprise { NUM($retry) } + } +queue-panel-done-size = { NUM($mb, decimals: 2) } Mo +queue-panel-copy = Copier +queue-panel-copy-tooltip = Copier le fichier pour le coller dans la conversation +queue-panel-show = Afficher +queue-panel-show-tooltip = Afficher dans l’Explorateur +queue-panel-estimate = + { $target } · ≈ { NUM($mb, decimals: 1) } Mo · { $quality }{ $queued -> + [yes] { " · " }en attente + *[other] { "" } + } +queue-panel-settings-changed = Réglages modifiés… +queue-panel-encode-selected = Encoder la sélection ({ NUM($count) }) +queue-panel-encode-selected-tooltip = Encoder les vidéos sélectionnées selon leur estimation (Ctrl+E) +queue-panel-encode-all = Tout encoder ({ NUM($count) }) +queue-panel-stop-all = Tout arrêter +queue-panel-copy-encoded = Copier les vidéos encodées ({ NUM($count) }) +queue-panel-copy-encoded-tooltip = Copier tous les fichiers encodés pour les coller dans une conversation + +## Main window: menus, status bar, log, shortcuts, dialogs (src/app/mod.rs) + +menu-file = Fichier +menu-file-add-videos = Ajouter des vidéos… (Ctrl+O) +menu-file-remove-selected = Retirer la sélection (Suppr) +menu-file-remove-encoded = Retirer les vidéos encodées +menu-file-quit = Quitter +menu-profiles = Profils +menu-profiles-edit = Modifier les profils… +menu-profiles-open-folder = Ouvrir le dossier de profiles.toml +menu-view = Affichage +menu-view-log = Journal +menu-help = Aide +menu-help-shortcuts = Raccourcis clavier +menu-help-documentation = Documentation +menu-help-about = À propos de Quick Video Transcoder + +status-summary = + { $total -> + [one] { NUM($total) } vidéo + *[other] { NUM($total) } vidéos + } · { NUM($encoding) } en encodage · { NUM($estimating) } en estimation · { NUM($done) } { $done -> + [one] terminée + *[other] terminées + } +status-detecting = Détection des encodeurs… + +shortcuts-title = Raccourcis clavier +shortcuts-play-keys = Espace +shortcuts-play-action = Lire / mettre en pause la partie conservée +shortcuts-step-keys = Gauche / Droite +shortcuts-step-action = Image précédente / suivante +shortcuts-second-keys = Maj + Gauche / Droite +shortcuts-second-action = −1 s / +1 s +shortcuts-ten-seconds-keys = Pg. préc. / Pg. suiv. +shortcuts-ten-seconds-action = −10 s / +10 s +shortcuts-trim-keys = I / O +shortcuts-trim-action = Début / fin de la partie conservée à l’image actuelle +shortcuts-goto-keys = Début / Fin +shortcuts-goto-action = Aller au début / à la fin de la partie conservée +shortcuts-mute-keys = M +shortcuts-mute-action = Couper / rétablir le son +shortcuts-add-keys = Ctrl + O +shortcuts-add-action = Ajouter des vidéos +shortcuts-select-all-keys = Ctrl + A +shortcuts-select-all-action = Sélectionner toutes les vidéos +shortcuts-encode-keys = Ctrl + E +shortcuts-encode-action = Encoder les vidéos sélectionnées +shortcuts-delete-keys = Suppr +shortcuts-delete-action = Retirer les vidéos sélectionnées +shortcuts-handle-keys = Faire glisser une poignée +shortcuts-handle-action = Déplacer le début ou la fin de la partie conservée +shortcuts-shift-drag-keys = Maj + glisser +shortcuts-shift-drag-action = Déplacer la partie conservée d’un bloc + +title-idle = + Quick Video Transcoder — { $total -> + [one] { NUM($total) } vidéo + *[other] { NUM($total) } vidéos + } +title-encoding = + Quick Video Transcoder — { $count -> + [one] { NUM($count) } encodage en cours + *[other] { NUM($count) } encodages en cours + } ({ NUM($percent) } %) + +dialog-add-title = Ajouter des vidéos +dialog-add-filter-videos = Vidéos +dialog-add-filter-all = Tous les fichiers +dialog-close-title = Encodages en cours +dialog-close-description = Fermer arrête les encodages en cours et supprime leurs fichiers partiels. Fermer quand même ? + +app-profiles-load-failed = { $detail } ; utilisation du profil intégré +app-folder-not-video = { $path } est un dossier, pas une vidéo +app-files-copied = + { $count -> + [one] { NUM($count) } fichier copié : collez-le dans la conversation + *[other] { NUM($count) } fichiers copiés : collez-les dans la conversation + } +app-profiles-no-folder = aucun dossier de données : impossible d’enregistrer les profils +app-profiles-saved = profils enregistrés dans { $path } +app-ffmpeg-missing = { $program } est introuvable dans le PATH +app-ffmpeg-too-old = { $version } : il faut FFmpeg { NUM($required) } ou une version plus récente +app-hardware = matériel : { $summary } +app-no-encoder = FFmpeg fonctionne, mais aucun de ses encodeurs vidéo n’est utilisable sur cet ordinateur +app-measuring = mesure du nombre d’encodages simultanés possibles avec { $encoder }… +app-measure-failed = l’encodeur a échoué pendant la mesure des encodages simultanés +app-measured = + { $key } : { $count -> + [one] { NUM($count) } encodage simultané + *[other] { NUM($count) } encodages simultanés + } + +## Help windows: About, FFmpeg, Send to (src/app/help.rs) + +app-files-received = + { $count -> + [one] { NUM($count) } fichier reçu + *[other] { NUM($count) } fichiers reçus + } via Envoyer vers + +sendto-menu-add = Ajouter au menu Envoyer vers de l’Explorateur +sendto-menu-update = Mettre à jour le raccourci Envoyer vers +sendto-menu-tooltip = Dans l’Explorateur, sélectionnez des vidéos, faites un clic droit, puis Envoyer vers > Quick Video Transcoder +sendto-menu-remove = Retirer du menu Envoyer vers de l’Explorateur +sendto-menu-written = Raccourci Envoyer vers créé : { $path } +sendto-menu-removed = Raccourci Envoyer vers supprimé + +about-title = À propos de Quick Video Transcoder +about-heading = Quick Video Transcoder { $version } +about-summary = Découpe vos captures de jeu et les réencode pour tenir dans une taille maximale. +about-commit = Commit +about-documentation = Documentation +about-documentation-link = de cette version +about-changes = Historique +about-licence = Licence +about-built-with = Conçu avec +about-third-party-link = des bibliothèques tierces et leurs licences +about-notices-no-folder = aucun dossier de données où ouvrir les mentions des bibliothèques tierces +about-notices-failed = impossible d’écrire { $path } : { $detail } + +ffmpeg-title = FFmpeg est nécessaire +ffmpeg-missing = Quick Video Transcoder lit et encode les vidéos avec FFmpeg, un programme gratuit qu’il n’inclut pas, et { $program } est introuvable sur cet ordinateur. +ffmpeg-too-old = La version de FFmpeg trouvée est trop ancienne ({ $version }). Il faut la version { NUM($required) } ou une version plus récente. +ffmpeg-installing = Installation de FFmpeg avec winget : une minute ou deux… +ffmpeg-winget-offer = Quick Video Transcoder peut l’installer pour vous avec winget, le gestionnaire de paquets de Windows : paquet { $package } (version complète de gyan.dev, environ 100 Mo, pour votre compte uniquement). +ffmpeg-install-button = Installer FFmpeg pour moi +ffmpeg-licence-note = L’installation vaut acceptation de la licence du paquet (GPL) et des conditions de la source winget. +ffmpeg-or-yourself = Ou installez-le vous-même : +ffmpeg-looking-for-winget = Recherche de winget… +ffmpeg-in-terminal = Dans le Terminal : +ffmpeg-copy = Copier +ffmpeg-download = Ou téléchargez la version « release full » sur +ffmpeg-unzip = décompressez-la, puis ajoutez son dossier bin à la variable d’environnement Path. +ffmpeg-check-again = Vérifier à nouveau +ffmpeg-install-log = installation de FFmpeg avec winget ({ $package })… + +## Queue, estimate and encode messages (src/queue.rs, src/estimate.rs, src/encode.rs) + +queue-probed = + { $name } : { $summary }, { $duration }, { $tracks -> + [one] { NUM($tracks) } piste audio + *[other] { NUM($tracks) } pistes audio + }, couleur { $color } ; { $engine } +queue-job-error = { $name } : { $detail } +queue-estimate-failed = { $name } : échec de l’estimation : { $detail } +queue-engine-changed = { $name } : passage à { $engine } +queue-encoded = { $name } : encodage terminé, { $path } ({ NUM($mb, decimals: 2) } Mo en { NUM($seconds, decimals: 1) } s) +queue-encode-failed = { $name } : échec de l’encodage : { $detail } +queue-no-estimate = impossible d’encoder sans estimation : { $detail } + +estimate-quality-excellent = excellente +estimate-quality-very-good = très bonne +estimate-quality-good = bonne +estimate-quality-fair = correcte +estimate-quality-poor = médiocre +estimate-no-size = aucune taille de sortie à essayer +estimate-empty-range = la partie conservée est vide +estimate-too-small = { NUM($mb, decimals: 0) } Mo ne suffisent même pas pour le son de { $duration } : raccourcissez la partie conservée +estimate-sample-failed = échec de l’encodage d’essai ({ $status }) : { $detail } +estimate-sample-failed-silent = échec de l’encodage d’essai ({ $status }) : aucune sortie + +encode-output-exists = { $path } existe déjà +encode-cannot-read = impossible de lire { $path } +encode-cannot-rename = impossible de renommer le fichier encodé en { $path } +encode-overshoot = + l’encodeur a dépassé { NUM($mb, decimals: 1) } Mo { $count -> + [one] { NUM($count) } fois + *[other] { NUM($count) } fois + } : baissez la qualité minimale ou raccourcissez la partie conservée +encode-ffmpeg-failed = échec de ffmpeg ({ $status }) : { $detail } +encode-ffmpeg-failed-silent = échec de ffmpeg ({ $status }) : aucun message +encode-refuse-partial = écriture de { $path } refusée : ce n’est pas un fichier partiel +encode-refuse-source = écriture refusée : { $path } est la source + +## Profiles and settings values (src/profile.rs, src/plan.rs) + +profile-tone-auto = Automatique (libplacebo) +profile-tone-bt2390 = BT.2390 +profile-tone-spline = Spline +profile-tone-hable = Hable (filmique) +profile-tone-mobius = Möbius +profile-invalid-file = fichier de profils non valide +profile-cannot-read = impossible de lire { $path } +profile-cannot-create = impossible de créer { $path } +profile-cannot-write = impossible d’écrire { $path } +profile-cannot-replace = impossible de remplacer { $path } + +plan-rate-whole = { NUM($fps, decimals: 0) } +plan-rate-fraction = { NUM($fps, decimals: 2) } + +## Media details (src/ffmpeg/) + +media-ffmpeg-start-failed = impossible de démarrer ffmpeg (FFmpeg est-il dans le PATH ?) +media-ffprobe-start-failed = impossible d’exécuter ffprobe (FFmpeg est-il dans le PATH ?) +media-ffprobe-failed = échec de ffprobe : { $detail } +media-probe-invalid = sortie de ffprobe non valide +media-no-video = aucun flux vidéo +media-no-dimensions = flux vidéo sans dimensions +media-no-frame = aucune image ({ $status }) : { $detail } + +media-engine-vulkan = décodage Vulkan + libplacebo +media-engine-placebo = libplacebo +media-engine-software = filtres logiciels + +media-dynamic-sdr = SDR +media-dynamic-pq = HDR10 +media-dynamic-hlg = HLG + +media-audio-layout = + { $channels -> + [1] mono + [2] stéréo + [6] 5.1 + [8] 7.1 + *[other] { NUM($channels) } canaux + } +media-audio-track = { NUM($number) } · { $codec }, { $layout } +media-audio-track-titled = { NUM($number) } · { $title } ({ $codec }, { $layout }) + +media-summary = { $width }x{ $height } { $fps } i/s { $codec } { $dynamic } + +media-hardware-summary = + encodeurs : { $encoders } ; mappage tonal GPU (libplacebo) : { $placebo -> + [yes] oui + *[no] non + } +media-hardware-none = aucun + +media-winget-start-failed = impossible de démarrer winget +media-winget-failed = échec de winget ({ $status }) : { $detail } + +## Startup, Send to, clipboard (src/main.rs, src/sendto.rs, src/clipboard.rs) + +startup-window-failed-title = Quick Video Transcoder ne peut pas ouvrir sa fenêtre +startup-window-failed = + { $detail } + + La fenêtre a besoin d’un pilote graphique compatible DirectX 12 ou Vulkan. Mettre à jour le pilote graphique règle généralement le problème. +startup-stopped-title = Quick Video Transcoder s’est arrêté +startup-stopped = + Un problème est survenu : { $detail } + + Les encodages en cours n’ont pas abouti. +startup-log-hint = Les détails se trouvent dans { $path } + +sendto-no-folder = aucun dossier Envoyer vers sur ce système +sendto-no-executable = impossible de trouver cet exécutable +sendto-no-exe-folder = l’exécutable n’a pas de dossier +sendto-start-failed = impossible de démarrer PowerShell +sendto-create-failed = impossible de créer { $path } : { $detail } +sendto-delete-failed = impossible de supprimer { $path } +sendto-shortcut-description = Découper et réencoder des vidéos pour tenir dans une taille maximale + +clipboard-copy-failed = impossible de copier dans le Presse-papiers : { $detail } +clipboard-unsupported = la copie de fichiers dans le Presse-papiers n’est prise en charge que sous Windows + +## Updates window (src/app/update_window.rs) + +menu-help-updates = Rechercher des mises à jour… +update-title = Mises à jour +update-running = Vous utilisez Quick Video Transcoder { $version }. +update-check = Rechercher des mises à jour +update-check-again = Rechercher à nouveau +update-checking = Recherche de mises à jour… +update-up-to-date = La version { $version } est la plus récente. +update-available = La version { $version } est disponible +update-download = Télécharger et installer ({ NUM($mb, decimals: 1) } Mo) +update-release-page = Voir sur GitHub +update-downloading = Téléchargement de la version { $version }… +update-ready = La version { $version } est téléchargée et vérifiée. Elle s’installera au redémarrage. +update-restart = Redémarrer maintenant +update-wait-for-encodes = Disponible une fois les encodages terminés ou arrêtés. +update-restarting = Installation de la version { $version } : l’application se ferme et revient… +update-updated = Mise à jour vers la version { $version } effectuée. +update-see-log = Détails dans le journal (Affichage > Journal). +update-retry = Réessayer +update-fault-connection = Impossible de joindre GitHub : pas de connexion, ou pas de réponse. +update-fault-status = GitHub a répondu par une erreur ({ $status }). Réessayez plus tard. +update-fault-unexpected = La réponse de GitHub ne correspond pas à ce que cette version attend. Consultez la page de la version. +update-fault-not-verified = Le fichier téléchargé ne correspond pas au fichier publié : il a été supprimé. Réessayez. +update-fault-cannot-write = Le dossier de cette copie n’est pas modifiable. Téléchargez plutôt la nouvelle version depuis sa page. +update-fault-install = La mise à jour n’a pas pu être installée : { $detail } diff --git a/src/app/help.rs b/src/app/help.rs index 3fa7b12..d45377e 100644 --- a/src/app/help.rs +++ b/src/app/help.rs @@ -22,7 +22,7 @@ impl TranscoderApp { if files.is_empty() { return; } - self.info(format!("{} file(s) received from Send to", files.len())); + self.info(crate::tr!("app-files-received", count = files.len())); self.add_files(files); ctx.send_viewport_cmd(egui::ViewportCommand::Minimized(false)); ctx.send_viewport_cmd(egui::ViewportCommand::Focus); @@ -35,20 +35,21 @@ impl TranscoderApp { /// *File* menu: add the application to Explorer's *Send to* menu, or take it away. pub(super) fn sendto_menu(&mut self, ui: &mut egui::Ui) { let label = if self.sendto_installed { - "Update the Send to shortcut" + crate::tr!("sendto-menu-update") } else { - "Add to Explorer's Send to menu" + crate::tr!("sendto-menu-add") }; if ui .button(label) - .on_hover_text( - "Select videos in Explorer, right-click, Send to, Quick Video Transcoder", - ) + .on_hover_text(crate::tr!("sendto-menu-tooltip")) .clicked() { ui.close(); match crate::sendto::install() { - Ok(link) => self.info(format!("Send to shortcut written: {}", link.display())), + Ok(link) => self.info(crate::tr!( + "sendto-menu-written", + path = link.display().to_string() + )), Err(error) => self.error(format!("{error:#}")), } self.sendto_installed = crate::sendto::is_installed(); @@ -56,13 +57,13 @@ impl TranscoderApp { if ui .add_enabled( self.sendto_installed, - egui::Button::new("Remove from Explorer's Send to menu"), + egui::Button::new(crate::tr!("sendto-menu-remove")), ) .clicked() { ui.close(); match crate::sendto::remove() { - Ok(()) => self.info("Send to shortcut removed"), + Ok(()) => self.info(crate::tr!("sendto-menu-removed")), Err(error) => self.error(format!("{error:#}")), } self.sendto_installed = crate::sendto::is_installed(); @@ -71,32 +72,34 @@ impl TranscoderApp { pub(super) fn about_window(&mut self, ctx: &egui::Context) { let mut show_notices = false; - egui::Window::new("About Quick Video Transcoder") + // A fixed id: the title changes with the language, and the window keeps its place. + egui::Window::new(crate::tr!("about-title")) + .id(egui::Id::unique("about window")) .open(&mut self.show_about) .resizable(false) .collapsible(false) .show(ctx, |ui| { - ui.heading(format!("Quick Video Transcoder {}", build_info::VERSION)); - ui.label("Trims game captures and re-encodes them to fit a size limit."); + ui.heading(crate::tr!("about-heading", version = build_info::VERSION)); + ui.label(crate::tr!("about-summary")); ui.add_space(8.0); egui::Grid::new("about").num_columns(2).show(ui, |ui| { - ui.label("Commit"); + ui.label(crate::tr!("about-commit")); ui.monospace(format!("{}{}", build_info::COMMIT_SHORT, build_info::DIRTY)); ui.end_row(); - ui.label("Documentation"); - ui.hyperlink_to("for this version", build_info::documentation()); + ui.label(crate::tr!("about-documentation")); + ui.hyperlink_to( + crate::tr!("about-documentation-link"), + build_info::documentation(), + ); ui.end_row(); - ui.label("Changes"); + ui.label(crate::tr!("about-changes")); ui.hyperlink_to("CHANGELOG.md", build_info::doc_url("CHANGELOG.md")); ui.end_row(); - ui.label("Licence"); + ui.label(crate::tr!("about-licence")); ui.hyperlink_to("MIT", build_info::doc_url("LICENSE")); ui.end_row(); - ui.label("Built with"); - if ui - .link("third-party libraries and their licences") - .clicked() - { + ui.label(crate::tr!("about-built-with")); + if ui.link(crate::tr!("about-third-party-link")).clicked() { show_notices = true; } ui.end_row(); @@ -110,7 +113,7 @@ impl TranscoderApp { /// Writes the notices built into the executable to the data folder and opens them in the browser. fn open_notices(&mut self) { let Some(dir) = crate::profile::data_dir() else { - self.error("no data folder to open the third-party notices from"); + self.error(crate::tr!("about-notices-no-folder")); return; }; let path = dir.join("THIRD-PARTY-NOTICES.html"); @@ -118,7 +121,11 @@ impl TranscoderApp { std::fs::create_dir_all(&dir).and_then(|()| std::fs::write(&path, build_info::NOTICES)); match written { Ok(()) => super::open_file(&path), - Err(error) => self.error(format!("cannot write {}: {error}", path.display())), + Err(error) => self.error(crate::tr!( + "about-notices-failed", + path = path.display().to_string(), + detail = error.to_string() + )), } } @@ -131,7 +138,8 @@ impl TranscoderApp { help.poll(); let mut open = true; let mut action = None; - egui::Window::new("FFmpeg is needed") + egui::Window::new(crate::tr!("ffmpeg-title")) + .id(egui::Id::unique("ffmpeg window")) .open(&mut open) .resizable(false) .collapsible(false) @@ -163,9 +171,9 @@ fn help_install(app: &mut TranscoderApp) { }); help.installing = Some(receiver); help.failure = None; - app.info(format!( - "installing FFmpeg with winget ({})…", - crate::ffmpeg::WINGET_PACKAGE + app.info(crate::tr!( + "ffmpeg-install-log", + package = crate::ffmpeg::WINGET_PACKAGE )); } @@ -223,12 +231,13 @@ impl FfmpegHelp { fn ui(&mut self, ui: &mut egui::Ui) -> Option { let mut action = None; ui.label(match &self.problem { - Install::Missing(program) => format!( - "Quick Video Transcoder reads and encodes videos with FFmpeg, a free program it does \ - not include, and {program} cannot be found on this computer." - ), - Install::TooOld(version) => format!( - "The FFmpeg found is too old ({version}). Version {MIN_MAJOR_VERSION} or later is needed." + Install::Missing(program) => { + crate::tr!("ffmpeg-missing", program = program.to_string()) + } + Install::TooOld(version) => crate::tr!( + "ffmpeg-too-old", + version = version.clone(), + required = MIN_MAJOR_VERSION ), Install::Ready(_) => String::new(), }); @@ -241,54 +250,54 @@ impl FfmpegHelp { (_, Some(_)) => { ui.horizontal(|ui| { ui.spinner(); - ui.label("Installing FFmpeg with winget: a minute or two…"); + ui.label(crate::tr!("ffmpeg-installing")); }); } (Some(true), None) => { - ui.label(format!( - "It can be installed for you with winget, Windows' package manager: the {} \ - package (gyan.dev's full build, about 100 MB, for your account only).", - crate::ffmpeg::WINGET_PACKAGE + ui.label(crate::tr!( + "ffmpeg-winget-offer", + package = crate::ffmpeg::WINGET_PACKAGE )); - if ui.button("Install FFmpeg for me").clicked() { + if ui.button(crate::tr!("ffmpeg-install-button")).clicked() { action = Some(Action::Install); } ui.label( - egui::RichText::new( - "Installing accepts the package's licence (GPL) and the winget source's terms.", - ) - .small() - .weak(), + egui::RichText::new(crate::tr!("ffmpeg-licence-note")) + .small() + .weak(), ); if let Some(failure) = &self.failure { ui.colored_label(ui.visuals().error_fg_color, failure); } ui.add_space(10.0); - ui.label("Or install it yourself:"); + ui.label(crate::tr!("ffmpeg-or-yourself")); } (None, None) => { ui.horizontal(|ui| { ui.spinner(); - ui.label("Looking for winget…"); + ui.label(crate::tr!("ffmpeg-looking-for-winget")); }); } (Some(false), None) => {} } ui.horizontal(|ui| { - ui.label("In Terminal:"); + ui.label(crate::tr!("ffmpeg-in-terminal")); ui.code(WINGET_COMMAND); - if ui.small_button("Copy").clicked() { + if ui.small_button(crate::tr!("ffmpeg-copy")).clicked() { ui.ctx().copy_text(WINGET_COMMAND.to_owned()); } }); ui.horizontal(|ui| { - ui.label("Or download the \"release full\" build from"); + ui.label(crate::tr!("ffmpeg-download")); ui.hyperlink(FFMPEG_BUILDS); }); - ui.label("unzip it, and add its bin folder to the Path environment variable."); + ui.label(crate::tr!("ffmpeg-unzip")); ui.add_space(12.0); if ui - .add_enabled(self.installing.is_none(), egui::Button::new("Check again")) + .add_enabled( + self.installing.is_none(), + egui::Button::new(crate::tr!("ffmpeg-check-again")), + ) .clicked() { action = Some(Action::CheckAgain); diff --git a/src/app/mod.rs b/src/app/mod.rs index 32df62e..9ce8d95 100644 --- a/src/app/mod.rs +++ b/src/app/mod.rs @@ -14,6 +14,7 @@ mod preview; mod queue_panel; mod settings; mod timeline; +mod update_window; use std::collections::{HashMap, HashSet, VecDeque}; use std::path::{Path, PathBuf}; @@ -62,6 +63,8 @@ struct Preferences { output_dir: Option, volume: f32, muted: bool, + /// The language chosen in *View → Language* (a tag of `i18n::LANGUAGES`); `None` follows the OS. + language: Option, /// Last detected hardware, used until this session's detection finishes. capabilities: Option, } @@ -78,6 +81,7 @@ impl Default for Preferences { output_dir: None, volume: 1.0, muted: false, + language: None, capabilities: None, } } @@ -137,6 +141,10 @@ pub struct TranscoderApp { /// The *Send to* shortcut exists (checked at start and after each change). sendto_installed: bool, show_about: bool, + /// *Help → Check for updates* and its window. + updater: update_window::Updater, + /// The swap script is started: close the window at the next frame. + close_for_update: bool, /// The GPU drawing the window and its driver: with the encoder, the key of a parallelism measurement. gpu: String, /// A running measurement of encodes at once, and its key. @@ -164,6 +172,12 @@ impl TranscoderApp { .storage .and_then(|s| eframe::get_value(s, PREFERENCES_KEY)) .unwrap_or_default(); + // Debug builds: `QVT_LANGUAGE=fr-CA` shows a language without changing the saved choice (screenshots). + #[cfg(debug_assertions)] + let forced = std::env::var("QVT_LANGUAGE").ok(); + #[cfg(not(debug_assertions))] + let forced: Option = None; + crate::i18n::apply(forced.as_deref().or(prefs.language.as_deref())); // Selectable labels sense clicks and drags for text selection, which steals the click from a queue // row under its file name: nothing in this window is text to copy. cc.egui_ctx @@ -179,7 +193,7 @@ impl TranscoderApp { Some(Err(error)) => { log.push_back(( Level::Error, - format!("{error:#}; using the built-in profile"), + crate::tr!("app-profiles-load-failed", detail = format!("{error:#}")), )); ProfileSet::default() } @@ -210,6 +224,8 @@ impl TranscoderApp { incoming, sendto_installed: crate::sendto::is_installed(), show_about: false, + updater: update_window::Updater::new(), + close_for_update: false, gpu: cc .wgpu_render_state .as_ref() @@ -267,7 +283,10 @@ impl TranscoderApp { for path in files { let path = native_separators(path); if path.is_dir() { - self.error(format!("{} is a folder, not a video", path.display())); + self.error(crate::tr!( + "app-folder-not-video", + path = path.display().to_string() + )); continue; } if let Some(dir) = path.parent() { @@ -284,9 +303,9 @@ impl TranscoderApp { fn add_dialog(&mut self) { let mut dialog = rfd::FileDialog::new() - .set_title("Add videos") - .add_filter("Videos", &VIDEO_EXTENSIONS) - .add_filter("All files", &["*"]); + .set_title(crate::tr!("dialog-add-title")) + .add_filter(crate::tr!("dialog-add-filter-videos"), &VIDEO_EXTENSIONS) + .add_filter(crate::tr!("dialog-add-filter-all"), &["*"]); if let Some(dir) = &self.prefs.last_dir { dialog = dialog.set_directory(dir); } @@ -353,21 +372,21 @@ impl TranscoderApp { return; } match crate::clipboard::copy_files(&files) { - Ok(()) => self.info(format!( - "{} file(s) copied: paste them into the conversation", - files.len() - )), + Ok(()) => self.info(crate::tr!("app-files-copied", count = files.len())), Err(error) => self.error(format!("{error:#}")), } } fn save_profiles(&mut self) { let Some(path) = self.profiles_path.clone() else { - self.error("no data folder: the profiles cannot be saved"); + self.error(crate::tr!("app-profiles-no-folder")); return; }; match self.profiles.save(&path) { - Ok(()) => self.info(format!("profiles saved to {}", path.display())), + Ok(()) => self.info(crate::tr!( + "app-profiles-saved", + path = path.display().to_string() + )), Err(error) => self.error(format!("{error:#}")), } } @@ -380,19 +399,25 @@ impl TranscoderApp { self.detection = None; match &install { Install::Ready(version) => self.info(version.clone()), - Install::Missing(program) => self.error(format!("{program} is not on the PATH")), - Install::TooOld(version) => self.error(format!( - "{version}: FFmpeg {} or later is needed", - crate::ffmpeg::MIN_MAJOR_VERSION + Install::Missing(program) => { + self.error(crate::tr!( + "app-ffmpeg-missing", + program = program.to_string() + )); + } + Install::TooOld(version) => self.error(crate::tr!( + "app-ffmpeg-too-old", + version = version.clone(), + required = crate::ffmpeg::MIN_MAJOR_VERSION )), } if !matches!(install, Install::Ready(_)) { self.ffmpeg_help = Some(help::FfmpegHelp::new(install, Arc::clone(&self.notify))); return; } - self.info(format!("hardware: {}", capabilities.summary())); + self.info(crate::tr!("app-hardware", summary = capabilities.summary())); if capabilities.encoders.is_empty() { - self.error("FFmpeg runs, but none of its video encoders works on this computer"); + self.error(crate::tr!("app-no-encoder")); } self.prefs.capabilities = Some(capabilities.clone()); if capabilities != self.queue.capabilities { @@ -426,10 +451,7 @@ impl TranscoderApp { if (known && !again) || self.measuring.is_some() { return; } - self.info(format!( - "measuring how many encodes {} runs at once…", - spec.name - )); + self.info(crate::tr!("app-measuring", encoder = spec.name.to_string())); self.queue.set_paused(true); let (sender, receiver) = crossbeam_channel::bounded(1); let notify = Arc::clone(&self.notify); @@ -448,10 +470,10 @@ impl TranscoderApp { let (key, _) = self.measuring.take().expect("a measurement was running"); self.queue.set_paused(false); let Some(count) = result else { - self.error("the encoder failed while measuring its parallel encodes"); + self.error(crate::tr!("app-measure-failed")); return; }; - self.info(format!("{key}: {count} encode(s) at once")); + self.info(crate::tr!("app-measured", key = key.clone(), count = count)); self.prefs.measured_parallel = Some((key, count)); if !self.prefs.parallel_manual && self.prefs.parallel_encodes != count { self.prefs.parallel_encodes = count; @@ -744,22 +766,22 @@ impl TranscoderApp { fn menu_bar(&mut self, ui: &mut egui::Ui) { egui::MenuBar::new().ui(ui, |ui| { - ui.menu_button("File", |ui| { - if ui.button("Add videos… (Ctrl+O)").clicked() { + ui.menu_button(crate::tr!("menu-file"), |ui| { + if ui.button(crate::tr!("menu-file-add-videos")).clicked() { ui.close(); self.add_dialog(); } if ui .add_enabled( !self.selection.is_empty(), - egui::Button::new("Remove selected (Del)"), + egui::Button::new(crate::tr!("menu-file-remove-selected")), ) .clicked() { ui.close(); self.remove_selected(); } - if ui.button("Remove encoded videos").clicked() { + if ui.button(crate::tr!("menu-file-remove-encoded")).clicked() { ui.close(); self.selection = self .queue @@ -773,17 +795,17 @@ impl TranscoderApp { ui.separator(); self.sendto_menu(ui); ui.separator(); - if ui.button("Quit").clicked() { + if ui.button(crate::tr!("menu-file-quit")).clicked() { ui.ctx().send_viewport_cmd(egui::ViewportCommand::Close); } }); - ui.menu_button("Profiles", |ui| { - if ui.button("Edit profiles…").clicked() { + ui.menu_button(crate::tr!("menu-profiles"), |ui| { + if ui.button(crate::tr!("menu-profiles-edit")).clicked() { ui.close(); self.show_profiles = true; } if let Some(path) = &self.profiles_path - && ui.button("Open profiles.toml folder").clicked() + && ui.button(crate::tr!("menu-profiles-open-folder")).clicked() { ui.close(); if let Some(dir) = path.parent() { @@ -792,21 +814,26 @@ impl TranscoderApp { } } }); - ui.menu_button("View", |ui| { - ui.checkbox(&mut self.show_log, "Log"); + ui.menu_button(crate::tr!("menu-view"), |ui| { + ui.checkbox(&mut self.show_log, crate::tr!("menu-view-log")); + ui.menu_button(crate::tr!("menu-language"), |ui| self.language_menu(ui)); }); - ui.menu_button("Help", |ui| { - if ui.button("Keyboard shortcuts").clicked() { + ui.menu_button(crate::tr!("menu-help"), |ui| { + if ui.button(crate::tr!("menu-help-shortcuts")).clicked() { ui.close(); self.show_shortcuts = true; } - if ui.button("Documentation").clicked() { + if ui.button(crate::tr!("menu-help-documentation")).clicked() { ui.close(); ui.ctx() .open_url(egui::OpenUrl::new_tab(crate::build_info::documentation())); } ui.separator(); - if ui.button("About Quick Video Transcoder").clicked() { + if ui.button(crate::tr!("menu-help-updates")).clicked() { + ui.close(); + self.open_updates(); + } + if ui.button(crate::tr!("menu-help-about")).clicked() { ui.close(); self.show_about = true; } @@ -814,6 +841,21 @@ impl TranscoderApp { }); } + /// *View → Language*: automatic, or one regional variant. Applies at once. + fn language_menu(&mut self, ui: &mut egui::Ui) { + let mut chosen = self.prefs.language.clone(); + ui.radio_value(&mut chosen, None, crate::tr!("language-automatic")); + ui.separator(); + for (tag, name) in crate::i18n::LANGUAGES { + ui.radio_value(&mut chosen, Some(tag.to_owned()), name); + } + if chosen != self.prefs.language { + crate::i18n::apply(chosen.as_deref()); + self.prefs.language = chosen; + ui.ctx().request_repaint(); + } + } + fn status_bar(&mut self, ui: &mut egui::Ui) { ui.horizontal(|ui| { let encoding = self @@ -834,14 +876,17 @@ impl TranscoderApp { .iter() .filter(|j| matches!(j.phase, Phase::Done(_))) .count(); - ui.label(format!( - "{} video(s) · {encoding} encoding · {estimating} estimating · {done} done", - self.queue.jobs.len() + ui.label(crate::tr!( + "status-summary", + total = self.queue.jobs.len(), + encoding = encoding, + estimating = estimating, + done = done )); if self.detection.is_some() { ui.separator(); ui.spinner(); - ui.label("Detecting the encoders…"); + ui.label(crate::tr!("status-detecting")); } if let Some((level, line)) = self.log.back() { ui.separator(); @@ -883,26 +928,67 @@ impl TranscoderApp { } fn shortcuts_window(&mut self, ctx: &egui::Context) { - egui::Window::new("Keyboard shortcuts") + // A fixed id: the title changes with the language, and the window keeps its place. + egui::Window::new(crate::tr!("shortcuts-title")) + .id(egui::Id::unique("shortcuts window")) .open(&mut self.show_shortcuts) .resizable(false) .collapsible(false) .show(ctx, |ui| { egui::Grid::new("shortcuts").striped(true).show(ui, |ui| { for (keys, action) in [ - ("Space", "Play / pause the kept part"), - ("Left / Right", "Previous / next frame"), - ("Shift + Left / Right", "-1 s / +1 s"), - ("Page Up / Down", "-10 s / +10 s"), - ("I / O", "Start / end of the kept part at the current frame"), - ("Home / End", "Go to the start / end of the kept part"), - ("M", "Mute / unmute"), - ("Ctrl + O", "Add videos"), - ("Ctrl + A", "Select every video"), - ("Ctrl + E", "Encode the selected videos"), - ("Delete", "Remove the selected videos"), - ("Drag a handle", "Move the start or end of the kept part"), - ("Shift + drag", "Move the kept part as a whole"), + ( + crate::tr!("shortcuts-play-keys"), + crate::tr!("shortcuts-play-action"), + ), + ( + crate::tr!("shortcuts-step-keys"), + crate::tr!("shortcuts-step-action"), + ), + ( + crate::tr!("shortcuts-second-keys"), + crate::tr!("shortcuts-second-action"), + ), + ( + crate::tr!("shortcuts-ten-seconds-keys"), + crate::tr!("shortcuts-ten-seconds-action"), + ), + ( + crate::tr!("shortcuts-trim-keys"), + crate::tr!("shortcuts-trim-action"), + ), + ( + crate::tr!("shortcuts-goto-keys"), + crate::tr!("shortcuts-goto-action"), + ), + ( + crate::tr!("shortcuts-mute-keys"), + crate::tr!("shortcuts-mute-action"), + ), + ( + crate::tr!("shortcuts-add-keys"), + crate::tr!("shortcuts-add-action"), + ), + ( + crate::tr!("shortcuts-select-all-keys"), + crate::tr!("shortcuts-select-all-action"), + ), + ( + crate::tr!("shortcuts-encode-keys"), + crate::tr!("shortcuts-encode-action"), + ), + ( + crate::tr!("shortcuts-delete-keys"), + crate::tr!("shortcuts-delete-action"), + ), + ( + crate::tr!("shortcuts-handle-keys"), + crate::tr!("shortcuts-handle-action"), + ), + ( + crate::tr!("shortcuts-shift-drag-keys"), + crate::tr!("shortcuts-shift-drag-action"), + ), ] { ui.monospace(keys); ui.label(action); @@ -924,13 +1010,13 @@ impl TranscoderApp { }) .collect(); let title = if encoding.is_empty() { - format!("Quick Video Transcoder — {total} video(s)") + crate::tr!("title-idle", total = total) } else { let average = encoding.iter().sum::() / encoding.len() as f32; - format!( - "Quick Video Transcoder — encoding {} ({:.0} %)", - encoding.len(), - average * 100.0 + crate::tr!( + "title-encoding", + count = encoding.len(), + percent = f64::from(average * 100.0) ) }; if title != self.title { @@ -990,8 +1076,8 @@ impl TranscoderApp { .any(|j| matches!(j.phase, Phase::Encoding(_) | Phase::Waiting)); if ctx.input(|i| i.viewport().close_requested()) && running { let quit = rfd::MessageDialog::new() - .set_title("Encodes running") - .set_description("Closing stops the running encodes and deletes their partial files. Close anyway?") + .set_title(crate::tr!("dialog-close-title")) + .set_description(crate::tr!("dialog-close-description")) .set_buttons(rfd::MessageButtons::YesNo) .set_level(rfd::MessageLevel::Warning) .show(); @@ -1091,6 +1177,7 @@ impl eframe::App for TranscoderApp { self.handle_dropped_files(&ctx); self.handle_shortcuts(&ctx); self.poll_incoming(&ctx); + self.poll_updates(); self.poll_queue(); self.poll_thumbnails(&ctx); self.update_player(&ctx); @@ -1123,6 +1210,10 @@ impl eframe::App for TranscoderApp { self.shortcuts_window(&ctx); self.profiles_window(&ctx); self.about_window(&ctx); + self.update_window(&ctx); + if self.close_for_update { + ctx.send_viewport_cmd(egui::ViewportCommand::Close); + } self.ffmpeg_window(&ctx); self.take_screenshot(&ctx); } diff --git a/src/app/preview.rs b/src/app/preview.rs index 82205c4..1d8c8a6 100644 --- a/src/app/preview.rs +++ b/src/app/preview.rs @@ -17,11 +17,11 @@ impl TranscoderApp { } let (Some(texture), Some(size)) = (&self.frame_texture, self.frame_size) else { let text = if self.queue.jobs.is_empty() { - "Drop game captures here, or add them with Ctrl+O" + crate::tr!("preview-empty-queue") } else if self.playing_job.is_some() { - "Decoding…" + crate::tr!("preview-decoding") } else { - "Select a video" + crate::tr!("preview-select-video") }; painter.text( area.center(), @@ -51,27 +51,47 @@ impl TranscoderApp { let Some(media) = &job.media else { return }; let mut lines = Vec::new(); if let Some(size) = self.frame_size { - let mut line = format!( - "Preview {size} · source {}x{} {}", - media.width, - media.height, - codec_label(&media.codec) - ); - if media.dynamic.is_hdr() { - let shown = if job.profile.sdr_only { - "tone mapped as encoded" - } else { - "kept HDR, shown tone mapped" - }; - line.push_str(&format!(" · {} {shown}", media.dynamic.label())); - } + let size = size.to_string(); + let width = media.width.to_string(); + let height = media.height.to_string(); + let codec = codec_label(&media.codec); + let line = if !media.dynamic.is_hdr() { + crate::tr!( + "preview-info", + size = size, + width = width, + height = height, + codec = codec + ) + } else if job.profile.sdr_only { + crate::tr!( + "preview-info-hdr-encoded", + size = size, + width = width, + height = height, + codec = codec, + dynamic = media.dynamic.label() + ) + } else { + crate::tr!( + "preview-info-hdr-kept", + size = size, + width = width, + height = height, + codec = codec, + dynamic = media.dynamic.label() + ) + }; lines.push(line); } if self.player.is_loading() { - lines.push("Seeking…".to_owned()); + lines.push(crate::tr!("preview-seeking")); } if let Some(error) = self.player.error() { - lines.push(format!("Decoder: {error}")); + lines.push(crate::tr!( + "preview-decoder-error", + detail = error.to_string() + )); } let font = FontId::monospace(12.5); let mut pos = area.left_top() + vec2(10.0, 8.0); diff --git a/src/app/queue_panel.rs b/src/app/queue_panel.rs index f22795e..9bafbaf 100644 --- a/src/app/queue_panel.rs +++ b/src/app/queue_panel.rs @@ -30,11 +30,11 @@ impl TranscoderApp { pub(super) fn queue_panel(&mut self, ui: &mut egui::Ui) { ui.add_space(6.0); ui.horizontal(|ui| { - ui.heading("Queue"); + ui.heading(crate::tr!("queue-panel-heading")); ui.with_layout(Layout::right_to_left(Align::Center), |ui| { if ui - .button("➕ Add…") - .on_hover_text("Add videos (Ctrl+O), or drop them here") + .button(format!("➕ {}", crate::tr!("queue-panel-add"))) + .on_hover_text(crate::tr!("queue-panel-add-tooltip")) .clicked() { self.add_dialog(); @@ -48,8 +48,12 @@ impl TranscoderApp { if self.queue.jobs.is_empty() { ui.add_space(40.0); ui.vertical_centered(|ui| { - ui.label(RichText::new("Drop videos here").size(18.0).weak()); - ui.label(RichText::new("or use Explorer's Send to menu").weak()); + ui.label( + RichText::new(crate::tr!("queue-panel-empty-title")) + .size(18.0) + .weak(), + ); + ui.label(RichText::new(crate::tr!("queue-panel-empty-hint")).weak()); }); return; } @@ -185,20 +189,21 @@ impl TranscoderApp { let kept = job.trim.duration(); let trimmed = (kept - media.duration).abs() > 0.05; let duration = if trimmed { - format!( - "{} of {}", - timecode::format_short(kept, true), - timecode::format_short(media.duration, false) + crate::tr!( + "queue-panel-duration-trimmed", + kept = timecode::format_short(kept, true), + total = timecode::format_short(media.duration, false) ) } else { timecode::format_short(kept, true) }; ui.add( egui::Label::new( - RichText::new(format!( - "{} · {duration} · {}", - media.summary(), - job.profile.name + RichText::new(crate::tr!( + "queue-panel-row-details", + summary = media.summary(), + duration = duration, + profile = job.profile.name.clone() )) .small() .weak(), @@ -211,7 +216,7 @@ impl TranscoderApp { Phase::Probing => { ui.horizontal(|ui| { ui.spinner(); - ui.label(RichText::new("Reading…").small()); + ui.label(RichText::new(crate::tr!("queue-panel-reading")).small()); }); } Phase::Unusable(error) => { @@ -227,55 +232,58 @@ impl TranscoderApp { Phase::Estimating => { ui.horizontal(|ui| { ui.spinner(); - ui.label(RichText::new("Estimating the size…").small()); + ui.label(RichText::new(crate::tr!("queue-panel-estimating")).small()); }); } Phase::Waiting => { ui.horizontal(|ui| { - ui.label(RichText::new("Waiting for an encoder…").small()); - if ui.small_button("Cancel").clicked() { + ui.label(RichText::new(crate::tr!("queue-panel-waiting")).small()); + if ui.small_button(crate::tr!("queue-panel-cancel")).clicked() { action = Some(RowAction::Cancel); } }); } Phase::Encoding(progress) => { ui.horizontal(|ui| { - let mut text = format!("{:.0} %", progress.fraction * 100.0); - if let Some(speed) = progress.speed { - text.push_str(&format!(" · {speed:.1}x")); - } - if progress.attempt > 1 { - text.push_str(&format!(" · retry {}", progress.attempt - 1)); - } + let text = crate::tr!( + "queue-panel-progress", + percent = f64::from(progress.fraction * 100.0), + speed = progress.speed.unwrap_or(0.0), + retry = progress.attempt.saturating_sub(1) + ); ui.add( egui::ProgressBar::new(progress.fraction) .desired_width(ui.available_width() - 60.0) .desired_height(14.0) .text(RichText::new(text).small()), ); - if ui.small_button("Cancel").clicked() { + if ui.small_button(crate::tr!("queue-panel-cancel")).clicked() { action = Some(RowAction::Cancel); } }); } Phase::Done(encoded) => { ui.horizontal(|ui| { + let mb = encoded.bytes as f64 / 1e6; ui.label( - RichText::new(format!("✔ {:.2} MB", encoded.bytes as f64 / 1e6)) - .small() - .color(GOOD), + RichText::new(format!( + "✔ {}", + crate::tr!("queue-panel-done-size", mb = mb) + )) + .small() + .color(GOOD), ) .on_hover_text(encoded.output.display().to_string()); if ui - .small_button("Copy") - .on_hover_text("Copy the file, to paste it into the conversation") + .small_button(crate::tr!("queue-panel-copy")) + .on_hover_text(crate::tr!("queue-panel-copy-tooltip")) .clicked() { action = Some(RowAction::Copy); } if ui - .small_button("Show") - .on_hover_text("Show in Explorer") + .small_button(crate::tr!("queue-panel-show")) + .on_hover_text(crate::tr!("queue-panel-show-tooltip")) .clicked() { action = Some(RowAction::Reveal); @@ -300,13 +308,14 @@ impl TranscoderApp { Verdict::Fitted => ui.visuals().text_color(), Verdict::BelowFloor => WARN, }; - let wanted = if job.wanted { " · queued" } else { "" }; + let mb = estimate.predicted_bytes as f64 / 1e6; ui.label( - RichText::new(format!( - "{} · ≈ {:.1} MB · {}{wanted}", - estimate.target.label(), - estimate.predicted_bytes as f64 / 1e6, - quality_word(estimate.quality) + RichText::new(crate::tr!( + "queue-panel-estimate", + target = estimate.target.label(), + mb = mb, + quality = quality_word(estimate.quality).to_string(), + queued = if job.wanted { "yes" } else { "no" } )) .small() .color(color), @@ -324,7 +333,11 @@ impl TranscoderApp { .on_hover_text(error); } None => { - ui.label(RichText::new("Settings changed…").small().weak()); + ui.label( + RichText::new(crate::tr!("queue-panel-settings-changed")) + .small() + .weak(), + ); } }, } @@ -349,12 +362,16 @@ impl TranscoderApp { .count(); ui.horizontal_wrapped(|ui| { let encode = egui::Button::new( - RichText::new(format!("▶ Encode selected ({selected_ready})")).strong(), + RichText::new(format!( + "▶ {}", + crate::tr!("queue-panel-encode-selected", count = selected_ready) + )) + .strong(), ) .fill(ACCENT.gamma_multiply(0.6)); if ui .add_enabled(selected_ready > 0, encode) - .on_hover_text("Encode the selected videos with their estimate (Ctrl+E)") + .on_hover_text(crate::tr!("queue-panel-encode-selected-tooltip")) .clicked() { self.encode_selected(); @@ -362,7 +379,7 @@ impl TranscoderApp { if ui .add_enabled( all_ready > 0, - egui::Button::new(format!("Encode all ({all_ready})")), + egui::Button::new(crate::tr!("queue-panel-encode-all", count = all_ready)), ) .clicked() { @@ -376,7 +393,10 @@ impl TranscoderApp { .map(|j| j.id) .collect(); if ui - .add_enabled(!running.is_empty(), egui::Button::new("⏹ Stop all")) + .add_enabled( + !running.is_empty(), + egui::Button::new(format!("⏹ {}", crate::tr!("queue-panel-stop-all"))), + ) .clicked() { for id in running { @@ -387,9 +407,9 @@ impl TranscoderApp { if ui .add_enabled( !done.is_empty(), - egui::Button::new(format!("Copy encoded ({})", done.len())), + egui::Button::new(crate::tr!("queue-panel-copy-encoded", count = done.len())), ) - .on_hover_text("Copy every encoded file, to paste them into a conversation") + .on_hover_text(crate::tr!("queue-panel-copy-encoded-tooltip")) .clicked() { self.copy_outputs(done); diff --git a/src/app/settings.rs b/src/app/settings.rs index d6557dc..40bbc57 100644 --- a/src/app/settings.rs +++ b/src/app/settings.rs @@ -99,8 +99,13 @@ impl TranscoderApp { match focus.and_then(|id| self.queue.get(id)) { Some(job) => { if selected.len() > 1 { - ui.heading(format!("{} videos selected", selected.len())); - ui.label(RichText::new("A change applies to each of them").weak()); + ui.heading(crate::tr!( + "settings-heading-selected", + count = selected.len() + )); + ui.label( + RichText::new(crate::tr!("settings-change-applies-to-all")).weak(), + ); } else { ui.add( egui::Label::new(RichText::new(job.name()).heading()).truncate(), @@ -109,7 +114,7 @@ impl TranscoderApp { } } None => { - ui.heading("No video selected"); + ui.heading(crate::tr!("settings-no-video")); } } if let Some(focus) = focus { @@ -132,11 +137,11 @@ impl TranscoderApp { .as_ref() .is_some_and(|p| p.name == before.name && *p != before); - section(ui, "Profile"); + section(ui, &crate::tr!("settings-section-profile")); let mut chosen: Option = None; ui.horizontal(|ui| { let label = if modified { - format!("{} (changed)", job.profile_name) + crate::tr!("settings-profile-changed", name = job.profile_name.as_str()) } else { job.profile_name.clone() }; @@ -156,8 +161,8 @@ impl TranscoderApp { if modified && let Some(origin) = &origin && ui - .button("Reset") - .on_hover_text("Back to the profile's settings") + .button(crate::tr!("settings-profile-reset")) + .on_hover_text(crate::tr!("settings-profile-reset-tooltip")) .clicked() { chosen = Some(origin.clone()); @@ -193,13 +198,13 @@ impl TranscoderApp { let backend = self.queue.settings.backend; let resolved = |codecs: &[VideoCodec]| { capabilities.choose(codecs, backend).map_or_else( - || "no encoder".to_owned(), + || crate::tr!("settings-codec-no-encoder"), |spec| format!("{} ({})", spec.codec.label(), spec.backend.label()), ) }; let list_label = |codecs: &[VideoCodec]| { if codecs.len() == 1 { - format!("{} only", codecs[0].label()) + crate::tr!("settings-codec-only", codec = codecs[0].label()) } else { codecs .iter() @@ -212,20 +217,25 @@ impl TranscoderApp { .num_columns(2) .spacing([12.0, 6.0]) .show(ui, |ui| { - ui.label("Size limit"); + ui.label(crate::tr!("settings-size-limit")); ui.add( egui::DragValue::new(&mut after.max_size_mb) .range(0.5..=4000.0) .speed(0.5) .max_decimals(1) - .suffix(" MB"), + // Shown and typed in the user's format ("25,0 Mo"): either separator is read. + .custom_formatter(|mb, _| crate::tr!("settings-size-value", mb = mb)) + .custom_parser(parse_localized_number), ) - .on_hover_text("Megabytes of 1,000,000 bytes"); + .on_hover_text(crate::tr!("settings-size-limit-tooltip")); ui.end_row(); - ui.label("Resolution"); + ui.label(crate::tr!("settings-resolution")); egui::ComboBox::from_id_salt("short side") - .selected_text(format!("up to {}p", after.max_short_side)) + .selected_text(crate::tr!( + "settings-resolution-up-to", + short = after.max_short_side.to_string() + )) .show_ui(ui, |ui| { for short in SHORT_SIDES { ui.selectable_value( @@ -237,17 +247,21 @@ impl TranscoderApp { }); ui.end_row(); - ui.label("Frame rate"); + ui.label(crate::tr!("settings-frame-rate")); egui::ComboBox::from_id_salt("fps") - .selected_text(format!("up to {} fps", after.max_fps)) + .selected_text(crate::tr!("settings-frame-rate-up-to", fps = after.max_fps)) .show_ui(ui, |ui| { for fps in FRAME_RATES { - ui.selectable_value(&mut after.max_fps, fps, format!("{fps} fps")); + ui.selectable_value( + &mut after.max_fps, + fps, + crate::tr!("settings-fps-value", fps = fps), + ); } }); ui.end_row(); - ui.label("Codec"); + ui.label(crate::tr!("settings-codec")); egui::ComboBox::from_id_salt("codec") .selected_text(format!( "{} ➡ {}", @@ -262,25 +276,20 @@ impl TranscoderApp { } }) .response - .on_hover_text( - "The codecs the destination plays, preferred first: the first one your GPU \ - encodes is used, else the first one the CPU encodes", - ); + .on_hover_text(crate::tr!("settings-codec-tooltip")); ui.end_row(); - ui.label("HDR"); + ui.label(crate::tr!("settings-hdr")); ui.add_enabled( after.codecs.iter().any(|c| c.supports_hdr()), - egui::Checkbox::new(&mut after.sdr_only, "Convert to SDR"), - ) - .on_hover_text( - "Off: an HDR video stays HDR (10-bit); phones without HDR show it washed out", + egui::Checkbox::new(&mut after.sdr_only, crate::tr!("settings-hdr-convert")), ) - .on_disabled_hover_text("H.264 cannot carry HDR"); + .on_hover_text(crate::tr!("settings-hdr-convert-tooltip")) + .on_disabled_hover_text(crate::tr!("settings-hdr-convert-disabled-tooltip")); ui.end_row(); let hdr_source = media.as_ref().is_some_and(|m| m.dynamic.is_hdr()); - ui.label("Tone mapping"); + ui.label(crate::tr!("settings-tone-mapping")); ui.add_enabled_ui(hdr_source || selected.len() > 1, |ui| { egui::ComboBox::from_id_salt("tone") .selected_text(after.tone_mapping.label()) @@ -291,10 +300,10 @@ impl TranscoderApp { }); }) .response - .on_disabled_hover_text("This video is SDR"); + .on_disabled_hover_text(crate::tr!("settings-tone-mapping-disabled-tooltip")); ui.end_row(); - ui.label("Sound"); + ui.label(crate::tr!("settings-sound")); egui::ComboBox::from_id_salt("audio") .selected_text(audio_label(after.audio, media.as_ref())) .width(220.0) @@ -304,7 +313,7 @@ impl TranscoderApp { AudioChoice::Auto, audio_label(AudioChoice::Auto, media.as_ref()), ) - .on_hover_text("The game's track: the first one whose name is not a microphone or a voice chat"); + .on_hover_text(crate::tr!("settings-sound-auto-tooltip")); if let Some(media) = &media { for track in &media.audio { let choice = AudioChoice::Track(track.index); @@ -318,70 +327,101 @@ impl TranscoderApp { ui.selectable_value( &mut after.audio, AudioChoice::MixAll, - "Every track mixed", + crate::tr!("settings-sound-mix-all"), + ); + ui.selectable_value( + &mut after.audio, + AudioChoice::None, + crate::tr!("settings-sound-none"), ); - ui.selectable_value(&mut after.audio, AudioChoice::None, "No sound"); }); ui.end_row(); - ui.label("Sound bitrate"); + ui.label(crate::tr!("settings-sound-bitrate")); egui::ComboBox::from_id_salt("audio rate") - .selected_text(format!("{} kbit/s", after.audio_bitrate_kbps)) + .selected_text(crate::tr!( + "settings-kbps-value", + kbps = after.audio_bitrate_kbps + )) .show_ui(ui, |ui| { for rate in AUDIO_RATES { ui.selectable_value( &mut after.audio_bitrate_kbps, rate, - format!("{rate} kbit/s"), + crate::tr!("settings-kbps-value", kbps = rate), ); } }); ui.end_row(); }); - egui::CollapsingHeader::new("Quality bounds") + egui::CollapsingHeader::new(crate::tr!("settings-quality-bounds")) .id_salt("quality bounds") .show(ui, |ui| { - egui::Grid::new("quality").num_columns(2).spacing([12.0, 6.0]).show(ui, |ui| { - ui.label("Best worth it").on_hover_text( - "Past this quality the extra bytes are not visible: an easy clip ends up smaller than the limit", - ); - ui.add( - egui::Slider::new(&mut after.quality_ceiling, 14..=30) - .clamping(egui::SliderClamping::Edits) - .custom_formatter(|v, _| format!("QP {v} ({})", quality_word(v))), - ); - ui.end_row(); - ui.label("Worst accepted").on_hover_text( - "Below this quality the frame rate, then the resolution, are lowered", - ); - ui.add( - egui::Slider::new(&mut after.quality_floor, 24..=42) - .clamping(egui::SliderClamping::Edits) - .custom_formatter(|v, _| format!("QP {v} ({})", quality_word(v))), - ); - ui.end_row(); - ui.label("Lowest resolution"); - egui::ComboBox::from_id_salt("min short side") - .selected_text(format!("{}p", after.min_short_side)) - .show_ui(ui, |ui| { - for short in SHORT_SIDES.into_iter().filter(|&s| s <= after.max_short_side) { - ui.selectable_value(&mut after.min_short_side, short, format!("{short}p")); - } - }); - ui.end_row(); - ui.label("Lowest frame rate"); - egui::ComboBox::from_id_salt("min fps") - .selected_text(format!("{} fps", after.min_fps)) - .show_ui(ui, |ui| { - for fps in FRAME_RATES.into_iter().filter(|&f| f <= after.max_fps) { - ui.selectable_value(&mut after.min_fps, fps, format!("{fps} fps")); - } - }); - ui.end_row(); - ui.label("File name suffix"); - ui.add(egui::TextEdit::singleline(&mut after.suffix).desired_width(120.0)); - ui.end_row(); - }); + egui::Grid::new("quality") + .num_columns(2) + .spacing([12.0, 6.0]) + .show(ui, |ui| { + ui.label(crate::tr!("settings-best-worth-it")) + .on_hover_text(crate::tr!("settings-best-worth-it-tooltip")); + ui.add( + egui::Slider::new(&mut after.quality_ceiling, 14..=30) + .clamping(egui::SliderClamping::Edits) + .custom_formatter(|v, _| { + crate::tr!( + "settings-quality-value", + qp = v, + word = quality_word(v) + ) + }), + ); + ui.end_row(); + ui.label(crate::tr!("settings-worst-accepted")) + .on_hover_text(crate::tr!("settings-worst-accepted-tooltip")); + ui.add( + egui::Slider::new(&mut after.quality_floor, 24..=42) + .clamping(egui::SliderClamping::Edits) + .custom_formatter(|v, _| { + crate::tr!( + "settings-quality-value", + qp = v, + word = quality_word(v) + ) + }), + ); + ui.end_row(); + ui.label(crate::tr!("settings-lowest-resolution")); + egui::ComboBox::from_id_salt("min short side") + .selected_text(format!("{}p", after.min_short_side)) + .show_ui(ui, |ui| { + for short in SHORT_SIDES + .into_iter() + .filter(|&s| s <= after.max_short_side) + { + ui.selectable_value( + &mut after.min_short_side, + short, + format!("{short}p"), + ); + } + }); + ui.end_row(); + ui.label(crate::tr!("settings-lowest-frame-rate")); + egui::ComboBox::from_id_salt("min fps") + .selected_text(crate::tr!("settings-fps-value", fps = after.min_fps)) + .show_ui(ui, |ui| { + for fps in FRAME_RATES.into_iter().filter(|&f| f <= after.max_fps) { + ui.selectable_value( + &mut after.min_fps, + fps, + crate::tr!("settings-fps-value", fps = fps), + ); + } + }); + ui.end_row(); + ui.label(crate::tr!("settings-file-name-suffix")); + ui.add(egui::TextEdit::singleline(&mut after.suffix).desired_width(120.0)); + ui.end_row(); + }); }); after.sanitize(); if after != before { @@ -402,19 +442,19 @@ impl TranscoderApp { ui.horizontal(|ui| { ui.add( egui::TextEdit::singleline(&mut self.new_profile_name) - .hint_text("Profile name") + .hint_text(crate::tr!("settings-profile-name-hint")) .desired_width(150.0), ); let name = self.new_profile_name.trim().to_owned(); let exists = self.profiles.find(&name).is_some(); let label = if exists { - "Update profile" + crate::tr!("settings-profile-update") } else { - "Save as profile" + crate::tr!("settings-profile-save") }; if ui .add_enabled(!name.is_empty(), egui::Button::new(label)) - .on_hover_text("Keep these settings as a profile for later videos") + .on_hover_text(crate::tr!("settings-profile-save-tooltip")) .clicked() { let mut profile = after.clone(); @@ -440,9 +480,9 @@ impl TranscoderApp { let Some(duration) = job.media.as_ref().map(|m| m.duration) else { return; }; - section(ui, "Kept part"); + section(ui, &crate::tr!("settings-section-kept-part")); if selected > 1 { - ui.label(RichText::new("The kept part is set video by video, on the timeline").weak()); + ui.label(RichText::new(crate::tr!("settings-kept-part-multi-note")).weak()); } let trim = job.trim; let mut start_text = ui @@ -457,17 +497,17 @@ impl TranscoderApp { .num_columns(2) .spacing([12.0, 6.0]) .show(ui, |ui| { - ui.label("Start"); + ui.label(crate::tr!("settings-trim-start")); ui.push_id(("start", focus), |ui| { start_edit = time_edit(ui, &mut start_text, trim.start) }); ui.end_row(); - ui.label("End"); + ui.label(crate::tr!("settings-trim-end")); ui.push_id(("end", focus), |ui| { end_edit = time_edit(ui, &mut end_text, trim.end) }); ui.end_row(); - ui.label("Duration"); + ui.label(crate::tr!("settings-trim-duration")); ui.monospace(timecode::format_precise(trim.duration())); ui.end_row(); }); @@ -478,13 +518,15 @@ impl TranscoderApp { let reset = ui .add_enabled( trim.start > 0.0 || trim.end < duration, - egui::Button::new("Keep everything"), + egui::Button::new(crate::tr!("settings-keep-everything")), ) .clicked(); if self.focus == Some(focus) { match start_edit { TimeEdit::Set(seconds) => self.set_trim_start(seconds), - TimeEdit::Invalid(text) => self.error(format!("not a time: {text}")), + TimeEdit::Invalid(text) => { + self.error(crate::tr!("settings-not-a-time", text = text)); + } TimeEdit::Unchanged => {} } match end_edit { @@ -497,7 +539,9 @@ impl TranscoderApp { .map_or(0.0, |m| 1.0 / m.fps()); self.set_trim_end(seconds - frame); } - TimeEdit::Invalid(text) => self.error(format!("not a time: {text}")), + TimeEdit::Invalid(text) => { + self.error(crate::tr!("settings-not-a-time", text = text)); + } TimeEdit::Unchanged => {} } } @@ -513,7 +557,7 @@ impl TranscoderApp { return; }; let Some(media) = &job.media else { return }; - section(ui, "Estimate"); + section(ui, &crate::tr!("settings-section-estimate")); let key = self.queue.key(job); let duration = job.trim.duration(); let audio = plan::audio_kbps(media, &job.profile); @@ -521,48 +565,52 @@ impl TranscoderApp { match job.current_estimate(key.as_ref()) { Some(Ok(estimate)) => { let (text, color) = match estimate.verdict { - Verdict::BestQuality => ( - "Fits at the best quality worth it: the file will be smaller than the limit", - GOOD, - ), - Verdict::Fitted => ("Fills the size limit", ui.visuals().text_color()), - Verdict::BelowFloor => ( - "Below the worst accepted quality even at the lowest settings: shorten the kept part", - WARN, + Verdict::BestQuality => (crate::tr!("settings-verdict-best-quality"), GOOD), + Verdict::Fitted => ( + crate::tr!("settings-verdict-fitted"), + ui.visuals().text_color(), ), + Verdict::BelowFloor => (crate::tr!("settings-verdict-below-floor"), WARN), }; ui.label(RichText::new(text).color(color)); egui::Grid::new("estimate") .num_columns(2) .spacing([12.0, 4.0]) .show(ui, |ui| { - ui.label("Output"); - ui.label(format!( - "{} at {} fps ({})", - estimate.target.size, - estimate.target.rate.label(), - estimate.target.label() + ui.label(crate::tr!("settings-estimate-output")); + ui.label(crate::tr!( + "settings-estimate-output-value", + size = estimate.target.size.to_string(), + fps = estimate.target.rate.label(), + target = estimate.target.label() )); ui.end_row(); - ui.label("Video bitrate"); - ui.label(format!("{:.0} kbit/s", estimate.video_bps / 1000.0)); + ui.label(crate::tr!("settings-estimate-video-bitrate")); + ui.label(crate::tr!( + "settings-kbps-value", + kbps = (estimate.video_bps / 1000.0).round() + )); ui.end_row(); - ui.label("Quality"); - ui.label(format!( - "{} (QP {:.1})", - quality_word(estimate.quality), - estimate.quality + ui.label(crate::tr!("settings-estimate-quality")); + ui.label(crate::tr!( + "settings-estimate-quality-value", + word = quality_word(estimate.quality), + qp = estimate.quality )); ui.end_row(); - ui.label("Size"); - ui.label(format!( - "≈ {:.1} MB of {:.1} MB", - estimate.predicted_bytes as f64 / 1e6, - job.profile.max_size_mb + ui.label(crate::tr!("settings-estimate-size")); + let predicted_mb: f64 = estimate.predicted_bytes as f64 / 1e6; + ui.label(crate::tr!( + "settings-estimate-size-value", + predicted = predicted_mb, + limit = job.profile.max_size_mb )); ui.end_row(); - ui.label("Measured"); - ui.label(format!("{} sample encode(s)", estimate.measurements)); + ui.label(crate::tr!("settings-estimate-measured")); + ui.label(crate::tr!( + "settings-estimate-measured-value", + count = estimate.measurements + )); ui.end_row(); }); } @@ -572,38 +620,48 @@ impl TranscoderApp { None => { ui.horizontal(|ui| { ui.spinner(); - ui.label("Estimating…"); + ui.label(crate::tr!("settings-estimating")); }); if let Some(bps) = budget { ui.label( - RichText::new(format!("Budget: {:.0} kbit/s of video", bps / 1000.0)) - .weak(), + RichText::new(crate::tr!( + "settings-estimate-budget", + kbps = (bps / 1000.0).round() + )) + .weak(), ); } } } if let Some(engine) = job.engine { ui.label( - RichText::new(format!("Filters: {}", engine.label())) - .weak() - .small(), + RichText::new(crate::tr!( + "settings-estimate-filters", + engine = engine.label() + )) + .weak() + .small(), ); } } fn output_section(&mut self, ui: &mut egui::Ui) { - section(ui, "Output"); + section(ui, &crate::tr!("settings-section-output")); let mut settings = self.queue.settings.clone(); ui.horizontal(|ui| { let folder = settings.output_dir.as_ref().map_or_else( - || "Next to each video".to_owned(), + || crate::tr!("settings-output-next-to-video"), |d| d.display().to_string(), ); ui.add(egui::Label::new(folder).truncate()); }); ui.horizontal(|ui| { - if ui.button("Choose folder…").clicked() { - let mut dialog = rfd::FileDialog::new().set_title("Output folder"); + if ui + .button(crate::tr!("settings-output-choose-folder")) + .clicked() + { + let mut dialog = rfd::FileDialog::new() + .set_title(crate::tr!("settings-output-folder-dialog-title")); if let Some(dir) = settings .output_dir .as_ref() @@ -618,7 +676,7 @@ impl TranscoderApp { if ui .add_enabled( settings.output_dir.is_some(), - egui::Button::new("Next to each video"), + egui::Button::new(crate::tr!("settings-output-use-next-to-video")), ) .clicked() { @@ -629,12 +687,19 @@ impl TranscoderApp { .num_columns(2) .spacing([12.0, 6.0]) .show(ui, |ui| { - ui.label("Encoder"); - let label = settings.backend.map_or("Automatic", EncoderBackend::label); + ui.label(crate::tr!("settings-encoder")); + let label = settings.backend.map_or_else( + || crate::tr!("settings-encoder-automatic"), + |backend| backend.label().to_owned(), + ); egui::ComboBox::from_id_salt("backend") .selected_text(label) .show_ui(ui, |ui| { - ui.selectable_value(&mut settings.backend, None, "Automatic"); + ui.selectable_value( + &mut settings.backend, + None, + crate::tr!("settings-encoder-automatic"), + ); for backend in EncoderBackend::ALL { let works = VideoCodec::ALL .into_iter() @@ -649,16 +714,13 @@ impl TranscoderApp { } }); ui.end_row(); - ui.label("Encodes at once"); + ui.label(crate::tr!("settings-parallel-encodes")); let measured = self.prefs.measured_parallel.as_ref().map(|(_, n)| *n); let slider = ui .add(egui::Slider::new(&mut settings.parallel_encodes, 1..=6)) .on_hover_text(match measured { - Some(n) => format!( - "Measured on this GPU: {n} at once before encodes slow each other down \ - (an RTX 4090 has two NVENC engines, an RTX 3080 one)" - ), - None => "Not measured yet".to_owned(), + Some(n) => crate::tr!("settings-parallel-measured-tooltip", count = n), + None => crate::tr!("settings-parallel-not-measured-tooltip"), }); if slider.changed() { self.prefs.parallel_manual = true; @@ -668,23 +730,25 @@ impl TranscoderApp { ui.horizontal(|ui| { let measuring = self.measuring.is_some(); let text = match (measuring, measured) { - (true, _) => "measuring…".to_owned(), - (false, Some(n)) => format!("measured: {n}"), - (false, None) => "not measured".to_owned(), + (true, _) => crate::tr!("settings-parallel-measuring"), + (false, Some(n)) => crate::tr!("settings-parallel-measured", count = n), + (false, None) => crate::tr!("settings-parallel-not-measured"), }; ui.label(egui::RichText::new(text).weak().small()); let back = self.prefs.parallel_manual && measured.is_some_and(|n| n != settings.parallel_encodes); - if back && ui.small_button("Use it").clicked() { + if back + && ui + .small_button(crate::tr!("settings-parallel-use-measured")) + .clicked() + { self.prefs.parallel_manual = false; settings.parallel_encodes = measured.unwrap_or(settings.parallel_encodes); } if !measuring && ui - .small_button("Measure again") - .on_hover_text( - "A few seconds; new estimates and encodes wait meanwhile", - ) + .small_button(crate::tr!("settings-parallel-measure-again")) + .on_hover_text(crate::tr!("settings-parallel-measure-again-tooltip")) .clicked() { self.prefs.parallel_manual = false; @@ -709,41 +773,63 @@ impl TranscoderApp { let mut changed = false; let mut remove = None; let mut raise = None; - egui::Window::new("Profiles") + egui::Window::new(crate::tr!("profiles-title")) .open(&mut open) .collapsible(false) .default_width(460.0) .show(ctx, |ui| { - ui.label("The first profile is given to new videos. A profile is changed by saving a video's settings under its name."); + ui.label(crate::tr!("profiles-intro")); ui.add_space(6.0); let count = self.profiles.profiles.len(); - egui::Grid::new("profiles list").striped(true).num_columns(4).show(ui, |ui| { - for (index, profile) in self.profiles.profiles.iter_mut().enumerate() { - let response = ui.add(egui::TextEdit::singleline(&mut profile.name).desired_width(140.0)); - if response.lost_focus() && response.changed() { - changed = true; - } - changed |= response.changed(); - ui.label( - RichText::new(format!( - "{:.0} MB · {}p{} · {}{}", - profile.max_size_mb, - profile.max_short_side, - profile.max_fps, - profile.codecs_label(), - if profile.sdr_only { " · SDR" } else { "" } - )) - .weak(), - ); - if ui.add_enabled(index > 0, egui::Button::new("⏶")).on_hover_text("Move up").clicked() { - raise = Some(index); - } - if ui.add_enabled(count > 1, egui::Button::new("✖")).on_hover_text("Delete").clicked() { - remove = Some(index); + egui::Grid::new("profiles list") + .striped(true) + .num_columns(4) + .show(ui, |ui| { + for (index, profile) in self.profiles.profiles.iter_mut().enumerate() { + let response = ui.add( + egui::TextEdit::singleline(&mut profile.name).desired_width(140.0), + ); + if response.lost_focus() && response.changed() { + changed = true; + } + changed |= response.changed(); + ui.label( + RichText::new(if profile.sdr_only { + crate::tr!( + "profiles-summary-sdr", + mb = profile.max_size_mb, + short = profile.max_short_side.to_string(), + fps = profile.max_fps, + codecs = profile.codecs_label() + ) + } else { + crate::tr!( + "profiles-summary", + mb = profile.max_size_mb, + short = profile.max_short_side.to_string(), + fps = profile.max_fps, + codecs = profile.codecs_label() + ) + }) + .weak(), + ); + if ui + .add_enabled(index > 0, egui::Button::new("⏶")) + .on_hover_text(crate::tr!("profiles-move-up-tooltip")) + .clicked() + { + raise = Some(index); + } + if ui + .add_enabled(count > 1, egui::Button::new("✖")) + .on_hover_text(crate::tr!("profiles-delete-tooltip")) + .clicked() + { + remove = Some(index); + } + ui.end_row(); } - ui.end_row(); - } - }); + }); ui.add_space(6.0); // Built-in profiles missing from the file (deleted, or added in a later version). let missing: Vec = Profile::built_ins() @@ -751,7 +837,7 @@ impl TranscoderApp { .filter(|p| self.profiles.find(&p.name).is_none()) .collect(); ui.add_enabled_ui(!missing.is_empty(), |ui| { - ui.menu_button("Add a built-in profile", |ui| { + ui.menu_button(crate::tr!("profiles-add-built-in"), |ui| { for profile in missing { if ui.button(&profile.name).clicked() { self.profiles.profiles.push(profile); @@ -786,21 +872,44 @@ fn audio_label(choice: AudioChoice, media: Option<&crate::ffmpeg::probe::MediaIn match choice { AudioChoice::Auto => match game_track(audio).and_then(|i| audio.get(i)) { Some(track) => match &track.title { - Some(title) => format!("Automatic: {title}"), - None => format!("Automatic: track {}", track.index + 1), + Some(title) => crate::tr!("settings-sound-auto-titled", title = title.as_str()), + None => crate::tr!( + "settings-sound-auto-numbered", + number = track.index.saturating_add(1) + ), }, - None => "Automatic (the game's track)".to_owned(), + None => crate::tr!("settings-sound-auto-default"), }, - AudioChoice::Track(index) => audio - .get(index) - .map_or_else(|| format!("Track {}", index + 1), |t| t.label()), - AudioChoice::MixAll => "Every track mixed".to_owned(), - AudioChoice::None => "No sound".to_owned(), + AudioChoice::Track(index) => audio.get(index).map_or_else( + || crate::tr!("settings-sound-track", number = index.saturating_add(1)), + |t| t.label(), + ), + AudioChoice::MixAll => crate::tr!("settings-sound-mix-all"), + AudioChoice::None => crate::tr!("settings-sound-none"), } } +/// A number typed in a number box, in any locale's format: the digits, and a comma or a point as the +/// decimal separator ("25,5 Mo", "25.5", "1 000"). Grouping spaces and units are ignored. +fn parse_localized_number(text: &str) -> Option { + let kept: String = text + .chars() + .filter(|c| c.is_ascii_digit() || matches!(c, ',' | '.' | '-')) + .map(|c| if c == ',' { '.' } else { c }) + .collect(); + kept.parse().ok() +} + #[cfg(test)] mod tests { + #[test] + fn number_boxes_read_either_decimal_separator() { + assert_eq!(super::parse_localized_number("25,5 Mo"), Some(25.5)); + assert_eq!(super::parse_localized_number("25.5 MB"), Some(25.5)); + assert_eq!(super::parse_localized_number("1\u{202f}000"), Some(1000.0)); + assert_eq!(super::parse_localized_number("MB"), None); + } + use super::*; #[test] diff --git a/src/app/timeline.rs b/src/app/timeline.rs index 56b67eb..49770e8 100644 --- a/src/app/timeline.rs +++ b/src/app/timeline.rs @@ -30,103 +30,133 @@ impl TranscoderApp { ui.add_space(6.0); } + /// The volume is laid out first, at the right edge, and the controls take what remains, wrapping to a + /// second row when a longer language (or a narrow window) does not fit: nothing overlaps the volume. fn transport(&mut self, ui: &mut egui::Ui, duration: f64, trim: Trim) { - ui.horizontal(|ui| { - if ui - .button("⏮") - .on_hover_text("Start of the kept part (Home)") - .clicked() - { - self.player.seek(trim.start); - } - if ui - .button("◀|") - .on_hover_text("Previous frame (Left)") - .clicked() - { - self.player.step(-1); + // The two sides are built by two closures alive at once: the volume works on copies. + let mut volume = Volume { + level: self.prefs.volume, + muted: self.prefs.muted, + available: self.player.has_audio(), + }; + egui::containers::Sides::new().shrink_left().show( + ui, + |ui| { + ui.horizontal_wrapped(|ui| self.transport_controls(ui, duration, trim)); + }, + |ui| volume.show(ui), + ); + self.prefs.volume = volume.level; + self.prefs.muted = volume.muted; + } + + fn transport_controls(&mut self, ui: &mut egui::Ui, duration: f64, trim: Trim) { + if ui + .button("⏮") + .on_hover_text(crate::tr!("timeline-first-tooltip")) + .clicked() + { + self.player.seek(trim.start); + } + if ui + .button("◀|") + .on_hover_text(crate::tr!("timeline-previous-tooltip")) + .clicked() + { + self.player.step(-1); + } + let play = if self.player.is_playing() { + "⏸" + } else { + "▶" + }; + if ui + .add(egui::Button::new(egui::RichText::new(play).size(16.0)).min_size(vec2(36.0, 0.0))) + .on_hover_text(crate::tr!("timeline-play-tooltip")) + .clicked() + { + self.toggle_playback(); + } + if ui + .button("|▶") + .on_hover_text(crate::tr!("timeline-next-tooltip")) + .clicked() + { + self.player.step(1); + } + if ui + .button("⏭") + .on_hover_text(crate::tr!("timeline-last-tooltip")) + .clicked() + { + self.player.seek(trim.end); + } + ui.separator(); + ui.monospace(format!( + "{} / {}", + timecode::format_precise(self.player.position()), + timecode::format_short(duration, true) + )); + ui.separator(); + if ui + .button(crate::tr!("timeline-start-here")) + .on_hover_text(crate::tr!("timeline-start-here-tooltip")) + .clicked() + { + self.set_trim_start(self.player.position()); + } + if ui + .button(crate::tr!("timeline-end-here")) + .on_hover_text(crate::tr!("timeline-end-here-tooltip")) + .clicked() + { + self.set_trim_end(self.player.position()); + } + } +} + +/// The volume controls' state, edited apart from the app while the transport row is built. +struct Volume { + level: f32, + muted: bool, + available: bool, +} + +impl Volume { + /// Mute button and volume slider, right to left (the kept duration lives in the settings panel and the + /// queue row, not here). + fn show(&mut self, ui: &mut egui::Ui) { + ui.spacing_mut().slider_width = 70.0; + let available = self.available; + ui.add_enabled_ui(available, |ui| { + let slider = ui + .add(egui::Slider::new(&mut self.level, 0.0..=1.0).show_value(false)) + .on_hover_text(crate::tr!( + "timeline-volume-tooltip", + percent = (self.level * 100.0).round() + )); + if slider.changed() { + self.muted = false; } - let play = if self.player.is_playing() { - "⏸" + let icon = if self.muted || !available { + "🔇" } else { - "▶" + "🔊" }; if ui - .add( - egui::Button::new(egui::RichText::new(play).size(16.0)) - .min_size(vec2(36.0, 0.0)), - ) - .on_hover_text("Play / pause the kept part (Space)") + .add(egui::Button::new(icon).selected(self.muted)) + .on_hover_text(crate::tr!("timeline-mute-tooltip")) .clicked() { - self.toggle_playback(); + self.muted = !self.muted; } - if ui - .button("|▶") - .on_hover_text("Next frame (Right)") - .clicked() - { - self.player.step(1); - } - if ui - .button("⏭") - .on_hover_text("End of the kept part (End)") - .clicked() - { - self.player.seek(trim.end); - } - ui.separator(); - ui.monospace(format!( - "{} / {}", - timecode::format_precise(self.player.position()), - timecode::format_short(duration, true) - )); - ui.separator(); - if ui - .button("[ Start here") - .on_hover_text("Start the kept part at the current frame (I)") - .clicked() - { - self.set_trim_start(self.player.position()); - } - if ui - .button("End here ]") - .on_hover_text("End the kept part after the current frame (O)") - .clicked() - { - self.set_trim_end(self.player.position()); - } - // The kept duration is shown in the settings panel and the queue row: here it collided with the - // volume slider once egui 0.37 drew the transport symbols as wider color emoji. - ui.with_layout(egui::Layout::right_to_left(egui::Align::Center), |ui| { - ui.spacing_mut().slider_width = 90.0; - let available = self.player.has_audio(); - ui.add_enabled_ui(available, |ui| { - let volume = ui - .add(egui::Slider::new(&mut self.prefs.volume, 0.0..=1.0).show_value(false)) - .on_hover_text(format!("Volume {:.0} %", self.prefs.volume * 100.0)); - if volume.changed() { - self.prefs.muted = false; - } - let icon = if self.prefs.muted || !available { - "🔇" - } else { - "🔊" - }; - if ui - .add(egui::Button::new(icon).selected(self.prefs.muted)) - .on_hover_text("Mute / unmute (M)") - .clicked() - { - self.prefs.muted = !self.prefs.muted; - } - }) - .response - .on_disabled_hover_text("No sound"); - }); - }); + }) + .response + .on_disabled_hover_text(crate::tr!("timeline-no-sound")); } +} +impl TranscoderApp { fn trim_bar(&mut self, ui: &mut egui::Ui, id: u64, duration: f64, fps: f64, trim: Trim) { let width = ui.available_width(); let (rect, response) = diff --git a/src/app/update_window.rs b/src/app/update_window.rs new file mode 100644 index 0000000..db51c4f --- /dev/null +++ b/src/app/update_window.rs @@ -0,0 +1,382 @@ +//! The *Check for updates* window: draws [`Machine`]'s phase and sends its buttons as events. The rules +//! are in [`crate::update`]; the work runs on a worker thread per effect, reporting back through a channel. + +use std::sync::Arc; + +use crossbeam_channel::{Receiver, Sender, unbounded}; +use eframe::egui; + +use super::TranscoderApp; +use crate::queue::Phase as JobPhase; +use crate::update::feed::GitHub; +use crate::update::install::{self, Paths}; +use crate::update::{Effect, Event, Fault, Machine, Phase, Release, Version}; + +/// The updater as the window sees it. +pub(super) struct Updater { + machine: Machine, + /// The window is shown. + pub(super) open: bool, + sender: Sender, + receiver: Receiver, + /// The data folder and executable are known (else nothing can be installed). + paths: Option, +} + +impl Updater { + /// The updater at start: the outcome of an update the previous run started opens the window. + pub(super) fn new() -> Self { + let current = running_version(); + let paths = Paths::current(); + let settled = paths.as_ref().and_then(|p| install::settle(p, current)); + let (sender, receiver) = unbounded(); + Self { + open: settled.is_some(), + machine: Machine::new(current, settled.unwrap_or(Phase::Idle)), + sender, + receiver, + paths, + } + } +} + +/// This executable's version; in debug builds `QVT_UPDATE_AS=0.9.0` pretends to be older, to try an +/// update against the real latest release. +fn running_version() -> Version { + #[cfg(debug_assertions)] + if let Some(pretend) = std::env::var("QVT_UPDATE_AS") + .ok() + .and_then(|v| Version::parse(&v)) + { + return pretend; + } + Version::current() +} + +impl TranscoderApp { + /// *Help → Check for updates*: opens the window and checks at once. + pub(super) fn open_updates(&mut self) { + self.updater.open = true; + self.send_update(Event::CheckAsked); + } + + /// Applies an event and runs the effect it asks for. + fn send_update(&mut self, event: Event) { + let Some(effect) = self.updater.machine.apply(event) else { + return; + }; + let sender = self.updater.sender.clone(); + let notify = Arc::clone(&self.notify); + match effect { + Effect::Check => { + log::info!("update: checking for updates"); + std::thread::spawn(move || { + let result = crate::update::feed::Feed::latest(&GitHub::new()); + match &result { + Ok(release) => log::info!("update: latest release is {}", release.version), + Err(fault) => log::warn!("update: check failed: {fault:?}"), + } + let _ = sender.send(Event::Checked(result)); + notify(); + }); + } + Effect::Download(release) => { + let Some(paths) = self.updater.paths.clone() else { + let _ = sender.send(Event::Downloaded(Err(Fault::CannotWrite( + "no data folder".to_owned(), + )))); + return; + }; + log::info!( + "update: downloading {} ({} bytes)", + release.version, + release.exe_size + ); + std::thread::spawn(move || { + let progress_sender = sender.clone(); + let progress_notify = Arc::clone(¬ify); + let mut last = 0u64; + let result = install::download(&GitHub::new(), &release, &paths, &mut |done| { + // A message per 1 % is plenty for a progress bar. + if done.saturating_sub(last) > release.exe_size / 100 { + last = done; + let _ = progress_sender.send(Event::Progress(done)); + progress_notify(); + } + }); + match &result { + Ok(()) => log::info!("update: downloaded and verified {}", release.version), + Err(fault) => log::warn!("update: download failed: {fault:?}"), + } + let _ = sender.send(Event::Downloaded(result)); + notify(); + }); + } + Effect::Restart(release) => { + let result = self + .updater + .paths + .as_ref() + .ok_or_else(|| Fault::Launch("no data folder".to_owned())) + .and_then(|paths| install::launch(&release, paths)); + match result { + // The swap script waits for this process: close now, the normal way. + Ok(()) => self.close_for_update = true, + Err(fault) => { + log::warn!("update: cannot start the swap: {fault:?}"); + self.updater.machine.apply(Event::LaunchFailed(fault)); + } + } + } + } + } + + /// Takes the worker's results. + pub(super) fn poll_updates(&mut self) { + while let Ok(event) = self.updater.receiver.try_recv() { + self.send_update(event); + } + } + + fn encoding(&self) -> bool { + self.queue + .jobs + .iter() + .any(|j| matches!(j.phase, JobPhase::Encoding(_) | JobPhase::Waiting)) + } + + pub(super) fn update_window(&mut self, ctx: &egui::Context) { + if !self.updater.open { + return; + } + let mut open = true; + let mut event = None; + let encoding = self.encoding(); + let phase = self.updater.machine.phase().clone(); + egui::Window::new(crate::tr!("update-title")) + .id(egui::Id::unique("update window")) + .open(&mut open) + .collapsible(false) + .resizable(false) + .default_width(460.0) + .anchor(egui::Align2::CENTER_CENTER, egui::Vec2::ZERO) + .show(ctx, |ui| { + ui.label(crate::tr!( + "update-running", + version = running_version().to_string() + )); + ui.add_space(8.0); + event = phase_ui(ui, &phase, encoding); + }); + if let Some(event) = event { + self.send_update(event); + } + // Closing hides the window; a download keeps going and is found again on reopening. + if !open { + self.updater.open = false; + } + } +} + +/// The body of the window for a phase; returns the event a button sent. +fn phase_ui(ui: &mut egui::Ui, phase: &Phase, encoding: bool) -> Option { + let mut event = None; + match phase { + Phase::Idle => { + if ui.button(crate::tr!("update-check")).clicked() { + event = Some(Event::CheckAsked); + } + } + Phase::Checking => { + ui.horizontal(|ui| { + ui.spinner(); + ui.label(crate::tr!("update-checking")); + }); + } + Phase::UpToDate(version) => { + ui.label(crate::tr!( + "update-up-to-date", + version = version.to_string() + )); + ui.add_space(8.0); + if ui.button(crate::tr!("update-check-again")).clicked() { + event = Some(Event::CheckAsked); + } + } + Phase::Available(release) => { + let mb = release.exe_size as f64 / 1e6; + ui.strong(crate::tr!( + "update-available", + version = release.version.to_string() + )); + notes(ui, release); + ui.horizontal(|ui| { + if ui.button(crate::tr!("update-download", mb = mb)).clicked() { + event = Some(Event::DownloadAsked); + } + ui.hyperlink_to(crate::tr!("update-release-page"), &release.page); + }); + } + Phase::Downloading(release, done) => { + ui.label(crate::tr!( + "update-downloading", + version = release.version.to_string() + )); + let fraction = *done as f32 / release.exe_size.max(1) as f32; + ui.add( + egui::ProgressBar::new(fraction) + .show_percentage() + .desired_width(420.0), + ); + } + Phase::Ready(release) => { + ui.label(crate::tr!( + "update-ready", + version = release.version.to_string() + )); + ui.add_space(8.0); + let restart = + ui.add_enabled(!encoding, egui::Button::new(crate::tr!("update-restart"))); + if encoding { + ui.label( + egui::RichText::new(crate::tr!("update-wait-for-encodes")) + .small() + .weak(), + ); + } + if restart.clicked() { + event = Some(Event::RestartAsked); + } + } + Phase::Restarting(release) => { + ui.horizontal(|ui| { + ui.spinner(); + ui.label(crate::tr!( + "update-restarting", + version = release.version.to_string() + )); + }); + } + Phase::Updated(version) => { + ui.label(crate::tr!("update-updated", version = version.to_string())); + } + Phase::Failed { fault, release } => { + ui.colored_label(ui.visuals().error_fg_color, fault_text(fault)); + ui.label( + egui::RichText::new(crate::tr!("update-see-log")) + .small() + .weak(), + ); + ui.add_space(8.0); + ui.horizontal(|ui| { + match release { + Some(release) if !matches!(fault, Fault::CannotWrite(_)) => { + if ui.button(crate::tr!("update-retry")).clicked() { + event = Some(Event::DownloadAsked); + } + } + _ => { + if ui.button(crate::tr!("update-check-again")).clicked() { + event = Some(Event::CheckAsked); + } + } + } + if let Some(release) = release { + ui.hyperlink_to(crate::tr!("update-release-page"), &release.page); + } + }); + } + } + event +} + +/// A block of the release notes. +#[derive(Debug, PartialEq, Eq)] +enum Block { + Heading(String), + Item(String), + Paragraph(String), +} + +/// The release notes (the changelog section, Markdown) as blocks: `#` headings, `- ` items with their +/// wrapped continuation lines joined, paragraphs; emphasis and code marks dropped; the footer after `---` +/// left out. +fn note_blocks(notes: &str) -> Vec { + let mut blocks: Vec = Vec::new(); + for line in notes.lines() { + let line = line.trim_end(); + if line.starts_with("---") { + break; + } + let clean = |text: &str| text.trim().replace(['*', '`'], ""); + if line.starts_with('#') { + blocks.push(Block::Heading(clean(line.trim_start_matches('#')))); + } else if let Some(item) = line.strip_prefix("- ") { + blocks.push(Block::Item(clean(item))); + } else if line.is_empty() { + continue; + } else if let (true, Some(Block::Item(text) | Block::Paragraph(text))) = + (line.starts_with(' '), blocks.last_mut()) + { + text.push(' '); + text.push_str(&clean(line)); + } else { + blocks.push(Block::Paragraph(clean(line))); + } + } + blocks +} + +fn notes(ui: &mut egui::Ui, release: &Release) { + ui.add_space(4.0); + egui::ScrollArea::vertical() + .max_height(220.0) + .auto_shrink([false, true]) + .show(ui, |ui| { + for block in note_blocks(&release.notes) { + match block { + Block::Heading(text) => { + ui.strong(text); + } + Block::Item(text) => { + ui.label(format!("• {text}")); + } + Block::Paragraph(text) => { + ui.label(text); + } + } + } + }); + ui.add_space(6.0); +} + +/// The user's sentence for a fault (the technical detail is in the log). +fn fault_text(fault: &Fault) -> String { + match fault { + Fault::NoConnection(_) => crate::tr!("update-fault-connection"), + Fault::Status(status) => crate::tr!("update-fault-status", status = status.to_string()), + Fault::Unexpected(_) => crate::tr!("update-fault-unexpected"), + Fault::NotVerified => crate::tr!("update-fault-not-verified"), + Fault::CannotWrite(_) => crate::tr!("update-fault-cannot-write"), + Fault::Launch(reason) => crate::tr!("update-fault-install", detail = reason.clone()), + } +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn release_notes_join_wrapped_items() { + let notes = "The first release.\n\n### Added\n\n- A queue, filled from *Send to*,\n with `I` / `O`.\n- One file.\n\n---\n\nBuilt from abc."; + assert_eq!( + note_blocks(notes), + [ + Block::Paragraph("The first release.".to_owned()), + Block::Heading("Added".to_owned()), + Block::Item("A queue, filled from Send to, with I / O.".to_owned()), + Block::Item("One file.".to_owned()), + ] + ); + } +} diff --git a/src/clipboard.rs b/src/clipboard.rs index e38efe5..731ee5c 100644 --- a/src/clipboard.rs +++ b/src/clipboard.rs @@ -12,7 +12,12 @@ pub fn copy_files(files: &[PathBuf]) -> Result<()> { .iter() .map(|p| p.to_string_lossy().into_owned()) .collect(); - let fail = |error| anyhow::anyhow!("cannot copy to the clipboard: {error}"); + fn fail(error: impl std::fmt::Display) -> anyhow::Error { + anyhow::anyhow!(crate::tr!( + "clipboard-copy-failed", + detail = error.to_string() + )) + } let _open = clipboard_win::Clipboard::new_attempts(10).map_err(fail)?; // Emptied first: a text copied earlier must not be pasted instead of the files. clipboard_win::raw::set_file_list_with(&paths, clipboard_win::options::DoClear).map_err(fail) @@ -21,5 +26,5 @@ pub fn copy_files(files: &[PathBuf]) -> Result<()> { /// Puts `files` on the clipboard as a file list (Windows only). #[cfg(not(windows))] pub fn copy_files(_files: &[PathBuf]) -> Result<()> { - anyhow::bail!("copying files to the clipboard is only supported on Windows") + anyhow::bail!(crate::tr!("clipboard-unsupported")) } diff --git a/src/encode.rs b/src/encode.rs index ff07f92..7a31179 100644 --- a/src/encode.rs +++ b/src/encode.rs @@ -157,7 +157,10 @@ pub fn run( let partial = partial_path(output); check_partial(&partial, output, &request.path)?; if output.exists() { - bail!("{} already exists", output.display()); + bail!(crate::tr!( + "encode-output-exists", + path = output.display().to_string() + )); } let max_bytes = request.profile.max_bytes(); let duration = request.duration(); @@ -183,11 +186,14 @@ pub fn run( return Err(error); } let bytes = std::fs::metadata(&partial) - .with_context(|| format!("cannot read {}", partial.display()))? + .with_context(|| { + crate::tr!("encode-cannot-read", path = partial.display().to_string()) + })? .len(); if bytes <= max_bytes { - std::fs::rename(&partial, output) - .with_context(|| format!("cannot rename the encode to {}", output.display()))?; + std::fs::rename(&partial, output).with_context(|| { + crate::tr!("encode-cannot-rename", path = output.display().to_string()) + })?; log::info!( "encoded {} -> {} ({bytes} bytes, attempt {attempt})", request.path.display(), @@ -210,11 +216,11 @@ pub fn run( video_bps /= overshoot; } let _ = remove_partial(&partial, output, &request.path); - bail!( - "the encoder overshot {:.1} MB {} times: lower the quality floor or shorten the clip", - request.profile.max_size_mb, - RETRIES + 1 - ) + bail!(crate::tr!( + "encode-overshoot", + mb = request.profile.max_size_mb, + count = ((RETRIES + 1) as u32) + )) } fn remove_partial(partial: &Path, output: &Path, source: &Path) -> Result<()> { @@ -241,7 +247,7 @@ fn run_once( .stdout(Stdio::piped()) .stderr(Stdio::piped()) .spawn() - .context("cannot start ffmpeg (is FFmpeg on the PATH?)")?; + .with_context(|| crate::tr!("media-ffmpeg-start-failed"))?; let mut stderr = StderrTail::collect(&mut child); let stdout = child.stdout.take().context("no ffmpeg stdout")?; let (tx, rx) = crossbeam_channel::unbounded(); @@ -282,14 +288,12 @@ fn run_once( let _ = reader.join(); if !status.success() { let detail = stderr.finish(); - bail!( - "ffmpeg failed ({status}): {}", - if detail.is_empty() { - "no message" - } else { - &detail - } - ); + let status = status.to_string(); + bail!(if detail.is_empty() { + crate::tr!("encode-ffmpeg-failed-silent", status = status) + } else { + crate::tr!("encode-ffmpeg-failed", status = status, detail = detail) + }); } Ok(()) } diff --git a/src/estimate.rs b/src/estimate.rs index 348f6c6..815861c 100644 --- a/src/estimate.rs +++ b/src/estimate.rs @@ -100,13 +100,13 @@ pub struct Estimate { } /// A word for an H.265 QP, for people who do not think in QPs. -pub fn quality_word(qp: f64) -> &'static str { +pub fn quality_word(qp: f64) -> String { match qp { - q if q < 22.0 => "excellent", - q if q < 26.0 => "very good", - q if q < 30.0 => "good", - q if q < 34.0 => "fair", - _ => "poor", + q if q < 22.0 => crate::tr!("estimate-quality-excellent"), + q if q < 26.0 => crate::tr!("estimate-quality-very-good"), + q if q < 30.0 => crate::tr!("estimate-quality-good"), + q if q < 34.0 => crate::tr!("estimate-quality-fair"), + _ => crate::tr!("estimate-quality-poor"), } } @@ -139,7 +139,7 @@ pub fn solve( mut measure: impl FnMut(Target, f64) -> Result, ) -> Result<(Target, f64, f64, Verdict, usize)> { if ladder.is_empty() { - bail!("no output size to try"); + bail!(crate::tr!("estimate-no-size")); } let start_qp = ((bounds.ceiling + bounds.floor) / 2.0).round(); let mut measurements = 0; @@ -306,15 +306,15 @@ impl EstimateRequest { pub fn run(request: &EstimateRequest, slots: &Slots, cancel: &Arc) -> Result { let duration = request.duration(); if duration < 0.2 { - bail!("the trimmed range is empty"); + bail!(crate::tr!("estimate-empty-range")); } let audio = plan::audio_kbps(&request.media, &request.profile); let Some(budget_bps) = plan::video_budget(request.profile.max_bytes(), duration, audio) else { - bail!( - "{:.0} MB cannot even hold the sound of {}: shorten the clip", - request.profile.max_size_mb, - timecode::format_short(duration, false) - ); + bail!(crate::tr!( + "estimate-too-small", + mb = request.profile.max_size_mb, + duration = timecode::format_short(duration, false) + )); }; let ladder = plan::ladder( request.media.width, @@ -453,7 +453,7 @@ fn encode_sample( .stdout(Stdio::piped()) .stderr(Stdio::piped()) .spawn() - .context("cannot start ffmpeg (is FFmpeg on the PATH?)")?; + .with_context(|| crate::tr!("media-ffmpeg-start-failed"))?; let mut stderr = StderrTail::collect(&mut child); let mut stdout = child.stdout.take().context("no ffmpeg stdout")?; let mut buffer = vec![0u8; 1 << 16]; @@ -474,14 +474,12 @@ fn encode_sample( let status = child.wait().context("ffmpeg did not exit")?; if !status.success() || bytes == 0 { let detail = stderr.finish(); - bail!( - "sample encode failed ({status}): {}", - if detail.is_empty() { - "no output" - } else { - &detail - } - ); + let status = status.to_string(); + bail!(if detail.is_empty() { + crate::tr!("estimate-sample-failed-silent", status = status) + } else { + crate::tr!("estimate-sample-failed", status = status, detail = detail) + }); } Ok(bytes) } diff --git a/src/ffmpeg/audio.rs b/src/ffmpeg/audio.rs index 3fcab36..2034b58 100644 --- a/src/ffmpeg/audio.rs +++ b/src/ffmpeg/audio.rs @@ -74,7 +74,7 @@ impl AudioDecoder { .stdout(Stdio::piped()) .stderr(Stdio::piped()) .spawn() - .context("cannot start ffmpeg (is FFmpeg on the PATH?)")?; + .with_context(|| crate::tr!("media-ffmpeg-start-failed"))?; let mut stderr = StderrTail::collect(&mut child); let mut stdout = child.stdout.take().context("no ffmpeg stdout")?; let reader = std::thread::Builder::new() diff --git a/src/ffmpeg/decoder.rs b/src/ffmpeg/decoder.rs index 75ccd58..ad4d4d2 100644 --- a/src/ffmpeg/decoder.rs +++ b/src/ffmpeg/decoder.rs @@ -114,7 +114,7 @@ impl FrameStream { .stdout(Stdio::piped()) .stderr(Stdio::piped()) .spawn() - .context("cannot start ffmpeg (is FFmpeg on the PATH?)")?; + .with_context(|| crate::tr!("media-ffmpeg-start-failed"))?; let mut stderr = StderrTail::collect(&mut child); let mut stdout = child.stdout.take().context("no ffmpeg stdout")?; let (event_tx, events) = bounded(Self::QUEUE); diff --git a/src/ffmpeg/filters.rs b/src/ffmpeg/filters.rs index 074be9d..fa250de 100644 --- a/src/ffmpeg/filters.rs +++ b/src/ffmpeg/filters.rs @@ -35,11 +35,11 @@ impl Engine { }; /// Name for the log and the status line. - pub fn label(self) -> &'static str { + pub fn label(self) -> String { match (self.placebo, self.vulkan_decode) { - (true, true) => "Vulkan decode + libplacebo", - (true, false) => "libplacebo", - (false, _) => "software filters", + (true, true) => crate::tr!("media-engine-vulkan"), + (true, false) => crate::tr!("media-engine-placebo"), + (false, _) => crate::tr!("media-engine-software"), } } } diff --git a/src/ffmpeg/hardware.rs b/src/ffmpeg/hardware.rs index 21d97e6..65a21d9 100644 --- a/src/ffmpeg/hardware.rs +++ b/src/ffmpeg/hardware.rs @@ -149,14 +149,14 @@ impl Capabilities { (!codecs.is_empty()).then(|| format!("{} {}", backend.label(), codecs.join("/"))) }) .collect(); - format!( - "encoders: {}; GPU tone mapping (libplacebo): {}", - if pairs.is_empty() { - "none".to_owned() + crate::tr!( + "media-hardware-summary", + encoders = if pairs.is_empty() { + crate::tr!("media-hardware-none") } else { pairs.join(", ") }, - if self.placebo { "yes" } else { "no" } + placebo = if self.placebo { "yes" } else { "no" } ) } } diff --git a/src/ffmpeg/mod.rs b/src/ffmpeg/mod.rs index 4f03491..cb572f5 100644 --- a/src/ffmpeg/mod.rs +++ b/src/ffmpeg/mod.rs @@ -248,7 +248,7 @@ pub fn install_with_winget() -> anyhow::Result<()> { .arg("--disable-interactivity") .stdin(std::process::Stdio::null()) .output() - .context("cannot start winget")?; + .with_context(|| crate::tr!("media-winget-start-failed"))?; if output.status.success() { return Ok(()); } @@ -260,7 +260,11 @@ pub fn install_with_winget() -> anyhow::Result<()> { .filter(|l| l.chars().any(char::is_alphanumeric)) .collect(); let tail = lines[lines.len().saturating_sub(3)..].join(" / "); - anyhow::bail!("winget failed ({}): {tail}", output.status) + anyhow::bail!(crate::tr!( + "media-winget-failed", + status = output.status.to_string(), + detail = tail + )) } /// The major version in `ffmpeg -version`'s first line (`ffmpeg version 9.0.2-full_build-www.gyan.dev diff --git a/src/ffmpeg/probe.rs b/src/ffmpeg/probe.rs index e6fa48d..0b549d0 100644 --- a/src/ffmpeg/probe.rs +++ b/src/ffmpeg/probe.rs @@ -31,11 +31,11 @@ impl Dynamic { } /// Short label for the queue. - pub fn label(self) -> &'static str { + pub fn label(self) -> String { match self { - Self::Sdr => "SDR", - Self::Pq => "HDR10", - Self::Hlg => "HLG", + Self::Sdr => crate::tr!("media-dynamic-sdr"), + Self::Pq => crate::tr!("media-dynamic-pq"), + Self::Hlg => crate::tr!("media-dynamic-hlg"), } } } @@ -74,17 +74,23 @@ impl AudioTrack { /// How the track reads in a menu: `2 · Microphone (AAC, stereo)`. pub fn label(&self) -> String { - let layout = match self.channels { - 1 => "mono".to_owned(), - 2 => "stereo".to_owned(), - 6 => "5.1".to_owned(), - 8 => "7.1".to_owned(), - n => format!("{n} channels"), - }; - let details = format!("{}, {layout}", codec_label(&self.codec)); + let layout = crate::tr!("media-audio-layout", channels = self.channels); + let codec = codec_label(&self.codec); + let number = self.index + 1; match &self.title { - Some(title) => format!("{} · {title} ({details})", self.index + 1), - None => format!("{} · {details}", self.index + 1), + Some(title) => crate::tr!( + "media-audio-track-titled", + number = number, + title = title.clone(), + codec = codec, + layout = layout + ), + None => crate::tr!( + "media-audio-track", + number = number, + codec = codec, + layout = layout + ), } } } @@ -144,13 +150,13 @@ impl MediaInfo { /// One line describing the source, for the queue (`3840x2160 60 fps AV1 HDR10`). pub fn summary(&self) -> String { - format!( - "{}x{} {} fps {} {}", - self.width, - self.height, - self.frame_rate.label(), - codec_label(&self.codec), - self.dynamic.label() + crate::tr!( + "media-summary", + width = self.width.to_string(), + height = self.height.to_string(), + fps = self.frame_rate.label(), + codec = codec_label(&self.codec), + dynamic = self.dynamic.label() ) } } @@ -304,7 +310,8 @@ fn nominal_rate(guess: Option, average: Option) -> FrameRa /// Parses the JSON printed by `ffprobe -print_format json -show_format -show_streams`. pub fn parse_probe_json(json: &str) -> Result { - let output: ProbeOutput = serde_json::from_str(json).context("invalid ffprobe output")?; + let output: ProbeOutput = + serde_json::from_str(json).with_context(|| crate::tr!("media-probe-invalid"))?; // Cover art is a video stream too (`attached_pic`): skip it. let video = output .streams @@ -313,9 +320,9 @@ pub fn parse_probe_json(json: &str) -> Result { s.codec_type.as_deref() == Some("video") && s.disposition.get("attached_pic").copied().unwrap_or(0) == 0 }) - .context("no video stream")?; + .with_context(|| crate::tr!("media-no-video"))?; let (Some(width), Some(height)) = (video.width, video.height) else { - bail!("video stream without dimensions"); + bail!(crate::tr!("media-no-dimensions")); }; let parse = |rate: &Option| { rate.as_deref() @@ -399,12 +406,12 @@ pub fn probe(path: &Path) -> Result { .arg(path) .stdin(std::process::Stdio::null()) .output() - .context("cannot run ffprobe (is FFmpeg on the PATH?)")?; + .with_context(|| crate::tr!("media-ffprobe-start-failed"))?; if !output.status.success() { - bail!( - "ffprobe failed: {}", - String::from_utf8_lossy(&output.stderr).trim() - ); + bail!(crate::tr!( + "media-ffprobe-failed", + detail = String::from_utf8_lossy(&output.stderr).trim().to_owned() + )); } parse_probe_json(&String::from_utf8_lossy(&output.stdout)) } diff --git a/src/i18n.rs b/src/i18n.rs new file mode 100644 index 0000000..29e44dc --- /dev/null +++ b/src/i18n.rs @@ -0,0 +1,343 @@ +//! Localization: Project Fluent messages and ICU4X number formats. +//! +//! Rules this module is shaped by: +//! - **Every text a user reads goes through [`crate::tr!`]** with a message id from +//! `i18n/en/quick_video_transcoder.ftl`; `fl!` checks the id and its arguments against that file at +//! compile time. Logs and technical details (FFmpeg's own messages, error chains) stay in English, for +//! support. +//! - **English is the reference and the fallback**: complete, every other file may be partial and falls +//! back message by message (`fr-CA` → `fr` → `en`). +//! - **A language is a regional variant** ([`LANGUAGES`]): it chooses the texts (the closest files) and the +//! number formats (CLDR data of that exact variant: `fr-CA` groups with a no-break space, `fr` with a +//! narrow one). *Automatic* takes the OS's preferred display languages. +//! - **Numbers are formatted by Fluent's `NUM` function**, never in Rust: `{ NUM($mb, decimals: 1) } Mo` +//! gives `25,0 Mo` in French. The CLDR data is compiled in (ICU4X `compiled_data`), so the result is the +//! same on every OS, and OS regional customizations are not followed (as Firefox does by default). +//! - **Languages are always negotiated** ([`i18n_embed::select`]): loading a language without files +//! panics in i18n-embed, so a stored preference is never loaded directly. + +use std::sync::{LazyLock, Mutex, PoisonError}; + +use fixed_decimal::{Decimal, FloatPrecision, SignedRoundingMode, UnsignedRoundingMode}; +use fluent_bundle::FluentValue; +use i18n_embed::fluent::{FluentLanguageLoader, fluent_language_loader}; +use i18n_embed::{DesktopLanguageRequester, LanguageLoader}; +use icu_decimal::DecimalFormatter; +use icu_locale_core::Locale; +use rust_embed::RustEmbed; +use unic_langid::LanguageIdentifier; + +/// The `.ftl` files, embedded in the executable. +#[derive(RustEmbed)] +#[folder = "i18n/"] +struct Localizations; + +/// The languages offered in the *Language* menu: a regional variant and its name in that language (a +/// language is always named in itself, so anyone finds theirs). +pub const LANGUAGES: [(&str, &str); 6] = [ + ("en-US", "English (United States)"), + ("en-GB", "English (United Kingdom)"), + ("fr-FR", "Français (France)"), + ("fr-CA", "Français (Canada)"), + ("fr-BE", "Français (Belgique)"), + ("fr-CH", "Français (Suisse)"), +]; + +/// The loader every [`crate::tr!`] reads. +pub static LOADER: LazyLock = LazyLock::new(|| { + let loader: FluentLanguageLoader = fluent_language_loader!(); + // The English file always loads: messages are never missing, even before `apply`. + if let Err(error) = i18n_embed::select( + &loader, + &Localizations, + &[loader.fallback_language().clone()], + ) { + log::error!("cannot load the English messages: {error}"); + } + register_functions(&loader, None); + loader +}); + +/// The language currently applied (`None`: automatic), for the menu. +static CHOICE: Mutex> = Mutex::new(None); + +/// A localized message: `tr!("id")` or `tr!("id", name = value, …)`. +#[macro_export] +macro_rules! tr { + ($id:literal) => { + i18n_embed_fl::fl!(&*$crate::i18n::LOADER, $id) + }; + ($id:literal, $($args:tt)*) => { + i18n_embed_fl::fl!(&*$crate::i18n::LOADER, $id, $($args)*) + }; +} + +/// Applies a language: `None` follows the OS, `Some("fr-CA")` a variant of [`LANGUAGES`]. An unknown tag +/// (an old preference) counts as automatic. Can be called again at any time; the next frame shows it. +pub fn apply(choice: Option<&str>) { + let choice = choice.filter(|tag| LANGUAGES.iter().any(|(known, _)| known == tag)); + let requested: Vec = match choice { + Some(tag) => tag.parse().into_iter().collect(), + None => DesktopLanguageRequester::requested_languages(), + }; + let loader = &*LOADER; + match i18n_embed::select(loader, &Localizations, &requested) { + Ok(loaded) => log::info!( + "language: {} (asked: {})", + loaded + .first() + .map_or_else(|| "en".to_owned(), ToString::to_string), + requested + .iter() + .map(ToString::to_string) + .collect::>() + .join(", ") + ), + Err(error) => log::error!("cannot load the messages: {error}"), + } + // Numbers follow the asked variant when its language is the one shown (fr-CA formats for French + // texts), else the language of each file. + register_functions(loader, requested.first()); + *CHOICE.lock().unwrap_or_else(PoisonError::into_inner) = choice.map(str::to_owned); +} + +/// The language chosen in the menu (`None`: automatic). +pub fn choice() -> Option { + CHOICE + .lock() + .unwrap_or_else(PoisonError::into_inner) + .clone() +} + +/// Sets up every loaded bundle: the `NUM` function, no bidi isolation marks (Fluent wraps each variable in +/// U+2068/U+2069 for right-to-left scripts, which egui does not lay out and would draw as boxes), and the +/// pseudo-localization in debug builds. i18n-embed rebuilds the bundles on each load, so this follows +/// every [`i18n_embed::select`]. +fn register_functions(loader: &FluentLanguageLoader, asked: Option<&LanguageIdentifier>) { + let asked = asked.cloned(); + #[cfg(debug_assertions)] + let pseudo = std::env::var_os("QVT_PSEUDO").is_some(); + loader.with_bundles_mut(move |bundle| { + let Some(language) = bundle.locales.first().cloned() else { + return; + }; + bundle.set_use_isolating(false); + #[cfg(debug_assertions)] + if pseudo { + bundle.set_transform(Some(|text| { + fluent_pseudo::transform_dom(text, false, true, true) + })); + } + let format_locale = asked + .as_ref() + .filter(|asked| asked.language == language.language) + .unwrap_or(&language); + let formatter = number_formatter(&format_locale.to_string()); + let added = bundle.add_function("NUM", move |positional, named| { + let Some(FluentValue::Number(number)) = positional.first() else { + return FluentValue::Error; + }; + let decimals = match named.get("decimals") { + Some(FluentValue::Number(d)) => d.value.clamp(0.0, 6.0) as i16, + _ => 0, + }; + format_number(&formatter, number.value, decimals) + .map_or(FluentValue::Error, |text| FluentValue::String(text.into())) + }); + if let Err(error) = added { + log::error!("cannot register NUM: {error}"); + } + }); +} + +/// A CLDR number formatter for a locale tag; the root (English-like) one if the tag does not parse. +fn number_formatter(tag: &str) -> DecimalFormatter { + let locale: Locale = tag.parse().unwrap_or(Locale::UNKNOWN); + DecimalFormatter::try_new(locale.into(), Default::default()) + .expect("the compiled CLDR data has every locale, falling back to root") +} + +/// `value` with exactly `decimals` digits after the separator (25 with 1 → "25.0" / "25,0"). +fn format_number(formatter: &DecimalFormatter, value: f64, decimals: i16) -> Option { + let mut decimal = Decimal::try_from_f64(value, FloatPrecision::RoundTrip).ok()?; + decimal.round_with_mode( + -decimals, + SignedRoundingMode::Unsigned(UnsignedRoundingMode::HalfExpand), + ); + decimal.pad_end(-decimals); + Some(formatter.format(&decimal).to_string()) +} + +#[cfg(test)] +mod tests { + use std::collections::{BTreeMap, BTreeSet}; + + use fluent_syntax::ast; + + use super::*; + + /// The message files, by language folder. + fn files() -> BTreeMap { + Localizations::iter() + .filter(|path| path.ends_with(".ftl")) + .map(|path| { + let language = path.split('/').next().unwrap().to_owned(); + let file = Localizations::get(&path).unwrap(); + (language, String::from_utf8(file.data.to_vec()).unwrap()) + }) + .collect() + } + + /// Each message id with the variables it uses (in its value and attributes, selectors included). + fn messages(text: &str) -> BTreeMap> { + let resource = fluent_syntax::parser::parse(text).unwrap_or_else(|(_, errors)| { + panic!("invalid Fluent syntax: {errors:?}"); + }); + let mut messages = BTreeMap::new(); + for entry in resource.body { + if let ast::Entry::Message(message) = entry { + let mut variables = BTreeSet::new(); + let patterns = message + .value + .iter() + .chain(message.attributes.iter().map(|a| &a.value)); + for pattern in patterns { + collect_pattern(pattern, &mut variables); + } + messages.insert(message.id.name.to_owned(), variables); + } + } + messages + } + + fn collect_pattern(pattern: &ast::Pattern<&str>, variables: &mut BTreeSet) { + for element in &pattern.elements { + if let ast::PatternElement::Placeable { expression } = element { + collect_expression(expression, variables); + } + } + } + + fn collect_expression(expression: &ast::Expression<&str>, variables: &mut BTreeSet) { + match expression { + ast::Expression::Select { selector, variants } => { + collect_inline(selector, variables); + for variant in variants { + collect_pattern(&variant.value, variables); + } + } + ast::Expression::Inline(inline) => collect_inline(inline, variables), + } + } + + fn collect_inline(inline: &ast::InlineExpression<&str>, variables: &mut BTreeSet) { + match inline { + ast::InlineExpression::VariableReference { id } => { + variables.insert(id.name.to_owned()); + } + ast::InlineExpression::FunctionReference { arguments, .. } => { + for argument in &arguments.positional { + collect_inline(argument, variables); + } + for argument in &arguments.named { + collect_inline(&argument.value, variables); + } + } + ast::InlineExpression::Placeable { expression } => { + collect_expression(expression, variables) + } + _ => {} + } + } + + /// Every file parses, and a translation has no message English lacks nor a variable English does not + /// pass (it would show as an error in the window). + #[test] + fn translations_match_the_english_messages() { + let files = files(); + let english = messages(files.get("en").expect("the English file")); + assert!(!english.is_empty()); + for (language, text) in &files { + for (id, variables) in messages(text) { + let Some(reference) = english.get(&id) else { + panic!("{language}: `{id}` is not an English message"); + }; + assert!( + variables.is_subset(reference), + "{language}: `{id}` uses {variables:?}, English passes {reference:?}" + ); + } + } + } + + /// French is complete: a message added in English must be translated in the same change (regional + /// files stay partial on purpose). + #[test] + fn french_is_complete() { + let files = files(); + let english: BTreeSet = messages(&files["en"]).into_keys().collect(); + let french: BTreeSet = messages(&files["fr"]).into_keys().collect(); + let missing: Vec<&String> = english.difference(&french).collect(); + assert!(missing.is_empty(), "not translated in French: {missing:?}"); + } + + /// Every English message is used by the code, so the file holds no dead text to translate. + #[test] + fn every_message_is_used() { + let mut source = String::new(); + let mut folders = vec![std::path::PathBuf::from(env!("CARGO_MANIFEST_DIR")).join("src")]; + while let Some(folder) = folders.pop() { + for entry in std::fs::read_dir(folder).unwrap().flatten() { + let path = entry.path(); + if path.is_dir() { + folders.push(path); + } else if path.extension().is_some_and(|e| e == "rs") { + source.push_str(&std::fs::read_to_string(path).unwrap()); + } + } + } + let used: BTreeSet<&str> = source + .split("tr!(") + .skip(1) + .filter_map(|after| after.trim_start().strip_prefix('"')?.split('"').next()) + .collect(); + let english = messages(files().get("en").unwrap()); + let unused: Vec<&String> = english + .keys() + .filter(|id| !used.contains(id.as_str())) + .collect(); + assert!( + unused.is_empty(), + "English messages no code uses: {unused:?}" + ); + } + + /// `tr!` with a number goes through NUM (English is loaded by default). + #[test] + fn numbers_reach_the_messages() { + assert_eq!( + crate::tr!("timeline-volume-tooltip", percent = 80.0), + "Volume 80%" + ); + } + + #[test] + fn every_offered_language_has_a_name_and_parses() { + for (tag, name) in LANGUAGES { + assert!(tag.parse::().is_ok(), "{tag}"); + assert!(!name.is_empty()); + } + } + + #[test] + fn formats_numbers_per_variant() { + let fr = number_formatter("fr-FR"); + assert_eq!(format_number(&fr, 25.0, 1).unwrap(), "25,0"); + assert_eq!(format_number(&fr, 1234.0, 0).unwrap(), "1\u{202f}234"); + assert_eq!(format_number(&fr, 29.97, 2).unwrap(), "29,97"); + let ca = number_formatter("fr-CA"); + assert_eq!(format_number(&ca, 1234.0, 0).unwrap(), "1\u{a0}234"); + let en = number_formatter("en-GB"); + assert_eq!(format_number(&en, 1234.56, 1).unwrap(), "1,234.6"); + } +} diff --git a/src/lib.rs b/src/lib.rs index a459924..ecd3cbe 100644 --- a/src/lib.rs +++ b/src/lib.rs @@ -13,6 +13,7 @@ pub mod clipboard; pub mod encode; pub mod estimate; pub mod ffmpeg; +pub mod i18n; pub mod instance; pub mod naming; pub mod plan; @@ -22,3 +23,4 @@ pub mod queue; pub mod sendto; pub mod thumbnails; pub mod timecode; +pub mod update; diff --git a/src/main.rs b/src/main.rs index fc5deb7..1e4c325 100644 --- a/src/main.rs +++ b/src/main.rs @@ -35,6 +35,9 @@ fn main() { Some("--licenses") => return print(build_info::NOTICES), _ => {} } + // The message boxes below run before the window: they follow the OS language (the app applies the + // stored choice once it starts). + quick_video_transcoder::i18n::apply(None); let data = profile::data_dir(); // Before the log: a launch that only hands its files over must not rotate the open window's log. let incoming = match data.as_deref().map(|dir| instance::claim(dir, &arguments)) { @@ -72,11 +75,10 @@ fn main() { if let Err(error) = result { log::error!("the window could not open: {error}"); show_error( - "Quick Video Transcoder cannot open its window", - &format!( - "{error}\n\nThe window needs a graphics driver with DirectX 12 or Vulkan. Updating the \ - graphics driver usually fixes this.{}", - log_hint(log_path.as_deref()) + &quick_video_transcoder::tr!("startup-window-failed-title"), + &with_log_hint( + quick_video_transcoder::tr!("startup-window-failed", detail = error.to_string()), + log_path.as_deref(), ), ); std::process::exit(1); @@ -124,19 +126,25 @@ fn install_panic_hook(log_path: Option) { default(info); if std::thread::current().name() == Some("main") { show_error( - "Quick Video Transcoder has stopped", - &format!( - "Something went wrong: {info}\n\nEncodes that were running did not finish.{}", - log_hint(log_path.as_deref()) + &quick_video_transcoder::tr!("startup-stopped-title"), + &with_log_hint( + quick_video_transcoder::tr!("startup-stopped", detail = info.to_string()), + log_path.as_deref(), ), ); } })); } -fn log_hint(path: Option<&Path>) -> String { - path.map(|p| format!("\n\nDetails are in {}", p.display())) - .unwrap_or_default() +/// The message with a last paragraph naming the log file, when there is one. +fn with_log_hint(text: String, path: Option<&Path>) -> String { + match path { + Some(path) => format!( + "{text}\n\n{}", + quick_video_transcoder::tr!("startup-log-hint", path = path.display().to_string()) + ), + None => text, + } } fn show_error(title: &str, text: &str) { diff --git a/src/naming.rs b/src/naming.rs index f7dce28..af46a31 100644 --- a/src/naming.rs +++ b/src/naming.rs @@ -80,13 +80,16 @@ pub fn check_partial(partial: &Path, output: &Path, source: &Path) -> Result<()> .extension() .is_some_and(|e| e.eq_ignore_ascii_case(PARTIAL_EXTENSION)); if !marked || partial != partial_path(output) || partial.parent() != output.parent() { - bail!( - "refusing to write {}: not a partial file", - partial.display() - ); + bail!(crate::tr!( + "encode-refuse-partial", + path = partial.display().to_string() + )); } if same_file(partial, source) || same_file(output, source) { - bail!("refusing to write over the source {}", source.display()); + bail!(crate::tr!( + "encode-refuse-source", + path = source.display().to_string() + )); } Ok(()) } diff --git a/src/plan.rs b/src/plan.rs index 8d79b76..a790ad5 100644 --- a/src/plan.rs +++ b/src/plan.rs @@ -87,9 +87,9 @@ impl FrameRate { pub fn label(self) -> String { let fps = self.as_f64(); if (fps - fps.round()).abs() < 0.005 { - format!("{}", fps.round()) + crate::tr!("plan-rate-whole", fps = fps.round()) } else { - format!("{fps:.2}") + crate::tr!("plan-rate-fraction", fps = fps) } } } diff --git a/src/profile.rs b/src/profile.rs index 4ec0021..a9c9d45 100644 --- a/src/profile.rs +++ b/src/profile.rs @@ -60,13 +60,13 @@ impl ToneMapping { } /// Name shown in the UI. - pub fn label(self) -> &'static str { + pub fn label(self) -> String { match self { - Self::Auto => "Automatic (libplacebo)", - Self::Bt2390 => "BT.2390", - Self::Spline => "Spline", - Self::Hable => "Hable (filmic)", - Self::Mobius => "Möbius", + Self::Auto => crate::tr!("profile-tone-auto"), + Self::Bt2390 => crate::tr!("profile-tone-bt2390"), + Self::Spline => crate::tr!("profile-tone-spline"), + Self::Hable => crate::tr!("profile-tone-hable"), + Self::Mobius => crate::tr!("profile-tone-mobius"), } } } @@ -298,13 +298,19 @@ impl Default for ProfileSet { } } +/// The user-facing "cannot read" text for a profiles file. +fn cannot_read(path: &Path) -> String { + crate::tr!("profile-cannot-read", path = path.display().to_string()) +} + impl ProfileSet { /// Name of the file in the data folder. pub const FILE_NAME: &'static str = "profiles.toml"; /// Parses the TOML text of a profiles file. Missing fields take the built-in profile's values. pub fn parse(text: &str) -> Result { - let mut set: Self = toml::from_str(text).context("invalid profiles file")?; + let mut set: Self = + toml::from_str(text).with_context(|| crate::tr!("profile-invalid-file"))?; if set.profiles.is_empty() { set = Self::default(); } @@ -326,25 +332,29 @@ impl ProfileSet { /// Reads `path`, or the built-in set when the file does not exist yet. pub fn load(path: &Path) -> Result { match std::fs::read_to_string(path) { - Ok(text) => { - Self::parse(&text).with_context(|| format!("cannot read {}", path.display())) - } + Ok(text) => Self::parse(&text).with_context(|| cannot_read(path)), Err(error) if error.kind() == std::io::ErrorKind::NotFound => Ok(Self::default()), - Err(error) => Err(error).with_context(|| format!("cannot read {}", path.display())), + Err(error) => Err(error).with_context(|| cannot_read(path)), } } /// Writes the set to `path` through a temporary file, so a crash never leaves half a file. pub fn save(&self, path: &Path) -> Result<()> { if let Some(dir) = path.parent() { - std::fs::create_dir_all(dir) - .with_context(|| format!("cannot create {}", dir.display()))?; + std::fs::create_dir_all(dir).with_context(|| { + crate::tr!("profile-cannot-create", path = dir.display().to_string()) + })?; } let temporary = path.with_extension("toml.tmp"); - std::fs::write(&temporary, self.to_toml()) - .with_context(|| format!("cannot write {}", temporary.display()))?; - std::fs::rename(&temporary, path) - .with_context(|| format!("cannot replace {}", path.display())) + std::fs::write(&temporary, self.to_toml()).with_context(|| { + crate::tr!( + "profile-cannot-write", + path = temporary.display().to_string() + ) + })?; + std::fs::rename(&temporary, path).with_context(|| { + crate::tr!("profile-cannot-replace", path = path.display().to_string()) + }) } /// The profile named `name`, if there is one. diff --git a/src/queue.rs b/src/queue.rs index 8408f3c..d0972ff 100644 --- a/src/queue.rs +++ b/src/queue.rs @@ -404,14 +404,14 @@ impl Queue { Ok((media, engine)) => { log.push(( false, - format!( - "{}: {}, {}, {} audio track(s), color {}; {}", - job.name(), - media.summary(), - crate::timecode::format_short(media.duration, true), - media.audio.len(), - media.color_tags, - engine.label() + crate::tr!( + "queue-probed", + name = job.name(), + summary = media.summary(), + duration = crate::timecode::format_short(media.duration, true), + tracks = media.audio.len(), + color = media.color_tags.clone(), + engine = engine.label() ), )); job.trim = Trim { @@ -424,7 +424,14 @@ impl Queue { job.changed = Instant::now() - SETTLE; } Err(error) => { - log.push((true, format!("{}: {error}", job.name()))); + log.push(( + true, + crate::tr!( + "queue-job-error", + name = job.name(), + detail = error.clone() + ), + )); job.phase = Phase::Unusable(error); } } @@ -437,12 +444,23 @@ impl Queue { if let Err(error) = &result && error != "cancelled" { - log.push((true, format!("{}: estimate failed: {error}", job.name()))); + log.push(( + true, + crate::tr!( + "queue-estimate-failed", + name = job.name(), + detail = error.clone() + ), + )); } if job.engine != Some(engine) { log.push(( false, - format!("{}: now using {}", job.name(), engine.label()), + crate::tr!( + "queue-engine-changed", + name = job.name(), + engine = engine.label() + ), )); job.engine = Some(engine); } @@ -473,19 +491,26 @@ impl Queue { Ok(encoded) => { log.push(( false, - format!( - "{}: encoded to {} ({:.2} MB in {:.1} s)", - job.name(), - encoded.output.display(), - encoded.bytes as f64 / 1e6, - encoded.elapsed.as_secs_f64() + crate::tr!( + "queue-encoded", + name = job.name(), + path = encoded.output.display().to_string(), + mb = (encoded.bytes as f64 / 1e6), + seconds = encoded.elapsed.as_secs_f64() ), )); Phase::Done(encoded) } Err(error) if error == "cancelled" => Phase::Idle, Err(error) => { - log.push((true, format!("{}: encode failed: {error}", job.name()))); + log.push(( + true, + crate::tr!( + "queue-encode-failed", + name = job.name(), + detail = error.clone() + ), + )); Phase::Failed(error) } }; @@ -566,8 +591,15 @@ impl Queue { let estimate = match job.current_estimate(Some(&key)) { Some(Ok(estimate)) => *estimate, Some(Err(error)) => { - let message = format!("cannot encode without an estimate: {error}"); - log.push((true, format!("{}: {message}", job.name()))); + let message = crate::tr!("queue-no-estimate", detail = error.clone()); + log.push(( + true, + crate::tr!( + "queue-job-error", + name = job.name(), + detail = message.clone() + ), + )); let job = &mut self.jobs[index]; job.wanted = false; job.phase = Phase::Failed(message); diff --git a/src/sendto.rs b/src/sendto.rs index e0b9cb0..18df122 100644 --- a/src/sendto.rs +++ b/src/sendto.rs @@ -39,37 +39,43 @@ pub fn is_installed() -> bool { /// Writes the shortcut to the running executable, replacing an older one (after a move of the folder). pub fn install() -> Result { - let link = shortcut_path().context("no Send to folder on this system")?; - let exe = std::env::current_exe().context("cannot find this executable")?; - let folder = exe.parent().context("the executable has no folder")?; + let link = shortcut_path().with_context(|| crate::tr!("sendto-no-folder"))?; + let exe = std::env::current_exe().with_context(|| crate::tr!("sendto-no-executable"))?; + let folder = exe + .parent() + .with_context(|| crate::tr!("sendto-no-exe-folder"))?; + // The description travels in an environment variable too, like the paths: no quoting can break. let script = "$link = (New-Object -ComObject WScript.Shell).CreateShortcut($env:QVT_LINK); \ $link.TargetPath = $env:QVT_TARGET; \ $link.WorkingDirectory = $env:QVT_FOLDER; \ - $link.Description = 'Trim and re-encode videos to fit a size limit'; \ + $link.Description = $env:QVT_DESCRIPTION; \ $link.Save()"; let output = crate::ffmpeg::tool("powershell.exe") .args(["-NoProfile", "-NonInteractive", "-Command", script]) .env("QVT_LINK", &link) .env("QVT_TARGET", &exe) .env("QVT_FOLDER", folder) + .env("QVT_DESCRIPTION", crate::tr!("sendto-shortcut-description")) .stdin(Stdio::null()) .output() - .context("cannot start PowerShell")?; + .with_context(|| crate::tr!("sendto-start-failed"))?; if !output.status.success() || !link.is_file() { - bail!( - "cannot create {}: {}", - link.display(), - String::from_utf8_lossy(&output.stderr).trim() - ); + bail!(crate::tr!( + "sendto-create-failed", + path = link.display().to_string(), + detail = String::from_utf8_lossy(&output.stderr).trim().to_owned() + )); } Ok(link) } /// Deletes the shortcut, if it is there. pub fn remove() -> Result<()> { - let link = shortcut_path().context("no Send to folder on this system")?; + let link = shortcut_path().with_context(|| crate::tr!("sendto-no-folder"))?; if link.is_file() { - std::fs::remove_file(&link).with_context(|| format!("cannot delete {}", link.display()))?; + std::fs::remove_file(&link).with_context(|| { + crate::tr!("sendto-delete-failed", path = link.display().to_string()) + })?; } Ok(()) } diff --git a/src/thumbnails.rs b/src/thumbnails.rs index ce8ccb7..80c0ac3 100644 --- a/src/thumbnails.rs +++ b/src/thumbnails.rs @@ -142,14 +142,14 @@ fn decode( .args(&args) .stdin(Stdio::null()) .output() - .context("cannot run ffmpeg")?; + .with_context(|| crate::tr!("media-ffmpeg-start-failed"))?; let expected = (size.width * size.height * 4) as usize; if output.stdout.len() < expected { - bail!( - "no frame ({}): {}", - output.status, - String::from_utf8_lossy(&output.stderr).trim() - ); + bail!(crate::tr!( + "media-no-frame", + status = output.status.to_string(), + detail = String::from_utf8_lossy(&output.stderr).trim().to_owned() + )); } let mut rgba = output.stdout; rgba.truncate(expected); diff --git a/src/update/feed.rs b/src/update/feed.rs new file mode 100644 index 0000000..98fdac6 --- /dev/null +++ b/src/update/feed.rs @@ -0,0 +1,310 @@ +//! Where releases come from: GitHub's REST API for the latest release (tag, notes, assets and their +//! digests), then the assets' download URLs. [`Feed`] is the seam the tests script. +//! +//! What GitHub answers (measured 2026-11-24 on this repository's v1.0.0): `GET +//! api.github.com/repos/{owner}/{repo}/releases/latest` gives `tag_name`, `html_url`, `body`, `draft`, +//! `prerelease` and per asset `name`, `size`, `browser_download_url` and `digest: "sha256:…"`; 60 requests +//! an hour per IP without a token. An asset's URL redirects to a signed `release-assets.githubusercontent.com` +//! URL valid for about an hour. + +use std::io::{Read, Write}; +use std::time::Duration; + +use serde::Deserialize; + +use super::{Fault, Release, Version}; + +/// The executable's asset name in a release. +pub const EXE_ASSET: &str = "quick-video-transcoder.exe"; +/// The checksums' asset name. +pub const SUMS_ASSET: &str = "SHA256SUMS.txt"; + +/// A source of releases. +pub trait Feed: Send + Sync { + /// The latest published release. + fn latest(&self) -> Result; + /// A small text file (the checksums). + fn text(&self, url: &str) -> Result; + /// Streams a file into `out`, calling `progress` with the bytes written so far. Returns the size. + fn download( + &self, + url: &str, + out: &mut dyn Write, + progress: &mut dyn FnMut(u64), + ) -> Result; +} + +/// GitHub, over HTTPS. +pub struct GitHub { + agent: ureq::Agent, + /// `https://api.github.com` (a local listener in tests). + api: String, + /// `owner/repo`. + repo: String, +} + +impl GitHub { + /// This application's own repository. + pub fn new() -> Self { + let repo = crate::build_info::REPOSITORY + .trim_end_matches('/') + .trim_start_matches("https://github.com/") + .to_owned(); + Self::with_api("https://api.github.com", &repo) + } + + /// Another API base, for the tests' listener. + pub fn with_api(api: &str, repo: &str) -> Self { + let agent = ureq::Agent::config_builder() + .tls_config( + ureq::tls::TlsConfig::builder() + .root_certs(ureq::tls::RootCerts::PlatformVerifier) + .build(), + ) + // Reading the whole executable: a slow line may need minutes, a dead one fails sooner. + .timeout_connect(Some(Duration::from_secs(15))) + .timeout_recv_response(Some(Duration::from_secs(30))) + .timeout_recv_body(Some(Duration::from_secs(600))) + // A generic client name: nothing about the user. + .user_agent(format!( + "quick-video-transcoder/{}", + crate::build_info::VERSION + )) + .http_status_as_error(false) + .build() + .new_agent(); + Self { + agent, + api: api.trim_end_matches('/').to_owned(), + repo: repo.to_owned(), + } + } + + fn get(&self, url: &str) -> Result, Fault> { + let response = self + .agent + .get(url) + .header("Accept", "application/vnd.github+json") + .header("X-GitHub-Api-Version", "2022-11-28") + .call() + .map_err(|error| Fault::NoConnection(error.to_string()))?; + let status = response.status().as_u16(); + if status == 200 { + Ok(response) + } else { + log::warn!("update: {url} answered {status}"); + Err(Fault::Status(status)) + } + } +} + +impl Default for GitHub { + fn default() -> Self { + Self::new() + } +} + +#[derive(Deserialize)] +struct ApiRelease { + tag_name: String, + html_url: String, + #[serde(default)] + body: Option, + #[serde(default)] + draft: bool, + #[serde(default)] + prerelease: bool, + #[serde(default)] + assets: Vec, +} + +#[derive(Deserialize)] +struct ApiAsset { + name: String, + size: u64, + browser_download_url: String, + #[serde(default)] + digest: Option, +} + +/// Reads GitHub's answer for the latest release. +pub fn parse_release(json: &str) -> Result { + let api: ApiRelease = serde_json::from_str(json) + .map_err(|error| Fault::Unexpected(format!("not a release: {error}")))?; + if api.draft || api.prerelease { + return Err(Fault::Unexpected(format!( + "{} is a draft or a pre-release", + api.tag_name + ))); + } + let version = Version::from_tag(&api.tag_name) + .ok_or_else(|| Fault::Unexpected(format!("tag {} is not vX.Y.Z", api.tag_name)))?; + let asset = |name: &str| { + api.assets + .iter() + .find(|a| a.name == name) + .ok_or_else(|| Fault::Unexpected(format!("{} has no {name}", api.tag_name))) + }; + let exe = asset(EXE_ASSET)?; + let sums = asset(SUMS_ASSET)?; + let exe_digest = exe + .digest + .as_deref() + .and_then(|d| d.strip_prefix("sha256:")) + .map(str::to_ascii_lowercase); + Ok(Release { + version, + page: api.html_url.clone(), + notes: api.body.clone().unwrap_or_default(), + exe_url: exe.browser_download_url.clone(), + exe_size: exe.size, + exe_digest, + sums_url: sums.browser_download_url.clone(), + }) +} + +impl Feed for GitHub { + fn latest(&self) -> Result { + let url = format!("{}/repos/{}/releases/latest", self.api, self.repo); + let text = self.text(&url)?; + parse_release(&text) + } + + fn text(&self, url: &str) -> Result { + let mut response = self.get(url)?; + response + .body_mut() + .with_config() + .limit(1 << 20) + .read_to_string() + .map_err(|error| Fault::NoConnection(error.to_string())) + } + + fn download( + &self, + url: &str, + out: &mut dyn Write, + progress: &mut dyn FnMut(u64), + ) -> Result { + let mut response = self.get(url)?; + let mut reader = response.body_mut().with_config().limit(512 << 20).reader(); + let mut buffer = vec![0u8; 256 << 10]; + let mut total = 0u64; + loop { + let read = reader + .read(&mut buffer) + .map_err(|error| Fault::NoConnection(error.to_string()))?; + if read == 0 { + return Ok(total); + } + out.write_all(&buffer[..read]) + .map_err(|error| Fault::CannotWrite(error.to_string()))?; + total += read as u64; + progress(total); + } + } +} + +#[cfg(test)] +mod tests { + use std::io::{BufRead, BufReader}; + use std::net::TcpListener; + + use super::*; + + const RELEASE: &str = r##"{ + "tag_name": "v1.1.0", "html_url": "https://github.com/o/r/releases/tag/v1.1.0", + "body": "Added: languages", "draft": false, "prerelease": false, + "assets": [ + {"name": "quick-video-transcoder.exe", "size": 5, "browser_download_url": "URL/exe", + "digest": "sha256:2CF24DBA5FB0A30E26E83B2AC5B9E29E1B161E5C1FA7425E73043362938B9824"}, + {"name": "SHA256SUMS.txt", "size": 92, "browser_download_url": "URL/sums", "digest": null} + ] + }"##; + + #[test] + fn reads_the_latest_release() { + let release = parse_release(RELEASE).unwrap(); + assert_eq!(release.version, Version(1, 1, 0)); + assert_eq!(release.exe_url, "URL/exe"); + assert_eq!(release.sums_url, "URL/sums"); + assert_eq!( + release.exe_digest.as_deref(), + Some("2cf24dba5fb0a30e26e83b2ac5b9e29e1b161e5c1fa7425e73043362938b9824") + ); + assert!(release.notes.contains("languages")); + } + + #[test] + fn refuses_what_it_does_not_understand() { + for (from, to) in [ + ("v1.1.0", "v1.1"), + ("v1.1.0", "1.1.0"), + ("\"draft\": false", "\"draft\": true"), + ("\"prerelease\": false", "\"prerelease\": true"), + ("quick-video-transcoder.exe", "other.exe"), + ("SHA256SUMS.txt", "sums.txt"), + ] { + let json = RELEASE.replace(from, to); + assert!( + matches!(parse_release(&json), Err(Fault::Unexpected(_))), + "{from} -> {to}" + ); + } + assert!(matches!( + parse_release("captive portal"), + Err(Fault::Unexpected(_)) + )); + } + + /// A one-shot HTTP server on 127.0.0.1 answering each request with the next canned response. + fn serve(responses: Vec<(u16, String)>) -> String { + let listener = TcpListener::bind("127.0.0.1:0").unwrap(); + let address = listener.local_addr().unwrap(); + std::thread::spawn(move || { + for (status, body) in responses { + let Ok((mut stream, _)) = listener.accept() else { + return; + }; + let mut reader = BufReader::new(stream.try_clone().unwrap()); + let mut line = String::new(); + while reader.read_line(&mut line).is_ok_and(|n| n > 2) { + line.clear(); + } + let _ = write!( + stream, + "HTTP/1.1 {status} X\r\nContent-Length: {}\r\nConnection: close\r\n\r\n{body}", + body.len() + ); + } + }); + format!("http://{address}") + } + + #[test] + fn talks_http_and_reports_statuses() { + let base = serve(vec![ + (200, RELEASE.to_owned()), + (503, "busy".to_owned()), + (200, "hello".to_owned()), + ]); + let feed = GitHub::with_api(&base, "o/r"); + assert_eq!(feed.latest().unwrap().version, Version(1, 1, 0)); + assert_eq!(feed.text(&format!("{base}/x")), Err(Fault::Status(503))); + let mut out = Vec::new(); + let mut seen = 0; + let size = feed + .download(&format!("{base}/exe"), &mut out, &mut |n| seen = n) + .unwrap(); + assert_eq!((size, seen, out.as_slice()), (5, 5, b"hello".as_slice())); + } + + #[test] + fn a_port_nobody_listens_on_is_no_connection() { + let free = TcpListener::bind("127.0.0.1:0").unwrap(); + let address = free.local_addr().unwrap(); + drop(free); + let feed = GitHub::with_api(&format!("http://{address}"), "o/r"); + assert!(matches!(feed.latest(), Err(Fault::NoConnection(_)))); + } +} diff --git a/src/update/install.rs b/src/update/install.rs new file mode 100644 index 0000000..34c315e --- /dev/null +++ b/src/update/install.rs @@ -0,0 +1,435 @@ +//! Downloading and verifying a release beside the executable, the swap at exit, and the verdict at the +//! next start. +//! +//! The swap is GameModeExecutor's, measured there on real updates (2026-09-18/23): the process never +//! touches its own image. It writes `pending.txt` (the version it installs), starts a hidden Windows +//! PowerShell and closes. The script waits for this exact process to end (`Wait-Process -Id`, 30 s at +//! most), renames `` to `.old` and `.new` to `` (renames on the same folder: no copy; +//! retried a few times, since OneDrive or an antivirus may hold a file just written), starts the new +//! executable, and on any failure writes `result.txt`, puts the old executable back and starts it. The next +//! start compares `pending.txt` with its own version ([`settle`]). +//! +//! Write rules (no other path is ever written): `.new` and `.old` beside the running executable, +//! named from it; `pending.txt` and `result.txt` in the data folder's `updates`. Paths reach the script only +//! as PowerShell single-quoted literals (`'` doubled) and through `-LiteralPath`, so spaces, quotes and +//! brackets in a path cannot change the command. + +use std::fs::File; +use std::io::Write; +use std::path::{Path, PathBuf}; +use std::process::Stdio; + +use sha2::{Digest, Sha256}; + +use super::feed::{EXE_ASSET, Feed}; +use super::{Fault, Phase, Release, Version}; + +/// The files an update touches. +#[derive(Clone, Debug, PartialEq, Eq)] +pub struct Paths { + /// The running executable. + pub exe: PathBuf, + /// The downloaded one, beside it. + pub new: PathBuf, + /// The previous one, kept until the new version has started. + pub old: PathBuf, + /// `pending.txt`: the version being installed. + pub pending: PathBuf, + /// `result.txt`: why the swap failed, written by the script. + pub result: PathBuf, +} + +impl Paths { + /// The paths for this executable and data folder. + pub fn new(exe: &Path, data_dir: &Path) -> Self { + let sibling = |suffix: &str| { + let mut name = exe.file_name().unwrap_or_default().to_os_string(); + name.push(suffix); + exe.with_file_name(name) + }; + let updates = data_dir.join("updates"); + Self { + exe: exe.to_path_buf(), + new: sibling(".new"), + old: sibling(".old"), + pending: updates.join("pending.txt"), + result: updates.join("result.txt"), + } + } + + /// The paths of this process, if its executable and data folder are known. + pub fn current() -> Option { + let exe = std::env::current_exe().ok()?; + Some(Self::new(&exe, &crate::profile::data_dir()?)) + } + + /// `true` when `path` is one of the two files this module may write beside the executable. + fn is_sibling(&self, path: &Path) -> bool { + path.parent() == self.exe.parent() && (path == self.new || path == self.old) + } +} + +/// Writes through to a file while hashing what was written. +struct Hashing<'a> { + file: &'a mut File, + hasher: Sha256, +} + +impl Write for Hashing<'_> { + fn write(&mut self, bytes: &[u8]) -> std::io::Result { + let written = self.file.write(bytes)?; + self.hasher.update(&bytes[..written]); + Ok(written) + } + + fn flush(&mut self) -> std::io::Result<()> { + self.file.flush() + } +} + +/// The SHA-256 `SHA256SUMS.txt` gives for `name` (` ` lines). +pub fn published_hash(sums: &str, name: &str) -> Option { + sums.lines().find_map(|line| { + let (hash, file) = line.trim().split_once(char::is_whitespace)?; + (file.trim().trim_start_matches('*') == name && hash.len() == 64) + .then(|| hash.to_ascii_lowercase()) + }) +} + +/// Downloads `release`'s executable to `.new` and verifies it against both witnesses; a file that does +/// not verify is deleted. `progress` receives the bytes downloaded so far. +pub fn download( + feed: &dyn Feed, + release: &Release, + paths: &Paths, + progress: &mut dyn FnMut(u64), +) -> Result<(), Fault> { + assert!( + paths.is_sibling(&paths.new), + "the download goes beside the executable" + ); + let sums = feed.text(&release.sums_url)?; + let published = published_hash(&sums, EXE_ASSET) + .ok_or_else(|| Fault::Unexpected(format!("{EXE_ASSET} is not in the checksums")))?; + if let Some(digest) = &release.exe_digest + && *digest != published + { + return Err(Fault::Unexpected( + "GitHub's digest and the checksums disagree".to_owned(), + )); + } + // Creating it is also the test that the folder can be written. + let mut file = File::create(&paths.new) + .map_err(|error| Fault::CannotWrite(format!("{}: {error}", paths.new.display())))?; + let mut writer = Hashing { + file: &mut file, + hasher: Sha256::new(), + }; + let result = feed.download(&release.exe_url, &mut writer, progress); + let actual = hex(&writer.hasher.finalize()); + let flushed = file.sync_all(); + drop(file); + let verdict = match (result, flushed) { + (Err(fault), _) => Err(fault), + (Ok(_), Err(error)) => Err(Fault::CannotWrite(error.to_string())), + (Ok(size), Ok(())) if size != release.exe_size => Err(Fault::Unexpected(format!( + "{size} bytes received, {} published", + release.exe_size + ))), + (Ok(_), Ok(())) if actual != published => { + log::warn!("update: downloaded {actual}, published {published}"); + Err(Fault::NotVerified) + } + (Ok(_), Ok(())) => Ok(()), + }; + if verdict.is_err() { + let _ = std::fs::remove_file(&paths.new); + } + verdict +} + +fn hex(bytes: &[u8]) -> String { + bytes.iter().map(|b| format!("{b:02x}")).collect() +} + +/// A PowerShell single-quoted literal: nothing inside is interpreted, `'` is doubled. +fn quoted(path: &Path) -> String { + format!("'{}'", path.to_string_lossy().replace('\'', "''")) +} + +/// The script run after this process (`pid`) exits. +pub fn swap_script(pid: u32, paths: &Paths) -> String { + let (exe, new, old, result) = ( + quoted(&paths.exe), + quoted(&paths.new), + quoted(&paths.old), + quoted(&paths.result), + ); + format!( + "$ErrorActionPreference = 'Stop' +Wait-Process -Id {pid} -Timeout 30 -ErrorAction SilentlyContinue +function Retry([scriptblock] $Step) {{ + for ($i = 1; ; $i++) {{ + try {{ & $Step; return }} catch {{ if ($i -ge 10) {{ throw }}; Start-Sleep -Milliseconds 500 }} + }} +}} +try {{ + if (Get-Process -Id {pid} -ErrorAction SilentlyContinue) {{ throw 'the application did not close' }} + if (Test-Path -LiteralPath {old}) {{ Retry {{ Remove-Item -LiteralPath {old} -Force }} }} + Retry {{ Move-Item -LiteralPath {exe} -Destination {old} -Force }} + Retry {{ Move-Item -LiteralPath {new} -Destination {exe} }} + Start-Process -FilePath {exe} +}} catch {{ + Set-Content -LiteralPath {result} -Value $_.Exception.Message -Encoding UTF8 + if (-not (Test-Path -LiteralPath {exe}) -and (Test-Path -LiteralPath {old})) {{ + Move-Item -LiteralPath {old} -Destination {exe} -Force + }} + if (-not (Get-Process -Id {pid} -ErrorAction SilentlyContinue)) {{ Start-Process -FilePath {exe} }} +}} +" + ) +} + +/// Writes `pending.txt` and starts the swap script. The caller closes the application at once. +pub fn launch(release: &Release, paths: &Paths) -> Result<(), Fault> { + let updates = paths.pending.parent().expect("pending.txt is in a folder"); + std::fs::create_dir_all(updates) + .and_then(|()| std::fs::write(&paths.pending, release.version.to_string())) + .map_err(|error| Fault::CannotWrite(format!("{}: {error}", paths.pending.display())))?; + let _ = std::fs::remove_file(&paths.result); + let script = swap_script(std::process::id(), paths); + log::info!( + "update: installing {}; the application closes and comes back on it", + release.version + ); + crate::ffmpeg::tool("powershell.exe") + .args([ + "-NoProfile", + "-NonInteractive", + "-WindowStyle", + "Hidden", + "-Command", + ]) + .arg(script) + .stdin(Stdio::null()) + .stdout(Stdio::null()) + .stderr(Stdio::null()) + .spawn() + .map(drop) + .map_err(|error| { + let _ = std::fs::remove_file(&paths.pending); + Fault::Launch(error.to_string()) + }) +} + +/// At start: the outcome of an update the previous run started, if any, and tidying. `None` when no update +/// was pending. A leftover `.new` without a pending update (a download never installed) is deleted. +pub fn settle(paths: &Paths, current: Version) -> Option { + let Ok(text) = std::fs::read_to_string(&paths.pending) else { + if paths.new.is_file() { + let _ = std::fs::remove_file(&paths.new); + } + return None; + }; + let pending = Version::parse(text.trim_start_matches('\u{feff}').trim()); + let reason = std::fs::read_to_string(&paths.result) + .ok() + .map(|r| r.trim_start_matches('\u{feff}').trim().to_owned()); + let _ = std::fs::remove_file(&paths.pending); + let _ = std::fs::remove_file(&paths.result); + if pending == Some(current) { + log::info!("update: updated to {current}"); + if paths.old.is_file() { + let _ = std::fs::remove_file(&paths.old); + } + Some(Phase::Updated(current)) + } else { + // The download that was not installed goes: a new attempt downloads again. + if paths.new.is_file() { + let _ = std::fs::remove_file(&paths.new); + } + let reason = reason.unwrap_or_else(|| "did not take".to_owned()); + log::warn!( + "update: the update to {} failed ({reason}); still {current}", + text.trim() + ); + Some(Phase::Failed { + fault: Fault::Launch(reason), + release: None, + }) + } +} + +#[cfg(test)] +mod tests { + use std::sync::Mutex; + + use super::*; + + /// A scripted feed: fixed checksums and file, no network. + struct Scripted { + sums: String, + file: Vec, + seen: Mutex>, + } + + impl Feed for Scripted { + fn latest(&self) -> Result { + unreachable!() + } + fn text(&self, url: &str) -> Result { + self.seen.lock().unwrap().push(url.to_owned()); + Ok(self.sums.clone()) + } + fn download( + &self, + url: &str, + out: &mut dyn Write, + progress: &mut dyn FnMut(u64), + ) -> Result { + self.seen.lock().unwrap().push(url.to_owned()); + out.write_all(&self.file).unwrap(); + progress(self.file.len() as u64); + Ok(self.file.len() as u64) + } + } + + const HELLO_SHA256: &str = "2cf24dba5fb0a30e26e83b2ac5b9e29e1b161e5c1fa7425e73043362938b9824"; + + fn release(digest: Option<&str>) -> Release { + Release { + version: Version(1, 1, 0), + page: String::new(), + notes: String::new(), + exe_url: "exe-url".to_owned(), + exe_size: 5, + exe_digest: digest.map(str::to_owned), + sums_url: "sums-url".to_owned(), + } + } + + fn setup() -> (tempfile::TempDir, Paths) { + let dir = tempfile::tempdir().unwrap(); + let exe = dir + .path() + .join("app folder") + .join("quick-video-transcoder.exe"); + std::fs::create_dir_all(exe.parent().unwrap()).unwrap(); + std::fs::write(&exe, b"old").unwrap(); + let paths = Paths::new(&exe, &dir.path().join("data")); + (dir, paths) + } + + #[test] + fn names_its_files_beside_the_executable_and_in_the_data_folder() { + let paths = Paths::new( + Path::new(r"C:\Tools\quick-video-transcoder.exe"), + Path::new(r"C:\Data"), + ); + assert_eq!( + paths.new, + Path::new(r"C:\Tools\quick-video-transcoder.exe.new") + ); + assert_eq!( + paths.old, + Path::new(r"C:\Tools\quick-video-transcoder.exe.old") + ); + assert_eq!(paths.pending, Path::new(r"C:\Data\updates\pending.txt")); + assert!(paths.is_sibling(&paths.new)); + assert!(!paths.is_sibling(&paths.exe)); + } + + #[test] + fn reads_the_checksums_file() { + let sums = format!( + "{} quick-video-transcoder.exe\n", + HELLO_SHA256.to_uppercase() + ); + assert_eq!( + published_hash(&sums, "quick-video-transcoder.exe").as_deref(), + Some(HELLO_SHA256) + ); + assert_eq!(published_hash(&sums, "other.exe"), None); + assert_eq!(published_hash("", "quick-video-transcoder.exe"), None); + } + + #[test] + fn keeps_a_verified_download_and_deletes_a_bad_one() { + let (_dir, paths) = setup(); + let good = Scripted { + sums: format!("{HELLO_SHA256} quick-video-transcoder.exe"), + file: b"hello".to_vec(), + seen: Mutex::default(), + }; + download(&good, &release(Some(HELLO_SHA256)), &paths, &mut |_| {}).unwrap(); + assert_eq!(std::fs::read(&paths.new).unwrap(), b"hello"); + assert_eq!( + std::fs::read(&paths.exe).unwrap(), + b"old", + "the executable is untouched" + ); + + let tampered = Scripted { + file: b"hellO".to_vec(), + ..good + }; + assert_eq!( + download(&tampered, &release(Some(HELLO_SHA256)), &paths, &mut |_| {}), + Err(Fault::NotVerified) + ); + assert!(!paths.new.exists(), "a file that did not verify is deleted"); + let disagreeing = release(Some(&"0".repeat(64))); + assert!(matches!( + download(&tampered, &disagreeing, &paths, &mut |_| {}), + Err(Fault::Unexpected(_)) + )); + } + + #[test] + fn the_script_quotes_every_path_and_puts_the_old_executable_back() { + let paths = Paths::new( + Path::new(r"C:\It's [a] folder\quick-video-transcoder.exe"), + Path::new(r"C:\Data"), + ); + let script = swap_script(4242, &paths); + assert!(script.contains("Wait-Process -Id 4242 -Timeout 30")); + assert!(script.contains(r"-LiteralPath 'C:\It''s [a] folder\quick-video-transcoder.exe'")); + assert!(!script.contains("\""), "no double quote reaches PowerShell"); + let rename = script + .find("-Destination 'C:\\It''s [a] folder\\quick-video-transcoder.exe.old'") + .unwrap(); + let start = script.find("Start-Process").unwrap(); + assert!(rename < start, "the swap happens before the restart"); + assert!(script.contains("catch")); + } + + #[test] + fn the_next_start_says_whether_the_update_took() { + let (_dir, paths) = setup(); + assert_eq!(settle(&paths, Version(1, 1, 0)), None); + + std::fs::create_dir_all(paths.pending.parent().unwrap()).unwrap(); + std::fs::write(&paths.pending, "\u{feff}1.1.0\r\n").unwrap(); + std::fs::write(&paths.old, b"old").unwrap(); + assert_eq!( + settle(&paths, Version(1, 1, 0)), + Some(Phase::Updated(Version(1, 1, 0))) + ); + assert!(!paths.old.exists() && !paths.pending.exists()); + + std::fs::write(&paths.pending, "1.1.0").unwrap(); + std::fs::write(&paths.result, "\u{feff}access denied").unwrap(); + assert_eq!( + settle(&paths, Version(1, 0, 0)), + Some(Phase::Failed { + fault: Fault::Launch("access denied".to_owned()), + release: None + }) + ); + assert!(!paths.result.exists()); + + std::fs::write(&paths.new, b"stale").unwrap(); + assert_eq!(settle(&paths, Version(1, 0, 0)), None); + assert!(!paths.new.exists(), "a download never installed is tidied"); + } +} diff --git a/src/update/mod.rs b/src/update/mod.rs new file mode 100644 index 0000000..9c1d5a9 --- /dev/null +++ b/src/update/mod.rs @@ -0,0 +1,340 @@ +//! Updating the application from its GitHub releases, from a window the user opens (*Help → Check for +//! updates*): check, download and verify, then swap the executable and restart. +//! +//! Rules this module is shaped by (docs/updating.md has the design and its measurements): +//! - **Never a silent connection.** Nothing connects unless the user clicked; no check at start. +//! - **The UI reflects [`Machine`]**: every rule (which actions a phase takes, what a result means) lives +//! here; the window draws [`Machine::phase`] and sends [`Event`]s. The worker runs the [`Effect`]s. +//! - **One release, named by its tag.** The check reads the latest release once; the download uses that +//! release's own URLs, so a release published in between cannot mix one version's file with another's +//! hash. A tag that is not exactly `vX.Y.Z` is "a release this version does not understand". Never a +//! downgrade. +//! - **Two witnesses to the file**: the workflow's `SHA256SUMS.txt` and GitHub's own digest of the asset, +//! both fetched over TLS, must equal the downloaded file's SHA-256. They protect against a corrupted or +//! truncated download, not against a compromised account (said in the docs). +//! - **The running executable is never written.** The new one is downloaded beside it +//! (`.new`, same folder, so the swap is a rename), and a hidden PowerShell started at exit waits for +//! this process to end, renames, restarts, and puts the old one back on failure ([`install`]). The +//! version that starts next says whether it worked, from `pending.txt` ([`install::settle`]). +//! - Tests never call GitHub: [`feed::Feed`] is scripted, and the HTTP feed is tested against a listener on +//! 127.0.0.1. + +pub mod feed; +pub mod install; + +use std::fmt; + +/// A version, `major.minor.patch`. +#[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord)] +pub struct Version(pub u16, pub u16, pub u16); + +impl Version { + /// This executable's version. + pub fn current() -> Self { + Self::parse(crate::build_info::VERSION).expect("Cargo.toml has an x.y.z version") + } + + /// `1.2.3`, without suffix. + pub fn parse(text: &str) -> Option { + let mut parts = text.split('.').map(|p| { + (!p.is_empty() && p.bytes().all(|b| b.is_ascii_digit())) + .then(|| p.parse::().ok()) + .flatten() + }); + let version = Self(parts.next()??, parts.next()??, parts.next()??); + parts.next().is_none().then_some(version) + } + + /// A release tag, exactly `vX.Y.Z`. + pub fn from_tag(tag: &str) -> Option { + Self::parse(tag.strip_prefix('v')?) + } +} + +impl fmt::Display for Version { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + write!(f, "{}.{}.{}", self.0, self.1, self.2) + } +} + +/// What the latest release offers. +#[derive(Clone, Debug, PartialEq, Eq)] +pub struct Release { + /// Its version, from the tag. + pub version: Version, + /// Its page on GitHub. + pub page: String, + /// Its notes (the changelog section), Markdown. + pub notes: String, + /// The executable's download URL. + pub exe_url: String, + /// The executable's size in bytes. + pub exe_size: u64, + /// GitHub's SHA-256 of the executable, lower-case hex, when GitHub gives it. + pub exe_digest: Option, + /// `SHA256SUMS.txt`'s download URL. + pub sums_url: String, +} + +/// Why a step failed. Shown to the user by the window (localized there); the log has the details. +#[derive(Clone, Debug, PartialEq, Eq)] +pub enum Fault { + /// No answer: no connection, DNS, timeout, TLS. The detail is technical. + NoConnection(String), + /// GitHub answered with this HTTP status. + Status(u16), + /// An answer this version does not understand (no such asset, a tag not `vX.Y.Z`, not JSON…). + Unexpected(String), + /// The downloaded file's SHA-256 is not the published one. + NotVerified, + /// The executable's folder cannot be written (installed under Program Files, read-only…). + CannotWrite(String), + /// The restart could not be started. + Launch(String), +} + +/// The updater's state. Starts [`Phase::Idle`], or with the outcome of an update that ran before this +/// start ([`install::settle`]). +#[derive(Clone, Debug, PartialEq)] +pub enum Phase { + /// Nothing asked. + Idle, + /// The check is running. + Checking, + /// This version is the latest. + UpToDate(Version), + /// A newer release exists. + Available(Release), + /// Downloading it: bytes so far. + Downloading(Release, u64), + /// Downloaded and verified beside the executable: restarting installs it. + Ready(Release), + /// The swap script is starting: the application closes now. + Restarting(Release), + /// The previous run updated to this version (said once, at start). + Updated(Version), + /// A step failed; `release` is kept when the failure came after a release was found. + Failed { + /// What failed. + fault: Fault, + /// The release found, if any (to offer its page). + release: Option, + }, +} + +/// What happened, sent by the window (a click) or the worker (a result). +#[derive(Clone, Debug, PartialEq)] +pub enum Event { + /// *Check for updates*. + CheckAsked, + /// The check's result: the latest release, or why it failed. + Checked(Result), + /// *Download and install*. + DownloadAsked, + /// Bytes downloaded so far. + Progress(u64), + /// The download's result (verified or not). + Downloaded(Result<(), Fault>), + /// *Restart now* (the window checks nothing is encoding first). + RestartAsked, + /// The swap script could not be started. + LaunchFailed(Fault), +} + +/// Work the worker must do for an event. +#[derive(Clone, Debug, PartialEq, Eq)] +pub enum Effect { + /// Read the latest release. + Check, + /// Download and verify this release beside the executable. + Download(Release), + /// Write `pending.txt`, start the swap script and close the application. + Restart(Release), +} + +/// The update state machine. Pure: no I/O, so every rule is tested. +#[derive(Clone, Debug, PartialEq)] +pub struct Machine { + phase: Phase, + current: Version, +} + +impl Machine { + /// A machine for the running version, starting in `phase`. + pub fn new(current: Version, phase: Phase) -> Self { + Self { phase, current } + } + + /// The current phase, for the window. + pub fn phase(&self) -> &Phase { + &self.phase + } + + /// Applies an event and returns the work it asks for. An event the phase does not take (a click on a + /// stale button, a result nobody waits for) changes nothing. + pub fn apply(&mut self, event: Event) -> Option { + use Phase as P; + let (phase, effect) = match (&self.phase, event) { + ( + P::Idle | P::UpToDate(_) | P::Available(_) | P::Updated(_) | P::Failed { .. }, + Event::CheckAsked, + ) => (P::Checking, Some(Effect::Check)), + (P::Checking, Event::Checked(Ok(release))) => { + if release.version > self.current { + (P::Available(release), None) + } else { + // Equal, or older (a release withdrawn): never offered as an update. + (P::UpToDate(self.current), None) + } + } + (P::Checking, Event::Checked(Err(fault))) => ( + P::Failed { + fault, + release: None, + }, + None, + ), + (P::Available(release), Event::DownloadAsked) + | ( + P::Failed { + release: Some(release), + .. + }, + Event::DownloadAsked, + ) => ( + P::Downloading(release.clone(), 0), + Some(Effect::Download(release.clone())), + ), + (P::Downloading(release, _), Event::Progress(done)) => { + (P::Downloading(release.clone(), done), None) + } + (P::Downloading(release, _), Event::Downloaded(Ok(()))) => { + (P::Ready(release.clone()), None) + } + (P::Downloading(release, _), Event::Downloaded(Err(fault))) => ( + P::Failed { + fault, + release: Some(release.clone()), + }, + None, + ), + (P::Ready(release), Event::RestartAsked) => ( + P::Restarting(release.clone()), + Some(Effect::Restart(release.clone())), + ), + (P::Restarting(release), Event::LaunchFailed(fault)) => ( + P::Failed { + fault, + release: Some(release.clone()), + }, + None, + ), + _ => return None, + }; + self.phase = phase; + effect + } +} + +#[cfg(test)] +mod tests { + use super::*; + + fn release(version: Version) -> Release { + Release { + version, + page: format!("https://example.invalid/v{version}"), + notes: "### Added\n\n- something".to_owned(), + exe_url: "https://example.invalid/exe".to_owned(), + exe_size: 1000, + exe_digest: Some("ab".repeat(32)), + sums_url: "https://example.invalid/sums".to_owned(), + } + } + + #[test] + fn reads_versions_and_tags_strictly() { + assert_eq!(Version::parse("1.10.0"), Some(Version(1, 10, 0))); + assert_eq!(Version::from_tag("v2.0.1"), Some(Version(2, 0, 1))); + for bad in [ + "1.0", + "1.0.0.0", + "1.0.0-beta", + "v1.0.0", + "1..0", + "", + "a.b.c", + ] { + assert_eq!(Version::parse(bad), None, "{bad}"); + } + assert_eq!(Version::from_tag("1.0.0"), None); + assert_eq!(Version::from_tag("v1.0.0-rc1"), None); + assert!(Version(1, 10, 0) > Version(1, 9, 9)); + assert_eq!(Version(1, 2, 3).to_string(), "1.2.3"); + } + + #[test] + fn checks_downloads_and_restarts_in_order() { + let mut machine = Machine::new(Version(1, 0, 0), Phase::Idle); + assert_eq!( + machine.apply(Event::DownloadAsked), + None, + "nothing to download yet" + ); + assert_eq!(machine.apply(Event::CheckAsked), Some(Effect::Check)); + assert_eq!( + machine.apply(Event::CheckAsked), + None, + "one check at a time" + ); + let newer = release(Version(1, 1, 0)); + assert_eq!(machine.apply(Event::Checked(Ok(newer.clone()))), None); + assert_eq!(machine.phase(), &Phase::Available(newer.clone())); + assert_eq!( + machine.apply(Event::DownloadAsked), + Some(Effect::Download(newer.clone())) + ); + assert_eq!( + machine.apply(Event::CheckAsked), + None, + "not during a download" + ); + machine.apply(Event::Progress(500)); + assert_eq!(machine.phase(), &Phase::Downloading(newer.clone(), 500)); + machine.apply(Event::Downloaded(Ok(()))); + assert_eq!(machine.phase(), &Phase::Ready(newer.clone())); + assert_eq!( + machine.apply(Event::RestartAsked), + Some(Effect::Restart(newer.clone())) + ); + machine.apply(Event::LaunchFailed(Fault::Launch("x".to_owned()))); + assert!(matches!(machine.phase(), Phase::Failed { release: Some(r), .. } if *r == newer)); + } + + #[test] + fn never_offers_the_same_or_an_older_version() { + for latest in [Version(1, 0, 0), Version(0, 9, 0)] { + let mut machine = Machine::new(Version(1, 0, 0), Phase::Idle); + machine.apply(Event::CheckAsked); + machine.apply(Event::Checked(Ok(release(latest)))); + assert_eq!(machine.phase(), &Phase::UpToDate(Version(1, 0, 0))); + assert_eq!(machine.apply(Event::DownloadAsked), None); + } + } + + #[test] + fn a_failed_download_can_be_retried_and_a_failed_check_checked_again() { + let newer = release(Version(1, 1, 0)); + let mut machine = Machine::new(Version(1, 0, 0), Phase::Available(newer.clone())); + machine.apply(Event::DownloadAsked); + machine.apply(Event::Downloaded(Err(Fault::NotVerified))); + assert_eq!( + machine.apply(Event::DownloadAsked), + Some(Effect::Download(newer)) + ); + let mut offline = Machine::new(Version(1, 0, 0), Phase::Checking); + offline.apply(Event::Checked(Err(Fault::NoConnection("dns".to_owned())))); + assert_eq!(offline.apply(Event::DownloadAsked), None); + assert_eq!(offline.apply(Event::CheckAsked), Some(Effect::Check)); + } +}