3 Commits

Author SHA1 Message Date
70196fc3cd i18n phase 3: Italian catalog
- babel.cfg and the catalog sources: bal/locale/bal.pot (424 texts) and
  bal/locale/it_IT/LC_MESSAGES/bal.po, fully translated (43 entries taken
  from Electrum's it_IT catalog, the rest following the owner's glossary
  and review: "locktime" kept in English, "transazione senza
  Will-Executor" for the backup transaction).
- build_zip.py compiles each bal.po into bal.mo inside the zip (Babel
  required); .po/.pot are not shipped and *.mo is ignored by git.
- tests/test_translations.py: catalogs compile, {} fields and $tokens
  match, no address/e-mail/URL added by a translation (patterns from
  electrum-locale).
- AGENTS.md: how to update the catalogs or add a language.

See CHANGELOG entry 60 and PLAN_I18N.md.
2026-09-26 22:59:38 +02:00
9c654bf2bf i18n phases 1+2: BAL translation layer and translatable texts
Phase 1: new bal/i18n.py, BAL's own gettext layer (domain "bal", catalogs
read with plugin.read_file()). _() asks Electrum's catalog first, then
BAL's, then returns the English source. The Qt plugin loads the catalog of
Electrum's GUI language at start-up; the CLI stays English.

Phase 2: every user-visible GUI text is now a whole, extractable sentence
(Ruff INT rules enabled). Class-level texts are marked with N_() and
translated when shown. Stored data stays language-neutral: the status
history is written in English and translated for display, the calendar
defaults follow the GUI language, and the history label and wallet labels
are never translated because BAL uses them to recognise its transactions.

No visible change apart from the double colon fixed in the will detail.
See CHANGELOG entries 58 and 59 and PLAN_I18N.md.
2026-09-26 21:54:50 +02:00
e8db76338d docs: add PLAN_I18N.md (Italian translation plan)
Plan for translating the Qt GUI of the plugin into Italian via a
BAL-owned gettext catalog, with the owner's decisions recorded in
section 6. No code changes.
2026-09-26 17:01:38 +02:00
24 changed files with 5702 additions and 233 deletions

3
.gitignore vendored
View File

@@ -34,3 +34,6 @@ tmp*
# Release artifacts # Release artifacts
bal_v*.zip.* bal_v*.zip.*
tests/karen7 tests/karen7
# Compiled translations: build_zip.py rebuilds them from the .po sources
*.mo

View File

@@ -83,6 +83,32 @@ QT_QPA_PLATFORM=offscreen python3 -m pytest tests/test_core_*.py -q
registration API differs between them (`json_db.register_dict` vs registration API differs between them (`json_db.register_dict` vs
`stored_dict.register_name`). `stored_dict.register_name`).
## Translations (i18n)
How it works: `bal/i18n.py` (Electrum's catalog first, then BAL's, then
English). Plan and decisions: `PLAN_I18N.md`.
- Sources in git: `babel.cfg`, `bal/locale/bal.pot` (template) and
`bal/locale/<lang>/LC_MESSAGES/bal.po` (one per language). The compiled
`.mo` files are NOT in git: `build_zip.py` builds them into the zip.
- Writing texts: `_("... {}").format(x)`, never f-strings or `%` inside
`_()` (Ruff INT); `N_()` for class attributes/constants, translated with
`_()` when shown. Never translate stored or compared text (wallet labels,
`HISTORY_LABEL`, the status history).
- After changing texts, refresh the catalogs (then translate the new
entries, e.g. with Poedit):
```bash
pybabel extract -F babel.cfg --no-wrap -o bal/locale/bal.pot .
pybabel update -i bal/locale/bal.pot -d bal/locale -D bal --no-wrap
```
- New language: `pybabel init -i bal/locale/bal.pot -d bal/locale -D bal -l <lang>`
(use Electrum's language code, e.g. `de_DE`).
- Dev install (symlink, not the zip): compile once to see the translations,
`pybabel compile -d bal/locale -D bal`.
- `tests/test_translations.py` checks every catalog ({} fields, `$tokens`,
no addresses/links/e-mails added by a translation) and prints a summary
when run standalone.
## Build / release ## Build / release
```bash ```bash
@@ -90,6 +116,8 @@ python3 build_zip.py # -> bal-electrum-plugin.zip (deterministic, prints sha25
./make-release.sh [v0.x.y] # bump manifest version, tag, sign, push Gitea release ./make-release.sh [v0.x.y] # bump manifest version, tag, sign, push Gitea release
``` ```
- `build_zip.py` needs **Babel** (`pip install babel`): it compiles the
translation catalogs into the zip and stops if Babel is missing.
- `make-release.sh` requires gpg and Gitea credentials (`~/.git-credentials` - `make-release.sh` requires gpg and Gitea credentials (`~/.git-credentials`
or `GITEA_USER`/`GITEA_TOKEN`). It bumps `bal/manifest.json` — bump the or `GITEA_USER`/`GITEA_TOKEN`). It bumps `bal/manifest.json` — bump the
version there, never invent a new source of truth. version there, never invent a new source of truth.

View File

@@ -3327,3 +3327,124 @@ densest frames possible.
the base36 count fields are 3 chars regardless of how many frames exist. the base36 count fields are 3 chars regardless of how many frames exist.
**Outcome:** DONE. **Outcome:** DONE.
## 58. i18n phase 1: BAL translation layer (Electrum first, then BAL)
**Date:** 2026-09-26 (branch `feature/i18n`, see `PLAN_I18N.md`)
**Goal (owner request):** make the whole plugin translatable, starting with
Italian, so that BAL follows the language chosen in Electrum. This phase adds
the mechanism only: nothing visible changes yet.
**What changed:**
- New `bal/i18n.py`, BAL's own gettext layer (domain `bal`, catalogs in
`bal/locale/<lang>/LC_MESSAGES/bal.mo`, read with `plugin.read_file()` so it
works from the zip and from a development checkout):
- `_()` looks a text up in Electrum's catalog first, then in BAL's, then
returns the English source (owner's decision D7: BAL reads like Electrum,
and Electrum's translations would take over if BAL ever became an internal
plugin). BAL translations whose `{}` fields differ from the source are
rejected with the same rules as Electrum's.
- `N_()` marks texts defined at import time, translated when shown.
- `init_from_config()` repeats Electrum's own language choice (Preferences >
Language, else the supported system language, else English) once, in the
Qt `Plugin.__init__`. A missing or broken catalog never stops the plugin.
- `common.py`, `theme.py`, `core/will.py`, `core/willexecutors.py` now import
`_` from `bal.i18n`. The CLI keeps Electrum's translator and stays English,
like Electrum's own CLI.
**Verification:** new `tests/test_i18n.py`; results in entry 59.
**Outcome:** DONE (delivered in one test ZIP together with entry 59).
## 59. i18n phase 2: translatable texts and language-neutral stored data
**Date:** 2026-09-26 (branch `feature/i18n`, see `PLAN_I18N.md`)
**Goal:** make every user-visible text of the Qt GUI extractable and
translatable, without changing the English UI, and make sure no stored data
depends on the GUI language.
**What changed:**
- Texts built with f-strings or `.format()` inside `_()`, or glued together
from pieces, are now whole sentences with `{}` fields (Ruff INT clean).
- Class-level texts (list headers, wizard titles/messages, help texts,
download error messages, status labels) are marked with `N_()` and
translated when shown: class bodies run before the catalog is loaded.
- Helpers no longer translate their argument (`add_widget`, `get_window_title`,
`msg_set_status`, the will-detail `qlabel`): callers pass translated text.
This also stops heir names and URLs from going through the translator.
- Newly translatable: the settings help texts, the wizard download options,
the build report rows, the Ping/Select menu buttons, the QR size presets
(marked in `common.QR_PRESET_LABELS`: `core/qrtransfer.py` stays free of
Electrum imports because the Android reader ships a copy of it), and the
"(reminder i/n)" suffix of the calendar events (`build_ics_reminders` gained
`reminder_suffix`, English by default for the CLI).
- **Stored status history:** `WillItem.set_status` now always writes the
English label; the new `format_status_history()` translates it for display
(lists and will detail) and keeps unknown tokens as they are, so histories
saved by older versions (e.g. `New.Firmato.Pushed`) still display fine.
- **Calendar defaults:** `EVENT_SUMMARY` / `EVENT_DESCRIPTION` defaults follow
the GUI language (`BalConfig(..., translatable=True)`), while the English
original is what gets stored; a text written by the user is kept as it is.
- **Not translated on purpose:** `HISTORY_LABEL` (used by
`Util._label_matches_history` to recognise BAL's own local transactions),
the "BAL Invalidate/Inheritance transaction" wallet labels,
`heirs.TRANSACTION_LABEL` and the will-executor "info" fallback stored in the
config.
- Two small visible fixes: the will detail showed "Transaction fees::" and
"Status::" with a double colon.
- `pyproject.toml`: Ruff now also checks the `INT` (gettext) rules.
**Verification (Electrum 4.8.2, Python 3.14, offscreen):**
- `tests/test_i18n.py`: 20 passed (lookup order, rejected `{}` fields,
missing/broken catalogs, language fallback, English status storage and its
display translation, translatable config defaults, reminder suffix, QR
preset labels).
- Release-gate batch (as `make-release.sh`): 403 passed, 1 failed; the other
offline test files: 213 passed. Identical to the baseline taken before the
change; the only failures are pre-existing (`test_e5` and
`test_reproduce_none_type` need the local `tests/karen7` wallet,
`test_import_start_stop_scan_signal_wiring` fails on `main` too,
`test_gui_export_dialogs.py` hangs on `main` too).
- `smoke_test.py`, `build_zip.py` and `external_zip_test.py`: OK.
- Ruff: INT clean; no new errors (the only one left is the pre-existing
`dialogs.py` I001).
- Babel extraction (GUI + core): 424 strings (about 3,000 words), was 323.
**Outcome:** DONE, pending the owner's test of the ZIP.
## 60. i18n phase 3: Italian catalog
**Date:** 2026-09-26 (branch `feature/i18n`, see `PLAN_I18N.md`)
**Goal (owner request):** with Electrum set to Italian, BAL shows in Italian.
**What changed:**
- `babel.cfg` (extraction mapping, CLI and wallet_util excluded),
`bal/locale/bal.pot` (template, 424 texts) and the Italian catalog
`bal/locale/it_IT/LC_MESSAGES/bal.po`: 43 entries copied from Electrum's
own it_IT catalog (same English text), the others drafted following the
owner's glossary (D1). Draft to be reviewed by the owner (D2).
- `build_zip.py` compiles every `bal.po` into `bal.mo` inside the zip
(Babel required, the build stops without it); `.po`/`.pot` are not
shipped and `*.mo` is ignored by git (D4).
- New `tests/test_translations.py`: every catalog compiles; `{}` fields and
`$tokens` match the English text; no Bitcoin address, e-mail, URL or long
letters-and-digits word that the English text does not have (patterns from
Electrum's `electrum-locale/update.py`).
- `AGENTS.md`: how to update the catalogs, add a language, compile for the
development install.
**Verification (Electrum 4.8.2, offscreen):** `tests/test_translations.py`
OK (it_IT: 424 translated, 0 untranslated, 0 fuzzy); all offline tests 640
passed, only the pre-existing failures of entry 59; the built zip contains
only `bal/locale/it_IT/LC_MESSAGES/bal.mo` for the translations and
`external_zip_test.py` loads it; Ruff: no new errors.
**Outcome:** DONE, pending the owner's review of the Italian texts and test
of the ZIP.

453
PLAN_I18N.md Normal file
View File

@@ -0,0 +1,453 @@
# PLAN_I18N — Italian translation of the BAL Electrum plugin (i18n)
> **Status:** DRAFT. Every phase still needs the owner's explicit "OK" before any code is written (HANDOFF.md, rule R4).
> **Prepared:** 2026-09-25, from a read-only analysis (no code was changed). Owner's decisions recorded on 2026-09-26 (section 6).
> **Code base analysed:** `bal-electrum-plugin` `main` @ `4a33116` (2026-09-19, manifest `0.7.0`) and Electrum `4.8.0`.
> **Line numbers** refer to that commit. After merging a newer `main`, find the code by content.
## 0. Read this first
1. Read `HANDOFF.md` (rules R1–R4, ZIP-FIRST, CREDIT-SAVING) and `AGENTS.md` (venvs, tests). They still apply.
2. **One exception to HANDOFF.md.** Section 5 ("Git / delivery workflow") and section 7, step 7, say: work directly on `main`, push to `origin/main`, run `make-release.sh`. **That does NOT apply to this task.** See section 3 (dedicated branch).
3. The owner's decisions (D1–D7) are recorded in section 6. For anything not covered there, ask the owner (rule R3).
## 1. Goal and scope
**Goal:** when Electrum is set to Italian, the whole BAL interface appears in Italian. The mechanism must allow adding more languages later just by adding one `.po` file.
**In scope**
- The Qt GUI of the plugin (`bal/gui/qt/`) and the GUI-free strings it displays (`bal/core/`).
- One language for now: Italian (`it_IT`).
**Out of scope** (owner's decisions, or by design)
- **BAL Easy Heirs**: excluded by the owner.
- **CLI output** (`bal/cli/`): stays English, exactly like Electrum (`run_electrum`: "the CLI is intentionally always non-localized").
- `bal/wallet_util/` (standalone helper scripts), the Android reader (`android/`, which uses Android resources), the manual, the website and the docs.
- Other languages: later. The infrastructure will support them.
## 2. Background (verified)
### 2.1 How Electrum 4.8.0 does it
- **gettext with one domain, `electrum`.** Catalogs live in `electrum/locale/locale/<lang>/LC_MESSAGES/electrum.mo` (`electrum/i18n.py`, `LOCALE_DIR`). Every string goes through `electrum.i18n._()`.
- **The language is set once, at startup, for the GUI only** (`run_electrum` L433–451):
- it uses `config.LOCALIZATION_LANGUAGE` (config key `language`);
- if that is empty, it uses `electrum.gui.default_lang.get_default_language(gui_name)`, i.e. `QLocale.system().name()`, **but only if** that value is in `electrum.i18n.languages`; otherwise `en_UK`;
- `en_*` means no translation (the English source strings are shown);
- changing the language requires a restart.
- **Strings evaluated too early stay English.** Anything evaluated before `set_language()` (for example at import time) is not translated.
- **Safety check inside `_()`.** The decorator `_ensure_translation_keeps_format_string_syntax_similar` rejects a translation whose `{}` fields differ from the source. `_("")` returns `""`. There is an optional `context=` argument (pgettext).
- **Coding rules** (comments in `i18n.py`): no f-strings inside `_()`, no `%` formatting; write `_("… {}").format(x)`. There are no plural forms (`ngettext` is not used anywhere).
- **Pipeline:**
1. `contrib/locale/push_locale.py` runs xgettext over `electrum/**/*.py`. This includes *internal* plugins.
2. The strings go to Crowdin, where volunteers translate them.
3. The `.po` files are stored in the `electrum-locale` repo.
4. `contrib/locale/build_locale.sh` compiles them with msgfmt into `.mo` files and writes `stats.json`.
- **Translation security:**
- `electrum-locale/update.py` refuses any translation whose `msgstr` contains a Bitcoin address, an e-mail address, a URL, or a long word mixing letters and digits;
- `llm_proofreader/` checks every translation PR for vandalism in CI.
- **External plugins:**
- they are always ZIP files, imported with `zipimport` as `electrum_external_plugins.<name>`;
- `BasePlugin.read_file(filename) -> bytes` reads a file from inside the ZIP, or from the internal plugin folder;
- **Electrum provides nothing for translating external plugins.** Their strings are not in `electrum.mo`.
- `i18n.py`, `gui/default_lang.py` and `read_file()` are identical in 4.7.2, 4.8.0 and 4.8.2.
- **Swiss locales** (`it_CH`, `de_CH`, `fr_CH`) are not in Electrum's list, so Electrum starts in English until the user picks a language. BAL must simply follow Electrum and not detect the language itself. Otherwise the UI would be half in one language and half in another.
### 2.2 BAL today (`main` @ `4a33116`)
- Source strings are in English. Most are wrapped in `_`, imported from `electrum.i18n` in these places:
- `gui/qt/common.py:55`, which re-exports it to every `gui/qt` module;
- `gui/qt/theme.py:90,108`;
- `core/will.py:32` and `core/willexecutors.py:25`;
- `cli/controller.py:29`.
- The package has 483 `_()` calls in 11 files. xgettext finds 365 distinct strings (≈ 2,230 words).
- **With Electrum set to Italian, only 39 of the 365 strings (≈ 11 %) appear in Italian.** They are the generic words that Electrum already translates (Cancel, Save, Address…). Everything specific to BAL stays in English.
- **Issues to fix before translating** (exact locations are in the Appendix):
- 14 f-strings or `.format()` calls inside `_()`: these strings can never be translated (Ruff INT001/INT002);
- 15 `_()` calls with a non-literal argument: extraction tools cannot find the text;
- 14 concatenations around `_()`: the word order breaks in other languages;
- 18 `_()` calls evaluated at import time (in class bodies): they would stay English (see 4.2);
- 2 × `_("")`: plain gettext returns the catalog header instead of an empty string;
- 12 settings help texts (`HelpButton("…")`) and the help texts of 5 `add_widget()` calls are never translated (≈ 500 words in total);
- other text shown to the user without `_()`.
- **Some stored data depends on the UI language.**
- `WillItem.set_status()` (`core/will.py:1344`) appends the *translated* status label to `WillItem.status`.
- That field is saved via `to_dict()` in the wallet DB (`wallet.db.get_dict("will")`, `gui/qt/window.py:232`), in exported files and in QR transfers.
- Real example from `tests/samanta7`: `"New.Firmato.Pushed.Checked.Replaced"`. Electrum's Italian catalog already translates *Signed*, *Error* and *Expired*, so the saved history mixes languages today.
- **Default texts in `core/plugin_base.py` exist only in English:**
- `HISTORY_LABEL` (around L246, token `{willexecutor}`);
- `EVENT_DESCRIPTION` and `EVENT_SUMMARY` (around L331–337, tokens `$wallet_name` and `$heirs_complete`).
## 3. Branch and workflow for this task
The owner decided, on Truman's suggestion, to do this work on a **separate branch on Gitea**, not on `main`.
- **Branch:** `feature/i18n` (proposed name, see D6), created from `main`.
- **Never** commit or push to `main` during this task.
- **Never** run `make-release.sh` from the branch: it tags and publishes a Gitea release. Build test ZIPs with `python3 build_zip.py` only.
- **At the start of every phase:**
1. merge `origin/main` into `feature/i18n`;
2. resolve any conflicts;
3. run the tests again.
- **Where conflicts are likely:**
- `gui/qt/dialogs.py`, `window.py`, `lists.py`, `plugin.py`, `widgets.py` and `core/will.py`: all were changed on `main` on 2026-09-04, 09-14 and 09-19, and commit `fb88d75` alone changed ≈ 1,800 lines of `dialogs.py`;
- `CHANGELOG.md`: both sides append at the end, so keep both entries and renumber.
- **ZIP-FIRST for every phase:**
1. build the ZIP;
2. the owner (and Truman) test it;
3. only after the owner's explicit OK, commit on `feature/i18n` and push to `origin/feature/i18n` (who does this: see D3).
- Add one numbered `CHANGELOG.md` entry per phase, in English.
- Run ruff and the tests before every ZIP (HANDOFF.md). The known pre-existing test failures are listed in HANDOFF.md, section 7, step 3.
- **At the end:** open a Pull Request `feature/i18n` → `main` on Gitea (there is a precedent: `feature/bal-qr-transfer`). Release from `main` only after the merge.
## 4. Design (decided)
**Chosen:** a gettext catalog owned by BAL, domain `bal`, shipped inside the plugin ZIP, that follows Electrum's language and is consulted **after** Electrum's own catalog (D7).
**Rejected:**
- keep using `electrum.i18n._`: 89 % of the text stays English;
- Python dictionaries or JSON files: a home-made format with no tooling;
- Qt Linguist (`.ts` / `.qm`): Electrum desktop does not use it, and `core/` has no Qt.
### 4.1 New module `bal/i18n.py`
| Function | Behaviour |
|---|---|
| `_(msg)` | 1. `""` returns `""`. 2. **Electrum first (D7):** if `electrum.i18n._(msg)` differs from `msg`, return it (Electrum has already applied its own `{}` check). 3. Otherwise, if a BAL catalog is loaded and translates `msg`, apply the `{}` safety check and return the translation. The check uses the same logic as Electrum's decorator: **copy it** with an attribution comment (MIT); do not import Electrum's private function. 4. Otherwise return `msg` (English). The CLI and English behave exactly as in Electrum, because no BAL catalog is loaded there. |
| `N_(msg)` | Returns `msg` unchanged. It marks strings defined in tables, constants and class attributes, which are translated later with `_()` when displayed. Babel extracts `N_` by default. |
| `set_language(plugin, lang)` | `None`, `""` or `en_*`: no catalog. Otherwise read `locale/<lang>/LC_MESSAGES/bal.mo` with `plugin.read_file()`, falling back to `locale/<lang[:2]>/…`, and build `gettext.GNUTranslations(io.BytesIO(data))`. If the catalog is missing or broken, log at info level and continue in English. Never raise. |
| `init_from_config(plugin, config)` | `lang = config.LOCALIZATION_LANGUAGE`. If it is empty, use `electrum.gui.default_lang.get_default_language(gui_name="qt")`, guarding against `ImportError` as `run_electrum` does. Then call `set_language()`. |
- **Why Electrum first (D7):** BAL follows Electrum's wording wherever Electrum has it. If Electrum ever ships BAL as an internal plugin, Electrum's own translations (Crowdin) would be used automatically and the BAL catalog would only fill the gaps.
- **Trade-off of D7:** for a text that Electrum already translates, the BAL catalog cannot override Electrum's wording, not even with the D1 glossary. If one such case reads badly in BAL, handle that single case with the owner.
- A text that Electrum "translates" into the identical English text counts as not found and falls through to the BAL catalog. This is harmless: the BAL catalog is prefilled with Electrum's translations (3.3).
- **Do not use `gettext.translation(localedir=…)`.** When pointed inside a ZIP it silently returns `NullTranslations` (verified).
- `plugin.read_file()` is the same API BAL already uses for its icons. It works both for the ZIP install and for the dev symlink install (`AGENTS.md`).
- The state is module-level and set once. Changing the language requires restarting Electrum, as in Electrum itself.
### 4.2 Where the language is set
- In `bal/gui/qt/plugin.py`, `Plugin.__init__` (L67): call `init_from_config(self, config)` first.
- The CLI entry point (`bal/cli/plugin.py`) does not call it, so the CLI stays English.
- **Consequence:** `gui/qt/plugin.py` imports `dialogs`, `widgets` and `window` at module level (L49–51), and those import `lists`. So every class body is evaluated *before* `Plugin.__init__` runs, and any `_()` evaluated at import time would stay English. The cases in Appendix D must be converted in Phase 2.
### 4.3 Files and tools
```
babel.cfg # extraction mapping (repo root)
bal/locale/bal.pot # template, generated
bal/locale/it_IT/LC_MESSAGES/bal.po # Italian translations (source of truth)
bal/locale/it_IT/LC_MESSAGES/bal.mo # compiled (see D4)
```
The tool is **Babel** (`pip install babel`). It is pure Python and works on Windows without GNU gettext. These commands were tested on this code base:
```ini
# babel.cfg
[ignore: bal/cli/**]
[ignore: bal/wallet_util/**]
[python: bal/**.py]
```
```bash
mkdir -p bal/locale # extract does not create it
pybabel extract -F babel.cfg --no-wrap -o bal/locale/bal.pot .
pybabel init -i bal/locale/bal.pot -d bal/locale -D bal -l it_IT # once
pybabel update -i bal/locale/bal.pot -d bal/locale -D bal --no-wrap # after each extract
pybabel compile -d bal/locale -D bal --statistics
```
- Today this extracts 323 strings (≈ 1,900 words) from the GUI and core.
- After Phase 2, expect about 360 strings (≈ 2,500 words).
- Poedit (free) can be used to translate or review the `.po` file by hand.
### 4.4 Translation safety (as in Electrum)
- Add a check script (for example `scripts/check_translations.py`) and run it before every ZIP. It must check that:
- every `.po` file compiles;
- the `{}` fields are identical to the source (the same rule as the runtime check);
- the `$tokens` are identical (`$wallet_name`, `$heirs_complete`, …): Electrum does not check these;
- no `msgstr` contains a Bitcoin address, an e-mail address, a URL or a long letter-and-digit word (use the regexes from `electrum-locale/update.py`), unless the same text is in the `msgid`.
It must also print the counts of translated, untranslated and fuzzy strings.
- Never put addresses or URLs inside translatable strings; pass them with `{}`.
- The owner reviews every Italian string, especially the warnings about invalidation, locktime, fees and signing.
## 5. Phases
Each phase follows HANDOFF.md: DISCOVER → PLAN (owner's "OK") → EXECUTE → VERIFY → ZIP → test by the owner and Truman → commit on `feature/i18n`.
Phases 1 and 2 change nothing visible, so they may be delivered as a single ZIP/test cycle (see D5).
### Phase 1 — Infrastructure (no visible change)
- NEW `bal/i18n.py` (section 4.1), with docstrings explaining *why* (rule R2).
- `bal/gui/qt/common.py:55`: replace `from electrum.i18n import _` with an import of `_` and `N_` from `bal.i18n`. Use a relative import, zip-safe like the existing `from ...core…` imports.
- `bal/gui/qt/theme.py:90,108`: change the local imports to `bal.i18n`.
- `bal/core/will.py:32` and `bal/core/willexecutors.py:25`: import from `bal.i18n`.
- `bal/cli/controller.py:29`: **unchanged** (the CLI stays English by design).
- `bal/gui/qt/plugin.py`, `Plugin.__init__`: call `init_from_config(self, config)`.
- NEW `tests/test_i18n.py`, covering:
- the empty string;
- Electrum's translation wins; the BAL catalog is used only when Electrum has none (D7);
- rejection of a `{}` mismatch;
- `en_UK` means no catalog;
- a missing `.mo` does not crash;
- a catalog loaded from bytes (use a small test catalog).
- **Verify:**
- the existing tests (baseline as in HANDOFF.md, section 7);
- `tests/smoke_test.py`;
- `build_zip.py` followed by `tests/external_zip_test.py`;
- manually on Windows 11 with Electrum 4.8.0, once in Italian and once in English: the UI must look exactly as before.
### Phase 2 — String clean-up and language-neutral stored data (no visible change)
- **2.0** Merge `origin/main` first.
- **2.1** Appendix A: turn `_(f"…")` and `_("…".format(x))` into `_("… {}").format(x)`. Include `cli/controller.py`, for lint consistency only.
- **2.2** Appendix C: turn each concatenation into one string with `{}`.
- Keep HTML outside the strings where possible, e.g. `"<b>{}</b>".format(_("Support:"))`.
- Fix the malformed `_("<b>Willexecutor:</b:")` (`widgets.py:1366`).
- **2.3** Appendix B: mark the literal with `N_()` where it is defined, or translate it at the call site.
- The helpers `add_widget()` (`common.py:180`), `get_window_title()` (`plugin.py:1085`) and `qlabel()` (`widgets.py:1319`) need ONE rule: callers pass text that is already translated, and the helper does not call `_()` again.
- Today `window.py:290` translates twice.
- **2.4** Appendix D: replace class-level `_()` with `N_()` and translate when the text is displayed.
- In `lists.py`, `update_headers(self.__class__.headers)` (L248, 647, 1094) must receive a translated copy.
- For the wizard `title` / `message` (`dialogs.py` L380, 419–420, 527–528, 547–548), use `_(self.title)` and `_(self.message)` at L325 and L327.
- **2.5** Appendix E: replace `_("")` with `""`.
- **2.6** Appendix F and G: make the settings help texts and labels in `plugin.py` translatable.
- **2.7** Appendix H, plus a full sweep for any other text shown to the user.
- **2.8** **Stored status** (`core/will.py:1344`):
- store the **English** label (mark the `STATUS_DEFAULT` labels with `N_()`); no `_()` at write time;
- add a helper `format_status_history(status) -> str` that splits on `.`, translates the tokens that are known English labels (with an optional `NOT ` prefix), and leaves unknown or legacy tokens unchanged (`New`, `Firmato`, …);
- use it wherever the status is shown (`lists.py:589`, `widgets.py:1336`);
- this stays backward compatible: existing wallets keep displaying correctly, and older BAL versions still read plain English;
- test it with the real legacy strings in `tests/samanta7`.
- **2.9** **Default texts** (`core/plugin_base.py`: `HISTORY_LABEL`, `EVENT_DESCRIPTION`, `EVENT_SUMMARY`):
- mark the English defaults with `N_()`;
- when the stored value is missing **or equal to the English default**, use the translated default at the moment the text is used (calendar export, history label);
- the tokens must survive translation.
- **Changed during Phase 2 (safety):** `HISTORY_LABEL` stays English and is *not* translatable. `Util._label_matches_history()` uses it to recognise BAL's own local transactions (stale-history cleanup, spendable UTXOs), so a label that changed with the GUI language would no longer match the transactions saved before. Only `EVENT_SUMMARY` and `EVENT_DESCRIPTION` follow the language (`BalConfig(..., translatable=True)`). The same rule applies to every stored or compared text (wallet labels, `heirs.TRANSACTION_LABEL`, the status history).
- **2.10** `pyproject.toml`: add `"INT"` to `[tool.ruff.lint] select`.
- Ruff's hint suggests `%` formatting: **do not follow it**. Use `.format()`, which is Electrum's rule.
- `make-release.sh` treats Ruff errors as blocking, so INT must end up clean.
- **Verify:**
- Ruff INT is clean;
- the extraction count is about 360 (compare with 4.3);
- the tests pass, plus new tests for 2.8 and 2.9;
- manually in English: no visible text changed.
### Phase 3 — Italian catalog (visible change)
- **3.0** Merge `origin/main` first.
- **3.1** Add `babel.cfg` and the commands from 4.3, documented in `README.md` or `AGENTS.md`.
- **3.2** Generate `bal/locale/bal.pot` and create `it_IT/LC_MESSAGES/bal.po`.
- **3.3** Draft the translation using the glossary (D1); the owner reviews it (D2). Where Electrum's `it_IT` catalog already translates the exact same English text, copy Electrum's translation, so the two UIs match.
- **3.4** `build_zip.py`:
- compile `.po` into `.mo`, according to D4;
- put only the `.mo` files in the ZIP (no `.po` / `.pot`);
- run the check script (4.4) before zipping.
- **Verify:**
- Electrum in Italian shows BAL in Italian;
- Electrum in English shows BAL in English;
- missing entries fall back to English;
- `external_zip_test.py` passes;
- it works on Windows 11 with Electrum 4.8.0 (and 4.7.2);
- manual walkthrough of: wizard, settings, heirs list, will list and detail, will-executors, check / sign / broadcast, invalidate, export / import, QR transfer, calendar export.
### Phase 4 — Final test and merge
- The owner and Truman test the final branch ZIP.
- Merge `origin/main` into the branch one last time and test again.
- Open the Pull Request `feature/i18n` → `main` on Gitea. After the merge, follow the normal release flow from `main`.
## 6. Decisions
Recorded on 2026-09-26 from the owner's answers.
- **D1 — Italian glossary.** Rule: follow Electrum's `it_IT` wording wherever Electrum already has the term or the sentence. Grammatical variants (nouns, past participles, plurals, capitals in headers and buttons) are adapted in the draft and checked by the owner during the review (D2).
| English | Italian |
|---|---|
| will | testamento |
| heir / heirs | erede / eredi |
| will-executor | Will-Executor (kept in English) |
| check-alive | verifica se sei vivo |
| invalidate | invalida il piano |
| invalidation (noun) | invalidazione del piano |
| anticipate / postpone | anticipa / posticipa |
| locktime | locktime (kept in English; owner, 2026-09-26) |
| fee | commissione (as Electrum) |
| broadcast | trasmetti il piano |
| sign / signed | firma / firmato (as Electrum) |
| wallet | portafogli (as Electrum) |
- **D2 — Who translates.** The developer drafts `it_IT/bal.po`; the owner reviews and corrects it (for example in Poedit). For later languages: Weblate (supports Gitea and `.po`) or Crowdin, as Electrum does.
- **D3 — Branch and commits.** The developer creates `feature/i18n`, and commits and pushes on it, each time only after the owner's explicit OK (ZIP-FIRST).
- **D4 — `.mo` files.** `build_zip.py` compiles `.po` into `.mo` at build time with Babel; `.mo` files stay out of git (add `*.mo` to `.gitignore`). If Babel is missing, the build stops with a clear error, so an English-only ZIP is never shipped by mistake. Reasons: the `.po` is the only source (no stale `.mo`), every change to a translation is readable in review, and it is how Electrum works.
- **D5 — Cycles.** Phases 1 and 2 are delivered in one ZIP/test cycle. Phase 1 is not merged into `main` early.
- **D6 — Branch name:** `feature/i18n`.
- **D7 — Lookup order.** Electrum's catalog first, then BAL's, then English (see 4.1). Proposed by the owner so that BAL and Electrum read as one, also if Electrum ever integrates BAL.
## 7. Reminders for the developer
- Talk to the owner in **Italian**, with simple words and no jargon (the owner is not a programmer). Code, comments, docstrings, UI source strings, docs and commits are in **English**.
- UI source strings stay in English; Italian lives only in the `.po` file.
- Never invent. When in doubt, stop and ask.
- Before writing any code, present the phase PLAN and wait for "OK".
- ZIP-FIRST; run ruff and the tests before every ZIP; one CHANGELOG entry per phase; keep reports brief (CREDIT-SAVING).
- Wallet data compatibility comes first: apart from 2.8 (status labels), do not change what is stored.
## Appendix — Inventory at `main` @ `4a33116`
Generated by a static scan (AST, Ruff `INT` and xgettext). The line numbers will move after merging a newer `main`: re-run the scan or search by content. These lists cover the known cases; Phase 2 still needs a full sweep.
#### A. f-string / `.format()` inside `_()` — Ruff INT001/INT002 (14)
| Location | Rule |
|---|---|
| `bal/cli/controller.py:92` | INT001 |
| `bal/cli/controller.py:98` | INT001 |
| `bal/cli/controller.py:104` | INT001 |
| `bal/gui/qt/common.py:225` | INT002 |
| `bal/gui/qt/common.py:240` | INT002 |
| `bal/gui/qt/dialogs.py:1226` | INT001 |
| `bal/gui/qt/dialogs.py:2491` | INT001 |
| `bal/gui/qt/window.py:831` | INT001 |
| `bal/gui/qt/window.py:836` | INT001 |
| `bal/gui/qt/window.py:1090` | INT001 |
| `bal/gui/qt/window.py:1091` | INT001 |
| `bal/gui/qt/window.py:2228` | INT001 |
| `bal/gui/qt/window.py:2236` | INT001 |
| `bal/gui/qt/window.py:2246` | INT001 |
#### B. `_()` with a non-literal argument (not extractable) (15)
| Location | Code |
|---|---|
| `bal/core/will.py:1344` | `_(self.STATUS[status][0])` |
| `bal/gui/qt/common.py:181` | `_(label)` |
| `bal/gui/qt/dialogs.py:327` | `_(self.message)` |
| `bal/gui/qt/dialogs.py:2288` | `_(msg)` |
| `bal/gui/qt/dialogs.py:2291` | `_(msg)` |
| `bal/gui/qt/lists.py:1240` | `_(label)` |
| `bal/gui/qt/plugin.py:1086` | `_(title)` |
| `bal/gui/qt/widgets.py:284` | `_(self.tooltip_text)` |
| `bal/gui/qt/widgets.py:1320` | `_(str(title))` |
| `bal/gui/qt/window.py:290` | `_(title)` |
| `bal/gui/qt/window.py:942` | `_(message)` |
| `bal/gui/qt/window.py:2217` | `_(self.DOWNLOAD_FAILED_TOR_MESSAGE)` |
| `bal/gui/qt/window.py:2219` | `_(self.DOWNLOAD_FAILED_MESSAGE)` |
| `bal/gui/qt/window.py:2253` | `_(self.DOWNLOAD_FAILED_TOR_MESSAGE)` |
| `bal/gui/qt/window.py:2255` | `_(self.DOWNLOAD_FAILED_MESSAGE)` |
#### C. Concatenations around `_()` (14)
| Location | Expression |
|---|---|
| `bal/core/will.py:1344` | `'.' + (('NOT ' if not value else '') + _(self.STATUS[status][0]))` |
| `bal/gui/qt/dialogs.py:1010` | `_('Wallet balance is too low: {} satoshi available, but the miner and…` |
| `bal/gui/qt/dialogs.py:2206` | `messages[reason] + '\n\n' + _('Skipped')` |
| `bal/gui/qt/dialogs.py:2209` | `_("Could not build the will, and the exact cause could not be determi…` |
| `bal/gui/qt/dialogs.py:2419` | `_('Expiration date: ') + str(BalTimestamp(self.threshold))` |
| `bal/gui/qt/dialogs.py:2425` | `_('Valid Txs:') + str(len(Will.only_valid_list(self.will)))` |
| `bal/gui/qt/dialogs.py:2427` | `_('Total Txs:') + str(len(self.will))` |
| `bal/gui/qt/lists.py:679` | `' ' + _('Build Your Will')` |
| `bal/gui/qt/plugin.py:301` | `'Bal ' + _('Bitcoin After Life')` |
| `bal/gui/qt/plugin.py:1034` | `'<b>' + _('Support:') + '</b>'` |
| `bal/gui/qt/plugin.py:1086` | `_('BAL - ') + _(title)` |
| `bal/gui/qt/widgets.py:1320` | `'<b>' + _(str(title)) + f':</b>\t{str(value)}'` |
| `bal/gui/qt/window.py:1022` | `_('Electrum was unable to deserialize the transaction:') + '\n' + str…` |
| `bal/gui/qt/window.py:1091` | `msg + _(f'signing: {tosign}')` |
#### D. `_()` evaluated at import time (class body) (18)
| Location | Scope | Call |
|---|---|---|
| `bal/gui/qt/dialogs.py:419` | class body | `_('Bitcoin After Life Will-Executors')` |
| `bal/gui/qt/dialogs.py:420` | class body | `_('Choose willexecutors download method')` |
| `bal/gui/qt/dialogs.py:528` | class body | `_('Configure and select your willexecutors')` |
| `bal/gui/qt/dialogs.py:548` | class body | `_('')` |
| `bal/gui/qt/lists.py:131` | class body | `_('Name')` |
| `bal/gui/qt/lists.py:132` | class body | `_('Address')` |
| `bal/gui/qt/lists.py:133` | class body | `_('Amount')` |
| `bal/gui/qt/lists.py:340` | class body | `_('Locktime')` |
| `bal/gui/qt/lists.py:341` | class body | `_('Txid')` |
| `bal/gui/qt/lists.py:342` | class body | `_('Will-Executor')` |
| `bal/gui/qt/lists.py:343` | class body | `_('Status')` |
| `bal/gui/qt/lists.py:344` | class body | `_('Server')` |
| `bal/gui/qt/lists.py:907` | class body | `_('')` |
| `bal/gui/qt/lists.py:908` | class body | `_('Url')` |
| `bal/gui/qt/lists.py:909` | class body | `_('S')` |
| `bal/gui/qt/lists.py:910` | class body | `_('Base fee')` |
| `bal/gui/qt/lists.py:911` | class body | `_('Info')` |
| `bal/gui/qt/lists.py:912` | class body | `_('Default Address')` |
#### E. `_("")` (2)
| Location | Call |
|---|---|
| `bal/gui/qt/dialogs.py:548` | `_('')` |
| `bal/gui/qt/lists.py:907` | `_('')` |
#### F. Settings help texts never passed to `_()` (12)
| Location | Widget | Text |
|---|---|---|
| `bal/gui/qt/plugin.py:715` | HelpButton | When checking, automatically sign and broadcast the will transactions… |
| `bal/gui/qt/plugin.py:778` | HelpButton | `How many reminder alarms the exported calendar (.ics) event contains.…` |
| `bal/gui/qt/plugin.py:789` | HelpButton | `Default message to be used in event summary\nVariables:\n $wallet_na…` |
| `bal/gui/qt/plugin.py:803` | HelpButton | `Default message to be used in event description\nVariables:\n $walle…` |
| `bal/gui/qt/plugin.py:818` | HelpButton | URL of the server that provides the will-executor list. Only availab… |
| `bal/gui/qt/plugin.py:829` | HelpButton | `Command used to open .ics calendar files.\nLeave empty to use the sys…` |
| `bal/gui/qt/plugin.py:844` | HelpButton | `After each check, save the valid will transactions into the wallet's …` |
| `bal/gui/qt/plugin.py:858` | HelpButton | `Label applied to the will transactions saved into the wallet's local …` |
| `bal/gui/qt/plugin.py:880` | HelpButton | Broadcast all transactions to willexecutors including those already p… |
| `bal/gui/qt/plugin.py:891` | HelpButton | `Run the 'Build your will' wizard every time the wallet is closed or E…` |
| `bal/gui/qt/plugin.py:909` | HelpButton | When a new transaction arrives for the wallet, automatically rebuild … |
| `bal/gui/qt/plugin.py:933` | HelpButton | `Payload size of a single QR code when exporting a will via QR.\n\nLar…` |
#### G. `add_widget()` calls (label translated at runtime, help text never) (5)
| Location | Label | Help text |
|---|---|---|
| `bal/gui/qt/plugin.py:697` | Hide Replaced | Hide replaced transactions from will detail and l… |
| `bal/gui/qt/plugin.py:705` | Hide Invalidated | Hide invalidated transactions from will detail an… |
| `bal/gui/qt/plugin.py:727` | Panel editable Date and Fee | When enabled, the delivery-time and check-alive d… |
| `bal/gui/qt/plugin.py:742` | `Max Will-Executor Fee (satoshi)` | `Maximum fee (in satoshi) allowed to be paid to a …` |
| `bal/gui/qt/plugin.py:757` | User Type | `Choose how much detail the plugin shows.\n\nBASIC…` |
#### H. Other user-visible text not (correctly) translatable — known cases, not exhaustive
| Location | Code | Note |
|---|---|---|
| `bal/gui/qt/dialogs.py:380` | `title = "Bitcoin After Life Heirs"` | Wizard title, shown untranslated at `dialogs.py:325` |
| `bal/gui/qt/dialogs.py:527` | `title = "Bitcoin After Life Will-Executors"` | Same |
| `bal/gui/qt/dialogs.py:547` | `title = "Bitcoin After Life Will Settings"` | Same |
| `bal/gui/qt/lists.py:1472` | `setText("New Will Executor")` | Not wrapped |
| `bal/gui/qt/plugin.py:673` | `QPushButton("Rebroadcast transactions")` | Not wrapped |
| `bal/gui/qt/widgets.py:1323` | `qlabel("Locktime", …)` | Translated inside `qlabel()` but not extractable |
| `bal/gui/qt/widgets.py:1324` | `qlabel("Creation Time", …)` | Same |
| `bal/gui/qt/widgets.py:1334` | `qlabel("Transaction fees:", …)` | Same; `qlabel()` adds another `:` |
| `bal/gui/qt/widgets.py:1336` | `qlabel("Status:", …)` | Same; also shows the stored status (see 2.8) |
| `bal/gui/qt/widgets.py:1339` | `QLabel("<b>Heirs:</b>")` | Not wrapped |
| `bal/gui/qt/widgets.py:1366` | `_("<b>Willexecutor:</b:")` | Malformed HTML inside the string |
| `bal/gui/qt/window.py:1613` | `msg = "Broadcasting Transactions to Will-Executors:\n"` | Not wrapped |
Not to translate: `widgets.py:122` (icon glyph), `plugin.py:1020` (link to bitcoin-after.life).
#### Numbers (`main` @ `4a33116`)
| Measure | Value |
|---|---|
| `_()` calls | 483 in 11 files |
| Distinct strings, whole package (xgettext) | 365 (≈ 2,230 words) |
| …of which Electrum `it_IT` already translates | 39 (≈ 11 %) |
| Strings used only by the CLI | 36 (≈ 315 words), out of scope |
| Babel extraction today, GUI + core | 323 (≈ 1,900 words) |
| Expected after Phase 2 | ≈ 360 (≈ 2,500 words) |
## Sources
- Electrum 4.8.0: `electrum/i18n.py`, `run_electrum` (L433–451), `electrum/gui/default_lang.py`, `electrum/plugin.py` (`maybe_load_plugin_init_method`, `read_file`), `contrib/locale/` — https://github.com/spesmilo/electrum/tree/4.8.0
- `electrum-locale` at the 4.8.0 submodule commit `3d7594c`: `update.py`, `llm_proofreader/` — https://github.com/spesmilo/electrum-locale
- Gitea "Update branch" button on pull requests — https://github.com/go-gitea/gitea/pull/9784
- Weblate: Gitea and gettext PO support — https://docs.weblate.org/en/latest/vcs.html

5
babel.cfg Normal file
View File

@@ -0,0 +1,5 @@
# Babel extraction mapping for the BAL gettext catalog (see bal/i18n.py).
# The CLI and the wallet_util helpers stay English, like Electrum's CLI.
[ignore: bal/cli/**]
[ignore: bal/wallet_util/**]
[python: bal/**.py]

View File

@@ -91,17 +91,17 @@ def _user_facing(e):
_( _(
"In the inheritance process, the entire wallet will always be " "In the inheritance process, the entire wallet will always be "
"fully emptied. Your settings require an adjustment of the " "fully emptied. Your settings require an adjustment of the "
f"amounts: {e}" "amounts: {}"
) ).format(e)
) )
if isinstance(e, heirs_mod.WillExecutorFeeTooHighException): if isinstance(e, heirs_mod.WillExecutorFeeTooHighException):
return UserFacingException(_(f"Will-executor fee too high: {e}")) return UserFacingException(_("Will-executor fee too high: {}").format(e))
if isinstance(e, heirs_mod.BalanceTooLowException): if isinstance(e, heirs_mod.BalanceTooLowException):
return UserFacingException(str(e)) return UserFacingException(str(e))
if isinstance(e, heirs_mod.HeirAmountIsDustException): if isinstance(e, heirs_mod.HeirAmountIsDustException):
return UserFacingException(str(e)) return UserFacingException(str(e))
if isinstance(e, heirs_mod.NotAnAddress): if isinstance(e, heirs_mod.NotAnAddress):
return UserFacingException(_(f"not an address, {e}")) return UserFacingException(_("not an address, {}").format(e))
if isinstance(e, heirs_mod.AmountNotValid): if isinstance(e, heirs_mod.AmountNotValid):
return UserFacingException(str(e)) return UserFacingException(str(e))
if isinstance(e, heirs_mod.LocktimeNotValid): if isinstance(e, heirs_mod.LocktimeNotValid):

View File

@@ -32,6 +32,8 @@ from electrum.plugin import BasePlugin
from electrum.transaction import tx_from_any from electrum.transaction import tx_from_any
from electrum.util import classproperty from electrum.util import classproperty
from ..i18n import N_, _
_logger = get_logger(__name__) _logger = get_logger(__name__)
@@ -134,12 +136,20 @@ class BalConfig:
Wraps ``config.get`` / ``config.set_key`` and supplies a default value Wraps ``config.get`` / ``config.set_key`` and supplies a default value
when the key is missing. when the key is missing.
``translatable=True`` is for a default *text* (marked with ``N_()``) that
should follow the GUI language. The English default is what gets stored,
and :meth:`get` translates it when it is read, so the stored value never
depends on the GUI language. A text the user wrote is returned unchanged.
Only for texts that are shown: a text that is also used to recognise
stored data (e.g. ``HISTORY_LABEL``) must stay non-translatable.
""" """
def __init__(self, config, name, default): def __init__(self, config, name, default, translatable=False):
self.config = config self.config = config
self.name = name self.name = name
self.default = default self.default = default
self.translatable = translatable
def get(self, default=None): def get(self, default=None):
"""Return the stored value, falling back to ``default`` then ``self.default``.""" """Return the stored value, falling back to ``default`` then ``self.default``."""
@@ -149,10 +159,20 @@ class BalConfig:
v = default v = default
else: else:
v = self.default v = self.default
if self.translatable and v == self.default:
return _(v)
return v return v
def localized_default(self):
"""Return the default value, translated if the setting is translatable."""
return _(self.default) if self.translatable else self.default
def set(self, value, save=True): def set(self, value, save=True):
"""Persist ``value`` for this key.""" """Persist ``value`` for this key."""
if self.translatable and value == self.localized_default():
# The translated default is stored as its English original, so
# it keeps following the GUI language (see get()).
value = self.default
self.config.set_key(self.name, value, save=save) self.config.set_key(self.name, value, save=save)
@@ -243,6 +263,10 @@ class BalPlugin(BasePlugin):
# the wallet's local history. May contain the "{willexecutor}" token, # the wallet's local history. May contain the "{willexecutor}" token,
# which is replaced with the will-executor URL of each will item at # which is replaced with the will-executor URL of each will item at
# save time. # save time.
# Deliberately NOT translatable: Util._label_matches_history() uses
# this text to recognise BAL's own local transactions (stale-history
# cleanup, spendable UTXOs). A label that changed with the GUI
# language would no longer match the transactions saved before.
self.HISTORY_LABEL = BalConfig( self.HISTORY_LABEL = BalConfig(
config, config,
"bal_history_label", "bal_history_label",
@@ -328,13 +352,20 @@ class BalPlugin(BasePlugin):
self.WELIST_SERVER = BalConfig( self.WELIST_SERVER = BalConfig(
config, "bal_welist_server", "https://welist.bitcoin-after.life/" config, "bal_welist_server", "https://welist.bitcoin-after.life/"
) )
# Calendar (.ics) texts: only shown, never used to recognise data, so
# their defaults follow the GUI language (translatable=True). The
# $tokens must survive translation.
self.EVENT_DESCRIPTION = BalConfig( self.EVENT_DESCRIPTION = BalConfig(
config, config,
"bal_event_description", "bal_event_description",
"BAL will execution of $wallet_name\r\n heirs list: \r\n$heirs_complete", N_("BAL will execution of $wallet_name\r\n heirs list: \r\n$heirs_complete"),
translatable=True,
) )
self.EVENT_SUMMARY = BalConfig( self.EVENT_SUMMARY = BalConfig(
config, "bal_event_summary", "BAL -Will execution of $wallet_name" config,
"bal_event_summary",
N_("BAL -Will execution of $wallet_name"),
translatable=True,
) )
# Default will-executor servers, keyed by network. These addresses are # Default will-executor servers, keyed by network. These addresses are

View File

@@ -147,6 +147,7 @@ def build_ics_reminders(
num_reminders: int = 3, num_reminders: int = 3,
now: Optional[datetime] = None, now: Optional[datetime] = None,
threshold: Optional[datetime] = None, threshold: Optional[datetime] = None,
reminder_suffix: str = "(reminder {idx}/{total})",
) -> Optional[str]: ) -> Optional[str]:
"""Build the ``.ics`` content with one VEVENT per reminder date. """Build the ``.ics`` content with one VEVENT per reminder date.
@@ -169,6 +170,10 @@ def build_ics_reminders(
num_reminders: requested reminder count (ADVANCED mode only). num_reminders: requested reminder count (ADVANCED mode only).
now: "today" reference; defaults to ``datetime.now()``. now: "today" reference; defaults to ``datetime.now()``.
threshold: check-alive date (ADVANCED mode only; required there). threshold: check-alive date (ADVANCED mode only; required there).
reminder_suffix: text appended to each event summary, with the
``{idx}`` and ``{total}`` fields. This module stays free of
Electrum imports, so the GUI passes it already translated; the
English default keeps the CLI output unchanged.
Returns: Returns:
The ``.ics`` content string, or ``None`` when no reminder falls in the The ``.ics`` content string, or ``None`` when no reminder falls in the
@@ -210,7 +215,9 @@ def build_ics_reminders(
# The visible date of this event: "offset" days before the deadline. # The visible date of this event: "offset" days before the deadline.
event_dt = format_time(locktime - timedelta(days=offset)) event_dt = format_time(locktime - timedelta(days=offset))
# Suffix the summary so the N events are easy to tell apart. # Suffix the summary so the N events are easy to tell apart.
event_summary = ical_escape(f"{summary_base} (reminder {idx}/{total})") event_summary = ical_escape(
"{} {}".format(summary_base, reminder_suffix.format(idx=idx, total=total))
)
lines.extend([ lines.extend([
"BEGIN:VEVENT", "BEGIN:VEVENT",
# Offset in the UID keeps each event unique (no merging). # Offset in the UID keeps each event unique (no merging).

View File

@@ -29,7 +29,6 @@ The status flags themselves (the source of truth) stay here; only the mapping
from datetime import datetime, timezone from datetime import datetime, timezone
from electrum.address_synchronizer import TX_HEIGHT_FUTURE, TX_HEIGHT_LOCAL from electrum.address_synchronizer import TX_HEIGHT_FUTURE, TX_HEIGHT_LOCAL
from electrum.i18n import _
from electrum.logging import Logger, get_logger from electrum.logging import Logger, get_logger
from electrum.transaction import ( from electrum.transaction import (
PartialTransaction, PartialTransaction,
@@ -44,6 +43,7 @@ from electrum.util import (
bfh, bfh,
) )
from ..i18n import N_, _
from .heirs import WillExecutorFeeTooHighException from .heirs import WillExecutorFeeTooHighException
from .util import Util, copy_structure from .util import Util, copy_structure
from .willexecutors import Willexecutors from .willexecutors import Willexecutors
@@ -1273,6 +1273,34 @@ class Will:
def format_status_history(status: str) -> str:
"""Return the saved status history of a will item in the GUI language.
``WillItem.status`` is a dot-separated history such as
``".Signed.Pushed.NOT Valid"``. It is stored in English (see
``WillItem.set_status``) and translated only here, for display. A token
that is not a known English label is shown unchanged: this keeps working
the histories written by older versions, which stored the label already
translated (for example ``"Firmato"``).
"""
labels = {label for label, _flag in WillItem.STATUS_DEFAULT.values()}
labels.update(WillItem.LEGACY_STATUS_LABELS)
def translate(token):
# "ERROR!!!" is glued to the end of the history when an item has no
# id (see WillItem.__init__): keep it, translate what comes before.
suffix = ""
if token.endswith("ERROR!!!"):
token, suffix = token[: -len("ERROR!!!")], "ERROR!!!"
if token in labels:
token = _(token)
elif token.startswith("NOT ") and token[len("NOT "):] in labels:
token = _("NOT {}").format(_(token[len("NOT "):]))
return token + suffix
return ".".join(translate(token) for token in status.split("."))
class WillItem(Logger): class WillItem(Logger):
# Default status flags for an inheritance transaction. # Default status flags for an inheritance transaction.
# Each entry maps an internal status key to [human-readable label, default # Each entry maps an internal status key to [human-readable label, default
@@ -1286,28 +1314,37 @@ class WillItem(Logger):
# * "UPDATED" was added: the transaction was spendable AND valid, and a new # * "UPDATED" was added: the transaction was spendable AND valid, and a new
# transaction replaces it while keeping the SAME locktime and SAME heirs. # transaction replaces it while keeping the SAME locktime and SAME heirs.
# UPDATED keeps the VALID flag (see set_status). # UPDATED keeps the VALID flag (see set_status).
#
# The labels are marked with N_() but stay English here: they are written
# into the saved status history (see set_status) and translated only when
# shown, by format_status_history().
STATUS_DEFAULT = { STATUS_DEFAULT = {
"ANTICIPATED": ["Anticipated", False], "ANTICIPATED": [N_("Anticipated"), False],
"BROADCASTED": ["Broadcasted", False], "BROADCASTED": [N_("Broadcasted"), False],
"CHECKED": ["Checked", False], "CHECKED": [N_("Checked"), False],
"CHECK_FAIL": ["Check Failed", False], "CHECK_FAIL": [N_("Check Failed"), False],
"COMPLETE": ["Signed", False], "COMPLETE": [N_("Signed"), False],
"CONFIRMED": ["Confirmed", False], "CONFIRMED": [N_("Confirmed"), False],
"ERROR": ["Error", False], "ERROR": [N_("Error"), False],
"EXPIRED": ["Expired", False], "EXPIRED": [N_("Expired"), False],
"EXPORTED": ["Exported", False], "EXPORTED": [N_("Exported"), False],
"IMPORTED": ["Imported", False], "IMPORTED": [N_("Imported"), False],
"INVALIDATED": ["Invalidated", False], "INVALIDATED": [N_("Invalidated"), False],
"MEMPOOL": ["Mempool", False], "MEMPOOL": [N_("Mempool"), False],
"PUSH_FAIL": ["Push failed", False], "PUSH_FAIL": [N_("Push failed"), False],
"PUSHED": ["Pushed", False], "PUSHED": [N_("Pushed"), False],
"PARTIALLY_SIGNED": ["Partially Signed", False], "PARTIALLY_SIGNED": [N_("Partially Signed"), False],
"REPLACED": ["Replaced", False], "REPLACED": [N_("Replaced"), False],
"RESTORED": ["Restored", False], "RESTORED": [N_("Restored"), False],
"UPDATED": ["Updated", False], "UPDATED": [N_("Updated"), False],
"VALID": ["Valid", True], "VALID": [N_("Valid"), True],
} }
# Labels found in histories saved by older versions but no longer
# written: "New" opened every history (e.g. tests/samanta7).
# format_status_history() still translates them.
LEGACY_STATUS_LABELS = (N_("New"),)
def set_status(self, status, value=True): def set_status(self, status, value=True):
"""Set a status flag and apply the related side effects. """Set a status flag and apply the related side effects.
@@ -1341,7 +1378,11 @@ class WillItem(Logger):
if self.STATUS[status][1] == bool(value): if self.STATUS[status][1] == bool(value):
return None return None
self.status += "." + (("NOT " if not value else "") + _(self.STATUS[status][0])) # The history is saved in the wallet, in exported files and in QR
# transfers, so it is always written in English: the saved data must
# not depend on the GUI language (older versions wrote the translated
# label). format_status_history() translates it when it is shown.
self.status += "." + (("NOT " if not value else "") + self.STATUS[status][0])
self.STATUS[status][1] = bool(value) self.STATUS[status][1] = bool(value)
if value: if value:
# NOTE: ANTICIPATED and UPDATED are intentionally NOT in this list, # NOTE: ANTICIPATED and UPDATED are intentionally NOT in this list,

View File

@@ -22,10 +22,10 @@ from typing import Any
from aiohttp import ClientResponse from aiohttp import ClientResponse
from electrum import bitcoin, constants from electrum import bitcoin, constants
from electrum.bitcoin import COIN, TOTAL_COIN_SUPPLY_LIMIT_IN_BTC from electrum.bitcoin import COIN, TOTAL_COIN_SUPPLY_LIMIT_IN_BTC
from electrum.i18n import _
from electrum.logging import get_logger from electrum.logging import get_logger
from electrum.network import Network from electrum.network import Network
from ..i18n import _
from .plugin_base import BalPlugin, get_version from .plugin_base import BalPlugin, get_version
# Per-request timeout (seconds) for interactive operations (ping / info / # Per-request timeout (seconds) for interactive operations (ping / info /

View File

@@ -52,7 +52,6 @@ from electrum.gui.qt.util import (
read_QPixmap_from_bytes, read_QPixmap_from_bytes,
webopen, webopen,
) )
from electrum.i18n import _
from electrum.logging import get_logger from electrum.logging import get_logger
from electrum.network import BestEffortRequestFailed, Network, TxBroadcastError from electrum.network import BestEffortRequestFailed, Network, TxBroadcastError
from electrum.payment_identifier import PaymentIdentifier from electrum.payment_identifier import PaymentIdentifier
@@ -137,6 +136,7 @@ from ...core.will import (
WillExpiredException, WillExpiredException,
WillItem, WillItem,
WillPostponedException, WillPostponedException,
format_status_history,
) )
from ...core.willexecutors import ( # noqa: F401 from ...core.willexecutors import ( # noqa: F401
Willexecutors, Willexecutors,
@@ -144,6 +144,9 @@ from ...core.willexecutors import ( # noqa: F401
is_tor_active, is_tor_active,
) )
# BAL's translator: Electrum's catalog first, then BAL's (see bal/i18n.py).
from ...i18n import N_, _
# --- Presentation helpers --- # --- Presentation helpers ---
from .theme import ( from .theme import (
server_status_text, server_status_text,
@@ -161,6 +164,17 @@ from .window_utils import (
_logger = get_logger(__name__) _logger = get_logger(__name__)
# Labels of bal.core.qrtransfer.CHUNK_PRESETS, marked for translation here
# because qrtransfer.py must stay free of Electrum imports (the Android reader
# ships a copy of it). The combos show them with _(label);
# tests/test_i18n.py checks that this list matches CHUNK_PRESETS.
QR_PRESET_LABELS = (
N_("Small - ~150 bytes/QR (low-res cameras)"),
N_("Medium - ~400 bytes/QR"),
N_("Large - ~900 bytes/QR"),
N_("XL - ~1800 bytes/QR (high-res cameras)"),
)
class shown_cv: # noqa: N801 (intentionally lowercase: mirrors Qt signal naming) class shown_cv: # noqa: N801 (intentionally lowercase: mirrors Qt signal naming)
_type = bool _type = bool
@@ -178,13 +192,30 @@ class shown_cv: # noqa: N801 (intentionally lowercase: mirrors Qt signal namin
def add_widget(grid, label, widget, row, help_): def add_widget(grid, label, widget, row, help_):
grid.addWidget(QLabel(_(label)), row, 0) """Add a ``label | widget | help button`` row to ``grid``.
``label`` and ``help_`` must already be translated by the caller: a
variable passed to _() cannot be extracted into the catalog.
"""
grid.addWidget(QLabel(label), row, 0)
grid.addWidget(widget, row, 1) grid.addWidget(widget, row, 1)
grid.addWidget(HelpButton(help_), row, 2) grid.addWidget(HelpButton(help_), row, 2)
def translated_headers(headers):
"""Return a translated copy of a list's ``headers`` class attribute.
The column headers are class attributes marked with N_(): a class body
runs at import time, before the catalog is loaded, so they are
translated here, each time the headers are (re)built.
"""
return {column: _(text) for column, text in headers.items()}
def log_error(exec_info, window=None): def log_error(exec_info, window=None):
"""Log an error and optionally show it. """Log an error and optionally show it.
@@ -222,7 +253,7 @@ def export_meta_gui(electrum_window, title, exporter):
filter_ = "All files (*)" filter_ = "All files (*)"
filename = getSaveFileName( filename = getSaveFileName(
parent=electrum_window, parent=electrum_window,
title=_("Select file to save your {}".format(title)), title=_("Select file to save your {}").format(title),
filename="BALplugin_{}_{}_{}".format( filename="BALplugin_{}_{}_{}".format(
BalPlugin.chainname, str(electrum_window.wallet), title BalPlugin.chainname, str(electrum_window.wallet), title
), ),
@@ -237,7 +268,7 @@ def export_meta_gui(electrum_window, title, exporter):
electrum_window.show_critical(str(e)) electrum_window.show_critical(str(e))
else: else:
electrum_window.show_message( electrum_window.show_message(
_("Your {0} were exported to '{1}'".format(title, str(filename))) _("Your {0} were exported to '{1}'").format(title, str(filename))
) )

View File

@@ -62,6 +62,7 @@ from .calendar import BalCalendarButton
from .common import ( from .common import (
HEIR_DUST_AMOUNT, HEIR_DUST_AMOUNT,
HEIR_REAL_AMOUNT, HEIR_REAL_AMOUNT,
N_,
AmountException, AmountException,
Any, Any,
BalTimestamp, BalTimestamp,
@@ -322,7 +323,9 @@ class BalWizardWidget(QWidget):
self._bal_parent = parent self._bal_parent = parent
self.on_next = on_next self.on_next = on_next
self.on_cancel = on_cancel self.on_cancel = on_cancel
self.titleLabel = QLabel(self.title) # title/message are class attributes marked with N_(): translate them
# here, when shown (a class body runs before the catalog is loaded).
self.titleLabel = QLabel(_(self.title) if self.title else "")
self.vbox.addWidget(self.titleLabel) self.vbox.addWidget(self.titleLabel)
self.messageLabel = QLabel(_(self.message)) self.messageLabel = QLabel(_(self.message))
self.vbox.addWidget(self.messageLabel) self.vbox.addWidget(self.messageLabel)
@@ -377,8 +380,8 @@ class BalWizardWidget(QWidget):
class BalWizardHeirsWidget(BalWizardWidget): class BalWizardHeirsWidget(BalWizardWidget):
title = "Bitcoin After Life Heirs" title = N_("Bitcoin After Life Heirs")
message = ( message = N_(
"Please add your heirs\n remember that 100% of wallet balance will be spent" "Please add your heirs\n remember that 100% of wallet balance will be spent"
) )
@@ -416,18 +419,18 @@ class BalWizardHeirsWidget(BalWizardWidget):
class BalWizardWEDownloadWidget(BalWizardWidget): class BalWizardWEDownloadWidget(BalWizardWidget):
title = _("Bitcoin After Life Will-Executors") title = N_("Bitcoin After Life Will-Executors")
message = _("Choose willexecutors download method") message = N_("Choose willexecutors download method")
def get_content(self): def get_content(self):
# question = QLabel() # question = QLabel()
self.combo = QComboBox() self.combo = QComboBox()
self.combo.addItems( self.combo.addItems(
[ [
"Automatically download and select willexecutors", _("Automatically download and select willexecutors"),
"Only download willexecutors list", _("Only download willexecutors list"),
"Import willexecutor list from file", _("Import willexecutor list from file"),
"Manual", _("Manual"),
] ]
) )
# heir_name.setFixedWidth(32 * char_width_in_lineedit()) # heir_name.setFixedWidth(32 * char_width_in_lineedit())
@@ -524,8 +527,8 @@ class BalWizardWEDownloadWidget(BalWizardWidget):
class BalWizardWEWidget(BalWizardWidget): class BalWizardWEWidget(BalWizardWidget):
title = "Bitcoin After Life Will-Executors" title = N_("Bitcoin After Life Will-Executors")
message = _("Configure and select your willexecutors") message = N_("Configure and select your willexecutors")
def get_content(self): def get_content(self):
# Lazy import to avoid a dialogs<->lists import cycle. # Lazy import to avoid a dialogs<->lists import cycle.
@@ -544,8 +547,8 @@ class BalWizardWEWidget(BalWizardWidget):
class BalWizardLocktimeAndFeeWidget(BalWizardWidget): class BalWizardLocktimeAndFeeWidget(BalWizardWidget):
title = "Bitcoin After Life Will Settings" title = N_("Bitcoin After Life Will Settings")
message = _("") message = ""
def get_content(self): def get_content(self):
widget = QWidget() widget = QWidget()
@@ -748,7 +751,7 @@ class BalBuildWillDialog(BalDialog):
return return
txs = None txs = None
_logger.debug("close plugin phase 1 started") _logger.debug("close plugin phase 1 started")
varrow = self.msg_set_status("Checking variables") varrow = self.msg_set_status(_("Checking variables"))
try: try:
self.bal_window.init_class_variables() self.bal_window.init_class_variables()
except CheckAliveError as cae: except CheckAliveError as cae:
@@ -766,9 +769,9 @@ class BalBuildWillDialog(BalDialog):
"during phase1 CAE: {}, Continue to invalidate".format(cae) "during phase1 CAE: {}, Continue to invalidate".format(cae)
) )
self.msg_set_status( self.msg_set_status(
"Checking variables", varrow, _("Checking variables"), varrow,
"Check Alive Threshold Passed: you have to Invalidate " _("Check Alive Threshold Passed: you have to Invalidate "
"your old Will", "your old Will"),
self.COLOR_ERROR, self.COLOR_ERROR,
) )
else: else:
@@ -776,7 +779,7 @@ class BalBuildWillDialog(BalDialog):
return None, tx return None, tx
except NoHeirsException: except NoHeirsException:
self.msg_set_status( self.msg_set_status(
"Checking variables", varrow, self.msg_alert("No Heirs") _("Checking variables"), varrow, self.msg_alert(_("No Heirs"))
) )
return "no_heirs", None return "no_heirs", None
except Exception as e: except Exception as e:
@@ -799,18 +802,20 @@ class BalBuildWillDialog(BalDialog):
max_fee=self.bal_window.bal_plugin.MAX_WILLEXECUTOR_FEE.get(), max_fee=self.bal_window.bal_plugin.MAX_WILLEXECUTOR_FEE.get(),
) )
_logger.debug("variables ok") _logger.debug("variables ok")
self.msg_set_status("Checking variables", varrow, "Ok", self.COLOR_OK) self.msg_set_status(_("Checking variables"), varrow, _("Ok"), self.COLOR_OK)
except AmountException: except AmountException:
self.msg_set_checking( self.msg_set_checking(
self.msg_warning( self.msg_warning(
"In the inheritance process, " _(
+ "the entire wallet will always be fully emptied. \n" "In the inheritance process, "
+ "Your settings require an adjustment of the amounts" "the entire wallet will always be fully emptied. \n"
"Your settings require an adjustment of the amounts"
)
) )
) )
except WillExecutorFeeTooHighException as e: except WillExecutorFeeTooHighException as e:
self.msg_set_checking( self.msg_set_checking(
self.msg_warning(f"Will-executor fee too high: {e}") self.msg_warning(_("Will-executor fee too high: {}").format(e))
) )
self.msg_set_checking() self.msg_set_checking()
@@ -833,7 +838,7 @@ class BalBuildWillDialog(BalDialog):
# makes the CHECK button and the WIZARD behave identically and fixes # makes the CHECK button and the WIZARD behave identically and fixes
# the missing-label bug (#03). # the missing-label bug (#03).
_logger.debug("expired") _logger.debug("expired")
self.msg_set_checking("Expired") self.msg_set_checking(_("Expired"))
return "invalidate_classic", None return "invalidate_classic", None
except WillPostponedException as e: except WillPostponedException as e:
# An already signed/sent will is being postponed. Like an expired # An already signed/sent will is being postponed. Like an expired
@@ -856,7 +861,7 @@ class BalBuildWillDialog(BalDialog):
) )
except NoHeirsException: except NoHeirsException:
_logger.debug("no heirs") _logger.debug("no heirs")
self.msg_set_checking("No Heirs") self.msg_set_checking(_("No Heirs"))
except NotCompleteWillException as e: except NotCompleteWillException as e:
_logger.debug(f"not complete {e} true") _logger.debug(f"not complete {e} true")
message = False message = False
@@ -1051,9 +1056,11 @@ class BalBuildWillDialog(BalDialog):
dust_heirs.setdefault(hid, heir[HEIR_DUST_AMOUNT]) dust_heirs.setdefault(hid, heir[HEIR_DUST_AMOUNT])
for hid, dust_amount in dust_heirs.items(): for hid, dust_amount in dust_heirs.items():
self.msg_set_status( self.msg_set_status(
f"{_('Heir')} {hid}", _("Heir {}").format(hid),
None, None,
f"{dust_amount} is DUST - excluded (amount below dust limit)", _("{} is DUST - excluded (amount below dust limit)").format(
dust_amount
),
self.COLOR_WARNING, self.COLOR_WARNING,
) )
@@ -1223,14 +1230,14 @@ class BalBuildWillDialog(BalDialog):
for i in range(secs, 0, -1): for i in range(secs, 0, -1):
if self._stopping: if self._stopping:
return return
wait_row = self.msg_edit_row(_(f"Please wait {i}secs"), wait_row) wait_row = self.msg_edit_row(_("Please wait {}secs").format(i), wait_row)
time.sleep(1) time.sleep(1)
self.msg_del_row(wait_row) self.msg_del_row(wait_row)
def loop_broadcast_invalidating(self, tx): def loop_broadcast_invalidating(self, tx):
if self._stopping: if self._stopping:
return return
self.msg_set_invalidating("Broadcasting") self.msg_set_invalidating(_("Broadcasting"))
try: try:
tx.add_info_from_wallet(self.bal_window.wallet) tx.add_info_from_wallet(self.bal_window.wallet)
self.network.run_from_another_thread(tx.add_info_from_network(self.network)) self.network.run_from_another_thread(tx.add_info_from_network(self.network))
@@ -1341,7 +1348,7 @@ class BalBuildWillDialog(BalDialog):
done["count"] += 1 done["count"] += 1
# Show the per-server result (Ok/Ko) in bold + color so the # Show the per-server result (Ok/Ko) in bold + color so the
# outcome stands out, keeping the server URL in normal weight. # outcome stands out, keeping the server URL in normal weight.
result = self.msg_ok("Ok") if ok else self.msg_error("Ko") result = self.msg_ok(_("Ok")) if ok else self.msg_error(_("Ko"))
self.msg_edit_row("{} : {}".format(url, result)) self.msg_edit_row("{} : {}".format(url, result))
self.msg_set_pushing(_status_line()) self.msg_set_pushing(_status_line())
@@ -1393,8 +1400,11 @@ class BalBuildWillDialog(BalDialog):
if self._stopping: if self._stopping:
return return
row = self.msg_edit_row( row = self.msg_edit_row(
"checking {} - {} : <b>{}</b>".format( "{} : <b>{}</b>".format(
self.bal_window.willitems[wid].we["url"], wid, "Waiting" _("checking {} - {}").format(
self.bal_window.willitems[wid].we["url"], wid
),
_("Waiting"),
) )
) )
w = self.bal_window.willitems[wid] w = self.bal_window.willitems[wid]
@@ -1407,9 +1417,10 @@ class BalBuildWillDialog(BalDialog):
checked = self.bal_window.willitems[wid].get_status("CHECKED") checked = self.bal_window.willitems[wid].get_status("CHECKED")
result = self.msg_ok(checked) if checked else self.msg_error(checked) result = self.msg_ok(checked) if checked else self.msg_error(checked)
row = self.msg_edit_row( row = self.msg_edit_row(
"checked {} - {} : {}".format( "{} : {}".format(
self.bal_window.willitems[wid].we["url"], _("checked {} - {}").format(
wid, self.bal_window.willitems[wid].we["url"], wid
),
result, result,
), ),
row, row,
@@ -1457,7 +1468,7 @@ class BalBuildWillDialog(BalDialog):
raise Exception("not tx") raise Exception("not tx")
except Exception as e: except Exception as e:
(f"exception:{e}") (f"exception:{e}")
self.msg_set_invalidating(f"Error: {e}") self.msg_set_invalidating(_("Error: {}").format(e))
raise Exception("Impossible to sign") from e raise Exception("Impossible to sign") from e
def on_success_invalidate(self, success): def on_success_invalidate(self, success):
@@ -1825,8 +1836,11 @@ class BalBuildWillDialog(BalDialog):
basic_mode = self.bal_window.bal_plugin.is_basic_mode() basic_mode = self.bal_window.bal_plugin.is_basic_mode()
if basic_mode: if basic_mode:
raw_description = self.bal_window.bal_plugin.EVENT_DESCRIPTION.default # Factory defaults, in the GUI language (see BalConfig).
raw_summary = self.bal_window.bal_plugin.EVENT_SUMMARY.default raw_description = (
self.bal_window.bal_plugin.EVENT_DESCRIPTION.localized_default()
)
raw_summary = self.bal_window.bal_plugin.EVENT_SUMMARY.localized_default()
threshold = None threshold = None
num_reminders = 3 num_reminders = 3
else: else:
@@ -1863,6 +1877,7 @@ class BalBuildWillDialog(BalDialog):
version=self.bal_window.bal_plugin.version, version=self.bal_window.bal_plugin.version,
num_reminders=num_reminders, num_reminders=num_reminders,
threshold=threshold, threshold=threshold,
reminder_suffix=_("(reminder {idx}/{total})"),
) )
except Exception as e: except Exception as e:
_logger.error(f"failed to generate .ics: {e}") _logger.error(f"failed to generate .ics: {e}")
@@ -2006,7 +2021,7 @@ class BalBuildWillDialog(BalDialog):
def on_error_phase1(self, error): def on_error_phase1(self, error):
self.bal_window.update_all() self.bal_window.update_all()
a, b, c = error a, b, c = error
self.msg_edit_row(self.msg_error(f"Error: {b}")) self.msg_edit_row(self.msg_error(_("Error: {}").format(b)))
import traceback import traceback
_logger.error(f"error phase1: {b}\n{''.join(traceback.format_exception(a, b, c))}") _logger.error(f"error phase1: {b}\n{''.join(traceback.format_exception(a, b, c))}")
button=QPushButton(_("Close")) button=QPushButton(_("Close"))
@@ -2017,7 +2032,7 @@ class BalBuildWillDialog(BalDialog):
def on_error_phase2(self, error): def on_error_phase2(self, error):
self.bal_window.upade_all() self.bal_window.upade_all()
a, b, c = error a, b, c = error
self.msg_edit_row(self.msg_error(f"Error: {b}")) self.msg_edit_row(self.msg_error(_("Error: {}").format(b)))
_logger.error(f"error phase2: {b}") _logger.error(f"error phase2: {b}")
def _executed_inheritance_status(self): def _executed_inheritance_status(self):
@@ -2203,9 +2218,9 @@ class BalBuildWillDialog(BalDialog):
} }
if reason in messages: if reason in messages:
return messages[reason] + "\n\n" + _("Skipped") return "{}\n\n{}".format(messages[reason], _("Skipped"))
return ( return "{}\n\n{}".format(
_( _(
"Could not build the will, and the exact cause could not be " "Could not build the will, and the exact cause could not be "
"determined. Please check that:\n" "determined. Please check that:\n"
@@ -2213,12 +2228,14 @@ class BalBuildWillDialog(BalDialog):
"- each heir's share is above the minimum (dust limit),\n" "- each heir's share is above the minimum (dust limit),\n"
"- the Check Alive date is EARLIER than the delivery date,\n" "- the Check Alive date is EARLIER than the delivery date,\n"
"- at least one will-executor is selected and reachable." "- at least one will-executor is selected and reachable."
) ),
+ "\n\n" _("Skipped"),
+ _("Skipped")
) )
def msg_set_checking(self, status="Waiting", row=None): def msg_set_checking(self, status=None, row=None):
# The default is resolved here, not in the signature: a default
# argument is evaluated at import time, before the catalog is loaded.
status = _("Waiting") if status is None else status
row = self.check_row if row is None else row row = self.check_row if row is None else row
self.check_row = self.msg_set_status(_("Checking your will"), row, status) self.check_row = self.msg_set_status(_("Checking your will"), row, status)
@@ -2231,30 +2248,36 @@ class BalBuildWillDialog(BalDialog):
def msg_set_building(self, status=None, row=None,color=None): def msg_set_building(self, status=None, row=None,color=None):
row = self.build_row if row is None else row row = self.build_row if row is None else row
self.build_row = self.msg_set_status( self.build_row = self.msg_set_status(
"Building your will", self.build_row, status, color _("Building your will"), self.build_row, status, color
) )
def msg_set_signing(self, status=None, row=None): def msg_set_signing(self, status=None, row=None):
row = self.sign_row if row is None else row row = self.sign_row if row is None else row
self.sign_row = self.msg_set_status("Signing your will", self.sign_row, status) self.sign_row = self.msg_set_status(
_("Signing your will"), self.sign_row, status
)
def msg_set_pushing(self, status=None, row=None): def msg_set_pushing(self, status=None, row=None):
row = self.push_row if row is None else row row = self.push_row if row is None else row
self.push_row = self.msg_set_status( self.push_row = self.msg_set_status(
"Broadcasting your will to executors", self.push_row, status _("Broadcasting your will to executors"), self.push_row, status
) )
def msg_set_waiting(self, status=None, row=None): def msg_set_waiting(self, status=None, row=None):
row = self.wait_row if row is None else row row = self.wait_row if row is None else row
self.wait_row = self.msg_edit_row(f"Please wait {status}secs", self.wait_row) self.wait_row = self.msg_edit_row(
_("Please wait {}secs").format(status), self.wait_row
)
def msg_error(self, e): def msg_error(self, e):
# Results are shown in bold so the outcome stands out from the # Results are shown in bold so the outcome stands out from the
# left-side state label (which stays in normal weight). # left-side state label (which stays in normal weight).
return "<font color='{}'><b>{}</b></font>".format(self.COLOR_ERROR, e) return "<font color='{}'><b>{}</b></font>".format(self.COLOR_ERROR, e)
def msg_ok(self, e="Ok"): def msg_ok(self, e=None):
# Results are shown in bold (see msg_error). # Results are shown in bold (see msg_error). The default "Ok" is
# translated here, not in the signature (evaluated at import time).
e = _("Ok") if e is None else e
return "<font color='{}'><b>{}</b></font>".format(self.COLOR_OK, e) return "<font color='{}'><b>{}</b></font>".format(self.COLOR_OK, e)
def msg_warning(self, e): def msg_warning(self, e):
@@ -2283,12 +2306,14 @@ class BalBuildWillDialog(BalDialog):
# glance. ``status`` may already contain rich-text emitted by # glance. ``status`` may already contain rich-text emitted by
# msg_ok/msg_error/msg_warning (which add their own <b>...</b>); wrapping # msg_ok/msg_error/msg_warning (which add their own <b>...</b>); wrapping
# it again in <b> is harmless for those cases. # it again in <b> is harmless for those cases.
status = "Wait" if status is None else status # ``msg`` must already be translated by the caller: a variable
# passed to _() cannot be extracted into the catalog.
status = _("Wait") if status is None else status
if color is None: if color is None:
line = "{}:\t<b>{}</b>".format(_(msg), status) line = "{}:\t<b>{}</b>".format(msg, status)
else: else:
line = "{}:\t<font color={}><b>{}</b></font>".format( line = "{}:\t<font color={}><b>{}</b></font>".format(
_(msg), color, status msg, color, status
) )
return self.msg_edit_row(line, row) return self.msg_edit_row(line, row)
@@ -2416,15 +2441,15 @@ class WillDetailDialog(BalDialog):
self.paint_scroll_area() self.paint_scroll_area()
self.vlayout.addWidget( self.vlayout.addWidget(
QLabel(_("Expiration date: ") + str(BalTimestamp(self.threshold))) QLabel(_("Expiration date: {}").format(BalTimestamp(self.threshold)))
) )
self.vlayout.addWidget(self.scrollbox) self.vlayout.addWidget(self.scrollbox)
w = QWidget() w = QWidget()
hlayout = QHBoxLayout(w) hlayout = QHBoxLayout(w)
hlayout.addWidget( hlayout.addWidget(
QLabel(_("Valid Txs:") + str(len(Will.only_valid_list(self.will)))) QLabel(_("Valid Txs:{}").format(len(Will.only_valid_list(self.will))))
) )
hlayout.addWidget(QLabel(_("Total Txs:") + str(len(self.will)))) hlayout.addWidget(QLabel(_("Total Txs:{}").format(len(self.will))))
self.vlayout.addWidget(w) self.vlayout.addWidget(w)
self.setLayout(self.vlayout) self.setLayout(self.vlayout)
@@ -2477,18 +2502,19 @@ class WillDetailDialog(BalDialog):
def toggle_replaced(self): def toggle_replaced(self):
self.bal_window.bal_plugin.hide_replaced() self.bal_window.bal_plugin.hide_replaced()
toggle = _("Hide") # Whole sentences, so a translation can change the word order.
text = _("Hide replaced")
if self.bal_window.bal_plugin._hide_replaced: if self.bal_window.bal_plugin._hide_replaced:
toggle = _("Unhide") text = _("Unhide replaced")
self.toggle_replace_button.setText(f"{toggle} {_('replaced')}") self.toggle_replace_button.setText(text)
self.update() self.update()
def toggle_invalidated(self): def toggle_invalidated(self):
self.bal_window.bal_plugin.hide_invalidated() self.bal_window.bal_plugin.hide_invalidated()
toggle = _("Hide") text = _("Hide invalidated")
if self.bal_window.bal_plugin._hide_invalidated: if self.bal_window.bal_plugin._hide_invalidated:
toggle = _("Unhide") text = _("Unhide invalidated")
self.toggle_invalidate_button.setText(_(f"{toggle} {_('invalidated')}")) self.toggle_invalidate_button.setText(text)
self.update() self.update()
def update(self): def update(self):
@@ -2768,7 +2794,7 @@ class BalQrExportWidget(QWidget):
size_row = QHBoxLayout() size_row = QHBoxLayout()
size_row.addWidget(QLabel(_("QR code size:"))) size_row.addWidget(QLabel(_("QR code size:")))
self.size_combo = QComboBox() self.size_combo = QComboBox()
self.size_combo.addItems([label for label, _budget in CHUNK_PRESETS]) self.size_combo.addItems([_(label) for label, _budget in CHUNK_PRESETS])
self.size_combo.setCurrentIndex( self.size_combo.setCurrentIndex(
preset_index_for_chunk_size(self.chunk_size) preset_index_for_chunk_size(self.chunk_size)
) )
@@ -2783,7 +2809,8 @@ class BalQrExportWidget(QWidget):
self._format_options = ["balqr"] + list(ANIMATED_QR_FORMATS) self._format_options = ["balqr"] + list(ANIMATED_QR_FORMATS)
self.format_combo.addItems( self.format_combo.addItems(
[ [
format_name(fmt) + ((" (default)") if fmt == "balqr" else "") format_name(fmt)
+ (" {}".format(_("(default)")) if fmt == "balqr" else "")
for fmt in self._format_options for fmt in self._format_options
] ]
) )

View File

@@ -20,6 +20,7 @@ from PyQt6.QtWidgets import QLineEdit as _QLineEdit
from PyQt6.QtWidgets import QMessageBox, QStyledItemDelegate from PyQt6.QtWidgets import QMessageBox, QStyledItemDelegate
from .common import ( from .common import (
N_,
OP_RETURN_PREFIX, OP_RETURN_PREFIX,
BalTimestamp, BalTimestamp,
Buttons, Buttons,
@@ -59,6 +60,7 @@ from .common import (
datetime, datetime,
enum, enum,
export_meta_gui, export_meta_gui,
format_status_history,
getOpenFileName, getOpenFileName,
import_meta_gui, import_meta_gui,
is_op_return_address, is_op_return_address,
@@ -69,6 +71,7 @@ from .common import (
server_status_tooltip, server_status_tooltip,
signature_suffix, signature_suffix,
status_color, status_color,
translated_headers,
tx_from_any, tx_from_any,
write_json_file, write_json_file,
) )
@@ -128,9 +131,9 @@ class HeirListWidget(MyTreeView, MessageBoxMixin):
AMOUNT = enum.auto() AMOUNT = enum.auto()
headers = { headers = {
Columns.NAME: _("Name"), Columns.NAME: N_("Name"),
Columns.ADDRESS: _("Address"), Columns.ADDRESS: N_("Address"),
Columns.AMOUNT: _("Amount"), Columns.AMOUNT: N_("Amount"),
} }
filter_columns = [Columns.NAME, Columns.ADDRESS] filter_columns = [Columns.NAME, Columns.ADDRESS]
@@ -245,7 +248,7 @@ class HeirListWidget(MyTreeView, MessageBoxMixin):
col=self.Columns.NAME, role=self.ROLE_HEIR_KEY col=self.Columns.NAME, role=self.ROLE_HEIR_KEY
) )
self.model().clear() self.model().clear()
self.update_headers(self.__class__.headers) self.update_headers(translated_headers(self.__class__.headers))
set_current = None set_current = None
for key in sorted(self.bal_window.heirs.keys()): for key in sorted(self.bal_window.heirs.keys()):
heir = self.bal_window.heirs[key] heir = self.bal_window.heirs[key]
@@ -337,11 +340,11 @@ class PreviewList(MyTreeView, MessageBoxMixin):
SERVER = enum.auto() SERVER = enum.auto()
headers = { headers = {
Columns.LOCKTIME: _("Locktime"), Columns.LOCKTIME: N_("Locktime"),
Columns.TXID: _("Txid"), Columns.TXID: N_("Txid"),
Columns.WILLEXECUTOR: _("Will-Executor"), Columns.WILLEXECUTOR: N_("Will-Executor"),
Columns.STATUS: _("Status"), Columns.STATUS: N_("Status"),
Columns.SERVER: _("Server"), Columns.SERVER: N_("Server"),
} }
ROLE_HEIR_KEY = Qt.ItemDataRole.UserRole + 2000 ROLE_HEIR_KEY = Qt.ItemDataRole.UserRole + 2000
@@ -586,7 +589,7 @@ class PreviewList(MyTreeView, MessageBoxMixin):
if bal_tx.we: if bal_tx.we:
we = bal_tx.we["url"] we = bal_tx.we["url"]
labels[self.Columns.WILLEXECUTOR] = we labels[self.Columns.WILLEXECUTOR] = we
status = bal_tx.status + signature_suffix(bal_tx) status = format_status_history(bal_tx.status) + signature_suffix(bal_tx)
if len(status) > 53: if len(status) > 53:
status = "...{}".format(status[-50:]) status = "...{}".format(status[-50:])
labels[self.Columns.STATUS] = status labels[self.Columns.STATUS] = status
@@ -644,7 +647,7 @@ class PreviewList(MyTreeView, MessageBoxMixin):
col=self.Columns.TXID, role=self.ROLE_HEIR_KEY col=self.Columns.TXID, role=self.ROLE_HEIR_KEY
) )
self.model().clear() self.model().clear()
self.update_headers(self.__class__.headers) self.update_headers(translated_headers(self.__class__.headers))
set_current = None set_current = None
for txid, bal_tx in self.will.items(): for txid, bal_tx in self.will.items():
@@ -676,7 +679,7 @@ class PreviewList(MyTreeView, MessageBoxMixin):
# The Wizard is the main entry point to create an inheritance, so make # The Wizard is the main entry point to create an inheritance, so make
# it stand out: show a bold label next to a slightly larger icon (the # it stand out: show a bold label next to a slightly larger icon (the
# plain icon-only button was too easy to overlook). # plain icon-only button was too easy to overlook).
wizard = QPushButton(" " + _("Build Your Will")) wizard = QPushButton(" {}".format(_("Build Your Will")))
wizard.setIcon( wizard.setIcon(
read_QIcon_from_bytes( read_QIcon_from_bytes(
self.bal_window.bal_plugin.read_file("icons/wizard.png") self.bal_window.bal_plugin.read_file("icons/wizard.png")
@@ -904,12 +907,12 @@ class WillExecutorListWidget(MyTreeView):
ADDRESS = enum.auto() ADDRESS = enum.auto()
headers = { headers = {
Columns.SELECTED: _(""), Columns.SELECTED: "",
Columns.URL: _("Url"), Columns.URL: N_("Url"),
Columns.STATUS: _("S"), Columns.STATUS: N_("S"),
Columns.BASE_FEE: _("Base fee"), Columns.BASE_FEE: N_("Base fee"),
Columns.INFO: _("Info"), Columns.INFO: N_("Info"),
Columns.ADDRESS: _("Default Address"), Columns.ADDRESS: N_("Default Address"),
} }
filter_columns = [Columns.URL] filter_columns = [Columns.URL]
@@ -1091,7 +1094,7 @@ class WillExecutorListWidget(MyTreeView):
col=self.Columns.URL, role=self.ROLE_HEIR_KEY col=self.Columns.URL, role=self.ROLE_HEIR_KEY
) )
self.model().clear() self.model().clear()
self.update_headers(self.__class__.headers) self.update_headers(translated_headers(self.__class__.headers))
set_current = None set_current = None
@@ -1236,13 +1239,14 @@ class WillExecutorWidget(QWidget, MessageBoxMixin):
buttonbox.addWidget(b) buttonbox.addWidget(b)
def _menu_button(label): def _menu_button(label):
# ``label`` must already be translated by the caller.
btn = QToolButton() btn = QToolButton()
btn.setText(_(label)) btn.setText(label)
btn.setPopupMode(QToolButton.ToolButtonPopupMode.InstantPopup) btn.setPopupMode(QToolButton.ToolButtonPopupMode.InstantPopup)
buttonbox.addWidget(btn) buttonbox.addWidget(btn)
return btn return btn
export_btn = _menu_button("Export") export_btn = _menu_button(_("Export"))
export_menu = QMenu(export_btn) export_menu = QMenu(export_btn)
export_menu.addAction(_("Export all"), lambda: self.export_file()) export_menu.addAction(_("Export all"), lambda: self.export_file())
export_menu.addAction( export_menu.addAction(
@@ -1253,7 +1257,7 @@ class WillExecutorWidget(QWidget, MessageBoxMixin):
) )
export_btn.setMenu(export_menu) export_btn.setMenu(export_menu)
ping_btn = _menu_button("Ping All") ping_btn = _menu_button(_("Ping All"))
ping_menu = QMenu(ping_btn) ping_menu = QMenu(ping_btn)
ping_menu.addAction(_("Ping all"), lambda: self.update_willexecutors()) ping_menu.addAction(_("Ping all"), lambda: self.update_willexecutors())
ping_menu.addAction( ping_menu.addAction(
@@ -1261,7 +1265,7 @@ class WillExecutorWidget(QWidget, MessageBoxMixin):
) )
ping_btn.setMenu(ping_menu) ping_btn.setMenu(ping_menu)
select_btn = _menu_button("Select All") select_btn = _menu_button(_("Select All"))
select_menu = QMenu(select_btn) select_menu = QMenu(select_btn)
select_menu.addAction(_("Select all"), lambda: self.set_select_all(True)) select_menu.addAction(_("Select all"), lambda: self.set_select_all(True))
select_menu.addAction( select_menu.addAction(
@@ -1295,7 +1299,7 @@ class WillExecutorWidget(QWidget, MessageBoxMixin):
url_edit = QLineEdit() url_edit = QLineEdit()
url_edit.setFixedWidth(32 * char_width_in_lineedit()) url_edit.setFixedWidth(32 * char_width_in_lineedit())
info_edit = QLineEdit("New Will Executor") info_edit = QLineEdit(_("New Will Executor"))
info_edit.setFixedWidth(32 * char_width_in_lineedit()) info_edit.setFixedWidth(32 * char_width_in_lineedit())
base_fee_spin = QSpinBox() base_fee_spin = QSpinBox()
base_fee_spin.setRange(0, 1000000) base_fee_spin.setRange(0, 1000000)
@@ -1309,7 +1313,7 @@ class WillExecutorWidget(QWidget, MessageBoxMixin):
if executor: if executor:
url_edit.setText(edit_key) url_edit.setText(edit_key)
info_edit.setText(str(executor.get("info", "New Will Executor"))) info_edit.setText(str(executor.get("info", _("New Will Executor"))))
base_fee_spin.setValue(int(executor.get("base_fee", 0))) base_fee_spin.setValue(int(executor.get("base_fee", 0)))
address_edit.setText(str(executor.get("address", ""))) address_edit.setText(str(executor.get("address", "")))
@@ -1469,7 +1473,7 @@ class WillExecutorWidget(QWidget, MessageBoxMixin):
break break
self._add_another = False self._add_another = False
url_edit.clear() url_edit.clear()
info_edit.setText("New Will Executor") info_edit.setText(_("New Will Executor"))
base_fee_spin.setValue(0) base_fee_spin.setValue(0)
address_edit.clear() address_edit.clear()

View File

@@ -20,6 +20,7 @@ from electrum.util import EventListener, event_listener
from PyQt6.QtWidgets import QLayout from PyQt6.QtWidgets import QLayout
from ...core.qrtransfer import CHUNK_PRESETS, preset_index_for_chunk_size from ...core.qrtransfer import CHUNK_PRESETS, preset_index_for_chunk_size
from ...i18n import init_from_config
from .common import ( from .common import (
BalPlugin, BalPlugin,
Buttons, Buttons,
@@ -67,6 +68,11 @@ class Plugin(BalPlugin, EventListener):
def __init__(self, parent, config, name): def __init__(self, parent, config, name):
_logger.info("INIT BALPLUGIN") _logger.info("INIT BALPLUGIN")
BalPlugin.__init__(self, parent, config, name) BalPlugin.__init__(self, parent, config, name)
# Load BAL's catalog for the language Electrum's GUI is using, before
# any window or dialog builds its texts. It must come after
# BalPlugin.__init__: read_file() needs the plugin's parent and name.
# The CLI plugin does not call this, so the CLI stays in English.
init_from_config(self, config)
self.bal_windows = {} self.bal_windows = {}
# Status-bar buttons, keyed by id(sb.window()). Tracking them lets us # Status-bar buttons, keyed by id(sb.window()). Tracking them lets us
# remove a stale button before creating a fresh one when a wallet is # remove a stale button before creating a fresh one when a wallet is
@@ -298,7 +304,7 @@ class Plugin(BalPlugin, EventListener):
pass pass
b = StatusBarButton( b = StatusBarButton(
read_QIcon_from_bytes(self.read_file("icons/bal32x32.png")), read_QIcon_from_bytes(self.read_file("icons/bal32x32.png")),
"Bal " + _("Bitcoin After Life"), "Bal {}".format(_("Bitcoin After Life")),
lambda: self.settings_dialog(sb.window()), lambda: self.settings_dialog(sb.window()),
sb.height(), sb.height(),
) )
@@ -442,7 +448,7 @@ class Plugin(BalPlugin, EventListener):
def settings_dialog(self, window=None, wallet=None): def settings_dialog(self, window=None, wallet=None):
d = BalDialog(window, self, self.get_window_title("Settings")) d = BalDialog(window, self, self.get_window_title(_("Settings")))
d.setMinimumSize(100, 200) d.setMinimumSize(100, 200)
qicon = read_QPixmap_from_bytes(self.read_file("icons/bal16x16.png")) qicon = read_QPixmap_from_bytes(self.read_file("icons/bal16x16.png"))
lbl_logo = QLabel() lbl_logo = QLabel()
@@ -537,7 +543,8 @@ class Plugin(BalPlugin, EventListener):
# Ordered low -> high so the user picks the resolution matching their # Ordered low -> high so the user picks the resolution matching their
# camera. Visible to all users (BASIC and ADVANCED). # camera. Visible to all users (BASIC and ADVANCED).
qr_size_combo = QComboBox() qr_size_combo = QComboBox()
qr_size_combo.addItems([label for label, _budget in CHUNK_PRESETS]) # Labels marked for translation in common.QR_PRESET_LABELS.
qr_size_combo.addItems([_(label) for label, _budget in CHUNK_PRESETS])
qr_size_combo.setCurrentIndex( qr_size_combo.setCurrentIndex(
preset_index_for_chunk_size(int(self.QR_CHUNK_SIZE.get())) preset_index_for_chunk_size(int(self.QR_CHUNK_SIZE.get()))
) )
@@ -656,9 +663,9 @@ class Plugin(BalPlugin, EventListener):
elif kind == "spin": elif kind == "spin":
widget.setValue(int(cfg.default)) widget.setValue(int(cfg.default))
elif kind == "line": elif kind == "line":
widget.setText(cfg.default) widget.setText(cfg.localized_default())
elif kind == "text": elif kind == "text":
widget.setPlainText(cfg.default) widget.setPlainText(cfg.localized_default())
elif kind == "user_type": elif kind == "user_type":
widget.setCurrentIndex( widget.setCurrentIndex(
1 if str(cfg.default).lower() == "advanced" else 0 1 if str(cfg.default).lower() == "advanced" else 0
@@ -670,7 +677,7 @@ class Plugin(BalPlugin, EventListener):
btn.clicked.connect(reset) btn.clicked.connect(reset)
return btn return btn
heir_repush = QPushButton("Rebroadcast transactions") heir_repush = QPushButton(_("Rebroadcast transactions"))
heir_repush.clicked.connect(partial(self.broadcast_transactions, True)) heir_repush.clicked.connect(partial(self.broadcast_transactions, True))
bal_mode = QComboBox() bal_mode = QComboBox()
options = ["Easy", "Advanced", "Experimental"] options = ["Easy", "Advanced", "Experimental"]
@@ -696,27 +703,27 @@ class Plugin(BalPlugin, EventListener):
# advanced-only settings, so the user picks basic/advanced first. # advanced-only settings, so the user picks basic/advanced first.
add_widget( add_widget(
grid, grid,
"Hide Replaced", _("Hide Replaced"),
heir_hide_replaced, heir_hide_replaced,
0, 0,
"Hide replaced transactions from will detail and list", _("Hide replaced transactions from will detail and list"),
) )
grid.addWidget(_make_reset_btn(self.HIDE_REPLACED, heir_hide_replaced, "check"), 0, 3) grid.addWidget(_make_reset_btn(self.HIDE_REPLACED, heir_hide_replaced, "check"), 0, 3)
add_widget( add_widget(
grid, grid,
"Hide Invalidated", _("Hide Invalidated"),
heir_hide_invalidated, heir_hide_invalidated,
1, 1,
"Hide invalidated transactions from will detail and list", _("Hide invalidated transactions from will detail and list"),
) )
grid.addWidget(_make_reset_btn(self.HIDE_INVALIDATED, heir_hide_invalidated, "check"), 1, 3) grid.addWidget(_make_reset_btn(self.HIDE_INVALIDATED, heir_hide_invalidated, "check"), 1, 3)
lbl_auto_sign = QLabel(_("Auto-sign on Check")) lbl_auto_sign = QLabel(_("Auto-sign on Check"))
help_auto_sign = HelpButton( help_auto_sign = HelpButton(_(
"When checking, automatically sign and broadcast the will " "When checking, automatically sign and broadcast the will "
"transactions to their will-executors.\n" "transactions to their will-executors.\n"
"The wallet password is requested only if the wallet is " "The wallet password is requested only if the wallet is "
"encrypted." "encrypted."
) ))
grid.addWidget(_hide_if_basic(lbl_auto_sign), 2, 0) grid.addWidget(_hide_if_basic(lbl_auto_sign), 2, 0)
grid.addWidget(_hide_if_basic(heir_auto_sign), 2, 1) grid.addWidget(_hide_if_basic(heir_auto_sign), 2, 1)
grid.addWidget(_hide_if_basic(help_auto_sign), 2, 2) grid.addWidget(_hide_if_basic(help_auto_sign), 2, 2)
@@ -726,10 +733,10 @@ class Plugin(BalPlugin, EventListener):
grid.addWidget(_hide_if_basic(reset_btn_auto_sign), 2, 3) grid.addWidget(_hide_if_basic(reset_btn_auto_sign), 2, 3)
add_widget( add_widget(
grid, grid,
"Panel editable Date and Fee", _("Panel editable Date and Fee"),
heir_editable_dates, heir_editable_dates,
3, 3,
( _(
"When enabled, the delivery-time and check-alive date fields " "When enabled, the delivery-time and check-alive date fields "
"can be edited everywhere (toolbar / Heirs tab), not only in " "can be edited everywhere (toolbar / Heirs tab), not only in "
"the will-building wizard.\n" "the will-building wizard.\n"
@@ -741,10 +748,10 @@ class Plugin(BalPlugin, EventListener):
# will-executor. Visible to all users (BASIC and ADVANCED). # will-executor. Visible to all users (BASIC and ADVANCED).
add_widget( add_widget(
grid, grid,
"Max Will-Executor Fee (satoshi)", _("Max Will-Executor Fee (satoshi)"),
heir_max_willexecutor_fee, heir_max_willexecutor_fee,
4, 4,
( _(
"Maximum fee (in satoshi) allowed to be paid to a single " "Maximum fee (in satoshi) allowed to be paid to a single "
"will-executor. If a will-executor charges more than this, " "will-executor. If a will-executor charges more than this, "
"the will will not be built.\n" "the will will not be built.\n"
@@ -756,10 +763,10 @@ class Plugin(BalPlugin, EventListener):
# user chooses basic/advanced first, then sees the relevant options. # user chooses basic/advanced first, then sees the relevant options.
add_widget( add_widget(
grid, grid,
"User Type", _("User Type"),
user_type_combo, user_type_combo,
5, 5,
( _(
"Choose how much detail the plugin shows.\n\n" "Choose how much detail the plugin shows.\n\n"
"BASIC: simplified interface, safe configuration for most " "BASIC: simplified interface, safe configuration for most "
"users.\n\n" "users.\n\n"
@@ -774,10 +781,10 @@ class Plugin(BalPlugin, EventListener):
# only in ADVANCED mode. In BASIC mode the factory defaults are always # only in ADVANCED mode. In BASIC mode the factory defaults are always
# used and these settings are hidden. # used and these settings are hidden.
lbl_num_reminders = QLabel(_("Number of reminders")) lbl_num_reminders = QLabel(_("Number of reminders"))
help_num_reminders = HelpButton( help_num_reminders = HelpButton(_(
"How many reminder alarms the exported calendar (.ics) event " "How many reminder alarms the exported calendar (.ics) event "
"contains. Range: 1 to 5 (default 3). Only used in ADVANCED mode." "contains. Range: 1 to 5 (default 3). Only used in ADVANCED mode."
) ))
grid.addWidget(_hide_if_basic(lbl_num_reminders), 6, 0) grid.addWidget(_hide_if_basic(lbl_num_reminders), 6, 0)
grid.addWidget(_hide_if_basic(heir_num_reminders), 6, 1) grid.addWidget(_hide_if_basic(heir_num_reminders), 6, 1)
grid.addWidget(_hide_if_basic(help_num_reminders), 6, 2) grid.addWidget(_hide_if_basic(help_num_reminders), 6, 2)
@@ -785,13 +792,13 @@ class Plugin(BalPlugin, EventListener):
grid.addWidget(_hide_if_basic(reset_btn_6), 6, 3) grid.addWidget(_hide_if_basic(reset_btn_6), 6, 3)
lbl_event_summary = QLabel(_("Event summary")) lbl_event_summary = QLabel(_("Event summary"))
help_event_summary = HelpButton( help_event_summary = HelpButton(_(
"Default message to be used in event summary\n" "Default message to be used in event summary\n"
"Variables:\n" "Variables:\n"
" $wallet_name: name of wallet\n" " $wallet_name: name of wallet\n"
" $heirs_complete: list of heirs name,address,amount\n" " $heirs_complete: list of heirs name,address,amount\n"
"Only used in ADVANCED mode." "Only used in ADVANCED mode."
) ))
grid.addWidget(_hide_if_basic(lbl_event_summary), 7, 0) grid.addWidget(_hide_if_basic(lbl_event_summary), 7, 0)
grid.addWidget(_hide_if_basic(edit_event_summary), 7, 1) grid.addWidget(_hide_if_basic(edit_event_summary), 7, 1)
grid.addWidget(_hide_if_basic(help_event_summary), 7, 2) grid.addWidget(_hide_if_basic(help_event_summary), 7, 2)
@@ -799,13 +806,13 @@ class Plugin(BalPlugin, EventListener):
grid.addWidget(_hide_if_basic(reset_btn_7), 7, 3) grid.addWidget(_hide_if_basic(reset_btn_7), 7, 3)
lbl_event_description = QLabel(_("Event description")) lbl_event_description = QLabel(_("Event description"))
help_event_description = HelpButton( help_event_description = HelpButton(_(
"Default message to be used in event description\n" "Default message to be used in event description\n"
"Variables:\n" "Variables:\n"
" $wallet_name: name of wallet\n" " $wallet_name: name of wallet\n"
" $heirs_complete: list of heirs name,address,amount\n" " $heirs_complete: list of heirs name,address,amount\n"
"Only used in ADVANCED mode." "Only used in ADVANCED mode."
) ))
grid.addWidget(_hide_if_basic(lbl_event_description), 8, 0) grid.addWidget(_hide_if_basic(lbl_event_description), 8, 0)
grid.addWidget(_hide_if_basic(edit_event_description), 8, 1) grid.addWidget(_hide_if_basic(edit_event_description), 8, 1)
grid.addWidget(_hide_if_basic(help_event_description), 8, 2) grid.addWidget(_hide_if_basic(help_event_description), 8, 2)
@@ -814,10 +821,10 @@ class Plugin(BalPlugin, EventListener):
# Welist server URL: shown only in ADVANCED mode. In BASIC mode the # Welist server URL: shown only in ADVANCED mode. In BASIC mode the
# factory default is always used and the setting is hidden. # factory default is always used and the setting is hidden.
lbl_welist_server = QLabel(_("Welist Server URL")) lbl_welist_server = QLabel(_("Welist Server URL"))
help_welist_server = HelpButton( help_welist_server = HelpButton(_(
"URL of the server that provides the will-executor list. " "URL of the server that provides the will-executor list. "
"Only available in ADVANCED mode." "Only available in ADVANCED mode."
) ))
grid.addWidget(_hide_if_basic(lbl_welist_server), 9, 0) grid.addWidget(_hide_if_basic(lbl_welist_server), 9, 0)
grid.addWidget(_hide_if_basic(edit_welist_server), 9, 1) grid.addWidget(_hide_if_basic(edit_welist_server), 9, 1)
grid.addWidget(_hide_if_basic(help_welist_server), 9, 2) grid.addWidget(_hide_if_basic(help_welist_server), 9, 2)
@@ -825,11 +832,11 @@ class Plugin(BalPlugin, EventListener):
grid.addWidget(_hide_if_basic(reset_btn_9), 9, 3) grid.addWidget(_hide_if_basic(reset_btn_9), 9, 3)
lbl_calendar_app = QLabel(_("Calendar app command")) lbl_calendar_app = QLabel(_("Calendar app command"))
help_calendar_app = HelpButton( help_calendar_app = HelpButton(_(
"Command used to open .ics calendar files.\n" "Command used to open .ics calendar files.\n"
"Leave empty to use the system default (xdg-open/open/start).\n" "Leave empty to use the system default (xdg-open/open/start).\n"
"Only used in ADVANCED mode." "Only used in ADVANCED mode."
) ))
grid.addWidget(_hide_if_basic(lbl_calendar_app), 10, 0) grid.addWidget(_hide_if_basic(lbl_calendar_app), 10, 0)
grid.addWidget(_hide_if_basic(edit_calendar_app), 10, 1) grid.addWidget(_hide_if_basic(edit_calendar_app), 10, 1)
grid.addWidget(_hide_if_basic(help_calendar_app), 10, 2) grid.addWidget(_hide_if_basic(help_calendar_app), 10, 2)
@@ -840,13 +847,13 @@ class Plugin(BalPlugin, EventListener):
# label field is disabled while the checkbox is off (see # label field is disabled while the checkbox is off (see
# on_save_history_change above). # on_save_history_change above).
lbl_save_history = QLabel(_("Save inheritance transactions in history")) lbl_save_history = QLabel(_("Save inheritance transactions in history"))
help_save_history = HelpButton( help_save_history = HelpButton(_(
"After each check, save the valid will transactions into the " "After each check, save the valid will transactions into the "
"wallet's local history (the History tab), each with a label.\n" "wallet's local history (the History tab), each with a label.\n"
"The label may contain the variable:\n" "The label may contain the variable:\n"
" {willexecutor}: replaced with the will-executor URL of the item\n" " {willexecutor}: replaced with the will-executor URL of the item\n"
"Only used in ADVANCED mode." "Only used in ADVANCED mode."
) ))
grid.addWidget(_hide_if_basic(lbl_save_history), 11, 0) grid.addWidget(_hide_if_basic(lbl_save_history), 11, 0)
grid.addWidget(_hide_if_basic(heir_save_history), 11, 1) grid.addWidget(_hide_if_basic(heir_save_history), 11, 1)
grid.addWidget(_hide_if_basic(help_save_history), 11, 2) grid.addWidget(_hide_if_basic(help_save_history), 11, 2)
@@ -854,13 +861,13 @@ class Plugin(BalPlugin, EventListener):
grid.addWidget(_hide_if_basic(reset_btn_11), 11, 3) grid.addWidget(_hide_if_basic(reset_btn_11), 11, 3)
lbl_history_label = QLabel(_("History label")) lbl_history_label = QLabel(_("History label"))
help_history_label = HelpButton( help_history_label = HelpButton(_(
"Label applied to the will transactions saved into the wallet's " "Label applied to the will transactions saved into the wallet's "
"local history.\n" "local history.\n"
"Variables:\n" "Variables:\n"
" {willexecutor}: replaced with the will-executor URL of the item\n" " {willexecutor}: replaced with the will-executor URL of the item\n"
"Only used in ADVANCED mode." "Only used in ADVANCED mode."
) ))
grid.addWidget(_hide_if_basic(lbl_history_label), 12, 0) grid.addWidget(_hide_if_basic(lbl_history_label), 12, 0)
grid.addWidget(_hide_if_basic(edit_history_label), 12, 1) grid.addWidget(_hide_if_basic(edit_history_label), 12, 1)
grid.addWidget(_hide_if_basic(help_history_label), 12, 2) grid.addWidget(_hide_if_basic(help_history_label), 12, 2)
@@ -877,7 +884,7 @@ class Plugin(BalPlugin, EventListener):
grid.addWidget(heir_repush, 13, 0) grid.addWidget(heir_repush, 13, 0)
grid.addWidget( grid.addWidget(
HelpButton( HelpButton(
"Broadcast all transactions to willexecutors including those already pushed" _("Broadcast all transactions to willexecutors including those already pushed")
), ),
13, 13,
2, 2,
@@ -887,12 +894,12 @@ class Plugin(BalPlugin, EventListener):
# Placed below the rebroadcast button so the existing rows keep their # Placed below the rebroadcast button so the existing rows keep their
# numbers. # numbers.
lbl_rebuild_on_close = QLabel(_("Rebuild will on wallet close")) lbl_rebuild_on_close = QLabel(_("Rebuild will on wallet close"))
help_rebuild_on_close = HelpButton( help_rebuild_on_close = HelpButton(_(
"Run the 'Build your will' wizard every time the wallet is closed " "Run the 'Build your will' wizard every time the wallet is closed "
"or Electrum is quit, so the will is rebuilt and re-validated.\n" "or Electrum is quit, so the will is rebuilt and re-validated.\n"
"When disabled, the will is only rebuilt when you press Check or " "When disabled, the will is only rebuilt when you press Check or "
"Prepare. The last built state is still saved to the wallet." "Prepare. The last built state is still saved to the wallet."
) ))
grid.addWidget(lbl_rebuild_on_close, 14, 0) grid.addWidget(lbl_rebuild_on_close, 14, 0)
grid.addWidget(heir_rebuild_on_close, 14, 1) grid.addWidget(heir_rebuild_on_close, 14, 1)
grid.addWidget(help_rebuild_on_close, 14, 2) grid.addWidget(help_rebuild_on_close, 14, 2)
@@ -905,7 +912,7 @@ class Plugin(BalPlugin, EventListener):
# BASIC + ADVANCED), right below the "Rebuild will on wallet close" # BASIC + ADVANCED), right below the "Rebuild will on wallet close"
# row. # row.
lbl_auto_rebuild = QLabel(_("Rebuild automatically on new transactions")) lbl_auto_rebuild = QLabel(_("Rebuild automatically on new transactions"))
help_auto_rebuild = HelpButton( help_auto_rebuild = HelpButton(_(
"When a new transaction arrives for the wallet, automatically " "When a new transaction arrives for the wallet, automatically "
"rebuild the will the same way the wizard does at wallet close: " "rebuild the will the same way the wizard does at wallet close: "
"the delivery date is anticipated by one day so the new will " "the delivery date is anticipated by one day so the new will "
@@ -916,7 +923,7 @@ class Plugin(BalPlugin, EventListener):
"threshold, or when the threshold is already in the past.\n" "threshold, or when the threshold is already in the past.\n"
"When disabled (default), the will is only rebuilt on Check / " "When disabled (default), the will is only rebuilt on Check / "
"Prepare / wallet close." "Prepare / wallet close."
) ))
grid.addWidget(lbl_auto_rebuild, 15, 0) grid.addWidget(lbl_auto_rebuild, 15, 0)
grid.addWidget(heir_auto_rebuild, 15, 1) grid.addWidget(heir_auto_rebuild, 15, 1)
grid.addWidget(help_auto_rebuild, 15, 2) grid.addWidget(help_auto_rebuild, 15, 2)
@@ -929,13 +936,13 @@ class Plugin(BalPlugin, EventListener):
# size used when exporting a will via QR codes; changeable per export # size used when exporting a will via QR codes; changeable per export
# inside the export dialog itself. # inside the export dialog itself.
lbl_qr_size = QLabel(_("QR Code Size")) lbl_qr_size = QLabel(_("QR Code Size"))
help_qr_size = HelpButton( help_qr_size = HelpButton(_(
"Payload size of a single QR code when exporting a will via QR.\n\n" "Payload size of a single QR code when exporting a will via QR.\n\n"
"Larger QR codes hold more data (fewer shots) but are easier to " "Larger QR codes hold more data (fewer shots) but are easier to "
"scan with a high-resolution camera; smaller QR codes scan fine " "scan with a high-resolution camera; smaller QR codes scan fine "
"even with low-resolution cameras but require more shots.\n" "even with low-resolution cameras but require more shots.\n"
"The same selector is available inside the export dialog." "The same selector is available inside the export dialog."
) ))
grid.addWidget(lbl_qr_size, 16, 0) grid.addWidget(lbl_qr_size, 16, 0)
grid.addWidget(qr_size_combo, 16, 1) grid.addWidget(qr_size_combo, 16, 1)
grid.addWidget(help_qr_size, 16, 2) grid.addWidget(help_qr_size, 16, 2)
@@ -990,9 +997,9 @@ class Plugin(BalPlugin, EventListener):
elif kind == "spin": elif kind == "spin":
widget.setValue(int(cfg.default)) widget.setValue(int(cfg.default))
elif kind == "line": elif kind == "line":
widget.setText(cfg.default) widget.setText(cfg.localized_default())
elif kind == "text": elif kind == "text":
widget.setPlainText(cfg.default) widget.setPlainText(cfg.localized_default())
elif kind == "user_type": elif kind == "user_type":
# Default is "basic" -> combo index 0; "advanced" -> index 1. # Default is "basic" -> combo index 0; "advanced" -> index 1.
widget.setCurrentIndex( widget.setCurrentIndex(
@@ -1031,7 +1038,7 @@ class Plugin(BalPlugin, EventListener):
bottom_row = QHBoxLayout() bottom_row = QHBoxLayout()
bottom_row.addWidget(btn_reset) bottom_row.addWidget(btn_reset)
bottom_row.addStretch(1) bottom_row.addStretch(1)
bottom_row.addWidget(QLabel("<b>" + _("Support:") + "</b>")) bottom_row.addWidget(QLabel("<b>{}</b>".format(_("Support:"))))
bottom_row.addWidget(lbl_support) bottom_row.addWidget(lbl_support)
# Outer layout: warning (top) -> settings grid -> bottom button row. # Outer layout: warning (top) -> settings grid -> bottom button row.
@@ -1083,6 +1090,11 @@ class Plugin(BalPlugin, EventListener):
) )
def get_window_title(self, title): def get_window_title(self, title):
return _("BAL - ") + _(title) """Return the window title "BAL - <title>".
``title`` must already be translated by the caller: a variable passed
to _() cannot be extracted into the catalog.
"""
return _("BAL - {}").format(title)

View File

@@ -87,7 +87,7 @@ def server_status_text(will_item) -> str:
the user always knows whether each inheritance transaction is actually the user always knows whether each inheritance transaction is actually
stored on the will-executor servers, regardless of the row colour. stored on the will-executor servers, regardless of the row colour.
""" """
from electrum.i18n import _ from ...i18n import _
if will_item.get_status("CHECK_FAIL") and not will_item.get_status("CHECKED"): if will_item.get_status("CHECK_FAIL") and not will_item.get_status("CHECKED"):
return _("Not on server") return _("Not on server")
@@ -105,7 +105,7 @@ def server_status_text(will_item) -> str:
def server_status_tooltip(will_item) -> str: def server_status_tooltip(will_item) -> str:
"""Return a detailed tooltip for the "Server" column, including the """Return a detailed tooltip for the "Server" column, including the
will-executor URL (if any) and the current server state.""" will-executor URL (if any) and the current server state."""
from electrum.i18n import _ from ...i18n import _
url = None url = None
we = getattr(will_item, "we", None) we = getattr(will_item, "we", None)

View File

@@ -31,6 +31,7 @@ from ...core.reminders import build_ics_reminders, write_temp_ics
from .calendar import BalCalendar, BalCalendarButton from .calendar import BalCalendar, BalCalendarButton
from .common import ( from .common import (
DECIMAL_POINT, DECIMAL_POINT,
N_,
NLOCKTIME_BLOCKHEIGHT_MAX, NLOCKTIME_BLOCKHEIGHT_MAX,
NLOCKTIME_MAX, NLOCKTIME_MAX,
Any, Any,
@@ -67,6 +68,7 @@ from .common import (
_logger, _logger,
char_width_in_lineedit, char_width_in_lineedit,
datetime, datetime,
format_status_history,
getSaveFileName, getSaveFileName,
log_error, log_error,
os, os,
@@ -207,10 +209,10 @@ class BalTimeEditWidget(QWidget, _LockTimeEditor):
current_index = None current_index = None
default_value = None default_value = None
help_text = ( help_text = N_(
"if you choose Raw, you can insert various options based on suffix:\n" "if you choose Raw, you can insert various options based on suffix:\n"
+ " - d: number of days after current day(ex: 1d means tomorrow)\n" " - d: number of days after current day(ex: 1d means tomorrow)\n"
+ " - y: number of years after currrent day(ex: 1y means one year from today)\n" " - y: number of years after currrent day(ex: 1y means one year from today)\n"
) )
label_text = None label_text = None
tooltip_text = None tooltip_text = None
@@ -276,7 +278,9 @@ class BalTimeEditWidget(QWidget, _LockTimeEditor):
] ]
) )
#hbox.addWidget(QLabel(self.label_text)) #hbox.addWidget(QLabel(self.label_text))
help_button=HelpButton(self.help_text) # help_text and tooltip_text are class attributes marked with N_():
# translate them here, when shown.
help_button=HelpButton(_(self.help_text))
help_button.setText(self.label_text) help_button.setText(self.label_text)
# Show a short label (e.g. "Delivery time" / "Check Alive") when the # Show a short label (e.g. "Delivery time" / "Check Alive") when the
# user hovers the icon, so the emoji button is self-explanatory. # user hovers the icon, so the emoji button is self-explanatory.
@@ -625,7 +629,7 @@ class LockTimeDateEdit(QDateTimeEdit, _LockTimeEditor):
class ThresholdTimeWidget(BalTimeEditWidget): class ThresholdTimeWidget(BalTimeEditWidget):
# rich_text=True is used by the HelpButton, so HTML tags (<b>, <br>) render. # rich_text=True is used by the HelpButton, so HTML tags (<b>, <br>) render.
help_text = ( help_text = N_(
"<b>CHECK ALIVE</b><br><br>" "<b>CHECK ALIVE</b><br><br>"
"In DATA mode:<br>" "In DATA mode:<br>"
"set the date for the \u201ccheck alive\u201d parameter.<br>" "set the date for the \u201ccheck alive\u201d parameter.<br>"
@@ -644,7 +648,7 @@ class ThresholdTimeWidget(BalTimeEditWidget):
) )
label_text = "🚨" label_text = "🚨"
#label_text = "Check Alive" #label_text = "Check Alive"
tooltip_text = "Check Alive" tooltip_text = N_("Check Alive")
base_field = "threshold" base_field = "threshold"
def __init__(self, bal_window, parent, init_value=None): def __init__(self, bal_window, parent, init_value=None):
@@ -659,7 +663,7 @@ class ThresholdTimeWidget(BalTimeEditWidget):
class LockTimeWidget(BalTimeEditWidget): class LockTimeWidget(BalTimeEditWidget):
# rich_text=True is used by the HelpButton, so HTML tags (<b>, <br>) render. # rich_text=True is used by the HelpButton, so HTML tags (<b>, <br>) render.
help_text = ( help_text = N_(
"<b>DELIVERY TIME</b><br><br>" "<b>DELIVERY TIME</b><br><br>"
"Set Locktime for transactions.<br>" "Set Locktime for transactions.<br>"
"Any time is needed transaction will be anticipated by 1day<br><br>" "Any time is needed transaction will be anticipated by 1day<br><br>"
@@ -677,7 +681,7 @@ class LockTimeWidget(BalTimeEditWidget):
#label_text = "Locktime" #label_text = "Locktime"
# Hover tooltip for the delivery-time icon; mirrors the style of the fee # Hover tooltip for the delivery-time icon; mirrors the style of the fee
# icon tooltip ("..., click for more information") so the two are consistent. # icon tooltip ("..., click for more information") so the two are consistent.
tooltip_text = "Delivery Time, click for more information" tooltip_text = N_("Delivery Time, click for more information")
base_field = "locktime" base_field = "locktime"
def __init__(self, bal_window, parent, init_value=None): def __init__(self, bal_window, parent, init_value=None):
@@ -1088,9 +1092,12 @@ class WillSettingsWidget(QWidget):
basic_mode = self.bal_window.bal_plugin.is_basic_mode() basic_mode = self.bal_window.bal_plugin.is_basic_mode()
if basic_mode: if basic_mode:
# BASIC mode: use factory defaults (the hidden settings are # BASIC mode: use factory defaults (the hidden settings are
# ignored) and the fixed 30/10/1 offsets. # ignored) and the fixed 30/10/1 offsets. The defaults are in
raw_description = self.bal_window.bal_plugin.EVENT_DESCRIPTION.default # the GUI language (see BalConfig).
raw_summary = self.bal_window.bal_plugin.EVENT_SUMMARY.default raw_description = (
self.bal_window.bal_plugin.EVENT_DESCRIPTION.localized_default()
)
raw_summary = self.bal_window.bal_plugin.EVENT_SUMMARY.localized_default()
threshold = None threshold = None
num_reminders = 3 num_reminders = 3
else: else:
@@ -1120,6 +1127,7 @@ class WillSettingsWidget(QWidget):
version=self.bal_window.bal_plugin.version, version=self.bal_window.bal_plugin.version,
num_reminders=num_reminders, num_reminders=num_reminders,
threshold=threshold, threshold=threshold,
reminder_suffix=_("(reminder {idx}/{total})"),
) )
except Exception as e: except Exception as e:
_logger.error(f"failed to generate .ics: {e}") _logger.error(f"failed to generate .ics: {e}")
@@ -1199,7 +1207,7 @@ class PercAmountEdit(BTCAmountEdit):
painter.drawText( painter.drawText(
text_rect, text_rect,
int(Qt.AlignmentFlag.AlignRight | Qt.AlignmentFlag.AlignVCenter), int(Qt.AlignmentFlag.AlignRight | Qt.AlignmentFlag.AlignVCenter),
self.base_unit() + " or perc value", _("{} or perc value").format(self.base_unit()),
) )
@@ -1317,11 +1325,12 @@ class WillWidget(QWidget):
creation = str(BalTimestamp(self.will[w].time)) creation = str(BalTimestamp(self.will[w].time))
def qlabel(title, value): def qlabel(title, value):
label = "<b>" + _(str(title)) + f":</b>\t{str(value)}" # ``title`` is shown as it is: callers pass a translated
return QLabel(label) # label, or data (an heir name, a will-executor URL).
return QLabel("<b>{}:</b>\t{}".format(title, value))
detaillayout.addWidget(qlabel("Locktime", locktime)) detaillayout.addWidget(qlabel(_("Locktime"), locktime))
detaillayout.addWidget(qlabel("Creation Time", creation)) detaillayout.addWidget(qlabel(_("Creation Time"), creation))
try: try:
total_fees = ( total_fees = (
self.will[w].tx.input_value() - self.will[w].tx.output_value() self.will[w].tx.input_value() - self.will[w].tx.output_value()
@@ -1331,12 +1340,17 @@ class WillWidget(QWidget):
decoded_fees = total_fees decoded_fees = total_fees
fee_per_byte = round(total_fees / self.will[w].tx.estimated_size(), 3) fee_per_byte = round(total_fees / self.will[w].tx.estimated_size(), 3)
fees_str = str(decoded_fees) + " (" + str(fee_per_byte) + " sats/vbyte)" fees_str = str(decoded_fees) + " (" + str(fee_per_byte) + " sats/vbyte)"
detaillayout.addWidget(qlabel("Transaction fees:", fees_str)) detaillayout.addWidget(qlabel(_("Transaction fees"), fees_str))
# The saved status history is English: translate it for display.
detaillayout.addWidget( detaillayout.addWidget(
qlabel("Status:", self.will[w].status + signature_suffix(self.will[w])) qlabel(
_("Status"),
format_status_history(self.will[w].status)
+ signature_suffix(self.will[w]),
)
) )
detaillayout.addWidget(QLabel("")) detaillayout.addWidget(QLabel(""))
detaillayout.addWidget(QLabel("<b>Heirs:</b>")) detaillayout.addWidget(QLabel("<b>{}</b>".format(_("Heirs:"))))
for heir_name in self.will[w].heirs: for heir_name in self.will[w].heirs:
if 'w!ll3x3c"' in heir_name: if 'w!ll3x3c"' in heir_name:
continue continue
@@ -1363,7 +1377,9 @@ class WillWidget(QWidget):
) )
if self.will[w].we: if self.will[w].we:
detaillayout.addWidget(QLabel("")) detaillayout.addWidget(QLabel(""))
detaillayout.addWidget(QLabel(_("<b>Willexecutor:</b:"))) detaillayout.addWidget(
QLabel("<b>{}</b>".format(_("Willexecutor:")))
)
decoded_amount = Util.decode_amount( decoded_amount = Util.decode_amount(
self.will[w].we["base_fee"], self._bal_parent.decimal_point self.will[w].we["base_fee"], self._bal_parent.decimal_point
) )

View File

@@ -26,6 +26,7 @@ from ...core.checkalive import (
resolve_guard_threshold, resolve_guard_threshold,
) )
from .common import ( from .common import (
N_,
OP_RETURN_PREFIX, OP_RETURN_PREFIX,
AmountException, AmountException,
BalPlugin, BalPlugin,
@@ -282,12 +283,12 @@ class BalWindow:
def new_heir_dialog(self, heir_key=None): def new_heir_dialog(self, heir_key=None):
heir = self.heirs.get(heir_key) heir = self.heirs.get(heir_key)
title = "New heir" title = _("New heir")
if heir: if heir:
title = f"Edit: {heir_key}" title = _("Edit: {}").format(heir_key)
d = BalDialog( d = BalDialog(
self.window, self.bal_plugin, self.bal_plugin.get_window_title(_(title)) self.window, self.bal_plugin, self.bal_plugin.get_window_title(title)
) )
vbox = QVBoxLayout(d) vbox = QVBoxLayout(d)
@@ -828,12 +829,12 @@ class BalWindow:
except AmountException as e: except AmountException as e:
self.show_warning( self.show_warning(
_( _(
f"In the inheritance process, the entire wallet will always be fully emptied. Your settings require an adjustment of the amounts.{e}" "In the inheritance process, the entire wallet will always be fully emptied. Your settings require an adjustment of the amounts.{}"
) ).format(e)
) )
except WillExecutorFeeTooHighException as e: except WillExecutorFeeTooHighException as e:
self.show_error( self.show_error(
_(f"Will-executor fee too high: {e}") _("Will-executor fee too high: {}").format(e)
) )
return return
except CheckAliveError: except CheckAliveError:
@@ -919,27 +920,27 @@ class BalWindow:
_logger.info("{}:{}".format(type(e), e)) _logger.info("{}:{}".format(type(e), e))
message = False message = False
if isinstance(e, HeirChangeException): if isinstance(e, HeirChangeException):
message = "Heirs changed:" message = _("Heirs changed:")
elif isinstance(e, WillExecutorNotPresent): elif isinstance(e, WillExecutorNotPresent):
message = "Will-Executor not present:" message = _("Will-Executor not present:")
elif isinstance(e, WillexecutorChangeException): elif isinstance(e, WillexecutorChangeException):
message = "Will-Executor changed" message = _("Will-Executor changed")
elif isinstance(e, TxFeesChangedException): elif isinstance(e, TxFeesChangedException):
message = "Txfees are changed" message = _("Txfees are changed")
elif isinstance(e, HeirNotFoundException): elif isinstance(e, HeirNotFoundException):
# Task #01b: replace the misleading "Heir not found" text. # Task #01b: replace the misleading "Heir not found" text.
# This branch is most often hit because the delivery date # This branch is most often hit because the delivery date
# was anticipated, not because an heir is missing, so we use # was anticipated, not because an heir is missing, so we use
# a clear message that covers both the DATE and the HEIRS # a clear message that covers both the DATE and the HEIRS
# cases (kept consistent with dialogs.py / the CHECK window). # cases (kept consistent with dialogs.py / the CHECK window).
message = ( message = _(
"Found CHANGES to the DATE or the HEIRS,\n" "Found CHANGES to the DATE or the HEIRS,\n"
"a NEW WILL must be prepared." "a NEW WILL must be prepared."
) )
if message: if message:
self.show_message( self.show_message(
f"{_(message)}:\n {e}\n{_('will have to be built')}" "{}:\n {}\n{}".format(message, e, _("will have to be built"))
) )
_logger.info("build will") _logger.info("build will")
@@ -959,7 +960,7 @@ class BalWindow:
self.invalidate_will() self.invalidate_will()
except NotCompleteWillException as e: except NotCompleteWillException as e:
self.show_error( self.show_error(
"Error:{}\n {}".format( _("Error:{}\n {}").format(
str(e), str(e),
_("Please, check your heirs, locktime and threshold!"), _("Please, check your heirs, locktime and threshold!"),
) )
@@ -1019,7 +1020,9 @@ class BalWindow:
except SerializationError as e: except SerializationError as e:
_logger.error("unable to deserialize the transaction") _logger.error("unable to deserialize the transaction")
parent.show_critical( parent.show_critical(
_("Electrum was unable to deserialize the transaction:") + "\n" + str(e) "{}\n{}".format(
_("Electrum was unable to deserialize the transaction:"), e
)
) )
else: else:
# Electrum's own TxDialog: keep it in front of the main window. # Electrum's own TxDialog: keep it in front of the main window.
@@ -1087,8 +1090,8 @@ class BalWindow:
def get_message(): def get_message():
msg = "" msg = ""
if signed: if signed:
msg = _(f"signed: {signed}\n") msg = _("signed: {}").format(signed) + "\n"
return msg + _(f"signing: {tosign}") return msg + _("signing: {}").format(tosign)
if txids is not None: if txids is not None:
targets = [ targets = [
@@ -1610,7 +1613,7 @@ class BalWindow:
willexecutors = Willexecutors.get_willexecutor_transactions(willitems, force=force) willexecutors = Willexecutors.get_willexecutor_transactions(willitems, force=force)
def getMsg(willexecutors): def getMsg(willexecutors):
msg = "Broadcasting Transactions to Will-Executors:\n" msg = _("Broadcasting Transactions to Will-Executors:") + "\n"
for url in willexecutors: for url in willexecutors:
msg += f"{url}:\t{willexecutors[url]['broadcast_status']}\n" msg += f"{url}:\t{willexecutors[url]['broadcast_status']}\n"
return msg return msg
@@ -1664,8 +1667,8 @@ class BalWindow:
if self.waiting_dialog._stopping: if self.waiting_dialog._stopping:
return return
self.waiting_dialog.update( self.waiting_dialog.update(
"checking {} - {} : {}".format( _("checking {} - {} : {}").format(
willitems[wid].we["url"], wid, "Waiting" willitems[wid].we["url"], wid, _("Waiting")
) )
) )
w = willitems[wid] w = willitems[wid]
@@ -1673,7 +1676,7 @@ class BalWindow:
Willexecutors.check_transaction(wid, w.we["url"]) Willexecutors.check_transaction(wid, w.we["url"])
) )
self.waiting_dialog.update( self.waiting_dialog.update(
"checked {} - {} : {}".format( _("checked {} - {} : {}").format(
willitems[wid].we["url"], willitems[wid].we["url"],
wid, wid,
willitems[wid].get_status("CHECKED"), willitems[wid].get_status("CHECKED"),
@@ -2142,7 +2145,7 @@ class BalWindow:
# Simple, user-facing message shown when the download fails for any reason # Simple, user-facing message shown when the download fails for any reason
# (the technical cause is in the Electrum log). # (the technical cause is in the Electrum log).
DOWNLOAD_FAILED_MESSAGE = ( DOWNLOAD_FAILED_MESSAGE = N_(
"Could not download the will-executors list.\n\n" "Could not download the will-executors list.\n\n"
"This is usually caused by your internet connection or a firewall, " "This is usually caused by your internet connection or a firewall, "
"not by the plugin. Please check your connection (a VPN often helps) " "not by the plugin. Please check your connection (a VPN often helps) "
@@ -2152,7 +2155,7 @@ class BalWindow:
# Shown when the download fails while Electrum is connected through Tor: # Shown when the download fails while Electrum is connected through Tor:
# the most common cause is a slow Tor connection, so guide the user # the most common cause is a slow Tor connection, so guide the user
# accordingly instead of the generic message above. # accordingly instead of the generic message above.
DOWNLOAD_FAILED_TOR_MESSAGE = ( DOWNLOAD_FAILED_TOR_MESSAGE = N_(
"Could not download the will-executors list over Tor.\n\n" "Could not download the will-executors list over Tor.\n\n"
"Electrum is connected through Tor and the connection is taking too " "Electrum is connected through Tor and the connection is taking too "
"long. Your Tor connection may be slow. Please try again, or use a VPN " "long. Your Tor connection may be slow. Please try again, or use a VPN "
@@ -2225,27 +2228,27 @@ class BalWindow:
if err.url and err.reason == "empty response": if err.url and err.reason == "empty response":
# Server reached but returned no data for this chain. # Server reached but returned no data for this chain.
self.show_warning(_( self.show_warning(_(
f"No active will-executor servers found for the " "No active will-executor servers found for the "
f"{err.chain} network.\n\n" "{chain} network.\n\n"
f"The welist server at {err.url} responded but " "The welist server at {url} responded but "
f"returned no will-executors for this chain." "returned no will-executors for this chain."
)) ).format(chain=err.chain, url=err.url))
elif err.url: elif err.url:
# Advanced mode with a non-empty error (network issue). # Advanced mode with a non-empty error (network issue).
self.show_warning(_( self.show_warning(_(
f"Could not reach the configured welist server.\n\n" "Could not reach the configured welist server.\n\n"
f"Server: {err.url}\n" "Server: {url}\n"
f"Error: {err.reason}\n\n" "Error: {reason}\n\n"
f"Please verify the welist server URL in the plugin " "Please verify the welist server URL in the plugin "
f"settings." "settings."
)) ).format(url=err.url, reason=err.reason))
else: else:
# Basic mode: the server responded but has no data for this # Basic mode: the server responded but has no data for this
# chain. # chain.
self.show_warning(_( self.show_warning(_(
f"No active will-executor found for the " "No active will-executor found for the "
f"{err.chain} network." "{chain} network."
)) ).format(chain=err.chain))
else: else:
# Tor-aware: a generic failure/timeout while on Tor is most # Tor-aware: a generic failure/timeout while on Tor is most
# likely a slow Tor connection. # likely a slow Tor connection.

198
bal/i18n.py Normal file
View File

@@ -0,0 +1,198 @@
"""
bal.i18n
========
Translation layer of the BAL plugin (gettext domain ``bal``).
Why BAL has its own catalog
---------------------------
Electrum translates its interface with gettext (domain ``electrum``). Its
translators only see Electrum's own source code, so the texts of an external
(zip) plugin such as BAL are not in Electrum's catalog, and Electrum offers no
way to translate external plugins. BAL therefore ships its own compiled
catalogs inside the plugin: ``locale/<lang>/LC_MESSAGES/bal.mo``.
Lookup order
------------
:func:`_` returns the first translation found in:
1. **Electrum's catalog.** When Electrum already translates the exact same
English text, its translation wins. BAL then reads like Electrum and
follows Electrum's own translation fixes; if Electrum ever ships BAL as an
internal plugin, Electrum's translations take over with no change here
(owner's decision D7 in ``PLAN_I18N.md``).
2. **BAL's catalog**, for the texts that only BAL has.
3. **The English source text.**
Language
--------
Electrum picks the GUI language once, at start-up (``run_electrum``), and a
change needs a restart. :func:`init_from_config` repeats Electrum's choice
once, when the Qt plugin is created. BAL never detects the language by
itself: otherwise part of a window could be in one language and part in
another. The CLI never calls it, so the CLI stays in English, like Electrum's.
Rules for translatable texts
----------------------------
* Wrap literal English text only: ``_("Sign the will")``.
* Put the variable parts in ``{}`` and fill them *after* translating:
``_("{} heirs").format(count)``. Never build the text with an f-string or
``%`` inside ``_()``: it would change at run time and never match a catalog
entry (Ruff rules INT001-INT003 catch this).
* Texts evaluated at import time (class attributes, tables, constants) are
marked with :func:`N_` and passed to ``_()`` when they are displayed. Every
class body runs before :func:`init_from_config`, so a ``_()`` there would
always return English.
* Never translate text that is stored or compared (wallet labels, the saved
status history, config values used to recognise BAL transactions): stored
data must not depend on the UI language.
"""
import gettext
import io
import string
from typing import Optional
from electrum.i18n import _ as _electrum_gettext
from electrum.logging import get_logger
_logger = get_logger(__name__)
#: gettext domain of the BAL catalogs.
DOMAIN = "bal"
# BAL catalog of the current language, or None (English, CLI, or no usable
# catalog). Set by set_language().
_catalog: Optional[gettext.GNUTranslations] = None
# Source texts whose BAL translation was rejected: the warning is logged once,
# not at every repaint of the widget that shows the text.
_rejected: set = set()
_formatter = string.Formatter()
def keeps_format_fields(msg: str, translation: str) -> bool:
"""Tell whether ``translation`` keeps the ``{}`` fields of ``msg``.
A translation that adds, drops or renames a replacement field would make
the ``.format()`` call that follows raise, or put a value in the wrong
place, so such a translation must not be used.
The rules are copied from Electrum's
``_ensure_translation_keeps_format_string_syntax_similar``
(``electrum/i18n.py``, MIT licence, Copyright (C) The Electrum developers)
rather than importing that private function, which may change without
notice. Keep them identical, so a BAL translation is accepted or rejected
exactly like an Electrum one. The only addition: a malformed source text
returns False here instead of raising.
"""
try:
# Tuples of (literal_text, field_name, format_spec, conversion).
parsed1 = list(_formatter.parse(msg))
parsed2 = list(_formatter.parse(translation))
except ValueError: # malformed format string
return False
if len(parsed1) != len(parsed2):
return False
# The set of field names must not change (re-ordering them is allowed).
return {t[1] for t in parsed1} == {t[1] for t in parsed2}
def _(msg: str) -> str:
"""Return ``msg`` translated into the GUI language.
See the module docstring for the lookup order. ``_("")`` returns ``""``:
for gettext the empty text is the key of the catalog header.
"""
if msg == "":
return ""
translation = _electrum_gettext(msg)
if translation != msg or _catalog is None:
# Electrum's translation wins (Electrum has already checked its {}
# fields); without a BAL catalog there is nothing else to look up.
return translation
translation = _catalog.gettext(msg)
if translation == msg or keeps_format_fields(msg, translation):
return translation
if msg not in _rejected:
_rejected.add(msg)
_logger.warning(
f"rejected BAL translation, replacement fields differ: "
f"{msg!r} -> {translation!r}"
)
return msg
def N_(msg: str) -> str: # noqa: N802 (the conventional gettext marker name)
"""Mark ``msg`` as translatable and return it unchanged.
Used where a text is defined at import time (class attributes, tables,
constants). Extraction tools (Babel, xgettext) collect ``N_("...")`` like
``_("...")``; the code passes the value to ``_()`` when it shows it.
"""
return msg
def set_language(plugin, lang: Optional[str]) -> None:
"""Load the BAL catalog of ``lang`` (for example ``"it_IT"``), or none.
``None``, ``""`` and English (``"en_*"``) load no catalog, so the English
source texts are shown, as Electrum does for ``en_*``.
The catalog is read with ``plugin.read_file()``, the Electrum API BAL uses
for its icons: it works both from the installed zip and from a development
checkout. ``gettext.translation(localedir=...)`` is not used because,
pointed inside a zip, it silently finds nothing.
If ``locale/<lang>/`` has no catalog, the plain language code is tried
(``locale/it/`` for ``it_IT``). A missing or unreadable catalog is logged
and BAL stays in English: a translation problem must never stop the
plugin.
"""
global _catalog
_catalog = None
_rejected.clear()
if not isinstance(lang, str) or not lang or lang.startswith("en_"):
return
codes = [lang]
if "_" in lang:
codes.append(lang.split("_", 1)[0])
for code in codes:
path = "locale/{}/LC_MESSAGES/{}.mo".format(code, DOMAIN)
try:
data = plugin.read_file(path)
except Exception:
# Not shipped for this code (a zip raises KeyError, a development
# folder raises OSError): try the next code.
continue
try:
_catalog = gettext.GNUTranslations(io.BytesIO(data))
except Exception as e:
_logger.info(f"unreadable BAL catalog {path}, using English: {e!r}")
return
_logger.info(f"BAL catalog loaded: {path}")
return
_logger.info(f"no BAL catalog for {lang!r}, using English")
def init_from_config(plugin, config) -> None:
"""Load the BAL catalog of the language Electrum's Qt GUI is using.
Repeats Electrum's own choice in ``run_electrum``: the ``language``
setting (Preferences > Language) or, when it is empty, the system language
if Electrum supports it, else English. Called once, from the Qt plugin's
``__init__``. Never raises.
"""
try:
lang = config.LOCALIZATION_LANGUAGE
if not lang:
from electrum.gui.default_lang import get_default_language
lang = get_default_language(gui_name="qt")
except Exception as e:
# Electrum also falls back to English when it cannot read the
# system language.
_logger.info(f"could not read the GUI language, using English: {e!r}")
lang = None
set_language(plugin, lang)

1918
bal/locale/bal.pot Normal file

File diff suppressed because it is too large Load Diff

File diff suppressed because it is too large Load Diff

View File

@@ -9,7 +9,12 @@ Electrum loads external plugins from a ``.zip`` using Python's ``zipimport``.
* uses standard DEFLATE compression (well supported by ``zipimport``); * uses standard DEFLATE compression (well supported by ``zipimport``);
* emits entries in a deterministic, sorted order so the archive is * emits entries in a deterministic, sorted order so the archive is
reproducible (stable SHA-256); reproducible (stable SHA-256);
* skips ``__pycache__`` directories and compiled ``*.pyc``/``*.pyo`` files. * skips ``__pycache__`` directories and compiled ``*.pyc``/``*.pyo`` files;
* compiles each translation catalog ``bal/locale/<lang>/LC_MESSAGES/bal.po``
into ``bal.mo`` inside the archive (the ``.mo`` files are not kept in
git, and the ``.po``/``.pot`` sources are not shipped). This needs Babel
(``pip install babel``); without it the build stops, so a release can
never ship without its translations by mistake.
The archive keeps the top-level ``bal/`` directory so that the package is The archive keeps the top-level ``bal/`` directory so that the package is
importable as ``bal`` (and Electrum derives ``dirname='bal'`` from the path of importable as ``bal`` (and Electrum derives ``dirname='bal'`` from the path of
@@ -23,14 +28,36 @@ Prints the resulting size and SHA-256 so the download can be integrity-checked.
""" """
import hashlib import hashlib
import io
import os import os
import sys import sys
import time
import zipfile import zipfile
SRC_ROOT = "bal" SRC_ROOT = "bal"
DEFAULT_OUT = "bal-electrum-plugin.zip" DEFAULT_OUT = "bal-electrum-plugin.zip"
def compile_catalog(po_path: str) -> bytes:
"""Return the compiled ``.mo`` bytes of the gettext catalog ``po_path``.
Fuzzy (unreviewed) entries are left out, as ``msgfmt`` does.
"""
try:
from babel.messages.mofile import write_mo
from babel.messages.pofile import read_po
except ImportError:
raise SystemExit(
"ERROR: Babel is needed to compile the translations "
"(pip install babel)"
) from None
with open(po_path, "rb") as f:
catalog = read_po(f)
buf = io.BytesIO()
write_mo(buf, catalog, use_fuzzy=False)
return buf.getvalue()
def build(out_path: str) -> None: def build(out_path: str) -> None:
if os.path.exists(out_path): if os.path.exists(out_path):
os.remove(out_path) os.remove(out_path)
@@ -40,17 +67,34 @@ def build(out_path: str) -> None:
# prune cache dirs in place so os.walk does not descend into them # prune cache dirs in place so os.walk does not descend into them
dirnames[:] = [d for d in dirnames if d != "__pycache__"] dirnames[:] = [d for d in dirnames if d != "__pycache__"]
for fn in filenames: for fn in filenames:
if fn.endswith((".pyc", ".pyo")): # .mo files are rebuilt from the .po sources below; the .po/.pot
# sources themselves are not shipped.
if fn.endswith((".pyc", ".pyo", ".po", ".pot", ".mo")):
continue continue
files.append(os.path.join(dirpath, fn)) files.append(os.path.join(dirpath, fn))
catalogs = {} # archive path of the .mo -> source .po
for dirpath, _dirnames, filenames in os.walk(os.path.join(SRC_ROOT, "locale")):
for fn in filenames:
if fn.endswith(".po"):
po = os.path.join(dirpath, fn)
catalogs[po[: -len(".po")] + ".mo"] = po
files.sort() files.sort()
with zipfile.ZipFile( with zipfile.ZipFile(
out_path, "w", compression=zipfile.ZIP_DEFLATED, compresslevel=6 out_path, "w", compression=zipfile.ZIP_DEFLATED, compresslevel=6
) as z: ) as z:
for f in files: entries = [(f, None) for f in files] + [
(mo, po) for mo, po in catalogs.items()
]
for f, po in sorted(entries):
arc = f.replace(os.sep, "/") # forward slashes inside the archive arc = f.replace(os.sep, "/") # forward slashes inside the archive
z.write(f, arc) if po is None:
z.write(f, arc)
else:
# Same timestamp rule as z.write(): the source file's mtime.
info = zipfile.ZipInfo(arc, time.localtime(os.path.getmtime(po))[:6])
info.compress_type = zipfile.ZIP_DEFLATED
z.writestr(info, compile_catalog(po))
# Integrity + summary # Integrity + summary
with zipfile.ZipFile(out_path) as z: with zipfile.ZipFile(out_path) as z:
@@ -63,7 +107,8 @@ def build(out_path: str) -> None:
data = open(out_path, "rb").read() data = open(out_path, "rb").read()
print(f"built : {out_path}") print(f"built : {out_path}")
print(f"files : {len(files)}") print(f"files : {len(files) + len(catalogs)}")
print(f"langs : {', '.join(sorted(os.path.basename(os.path.dirname(os.path.dirname(m))) for m in catalogs)) or '-'}")
print(f"size : {len(data)} bytes") print(f"size : {len(data)} bytes")
print(f"sha256: {hashlib.sha256(data).hexdigest()}") print(f"sha256: {hashlib.sha256(data).hexdigest()}")

View File

@@ -3,7 +3,7 @@ line-length = 88
target-version = "py312" target-version = "py312"
[tool.ruff.lint] [tool.ruff.lint]
select =["E", "W", "F", "I", "N", "B"] select =["E", "W", "F", "I", "N", "B", "INT"] # INT: gettext rules (see bal/i18n.py)
ignore = ["E501"] ignore = ["E501"]
[tool.ruff.lint.pep8-naming] [tool.ruff.lint.pep8-naming]

309
tests/test_i18n.py Normal file
View File

@@ -0,0 +1,309 @@
"""Tests for bal/i18n.py, BAL's translation layer (PLAN_I18N.md, phase 1).
The BAL catalogs are built in memory (see ``_mo_bytes``), so these tests need
no compiled .mo file and no Babel. Electrum's translator is replaced by a
small dictionary, so the tests do not depend on Electrum's own catalogs.
Run standalone (``python3 tests/test_i18n.py``) or with pytest.
"""
import array
import os
import struct
import sys
from contextlib import contextmanager
from types import SimpleNamespace
sys.path.insert(0, os.path.join(os.path.dirname(__file__), os.pardir))
from bal import i18n # noqa: E402
IT_MO = "locale/it_IT/LC_MESSAGES/bal.mo"
def _mo_bytes(messages):
"""Return a GNU .mo catalog (UTF-8) holding ``messages`` {msgid: msgstr}.
Same layout as CPython's Tools/i18n/msgfmt.py: header, the sorted msgid
and msgstr index tables, then the NUL-terminated strings.
"""
entries = {"": "Content-Type: text/plain; charset=UTF-8\n"}
entries.update(messages)
keys = sorted(entries)
ids = strs = b""
offsets = []
for key in keys:
msgid, msgstr = key.encode("utf-8"), entries[key].encode("utf-8")
offsets.append((len(ids), len(msgid), len(strs), len(msgstr)))
ids += msgid + b"\0"
strs += msgstr + b"\0"
keystart = 7 * 4 + 16 * len(keys)
valuestart = keystart + len(ids)
koffsets, voffsets = [], []
for o1, l1, o2, l2 in offsets:
koffsets += [l1, o1 + keystart]
voffsets += [l2, o2 + valuestart]
header = struct.pack(
"Iiiiiii", 0x950412DE, 0, len(keys), 7 * 4, 7 * 4 + len(keys) * 8, 0, 0
)
return header + array.array("i", koffsets + voffsets).tobytes() + ids + strs
class FakePlugin:
"""Stands in for Electrum's BasePlugin: serves read_file() from a dict."""
def __init__(self, files=None):
self.files = files or {}
self.requested = []
def read_file(self, filename):
self.requested.append(filename)
if filename not in self.files:
raise KeyError(filename) # what a missing entry in the zip raises
return self.files[filename]
@contextmanager
def _i18n_state(electrum=None, files=None, lang=None):
"""Fake Electrum's translations, load a fake BAL catalog, restore after.
Restoring matters: bal.i18n keeps module-level state, shared with every
other test of the same pytest run.
"""
saved = (i18n._electrum_gettext, i18n._catalog)
table = electrum or {}
i18n._electrum_gettext = lambda msg: table.get(msg, msg)
plugin = FakePlugin(files)
try:
i18n.set_language(plugin, lang)
yield plugin
finally:
i18n._electrum_gettext, i18n._catalog = saved
i18n._rejected.clear()
def test_empty_string_is_never_translated():
# For gettext "" is the key of the catalog header.
with _i18n_state(files={IT_MO: _mo_bytes({})}, lang="it_IT"):
assert i18n._catalog is not None
assert i18n._("") == ""
def test_electrum_translation_wins_over_bal_catalog():
catalog = _mo_bytes({"Cancel": "Cancella", "Heirs": "Eredi"})
with _i18n_state(
electrum={"Cancel": "Annulla"}, files={IT_MO: catalog}, lang="it_IT"
):
assert i18n._("Cancel") == "Annulla" # Electrum has it: Electrum wins
assert i18n._("Heirs") == "Eredi" # only BAL has it
def test_english_source_when_nobody_translates():
with _i18n_state(files={IT_MO: _mo_bytes({"Heirs": "Eredi"})}, lang="it_IT"):
assert i18n._("Not in any catalog") == "Not in any catalog"
def test_translation_with_different_fields_is_rejected():
catalog = _mo_bytes(
{
"{} heirs": "eredi", # field dropped: rejected
"Fee: {}": "Commissione: {}",
"{0} of {1}": "{1} di {0}", # re-ordered: allowed
"Hello {name}": "Ciao {nome}", # field renamed: rejected
}
)
with _i18n_state(files={IT_MO: catalog}, lang="it_IT"):
assert i18n._("{} heirs") == "{} heirs"
assert i18n._("Fee: {}") == "Commissione: {}"
assert i18n._("{0} of {1}") == "{1} di {0}"
assert i18n._("Hello {name}") == "Hello {name}"
def test_keeps_format_fields():
assert i18n.keeps_format_fields("Amount: {}", "Importo: {}")
assert not i18n.keeps_format_fields("Amount: {}", "Importo")
assert not i18n.keeps_format_fields("Amount: {}", "Importo: {} {}")
assert not i18n.keeps_format_fields("Amount: {}", "Importo: {") # malformed
assert i18n.keeps_format_fields("$wallet_name", "$wallet_name")
def test_english_loads_no_catalog():
with _i18n_state(files={IT_MO: _mo_bytes({"Heirs": "Eredi"})}, lang="en_UK") as p:
assert i18n._catalog is None
assert p.requested == []
assert i18n._("Heirs") == "Heirs"
def test_no_language_loads_no_catalog():
for lang in (None, ""):
with _i18n_state(files={IT_MO: _mo_bytes({"Heirs": "Eredi"})}, lang=lang):
assert i18n._catalog is None
def test_missing_catalog_falls_back_to_english():
with _i18n_state(files={}, lang="it_IT") as plugin:
assert i18n._catalog is None
assert plugin.requested == [IT_MO, "locale/it/LC_MESSAGES/bal.mo"]
assert i18n._("Heirs") == "Heirs"
def test_broken_catalog_falls_back_to_english():
with _i18n_state(files={IT_MO: b"this is not a catalog"}, lang="it_IT"):
assert i18n._catalog is None
assert i18n._("Heirs") == "Heirs"
def test_language_code_without_country_is_tried():
files = {"locale/it/LC_MESSAGES/bal.mo": _mo_bytes({"Heirs": "Eredi"})}
with _i18n_state(files=files, lang="it_IT"):
assert i18n._("Heirs") == "Eredi"
def test_n_marks_without_translating():
with _i18n_state(files={IT_MO: _mo_bytes({"Heirs": "Eredi"})}, lang="it_IT"):
assert i18n.N_("Heirs") == "Heirs"
assert i18n._(i18n.N_("Heirs")) == "Eredi"
def test_init_from_config_uses_electrum_language_setting():
config = SimpleNamespace(LOCALIZATION_LANGUAGE="it_IT")
plugin = FakePlugin({IT_MO: _mo_bytes({"Heirs": "Eredi"})})
with _i18n_state():
i18n.init_from_config(plugin, config)
assert i18n._("Heirs") == "Eredi"
def test_init_from_config_without_setting_uses_system_language():
import electrum.gui.default_lang as default_lang
saved = default_lang.get_default_language
default_lang.get_default_language = lambda gui_name=None: "it_IT"
config = SimpleNamespace(LOCALIZATION_LANGUAGE="")
plugin = FakePlugin({IT_MO: _mo_bytes({"Heirs": "Eredi"})})
try:
with _i18n_state():
i18n.init_from_config(plugin, config)
assert i18n._("Heirs") == "Eredi"
finally:
default_lang.get_default_language = saved
def test_init_from_config_never_raises():
plugin = FakePlugin({IT_MO: _mo_bytes({"Heirs": "Eredi"})})
with _i18n_state():
i18n.init_from_config(plugin, object()) # config without the setting
assert i18n._catalog is None
# --- Stored data stays language-neutral (PLAN_I18N.md, phase 2) -------------
def test_status_history_is_stored_in_english():
from bal.core.will import WillItem
catalog = _mo_bytes({"Signed": "Firmato", "Valid": "Valida"})
with _i18n_state(files={IT_MO: catalog}, lang="it_IT"):
# A bare item: set_status() only needs its status fields.
item = WillItem.__new__(WillItem)
item.status = ""
item.STATUS = WillItem.copy_status_table(WillItem.STATUS_DEFAULT)
item.set_status("COMPLETE", True)
item.set_status("VALID", False)
assert item.status == ".Signed.NOT Valid"
def test_status_history_is_translated_for_display():
from bal.core.will import format_status_history
catalog = _mo_bytes(
{
"Signed": "Firmato",
"Valid": "Valida",
"NOT {}": "NON {}",
"New": "Nuovo",
"Replaced": "Sostituita",
}
)
with _i18n_state(files={IT_MO: catalog}, lang="it_IT"):
assert format_status_history(".Signed.NOT Valid") == ".Firmato.NON Valida"
# A real history saved by an older version (tests/samanta7), which
# stored some labels already translated: known English labels are
# translated, the other tokens are kept as they are.
assert (
format_status_history("New.Firmato.Pushed.Checked.Replaced")
== "Nuovo.Firmato.Pushed.Checked.Sostituita"
)
assert format_status_history(".SignedERROR!!!") == ".FirmatoERROR!!!"
with _i18n_state(): # English GUI: shown exactly as stored
assert format_status_history("New.Firmato.Pushed") == "New.Firmato.Pushed"
class _FakeConfig(dict):
"""Minimal stand-in for Electrum's SimpleConfig (get / set_key)."""
def get(self, key, default=None):
return dict.get(self, key, default)
def set_key(self, key, value, save=True):
self[key] = value
def test_translatable_config_default_follows_language():
from bal.core.plugin_base import BalConfig
config = _FakeConfig()
summary = BalConfig(config, "summary", "Will of $wallet_name", translatable=True)
plain = BalConfig(config, "label", "BAL label")
catalog = _mo_bytes(
{"Will of $wallet_name": "Testamento di $wallet_name", "BAL label": "X"}
)
with _i18n_state(files={IT_MO: catalog}, lang="it_IT"):
assert summary.get() == "Testamento di $wallet_name" # nothing stored
assert summary.localized_default() == "Testamento di $wallet_name"
summary.set("Testamento di $wallet_name") # e.g. the reset button
assert config["summary"] == "Will of $wallet_name" # stored in English
assert summary.get() == "Testamento di $wallet_name"
summary.set("My own text") # the user's text is kept as it is
assert summary.get() == "My own text"
assert plain.get() == "BAL label" # not translatable: never translated
with _i18n_state():
summary.set("Will of $wallet_name")
assert summary.get() == "Will of $wallet_name"
def test_calendar_reminder_suffix_is_translatable():
from datetime import datetime, timedelta
from bal.core.reminders import build_ics_reminders
now = datetime(2026, 1, 1)
kwargs = dict(
locktime=now + timedelta(days=400), basic_mode=True, description="d",
summary="s", wallet_name="w", heirs_details="", version="0", now=now,
)
assert "s (reminder 1/" in build_ics_reminders(**kwargs) # CLI default
ics = build_ics_reminders(reminder_suffix="(promemoria {idx}/{total})", **kwargs)
assert "s (promemoria 1/" in ics
def test_qr_preset_labels_match_chunk_presets():
# The labels are marked for translation in common.py because
# qrtransfer.py must stay free of Electrum imports (Android copy).
from bal.core.qrtransfer import CHUNK_PRESETS
from bal.gui.qt.common import QR_PRESET_LABELS
assert tuple(label for label, _budget in CHUNK_PRESETS) == QR_PRESET_LABELS
def test_real_translator_is_electrums():
# Outside the fakes above, BAL asks Electrum's real translator first.
from electrum.i18n import _ as electrum_gettext
assert i18n._electrum_gettext is electrum_gettext
if __name__ == "__main__":
tests = [v for k, v in sorted(globals().items()) if k.startswith("test_")]
for test in tests:
test()
print(f"[OK] All {len(tests)} i18n tests passed")

135
tests/test_translations.py Normal file
View File

@@ -0,0 +1,135 @@
"""Safety checks on BAL's translation catalogs (PLAN_I18N.md, section 4.4).
Runs on every ``bal/locale/<lang>/LC_MESSAGES/bal.po`` (the sources that
build_zip.py compiles into the zip). A translation is shown to the user as
if BAL wrote it, so a wrong or malicious one must fail here, before a zip is
built:
* the catalog must parse and compile;
* the ``{}`` replacement fields must match the English text (the same rule
bal.i18n applies at run time), and so must the ``$tokens`` of the calendar
texts (``$wallet_name``, ``$heirs_complete``), which Electrum does not check;
* no Bitcoin address, e-mail address, URL or long letters-and-digits word may
appear in a translation unless the English text has the same one: the
patterns are copied from Electrum's ``electrum-locale/update.py`` (MIT
licence, Copyright (C) The Electrum developers), which rejects translations
that try to slip in an address or a link.
Run standalone (``python3 tests/test_translations.py``, prints a per-language
summary) or with pytest. Needs Babel, like build_zip.py.
"""
import io
import os
import re
import sys
from pathlib import Path
sys.path.insert(0, os.path.join(os.path.dirname(__file__), os.pardir))
from babel.messages.mofile import write_mo # noqa: E402
from babel.messages.pofile import read_po # noqa: E402
from bal.i18n import keeps_format_fields # noqa: E402
LOCALE_DIR = Path(__file__).resolve().parent.parent / "bal" / "locale"
# From electrum-locale/update.py (see the module docstring).
SUSPICIOUS = {
"Bitcoin address": re.compile("([13]|bc1)[a-zA-Z0-9]{30,}"),
"e-mail address": re.compile(r"[\w.+-]+@[\w-]+\.[\w.-]+"),
"URL": re.compile(r"\S+\.\S*\w+\S*/\S+"),
"URL scheme": re.compile(r"http(s){0,1}://"),
"letters-and-digits word": re.compile(
r"(?a)(?=\w{16,})((\w*[a-zA-Z]\w*[0-9]\w*)|(\w*[0-9]\w*[a-zA-Z]\w*))"
),
}
TOKEN = re.compile(r"\$\w+")
def _catalogs():
return sorted(LOCALE_DIR.glob("*/LC_MESSAGES/bal.po"))
def _messages(po_path):
"""Yield the translated, non-fuzzy (msgid, msgstr) pairs of a catalog."""
with open(po_path, "rb") as f:
catalog = read_po(f)
for m in catalog:
if m.id and isinstance(m.id, str) and m.string and not m.fuzzy:
yield m.id, m.string
def check_catalog(po_path):
"""Return a list of problems found in one catalog (empty = fine)."""
problems = []
for msgid, msgstr in _messages(po_path):
if not keeps_format_fields(msgid, msgstr):
problems.append("{} fields differ: {!r}".format("{}", msgid))
if sorted(TOKEN.findall(msgid)) != sorted(TOKEN.findall(msgstr)):
problems.append("$tokens differ: {!r}".format(msgid))
for name, regex in SUSPICIOUS.items():
for match in regex.finditer(msgstr):
if match.group(0) not in msgid:
problems.append(
"{} {!r} not in the English text: {!r}".format(
name, match.group(0), msgid
)
)
return problems
def summary(po_path):
"""Return (translated, untranslated, fuzzy) counts of a catalog."""
with open(po_path, "rb") as f:
catalog = read_po(f)
msgs = [m for m in catalog if m.id]
fuzzy = sum(1 for m in msgs if m.fuzzy)
translated = sum(1 for m in msgs if m.string and not m.fuzzy)
return translated, len(msgs) - translated - fuzzy, fuzzy
def test_there_is_an_italian_catalog():
assert LOCALE_DIR / "it_IT" / "LC_MESSAGES" / "bal.po" in _catalogs()
def test_catalogs_compile():
for po in _catalogs():
with open(po, "rb") as f:
catalog = read_po(f)
buf = io.BytesIO()
write_mo(buf, catalog)
assert buf.getvalue(), po
def test_translations_are_safe():
problems = [
"{}: {}".format(po.parent.parent.name, p)
for po in _catalogs()
for p in check_catalog(po)
]
assert not problems, "\n".join(problems)
def test_suspicious_patterns_are_detected():
# A translation that adds an address or a link must be caught.
regexes = SUSPICIOUS.values()
assert any(r.search("invia a bc1qar0srrr7xfkvy5l643lydnw9re59gtzzwf5mdq") for r in regexes)
assert any(r.search("scarica da https://example.com") for r in regexes)
assert any(r.search("scrivi a truffa@example.com") for r in regexes)
assert not any(r.search("Firma il testamento") for r in regexes)
if __name__ == "__main__":
test_there_is_an_italian_catalog()
test_catalogs_compile()
test_suspicious_patterns_are_detected()
for po in _catalogs():
translated, untranslated, fuzzy = summary(po)
print(
"{}: {} translated, {} untranslated, {} fuzzy".format(
po.parent.parent.name, translated, untranslated, fuzzy
)
)
test_translations_are_safe()
print("[OK] translation catalogs are safe")