diff --git a/CLAUDE.md b/CLAUDE.md index 943a817..716c63b 100644 --- a/CLAUDE.md +++ b/CLAUDE.md @@ -15,7 +15,8 @@ Works (texts) live in their own repos, e.g. `../Faust-VN`. - `uv sync` — install. `uv run pytest` — tests. `uv run ruff check . && uv run ruff format --check .` — lint. - `uv run vnpipe --help` — CLI (`--work` defaults to the current directory). Stages: `fetch`, `parse`, `annotate {run,status,prompt,merge}`, `assets {...}`, `voice {fetch,asr,build,cut}` - (`docs/voice.md`), `renpy [--with-test]` (default output `/vn`). + (`docs/voice.md`), `translate {fetch,build,status}` (`docs/translations.md`), + `renpy [--with-test]` (default output `/vn`). - `scripts/asr.py` runs on a GPU host (faster-whisper), never as a vnpipe dependency. - Ren'Py SDK: set `RENPY_SDK` to the unpacked SDK directory (tests that need it are skipped otherwise; fallback `tools/renpy-sdk`). See `docs/running.md`. diff --git a/docs/pipeline.md b/docs/pipeline.md index 54b7e89..591a6ff 100644 --- a/docs/pipeline.md +++ b/docs/pipeline.md @@ -29,6 +29,7 @@ redone unless their input changes. | Annotation | `annotate run/status/prompt/merge` ([details](annotation.md)) | `annotate.py` | | Assets | `assets prompt/import/process/check/status/placeholders/sheet/migrate` | `assets.py` | | Voice (optional) | `voice fetch/asr/build/cut` ([details](voice.md)) | `voice.py`, `voice_align.py` | +| Translations (optional) | `translate fetch/build/status` ([details](translations.md)) | `translate.py`, `translate_align.py`, `renpy_tl.py` | | Ren'Py | `renpy [--from-parsed] [--with-test] [--out DIR]` | `renpy_gen.py` | `--work DIR` (before the subcommand) selects the work root; default is the current directory. diff --git a/docs/running.md b/docs/running.md index d898830..f23896d 100644 --- a/docs/running.md +++ b/docs/running.md @@ -89,6 +89,18 @@ tweaks, `@@TOKEN@@` placeholders for title/build name/about text/menu background --accent '#c9a25b' --boring '#14110e' --template "$RENPY_SDK/gui" --start ``` +Since then the menus were redesigned around the scene title cards (gold rule with a diamond, +size-76 titles): a book-title main menu, a navigation column with the work's title, framed +panels, and a save/load register (one row per slot with thumbnail, scene title, the line on +screen and the date; Roman-numbered pages; autosave and quick save pages only when loading; +a delete button per slot). The scene and line come from `config.save_json_callbacks` +(`menus.rpy`). The ornament images (`gui/vn/*.png`, check/radio marks, bars) are drawn by +`gui_extra_images()` in `renpy_gen.py`. `tl/spanish/` holds the Spanish UI strings: Ren'Py's +SDK translation (corrected and completed) plus every `_()` string of the screens; a test +fails when a screen string has no translation. To check a project for untranslated strings, +run `renpy.sh translate spanish` on a throw-away copy and look for new `old` +entries after the "TODO: Translation updated" line. + These files are part of Ren'Py (MIT licence, Tom Rothamel and contributors). The font `game/fonts/RobotoSlab-*.ttf` is Roboto Slab (Apache 2.0), taken from the SDK documentation assets. @@ -106,7 +118,8 @@ The expected result is a statistics block with no warnings above it. Lint does not catch runtime errors (missing GUI images, display bugs). `--with-test` also writes `game/e2e_test.rpy`, a Ren'Py `testcase` that clicks "Start", advances through the whole game up to the final card (`label the_end`) and back to the main menu (then opens and -closes the Scenes and Credits screens), failing on any +closes the Scenes, Credits, Load, Preferences and About screens; a save made at the first +scene must carry its title), failing on any exception (`traceback.txt`). Use a throw-away output directory so the test file never ends up in `vn/` or in a build: diff --git a/docs/translations.md b/docs/translations.md new file mode 100644 index 0000000..7d134a4 --- /dev/null +++ b/docs/translations.md @@ -0,0 +1,114 @@ +# Translations + +A work can be played in other languages besides its own, from a **published public-domain +translation** of the same text. vnpipe never translates or rewrites the play: every line shown +in another language is copied verbatim from that translation (a Project Gutenberg ebook). +Only the game's own interface strings (menu labels, scene subtitles, credits) are written in +`work.toml` per language. + +``` +translation ebook ──translate fetch──▶ data/raw/.txt (gitignored) + ──translate build──▶ data/translations/.json (committed) + ──renpy──▶ game/tl//script.rpy, strings.rpy + game/languages.rpy (the choice: Preferences, first launch) +``` + +## Mapping (`translate build`) + +The ebook (Gutenberg header, footer and licence removed) is cut at each scene's heading and +parsed into **units**: speeches (split at stage directions) and stage directions. The game +side has the same units: each direction line and each run of lines with the same speaker and +speech. The two sequences are aligned (dynamic programming): a speech pairs only with a speech +of the same speaker (two ids of `ensembles` may pair, at a penalty), a direction with a +direction; similar sizes score higher. + +Translators split and merge speeches differently, so the units are **grouped**: source units +left between two pairs are shown with the first unpaired game unit of the stretch (else with +the previous pair). Every source unit is shown exactly once, in the translation's order, each +with its own speaker. A game unit with no text of its own shows nothing in that language. + +Parsing rules worth knowing (`translate_align.parse_units`): + +- an upper-case line followed by a blank line is a speaker label, mapped by `speakers`; an + indented one only for a known speaker (a chorus inside a song); +- `(...)` blocks, `[Exit` lines (also at the end of a verse line) and italic paragraphs are + directions; a note under a label becomes `LABEL (note)`; a parenthesis inside a stanza + ending in punctuation (`(These elements),—`) is verse; +- before the first speech, place and cast lines form one **setting** unit, used only where an + override puts it; footnote numbers at line ends and illustration markers are dropped. + +`translate status` prints coverage per scene (worst first): `paired` and `carry` units show +their own text, `grouped` ones show nothing; `suspects` are groups whose size ratio is far from +the scene's. `translate status --scene ID` prints the alignment side by side. Fix a wrong +pairing with an override that quotes the translation verbatim (see below); the build fails if +the quote does not start exactly one unit. A scene is `complete` when its first unit has text. +The JSON stores hashes of `data/annotated.json` and of the mapping keys of +`[translations.]` (sections, speakers, overrides, ...); `vnpipe renpy` refuses a +mapping built from other ones (names and strings need no rebuild). + +## Ren'Py output + +Every say statement carries an explicit `id` (its first line id), and each translation writes +`translate :` for all of them: the first box of a game unit with text shows the +translated units (split into boxes like the original: stanzas, at most 4 lines in ADV and 8 in +NVL, long prose paragraphs cut at sentence ends), every other box is `pass`. The voice clips +are shared: each clip of the group, in order, starts on the next translated say box of the same +speaker (or, if none is left, on the next say box), and `voice sustain` carries it over that +speaker's next boxes and directions. Every clip is placed; a group with more clips than +translated say boxes is an error. + +Names, title cards, the scene list, About and the art-style labels go to `translate +strings:`; equal original strings that translate differently get `{#scene}` tags. The credits +are a list per language (`vn_credits_tl`). `vnpipe renpy` fails if the JSON is missing or was +built from another `data/annotated.json`. + +The language choice (`game/languages.rpy`): the work's own language is the default; the player +picks another in Preferences ("Language") or in the first-launch picker. The choice is stored +in `persistent.vn_language` and copied to `config.language`, so a stale preference never +switches the language and loading a save keeps it. `RENPY_LANGUAGE=` forces one +(e.g. for the playthrough test). + +## Configuration + +```toml +[translations.en] +language = "english" # Ren'Py language name +label = "English" # shown in the language choice +text_url = "https://www.gutenberg.org/cache/epub/NNN/pgNNN.txt" +text_file = "data/raw/pgNNN.txt" # cache (gitignored) +gutenberg_id = NNN # credited as the source +title = "Faust" # [work] fields in this language +subtitle = "First Part" +translator = "..." +end_text = "To be continued…" +voice_credits = ["..."] # [voice].credits in this language +ignore_lines = ["..."] # exact lines of the ebook that are not play text +ensembles = ["chorus"] # default: [voice].ensembles + +[translations.en.speakers] # speaker label as printed -> cast id +"MEPHISTOPHELES" = "mephisto" + +[translations.en.scene_speakers.] # per-scene overrides of `speakers`; a list +"THE FIRST" = ["artisans", "servant_girls"] # gives one cast id per occurrence, in order + +[translations.en.direction_labels] # labels printed like a speaker but read as a direction; +"FAUST AND WAGNER" = "" # the text after is spoken by this cast id ("" = none) + +[translations.en.names] # cast id -> name (every named cast member) +mephisto = "Mephistopheles" + +[translations.en.strings] # other strings of the work (art-style labels) +"Pictórico" = "Painterly" + +[[translations.en.sections]] # one per scene, in play order +scene = "noche" +heading = "NIGHT" # heading line in the ebook, searched in order +title = "NIGHT" # optional: shown heading (default: `heading`) +subtitle = "Faust’s study · Night" # card subtitle +# default_speaker = "poet_voice" # a section without speaker labels is one speech + +[[translations.en.overrides]] # forced pair: game unit (first line id) <-> source unit +scene = "dia_nebuloso" +game = "dia_nebuloso_0001" +source = "A FIELD" # verbatim start of the source unit (markup removed) +``` diff --git a/docs/voice.md b/docs/voice.md index 684b542..6beb50b 100644 --- a/docs/voice.md +++ b/docs/voice.md @@ -54,7 +54,7 @@ Then `vnpipe renpy` ships the clips. `--scenes` defaults to `[voice].scenes`, el 6. **Ren'Py**: `voice "voice/.ogg"` before the first box of the speech, `voice sustain` before its other boxes (a stage direction inside the speech keeps the clip going). Clips live in `game/voice/`, never under `audio/`, so they are not music moods. The Preferences - screen has a Voice Volume slider (translate it in `tl/`). Credits get a "Voces"/"Voices" + screen has a Voice Volume slider (translated in `renpy_templates/tl/`). Credits get a "Voces"/"Voices" section from `[voice].credits` when clips ship. `voice/report/.txt` lists, per scene, the game speeches and their status, the ASR diff --git a/docs/work-config.md b/docs/work-config.md index c97aa32..448552b 100644 --- a/docs/work-config.md +++ b/docs/work-config.md @@ -7,7 +7,7 @@ A work is a directory containing `work.toml`, plus the folders the pipeline fill | Table | Keys | |---|---| | `[work]` | `id`, `title`, `subtitle`, `author`, `translator`, `language` (`es`/`en`: About, menu and credits texts), `lyric_voice` (cast id for verse nobody speaks; default `poet_voice`), `end_text`, `menu_bg` (legacy alias of `[ui].main_menu_bg`). | -| `[ui]` | `main_menu_bg` (background asset id of the main menu and, darker, the game menu; default: `[work].menu_bg`, else the first staged `bg`); `language` (Ren'Py language name set as `config.default_language`, e.g. `spanish`; its strings come from `/tl//*.rpy`, copied into `game/tl/`). | +| `[ui]` | `main_menu_bg` (background asset id of the main menu and, darker, the game menu; default: `[work].menu_bg`, else the first staged `bg`); `language` (Ren'Py language name of the work's own language, e.g. `spanish`; it is the default and `config.language` follows only the player's explicit choice, so an old persistent preference cannot switch the menus back to English; `language_label` (its name in the language choice, default from `[work].language`); vnpipe ships `renpy_templates/tl//` (Ren'Py's common strings and every template screen string; only `spanish` so far) and copies `/tl//*.rpy` on top, a work file replacing a shipped file with the same name). | | `[source]` | `gutenberg_id`, `url`, `raw_file` (cache path, relative to the work root, gitignored). | | `[scope]` | `start_marker`, `end_marker` (whole stripped lines), `end_occurrence` (1-based, searched after the start; the end marker itself is excluded). | | `[speakers]` | Speaker heading as printed (upper case, without its italic note) → cast id. Several headings may share one id (anonymous crowd speakers). A key with punctuation or markup (`"CORO, TUTTI"`) is matched against the whole printed line first. An unknown speaker is a parse error. | @@ -127,3 +127,10 @@ heading = "Straße (I)" # heading line in the source text, s Voice data lives in the work: `voice/asr/NN.json` (committed ASR cache), `voice/map.json`, `voice/report/.txt`, `voice/clips/*.ogg`. `vnpipe renpy` copies the clips to `game/voice/` and credits them when `[voice].credits` is set. + +### Translations + +Optional `[translations.]` tables: other languages from a published translation of the +text (verbatim, never machine-translated). Configuration, mapping rules and the Ren'Py output +are in [translations.md](translations.md); the mapping is committed as +`data/translations/.json`. diff --git a/src/vnpipe/cli.py b/src/vnpipe/cli.py index 0487307..38ed560 100644 --- a/src/vnpipe/cli.py +++ b/src/vnpipe/cli.py @@ -8,7 +8,7 @@ import argparse import importlib from pathlib import Path -STAGE_MODULES = ["text", "annotate", "assets", "renpy_gen", "voice"] +STAGE_MODULES = ["text", "annotate", "assets", "renpy_gen", "voice", "translate"] def main(argv: list[str] | None = None) -> int: diff --git a/src/vnpipe/renpy_gen.py b/src/vnpipe/renpy_gen.py index 645a740..b7bd115 100644 --- a/src/vnpipe/renpy_gen.py +++ b/src/vnpipe/renpy_gen.py @@ -11,6 +11,7 @@ The GUI files in ``renpy_templates/`` were produced once with the Ren'Py SDK's import argparse import hashlib import json +import re import shutil import tomllib from dataclasses import dataclass, field @@ -30,6 +31,7 @@ NO_MANIFEST_STYLE = {"default": {"label": "Default"}} # work without an asset m ADV_MAX_LINES = 4 NVL_MAX_LINES = 8 +SAY_ID_RE = re.compile(r"^[A-Za-z_][A-Za-z0-9_]*$") SPLIT_INDENT = 6 # parsed `indent` at or above this marks a split verse line TITLE_PAUSE = 2.0 END_PAUSE = 3.0 @@ -164,24 +166,33 @@ def scan_audio(out: Path) -> Audio: def copy_translations(work: Work, out: Path) -> list[Path]: - """Copy ``/tl/**/*.rpy`` into ``game/tl/`` and set ``[ui].language`` as default.""" - src_root = work.path("tl") + """Install the UI translation for ``[ui].language``. + + vnpipe ships ``renpy_templates/tl//`` (Ren'Py's common strings plus every string + of the template screens); ``/tl/**/*.rpy`` is copied on top, so a work file with the + same path replaces the shipped one. Which language plays is decided in ``languages.rpy`` + (the work's own language unless the player picked a translation). + """ dest_root = out / "game" / "tl" - lang_file = out / "game" / "language.rpy" + (out / "game" / "language.rpy").unlink(missing_ok=True) # written by older versions + language = work.data.get("ui", {}).get("language") + sources: dict[Path, Path] = {} + roots = [TEMPLATE_DIR / "tl" / language] if language else [] + roots.append(work.path("tl")) + for i, root in enumerate(roots): + if not root.is_dir(): + continue + prefix = Path(language) if i == 0 and language else Path() + for src in sorted(root.rglob("*.rpy")): + sources[prefix / src.relative_to(root)] = src written = [] - if src_root.is_dir(): + if sources: shutil.rmtree(dest_root, ignore_errors=True) - for src in sorted(src_root.rglob("*.rpy")): - dest = dest_root / src.relative_to(src_root) + for rel, src in sorted(sources.items()): + dest = dest_root / rel dest.parent.mkdir(parents=True, exist_ok=True) shutil.copyfile(src, dest) written.append(dest) - language = work.data.get("ui", {}).get("language") - if language: - write_text(lang_file, f"define config.default_language = {quote(language)}\n") - written.append(lang_file) - else: - lang_file.unlink(missing_ok=True) return written @@ -351,6 +362,18 @@ class Box: is_direction: bool = False +@dataclass +class BoxRecord: + """A say statement as written, for the translations (``vnpipe.renpy_tl``): its ``id`` + (the first line id), speaker, mode and the voice statement it carries.""" + + line_id: str + speaker: str + nvl: bool + voice: str | None = None # clip path when the box starts the voice + sustain: bool = False # the box carries `voice sustain` + + def _playlist(files: list[str]) -> str: return "[" + ", ".join(_plain_quote(f) for f in files) + "]" @@ -369,8 +392,10 @@ class SceneWriter: audio: Audio, music_state: dict[str, str | None], voice_files: dict[int, str] | None = None, + records: list[BoxRecord] | None = None, ): self.work = work + self.records = records if records is not None else [] self.scene = scene self.audio = audio self.voice_files = voice_files or {} # speech index -> clip path (relative to game/) @@ -490,13 +515,19 @@ class SceneWriter: if self.mode == "adv": self.stage(box) text = "\\n".join(escape_text(line["text"]) for line in box.lines) - variable = char_var(box.speaker, nvl=self.mode == "nvl") - self.voice_statement(box) - self.emit(f'{variable} "{text}"') - if self.mode == "nvl": + nvl = self.mode == "nvl" + variable = char_var(box.speaker, nvl=nvl) + record = BoxRecord(first["id"], box.speaker, nvl) + if nvl: # before the say, so it belongs to the say's translation block self.emit("nvl clear") + self.voice_statement(box, record) + if not SAY_ID_RE.match(first["id"]): + raise ValueError(f"line id {first['id']!r} cannot be a Ren'Py say id") + # the explicit id names the translation block (`translate :`) + self.emit(f'{variable} "{text}" id {first["id"]}') + self.records.append(record) - def voice_statement(self, box: Box) -> None: + def voice_statement(self, box: Box, record: BoxRecord) -> None: """``voice`` before the first box of a voiced speech, ``voice sustain`` before the following ones (a stage direction inside the speech keeps the clip going, but never starts it).""" @@ -506,9 +537,11 @@ class SceneWriter: return if self.voice_started == speech: self.emit("voice sustain") + record.sustain = True elif not box.is_direction: self.emit(f"voice {_plain_quote(path)}") self.voice_started = speech + record.voice = path def music(self, spec: str | None) -> None: """Play/stop for a mood, ``track:`` or ``none``; never restarts what already plays.""" @@ -671,7 +704,9 @@ def render_script( annotated: dict[str, Any], audio: Audio | None = None, voice: dict[str, dict[int, str]] | None = None, + records: dict[str, list[BoxRecord]] | None = None, ) -> str: + """The game script; ``records`` (if given) receives every scene's say boxes.""" validate_staging(work, annotated) annotated = apply_overrides(work, annotated) out = [ @@ -687,9 +722,9 @@ def render_script( audio = audio or Audio() music_state: dict[str, str | None] = {"playing": UNKNOWN_MUSIC} for scene in annotated["scenes"]: - out.extend( - SceneWriter(work, scene, audio, music_state, (voice or {}).get(scene["id"])).render() - ) + boxes = [] if records is None else records.setdefault(scene["id"], []) + writer = SceneWriter(work, scene, audio, music_state, (voice or {}).get(scene["id"]), boxes) + out.extend(writer.render()) seen |= {line["id"] for line in scene["lines"]} missing = known - seen if missing: @@ -722,13 +757,19 @@ def _solid(size: tuple[int, int], color: tuple[int, ...]) -> Image.Image: def _check_image(selected: bool, round_: bool) -> Image.Image: + """Preference marks: a diamond (radio) or a square (check), filled with gold when set.""" img = Image.new("RGBA", (38, 38), (0, 0, 0, 0)) draw = ImageDraw.Draw(img) - box = [4, 4, 33, 33] - shape = draw.ellipse if round_ else draw.rectangle - shape(box, outline=IVORY + (255,), width=3) - if selected: - shape([12, 12, 25, 25], fill=ACCENT + (255,)) + if round_: + outer = [(19, 4), (34, 19), (19, 34), (4, 19)] + inner = [(19, 11), (27, 19), (19, 27), (11, 19)] + draw.polygon(outer, outline=IVORY + (200,), width=2) + if selected: + draw.polygon(inner, fill=ACCENT + (255,)) + else: + draw.rectangle([6, 6, 31, 31], outline=IVORY + (200,), width=2) + if selected: + draw.rectangle([12, 12, 25, 25], fill=ACCENT + (255,)) return img @@ -739,6 +780,84 @@ def _slot_image(border_alpha: int, fill_alpha: int) -> Image.Image: return img +def _card_image(fill: tuple[int, ...], outer_alpha: int, inner_alpha: int) -> Image.Image: + """A book-plate panel: tinted fill, a gold outline and a fainter inner rule 5 px inside. + Used as a Frame with 12 px borders, so the double rule never scales.""" + img = Image.new("RGBA", (64, 64), fill) + draw = ImageDraw.Draw(img) + draw.rectangle([0, 0, 63, 63], outline=ACCENT + (outer_alpha,), width=2) + draw.rectangle([5, 5, 58, 58], outline=ACCENT + (inner_alpha,), width=1) + return img + + +def _rule_image(width: int, height: int, diamond: int) -> Image.Image: + """A gold rule fading out at both ends, with a small diamond at its centre.""" + img = Image.new("RGBA", (width, height), (0, 0, 0, 0)) + mid_y = height // 2 + half = width / 2 + for x in range(width): + alpha = round(255 * min(1.0, (1 - abs(x + 0.5 - half) / half) * 1.6)) + img.putpixel((x, mid_y), ACCENT + (alpha,)) + img.putpixel((x, mid_y + 1), ACCENT + (alpha // 2,)) + cx, d = width // 2, diamond + ImageDraw.Draw(img).polygon( + [(cx, mid_y - d), (cx + d, mid_y), (cx, mid_y + d), (cx - d, mid_y)], fill=ACCENT + (255,) + ) + return img + + +def _nav_marker(alpha: int) -> Image.Image: + """Navigation highlight: a gold bar on the left edge and a tint fading to the right.""" + img = Image.new("RGBA", (96, 8), (0, 0, 0, 0)) + for x in range(96): + a = alpha if x < 4 else round(alpha * 0.28 * (1 - (x - 4) / 92)) + for y in range(8): + img.putpixel((x, y), ACCENT + (a,)) + return img + + +def _line_bar(color: tuple[int, ...], thickness: int) -> Image.Image: + """A bar/slider track: a thin horizontal line centred in a transparent 48x48 tile.""" + img = Image.new("RGBA", (48, 48), (0, 0, 0, 0)) + top = 24 - thickness // 2 + ImageDraw.Draw(img).rectangle([0, top, 47, top + thickness - 1], fill=color) + return img + + +def _vline_bar(color: tuple[int, ...], thickness: int) -> Image.Image: + return _line_bar(color, thickness).transpose(Image.Transpose.ROTATE_90) + + +def _diamond_thumb(width: int, height: int) -> Image.Image: + img = Image.new("RGBA", (width, height), (0, 0, 0, 0)) + cx, cy = width // 2, height // 2 + r = min(cx, cy) - 1 + ImageDraw.Draw(img).polygon( + [(cx, cy - r), (cx + r, cy), (cx, cy + r), (cx - r, cy)], + fill=ACCENT + (255,), + outline=DARK + (255,), + ) + return img + + +def _hairline() -> Image.Image: + """A faint gold line on the top edge (a Frame with a 1 px top border keeps it 1 px).""" + img = Image.new("RGBA", (64, 4), (0, 0, 0, 0)) + ImageDraw.Draw(img).line([(0, 0), (63, 0)], fill=ACCENT + (70,)) + return img + + +def _vignette() -> Image.Image: + """Menu shade (scaled up to the screen): darker towards the edges, never opaque.""" + w, h = 192, 108 + img = Image.new("RGBA", (w, h)) + for y in range(h): + for x in range(w): + d = min(1.0, (((x - w / 2) / (w / 2)) ** 2 + ((y - h / 2) / (h / 2)) ** 2) ** 0.5) + img.putpixel((x, y), DARK + (round(120 + 115 * d * d),)) + return img + + def gui_extra_images() -> dict[str, Image.Image]: """Deterministic simple GUI images, keyed by path relative to ``game/``.""" base: dict[str, Image.Image] = { @@ -751,22 +870,35 @@ def gui_extra_images() -> dict[str, Image.Image]: "button/check_selected_foreground.png": _check_image(True, False), "button/radio_foreground.png": _check_image(False, True), "button/radio_selected_foreground.png": _check_image(True, True), - "bar/left.png": _solid((48, 48), ACCENT + (255,)), - "bar/right.png": _solid((48, 48), IVORY + (60,)), - "bar/top.png": _solid((48, 48), IVORY + (60,)), - "bar/bottom.png": _solid((48, 48), ACCENT + (255,)), - "slider/horizontal_bar.png": _solid((48, 48), IVORY + (60,)), - "slider/horizontal_thumb.png": _solid((20, 38), ACCENT + (255,)), - "slider/vertical_bar.png": _solid((48, 48), IVORY + (60,)), - "slider/vertical_thumb.png": _solid((38, 20), ACCENT + (255,)), - "scrollbar/horizontal_bar.png": _solid((48, 48), IVORY + (40,)), - "scrollbar/horizontal_thumb.png": _solid((48, 48), ACCENT + (255,)), - "scrollbar/vertical_bar.png": _solid((48, 48), IVORY + (40,)), - "scrollbar/vertical_thumb.png": _solid((48, 48), ACCENT + (255,)), + "bar/left.png": _line_bar(ACCENT + (255,), 6), + "bar/right.png": _line_bar(IVORY + (70,), 2), + "bar/top.png": _vline_bar(IVORY + (70,), 2), + "bar/bottom.png": _vline_bar(ACCENT + (255,), 6), + "slider/horizontal_bar.png": _line_bar(IVORY + (90,), 2), + "slider/horizontal_thumb.png": _diamond_thumb(34, 38), + "slider/vertical_bar.png": _vline_bar(IVORY + (90,), 2), + "slider/vertical_thumb.png": _diamond_thumb(38, 34), + "scrollbar/horizontal_bar.png": _line_bar(IVORY + (50,), 2), + "scrollbar/horizontal_thumb.png": _line_bar(ACCENT + (220,), 6), + "scrollbar/vertical_bar.png": _vline_bar(IVORY + (50,), 2), + "scrollbar/vertical_thumb.png": _vline_bar(ACCENT + (220,), 6), + # Menu ornaments (screens.rpy): panels, rules, navigation marker, menu shade. + "vn/card_background.png": _card_image(DARK + (215,), 120, 45), + "vn/card_hover_background.png": _card_image((38, 31, 22, 235), 255, 140), + "vn/card_empty.png": _card_image(DARK + (120,), 55, 0), + "vn/rule.png": _rule_image(520, 18, 6), + "vn/rule_small.png": _rule_image(240, 14, 4), + "vn/nav_background.png": _solid((96, 8), (0, 0, 0, 0)), + "vn/nav_hover_background.png": _nav_marker(130), + "vn/nav_selected_background.png": _nav_marker(255), + "vn/nav_selected_hover_background.png": _nav_marker(255), + "vn/vignette.png": _vignette(), + "vn/hairline.png": _hairline(), } result = dict(base) for path, img in base.items(): - result[f"phone/{path}"] = img + if not path.startswith("vn/"): # ornaments are not looked up by variant prefix + result[f"phone/{path}"] = img return {f"gui/{path}": img for path, img in sorted(result.items())} @@ -806,15 +938,20 @@ testcase default: pause 1.0 # Actions, not label text: stock menu labels may be translated. run Start() -@@PICK@@ advance until eval (e2e_state["end"]) timeout 900 +@@PICK@@ pause 1.0 + # A save carries the scene title shown by the load screen. + run FileSave(1, confirm=False) + assert eval (FileJson(1, "vn_scene") is not None) + advance until eval (e2e_state["end"]) timeout 900 advance until screen "main_menu" timeout 60 @@MENUS@@ assert eval (e2e_state["end"]) """ -def render_e2e(styles: dict[str, Any], ui: dict[str, str]) -> str: +def render_e2e(styles: dict[str, Any]) -> str: """The playthrough testcase; with a style choice it also exercises the first-launch picker - (picking the last style, so the non-default switch branch is the one in use).""" + (picking the last style, so the non-default switch branch is the one in use). Menus are + opened by action, not label, so the test also runs in a translation (RENPY_LANGUAGE).""" pick = "" if len(styles) > 1: sid, cfg = list(styles.items())[-1] @@ -825,15 +962,17 @@ def render_e2e(styles: dict[str, Any], ui: dict[str, str]) -> str: f" assert eval (persistent.art_style == {sid!r})\n" ) menus = ( - f" click {_plain_quote(ui['credits'])}\n" + ' run ShowMenu("vn_credits")\n' ' assert screen "vn_credits"\n' " run Return()\n" ' assert screen "main_menu"\n' - f" click {_plain_quote(ui['scenes'])}\n" + ' run ShowMenu("vn_scene_select")\n' ' assert screen "vn_scene_select"\n' " run Return()\n" ' assert screen "main_menu"\n' ) + for screen in ("load", "preferences", "about"): + menus += f' run ShowMenu("{screen}")\n assert screen "{screen}"\n run Return()\n' return E2E_TESTCASE.replace("@@PICK@@", pick).replace("@@MENUS@@", menus) @@ -866,26 +1005,41 @@ def render_characters(work: Work) -> str: return "\n".join(out) -def title_cards(work: Work, annotated: dict[str, Any]) -> dict[str, tuple[str, str | None]]: - """Image name -> (heading, optional subtitle line: place/time, from ``[[scenes]].subtitle``).""" +def title_cards( + work: Work, annotated: dict[str, Any], tags: dict[str, str] | None = None +) -> dict[str, tuple[str, str | None]]: + """Image name -> (heading, optional subtitle line: place/time, from ``[[scenes]].subtitle``). + + ``tags`` (scene ids -> ``{#id}`` tag) tell apart equal texts that translate differently.""" + tags = tags or {} subtitles = {sc["id"]: sc.get("subtitle") for sc in work.data.get("scenes", [])} - cards: dict[str, tuple[str, str | None]] = { - f"card_{sc['id']}": (sc["heading"], subtitles.get(sc["id"])) for sc in annotated["scenes"] - } + cards: dict[str, tuple[str, str | None]] = {} + for sc in annotated["scenes"]: + tag = f"{{#{tags[sc['id']]}}}" if sc["id"] in tags else "" + subtitle = subtitles.get(sc["id"]) + cards[f"card_{sc['id']}"] = (sc["heading"] + tag, subtitle and subtitle + tag) cards["card_end"] = (work.data["work"].get("end_text", DEFAULT_END_TEXT), None) return cards +def _tagged(text: str) -> str: + """Escape markup, keeping a trailing ``{#...}`` disambiguation tag.""" + match = re.search(r"\{#[^{}]*\}$", text) + if not match: + return escape_text(text) + return escape_text(text[: match.start()]) + match.group(0) + + def render_card(heading: str, subtitle: str | None) -> str: """A spaced-out heading; with a subtitle, a thin gold rule and a smaller italic line below.""" props = "size=76, kerning=3, text_align=0.5, xmaximum=1600" if not subtitle: - return f'Text("{escape_text(heading)}", {props})' + return f'Text("{_tagged(heading)}", {props})' sub_props = 'size=34, italic=True, color="#c9a25b", text_align=0.5, xmaximum=1600' return ( - f'VBox(Text("{escape_text(heading)}", {props}, xalign=0.5), ' + f'VBox(Text("{_tagged(heading)}", {props}, xalign=0.5), ' 'Solid("#c9a25b", xsize=200, ysize=2, xalign=0.5), ' - f'Text("{escape_text(subtitle)}", {sub_props}, xalign=0.5), spacing=26)' + f'Text("{_tagged(subtitle)}", {sub_props}, xalign=0.5), spacing=26)' ) @@ -912,7 +1066,8 @@ def render_images(entries: list[ImageEntry], cards: dict[str, tuple[str, str | N return "\n".join(out) -def _about(work: Work) -> str: +def about_parts(work: Work) -> list[str]: + """Paragraphs of the About screen text.""" info = work.data["work"] text_l, trans_l, tail = ABOUT_LABELS.get(info.get("language", "es"), ABOUT_LABELS["en"]) parts = [info.get("subtitle", "")] @@ -921,7 +1076,11 @@ def _about(work: Work) -> str: if info.get("translator"): parts.append(f"{trans_l}: {info['translator']}") parts.append(tail) - return "\\n\\n".join(escape_text(p) for p in parts if p) + return [p for p in parts if p] + + +def _about(work: Work) -> str: + return "\\n\\n".join(escape_text(p) for p in about_parts(work)) def ui_labels(work: Work) -> dict[str, str]: @@ -986,8 +1145,11 @@ def credits_sections(work: Work, manifest: dict[str, Any] | None) -> list[tuple[ return [(title, [_markup(e) for e in entries]) for title, entries in sections] -def scene_menu_titles(work: Work, annotated: dict[str, Any]) -> list[tuple[str, str]]: +def scene_menu_titles( + work: Work, annotated: dict[str, Any], tags: dict[str, str] | None = None +) -> list[tuple[str, str]]: """(label, title) per scene; a repeated heading gets its subtitle, else its number.""" + tags = tags or {} subtitles = {sc["id"]: sc.get("subtitle") for sc in work.data.get("scenes", [])} headings = [sc["heading"] for sc in annotated["scenes"]] seen: dict[str, int] = {} @@ -997,11 +1159,21 @@ def scene_menu_titles(work: Work, annotated: dict[str, Any]) -> list[tuple[str, if headings.count(title) > 1: seen[title] = seen.get(title, 0) + 1 title += f" ({subtitles.get(sc['id']) or seen[title]})" - result.append((f"scene_{sc['id']}", _markup(title))) + tag = f"{{#{tags[sc['id']]} menu}}" if sc["id"] in tags else "" + result.append((f"scene_{sc['id']}", _markup(title) + tag)) return result -def render_menu_data(work: Work, annotated: dict[str, Any], manifest: dict[str, Any] | None) -> str: +def render_menu_data( + work: Work, + annotated: dict[str, Any], + manifest: dict[str, Any] | None, + tags: dict[str, str] | None = None, + credits_tl: dict[str, list[tuple[str, list[str]]]] | None = None, +) -> str: + """Menu data; ``credits_tl`` holds the credits of each translation (Ren'Py language -> + sections), shown instead of ``vn_credits`` in that language.""" + def py(value: Any) -> str: # JSON strings are valid Python literals return json.dumps(value, ensure_ascii=False) @@ -1011,8 +1183,9 @@ def render_menu_data(work: Work, annotated: dict[str, Any], manifest: dict[str, "## Generated by `vnpipe renpy`. Do not edit: regenerate instead.", "", f"define vn_subtitle = {py(subtitle)}", - f"define vn_scenes = {py(scene_menu_titles(work, annotated))}", + f"define vn_scenes = {py(scene_menu_titles(work, annotated, tags))}", f"define vn_credits = {py(credits_sections(work, manifest))}", + f"define vn_credits_tl = {py(credits_tl or {})}", "", ] ) @@ -1054,6 +1227,10 @@ def generate( ) if first_bg: menu_bg = bg_image_name(first_bg) + from vnpipe import renpy_tl # imports this module + + tls = renpy_tl.load_all(work, annotated) + tags = renpy_tl.collision_tags(work, annotated, tls) if tls else {} styles, default_style = art_styles(manifest) picker_title, picker_hint = ART_STYLE_LABELS.get( info.get("language", "es"), ART_STYLE_LABELS["en"] @@ -1073,6 +1250,7 @@ def generate( "UI_SCENES": ui["scenes"], "UI_CREDITS": ui["credits"], "LOCKED": LOCKED_SCENE, + "LANGUAGES": repr(renpy_tl.languages(work, tls)), } written: list[Path] = [] for src in sorted((TEMPLATE_DIR / "game").rglob("*")): @@ -1098,19 +1276,42 @@ def generate( test_file = game / E2E_FILE test_file.unlink(missing_ok=True) if with_test: - write_text(test_file, render_e2e(styles, ui)) + write_text(test_file, render_e2e(styles)) written.append(test_file) + records: dict[str, list[BoxRecord]] = {} + credits_tl = { + tl.language: renpy_tl.translated_credits(work, annotated, manifest, tl) for tl in tls + } for name, text in ( ("characters.rpy", render_characters(work)), - ("images.rpy", render_images(entries, title_cards(work, annotated))), - ("menu_data.rpy", render_menu_data(work, annotated, manifest)), + ("images.rpy", render_images(entries, title_cards(work, annotated, tags))), + ("menu_data.rpy", render_menu_data(work, annotated, manifest, tags, credits_tl)), ( "script.rpy", - render_script(work, annotated, scan_audio(out), voice_files(work, annotated)), + render_script(work, annotated, scan_audio(out), voice_files(work, annotated), records), ), ): write_text(game / name, text) written.append(game / name) + for tl in tls: + tl_dir = game / "tl" / tl.language + shutil.rmtree(tl_dir, ignore_errors=True) + for name, text in ( + ( + "script.rpy", + renpy_tl.render_tl_script( + tl, apply_overrides(work, annotated), records, lyric_voice(work), work.cast + ), + ), + ( + "strings.rpy", + renpy_tl.render_tl_strings( + tl, renpy_tl.string_pairs(work, annotated, manifest, tl, tags) + ), + ), + ): + write_text(tl_dir / name, text) + written.append(tl_dir / name) for e in entries: for _, rel, source in e.variants: diff --git a/src/vnpipe/renpy_templates/game/gui.rpy b/src/vnpipe/renpy_templates/game/gui.rpy index d2c2043..0d91572 100644 --- a/src/vnpipe/renpy_templates/game/gui.rpy +++ b/src/vnpipe/renpy_templates/game/gui.rpy @@ -28,21 +28,21 @@ define config.check_conflicting_properties = True define gui.accent_color = '#c9a25b' ## The color used for a text button when it is neither selected nor hovered. -define gui.idle_color = '#888888' +define gui.idle_color = '#b4a990' ## The small color is used for small text, which needs to be brighter/darker to ## achieve the same effect. -define gui.idle_small_color = '#aaaaaa' +define gui.idle_small_color = '#cfc4ab' ## The color that is used for buttons and bars that are hovered. -define gui.hover_color = '#dec79c' +define gui.hover_color = '#ecd4a0' ## The color used for a text button when it is selected but not focused. A ## button is selected if it is the current screen or preference value. -define gui.selected_color = '#ffffff' +define gui.selected_color = '#d9b46a' ## The color used for a text button when it cannot be selected. -define gui.insensitive_color = '#8888887f' +define gui.insensitive_color = '#7d74647f' ## Colors used for the portions of bars that are not filled in. These are not ## used directly, but are used when re-generating bar image files. @@ -188,10 +188,10 @@ define gui.confirm_button_text_xalign = 0.5 define gui.page_button_borders = Borders(15, 6, 15, 6) -define gui.quick_button_borders = Borders(15, 6, 15, 0) -define gui.quick_button_text_size = 21 +define gui.quick_button_borders = Borders(18, 6, 18, 6) +define gui.quick_button_text_size = 24 define gui.quick_button_text_idle_color = gui.idle_small_color -define gui.quick_button_text_selected_color = gui.accent_color +define gui.quick_button_text_selected_color = gui.selected_color ## You can also add your own customizations, by adding properly-named variables. ## For example, you can uncomment the following line to set the width of a @@ -211,9 +211,9 @@ define gui.choice_button_borders = Borders(150, 8, 150, 8) define gui.choice_button_text_font = gui.text_font define gui.choice_button_text_size = gui.text_size define gui.choice_button_text_xalign = 0.5 -define gui.choice_button_text_idle_color = '#888888' -define gui.choice_button_text_hover_color = "#ffffff" -define gui.choice_button_text_insensitive_color = '#8888887f' +define gui.choice_button_text_idle_color = '#cfc4ab' +define gui.choice_button_text_hover_color = '#ecd4a0' +define gui.choice_button_text_insensitive_color = '#7d74647f' ## File Slot Buttons ########################################################### @@ -237,8 +237,8 @@ define config.thumbnail_width = 384 define config.thumbnail_height = 216 ## The number of columns and rows in the grid of save slots. -define gui.file_slot_cols = 3 -define gui.file_slot_rows = 2 +define gui.file_slot_cols = 1 +define gui.file_slot_rows = 4 ## Positioning and Spacing ##################################################### @@ -251,10 +251,10 @@ define gui.file_slot_rows = 2 define gui.navigation_xpos = 60 ## The vertical position of the skip indicator. -define gui.skip_ypos = 15 +define gui.skip_ypos = 36 ## The vertical position of the notify screen. -define gui.notify_ypos = 68 +define gui.notify_ypos = 36 ## The spacing between menu choices. define gui.choice_spacing = 33 @@ -341,7 +341,7 @@ define config.history_length = 250 ## The height of a history screen entry, or None to make the height variable at ## the cost of performance. -define gui.history_height = 210 +define gui.history_height = None ## Additional space to add between history screen entries. define gui.history_spacing = 0 @@ -424,7 +424,7 @@ init python: @gui.variant def touch(): - gui.quick_button_borders = Borders(60, 21, 60, 0) + gui.quick_button_borders = Borders(54, 18, 54, 10) ## This changes the size and spacing of various GUI elements to ensure they ## are easily visible on phones. @@ -454,14 +454,13 @@ init python: gui.navigation_spacing = 30 gui.pref_button_spacing = 15 - gui.history_height = 285 gui.history_text_width = 1035 gui.quick_button_text_size = 30 ## File button layout. - gui.file_slot_cols = 2 - gui.file_slot_rows = 2 + gui.file_slot_cols = 1 + gui.file_slot_rows = 3 ## NVL-mode. gui.nvl_height = None diff --git a/src/vnpipe/renpy_templates/game/gui/overlay/confirm.png b/src/vnpipe/renpy_templates/game/gui/overlay/confirm.png deleted file mode 100644 index b95c47c..0000000 Binary files a/src/vnpipe/renpy_templates/game/gui/overlay/confirm.png and /dev/null differ diff --git a/src/vnpipe/renpy_templates/game/gui/overlay/game_menu.png b/src/vnpipe/renpy_templates/game/gui/overlay/game_menu.png deleted file mode 100644 index 5c588b7..0000000 Binary files a/src/vnpipe/renpy_templates/game/gui/overlay/game_menu.png and /dev/null differ diff --git a/src/vnpipe/renpy_templates/game/gui/overlay/main_menu.png b/src/vnpipe/renpy_templates/game/gui/overlay/main_menu.png deleted file mode 100644 index e56f58e..0000000 Binary files a/src/vnpipe/renpy_templates/game/gui/overlay/main_menu.png and /dev/null differ diff --git a/src/vnpipe/renpy_templates/game/gui/phone/overlay/game_menu.png b/src/vnpipe/renpy_templates/game/gui/phone/overlay/game_menu.png deleted file mode 100644 index 564cff0..0000000 Binary files a/src/vnpipe/renpy_templates/game/gui/phone/overlay/game_menu.png and /dev/null differ diff --git a/src/vnpipe/renpy_templates/game/gui/phone/overlay/main_menu.png b/src/vnpipe/renpy_templates/game/gui/phone/overlay/main_menu.png deleted file mode 100644 index a599090..0000000 Binary files a/src/vnpipe/renpy_templates/game/gui/phone/overlay/main_menu.png and /dev/null differ diff --git a/src/vnpipe/renpy_templates/game/languages.rpy b/src/vnpipe/renpy_templates/game/languages.rpy new file mode 100644 index 0000000..d484adb --- /dev/null +++ b/src/vnpipe/renpy_templates/game/languages.rpy @@ -0,0 +1,26 @@ +## Languages: the play's own text, plus every translation built by `vnpipe translate` +## (game/tl//). The player picks one in Preferences, or at first launch; the +## choice is kept in `persistent.vn_language`. `config.language` is set from that choice +## only, so a language preference left by an older build never overrides it, and loading a +## save keeps the chosen language. Static except for the substituted list. + +default persistent.vn_language = None + +## (Ren'Py language, label in that language) pairs; the first is the default. +define vn_languages = @@LANGUAGES@@ + +init 1 python: + + def vn_known_language(language): + return any(lang == language for lang, _label in vn_languages) + + def vn_set_language(language): + """Remember the player's choice; Language(language) then switches to it.""" + persistent.vn_language = language + config.language = language + + if vn_known_language(persistent.vn_language): + config.language = persistent.vn_language + else: + config.language = vn_languages[0][0] + config.default_language = vn_languages[0][0] diff --git a/src/vnpipe/renpy_templates/game/menus.rpy b/src/vnpipe/renpy_templates/game/menus.rpy index 6b3faca..0f5a282 100644 --- a/src/vnpipe/renpy_templates/game/menus.rpy +++ b/src/vnpipe/renpy_templates/game/menus.rpy @@ -1,15 +1,41 @@ ## Scene select and credits screens, reached from the main menu. The data they show -## (`vn_scenes`, `vn_credits`) is generated in menu_data.rpy; static otherwise. +## (`vn_scenes`, `vn_credits`, `vn_credits_tl`) is generated in menu_data.rpy; static +## otherwise. ## Labels of the scenes the player has reached; updated when a scene starts. default persistent.vn_seen_scenes = set() +## The scene being played (a label of `vn_scenes`); saved with the game. +default vn_current_scene = None + init python: def vn_mark_scene(label): + store.vn_current_scene = label if label not in persistent.vn_seen_scenes: persistent.vn_seen_scenes.add(label) renpy.save_persistent() + ## Save metadata shown by the file slots (screens.rpy): the scene title and the first + ## line of the text on screen. Text tags are dropped and markup is escaped. + VN_EXCERPT_CHARS = 90 + + def vn_excerpt(what): + line = renpy.filter_text_tags(what or "", allow=[]).strip().split("\n")[0].strip() + if len(line) > VN_EXCERPT_CHARS: + line = line[:VN_EXCERPT_CHARS].rsplit(" ", 1)[0] + "…" + return line.replace("[", "[[").replace("{", "{{") + + def vn_save_json(d): + titles = dict((l, t) for l, t in vn_scenes) + if store.vn_current_scene in titles: + d["vn_scene"] = titles[store.vn_current_scene] + if _history_list: + last = _history_list[-1] + d["vn_who"] = (last.who or "").replace("[", "[[").replace("{", "{{") + d["vn_line"] = vn_excerpt(last.what) + + config.save_json_callbacks.append(vn_save_json) + screen vn_scene_select(): tag menu @@ -33,6 +59,8 @@ style vn_scenes_button_text is gui_button_text style vn_scenes_button: properties gui.button_properties("navigation_button") xalign 0.0 + padding (26, 5, 20, 5) + background Frame("gui/vn/nav_[prefix_]background.png", 6, 0) style vn_scenes_button_text: properties gui.text_properties("navigation_button") @@ -50,7 +78,8 @@ screen vn_credits(): vbox: spacing 6 - for section_title, entries in vn_credits: + ## a translation has its own credits (its text comes from another translator) + for section_title, entries in vn_credits_tl.get(_preferences.language, vn_credits): null height 20 label section_title for entry in entries: diff --git a/src/vnpipe/renpy_templates/game/screens.rpy b/src/vnpipe/renpy_templates/game/screens.rpy index 467db21..5bfe685 100644 --- a/src/vnpipe/renpy_templates/game/screens.rpy +++ b/src/vnpipe/renpy_templates/game/screens.rpy @@ -230,10 +230,11 @@ style choice_button_text is default: properties gui.text_properties("choice_button") + ## Quick Menu screen ########################################################### ## ## The quick menu is displayed in-game to provide easy access to the out-of-game -## menus. +## menus. It sits on its own dark strip so it stays legible over any textbox. screen quick_menu(): @@ -242,18 +243,21 @@ screen quick_menu(): if quick_menu: - hbox: - style_prefix "quick" - style "quick_menu" + frame: + style "quick_frame" - textbutton _("Back") action Rollback() - textbutton _("History") action ShowMenu('history') - textbutton _("Skip") action Skip() alternate Skip(fast=True, confirm=True) - textbutton _("Auto") action Preference("auto-forward", "toggle") - textbutton _("Save") action ShowMenu('save') - textbutton _("Q.Save") action QuickSave() - textbutton _("Q.Load") action QuickLoad() - textbutton _("Prefs") action ShowMenu('preferences') + hbox: + style_prefix "quick" + style "quick_menu" + + textbutton _("Back") action Rollback() + textbutton _("History") action ShowMenu('history') + textbutton _("Skip") action Skip() alternate Skip(fast=True, confirm=True) + textbutton _("Auto") action Preference("auto-forward", "toggle") + textbutton _("Save") action ShowMenu('save') + textbutton _("Q.Save") action QuickSave() + textbutton _("Q.Load") action QuickLoad() + textbutton _("Prefs") action ShowMenu('preferences') ## This code ensures that the quick_menu screen is displayed in-game, whenever @@ -263,19 +267,41 @@ init python: default quick_menu = True +style quick_frame is empty style quick_menu is hbox style quick_button is default style quick_button_text is button_text -style quick_menu: +style quick_frame: xalign 0.5 yalign 1.0 + padding (24, 2, 24, 2) + background Solid("#0b0907b8") + +style quick_menu: + spacing 4 style quick_button: properties gui.button_properties("quick_button") style quick_button_text: properties gui.text_properties("quick_button") + kerning 1 + + +################################################################################ +## Shared menu ornaments +################################################################################ + +## A gold rule with a diamond at its centre (as on the scene title cards). +image vn_rule = "gui/vn/rule.png" +image vn_rule_small = "gui/vn/rule_small.png" + +## Darkens a menu background towards the edges so the panels stay readable. +image vn_vignette = Transform("gui/vn/vignette.png", xysize=(config.screen_width, config.screen_height)) + +## A diamond glyph, from a font that has it. +define vn_diamond = "{font=DejaVuSans.ttf}◆{/font}" ################################################################################ @@ -285,17 +311,13 @@ style quick_button_text: ## Navigation screen ########################################################### ## ## This screen is included in the main and game menus, and provides navigation -## to other menus, and to start the game. +## to other menus, and to start the game. On the main menu it is a centred list +## under the title; in the game menus, a column on the left. -screen navigation(): +screen navigation(centered=False): vbox: - style_prefix "navigation" - - xpos gui.navigation_xpos - yalign 0.5 - - spacing gui.navigation_spacing + style_prefix ("main_nav" if centered else "navigation") if main_menu: @@ -337,20 +359,53 @@ screen navigation(): textbutton _("Quit") action Quit(confirm=not main_menu) +style navigation_vbox is vbox style navigation_button is gui_button style navigation_button_text is gui_button_text +style navigation_vbox: + xpos gui.navigation_xpos + yalign 0.5 + spacing gui.navigation_spacing + style navigation_button: size_group "navigation" properties gui.button_properties("navigation_button") + xminimum 300 + padding (26, 9, 20, 9) + background Frame("gui/vn/nav_[prefix_]background.png", 6, 0) style navigation_button_text: properties gui.text_properties("navigation_button") + size 31 + kerning 1 + +style main_nav_vbox is vbox +style main_nav_button is gui_button +style main_nav_button_text is gui_button_text + +style main_nav_vbox: + xalign 0.5 + ypos 520 + spacing 2 + +style main_nav_button: + xalign 0.5 + padding (40, 4) + +style main_nav_button_text: + properties gui.text_properties("navigation_button") + size 34 + kerning 3 + xalign 0.5 + textalign 0.5 + outlines [(2, "#000000a0", 0, 1)] ## Main Menu screen ############################################################ ## -## Used to display the main menu when Ren'Py starts. +## Used to display the main menu when Ren'Py starts: the title as on a book's +## title page, a gold rule, and the menu centred below. ## ## https://www.renpy.org/doc/html/screen_special.html#main-menu @@ -360,16 +415,7 @@ screen main_menu(): tag menu add gui.main_menu_background - - ## Darkens the background so the title reads well. - add Solid("#000000a8") - - ## The left strip behind the navigation. - frame: - style "main_menu_frame" - - ## The actual contents of the main menu are in the navigation screen. - use navigation + add "vn_vignette" if gui.show_name: @@ -379,32 +425,29 @@ screen main_menu(): text "[config.name!t]": style "main_menu_title" + add "vn_rule" xalign 0.5 + if vn_subtitle: text "[vn_subtitle!t]": style "main_menu_subtitle" - text "[config.version]": - style "main_menu_version" + ## The actual contents of the main menu are in the navigation screen. + use navigation(centered=True) + + text "[config.version]": + style "main_menu_version" -style main_menu_frame is empty style main_menu_vbox is vbox style main_menu_text is gui_text style main_menu_title is main_menu_text style main_menu_subtitle is main_menu_text style main_menu_version is main_menu_text -style main_menu_frame: - xsize 420 - yfill True - - background "gui/overlay/main_menu.png" - style main_menu_vbox: - xpos 420 - xsize 1500 - yalign 0.42 - spacing 36 + xalign 0.5 + ypos 150 + spacing 22 style main_menu_text: properties gui.text_properties("main_menu", accent=True) @@ -412,30 +455,36 @@ style main_menu_text: style main_menu_title: properties gui.text_properties("title") size 132 - kerning 10 + kerning 14 xalign 0.5 - text_align 0.5 + textalign 0.5 color "#efe6d2" outlines [(4, "#000000b0", 0, 3)] style main_menu_subtitle: - size 46 + size 44 italic True kerning 3 xalign 0.5 - text_align 0.5 + textalign 0.5 color "#c9a25b" outlines [(3, "#000000b0", 0, 2)] style main_menu_version: properties gui.text_properties("version") - xalign 0.5 + size 20 + color "#efe6d260" + xalign 1.0 + yalign 1.0 + xoffset -30 + yoffset -20 ## Game Menu screen ############################################################ ## -## This lays out the basic common structure of a game menu screen. It's called -## with the screen title, and displays the background, title, and navigation. +## This lays out the basic common structure of a game menu screen: the art +## behind a dark shade, a navigation column on the left with the work's title, +## and the screen title over the content, underlined by the gold rule. ## ## The scroll parameter can be None, or one of "viewport" or "vpgrid". ## This screen is intended to be used with one or more children, which are @@ -450,58 +499,68 @@ screen game_menu(title, scroll=None, yinitial=0.0, spacing=0): else: add gui.game_menu_background - ## The game menu is darker than the main menu so text stays legible. - add Solid("#000000d0") + add "vn_vignette" + add Solid("#000000a0") + + ## The navigation column. + frame: + style "game_menu_navigation_frame" + + text "[config.name!t]": + style "game_menu_work_title" frame: - style "game_menu_outer_frame" + style "game_menu_work_rule" + add "vn_rule_small" - hbox: + ## The title and its rule, centred over the content. + vbox: + style "game_menu_title_vbox" - ## Reserve space for the navigation section. - frame: - style "game_menu_navigation_frame" + label title - frame: - style "game_menu_content_frame" + add "vn_rule" xalign 0.5 - if scroll == "viewport": + frame: + style "game_menu_content_frame" - viewport: - yinitial yinitial - scrollbars "vertical" - mousewheel True - draggable True - pagekeys True + if scroll == "viewport": - side_yfill True + viewport: + yinitial yinitial + scrollbars "vertical" + mousewheel True + draggable True + pagekeys True - vbox: - spacing spacing + side_yfill True - transclude - - elif scroll == "vpgrid": - - vpgrid: - cols 1 - yinitial yinitial - - scrollbars "vertical" - mousewheel True - draggable True - pagekeys True - - side_yfill True - - spacing spacing - - transclude - - else: + vbox: + spacing spacing transclude + elif scroll == "vpgrid": + + vpgrid: + cols 1 + yinitial yinitial + + scrollbars "vertical" + mousewheel True + draggable True + pagekeys True + + side_yfill True + + spacing spacing + + transclude + + else: + + transclude + use navigation textbutton _("Return"): @@ -509,15 +568,15 @@ screen game_menu(title, scroll=None, yinitial=0.0, spacing=0): action Return() - label title - if main_menu: key "game_menu" action ShowMenu("main_menu") -style game_menu_outer_frame is empty style game_menu_navigation_frame is empty style game_menu_content_frame is empty +style game_menu_title_vbox is vbox +style game_menu_work_title is gui_text +style game_menu_work_rule is empty style game_menu_viewport is gui_viewport style game_menu_side is gui_side style game_menu_scrollbar is gui_vscrollbar @@ -528,23 +587,40 @@ style game_menu_label_text is gui_label_text style return_button is navigation_button style return_button_text is navigation_button_text -style game_menu_outer_frame: - bottom_padding 45 - top_padding 180 - - background "gui/overlay/game_menu.png" - style game_menu_navigation_frame: - xsize 420 + xsize 400 yfill True + background Fixed(Solid("#0b0907d8"), Solid("#c9a25b50", xsize=1, ysize=960, xpos=399, ypos=60)) + +style game_menu_work_title: + xpos 200 + xanchor 0.5 + xmaximum 360 + textalign 0.5 + ypos 62 + size 34 + kerning 8 + color gui.accent_color + +style game_menu_work_rule: + xpos 200 + xanchor 0.5 + ypos 122 + +style game_menu_title_vbox: + xpos 1160 + xanchor 0.5 + ypos 44 + spacing 4 style game_menu_content_frame: - left_margin 60 - right_margin 30 - top_margin 15 + xpos 480 + ypos 228 + xsize 1360 + ysize 800 style game_menu_viewport: - xsize 1380 + xsize 1360 style game_menu_vscrollbar: unscrollable gui.unscrollable @@ -553,13 +629,14 @@ style game_menu_side: spacing 15 style game_menu_label: - xpos 75 - ysize 180 + xalign 0.5 style game_menu_label_text: - size 75 - color gui.accent_color - yalign 0.5 + size 76 + kerning 3 + color "#efe6d2" + xalign 0.5 + outlines [(3, "#00000090", 0, 2)] style return_button: xpos gui.navigation_xpos @@ -570,46 +647,63 @@ style return_button: ## About screen ################################################################ ## ## This screen gives credit and copyright information about the game and Ren'Py. -## -## There's nothing special about this screen, and hence it also serves as an -## example of how to make a custom screen. screen about(): tag menu - ## This use statement includes the game_menu screen inside this one. The - ## vbox child is then included inside the viewport inside the game_menu - ## screen. use game_menu(_("About"), scroll="viewport"): style_prefix "about" vbox: + xsize 1300 + spacing 6 label "[config.name!t]" - text _("Version [config.version!t]\n") + text _("Version [config.version!t]\n") style "about_version" ## gui.about is usually set in options.rpy. if gui.about: text "[gui.about!t]\n" - text _("Made with {a=https://www.renpy.org/}Ren'Py{/a} [renpy.version_only].\n\n[renpy.license!t]") + add "vn_rule_small" + null height 16 + + text _("Made with {a=https://www.renpy.org/}Ren'Py{/a} [renpy.version_only].\n\n[renpy.license!t]"): + style "about_small" style about_label is gui_label style about_label_text is gui_label_text style about_text is gui_text +style about_version is about_text +style about_small is about_text style about_label_text: - size gui.label_text_size + size 48 + kerning 4 + color gui.accent_color + +style about_text: + size 30 + +style about_version: + size 24 + italic True + color "#efe6d2a0" + +style about_small: + size 22 + color "#efe6d2b0" ## Load and Save screens ####################################################### ## -## These screens are responsible for letting the player save the game and load -## it again. Since they share nearly everything in common, both are implemented -## in terms of a third screen, file_slots. +## Both screens share file_slots: a page of saves shown as entries of a book's +## register (thumbnail, scene title, the line that was on screen and the date), +## a page name the player can edit, and pages numbered in Roman numerals. The +## load screen adds the autosave and quick save pages. ## ## https://www.renpy.org/doc/html/screen_special.html#save https:// ## www.renpy.org/doc/html/screen_special.html#load @@ -618,6 +712,10 @@ screen save(): tag menu + ## The automatic and quick save pages are only offered when loading. + on "show" action If(FileCurrentPage() in ("auto", "quick"), FilePage(1)) + on "replace" action If(FileCurrentPage() in ("auto", "quick"), FilePage(1)) + use file_slots(_("Save")) @@ -628,9 +726,52 @@ screen load(): use file_slots(_("Load")) +init python: + + def vn_roman(n): + """1 -> I, 4 -> IV, 9 -> IX, ...""" + out = "" + for value, numeral in ((1000, "M"), (900, "CM"), (500, "D"), (400, "CD"), (100, "C"), + (90, "XC"), (50, "L"), (40, "XL"), (10, "X"), (9, "IX"), (5, "V"), (4, "IV"), + (1, "I")): + while n >= value: + out += numeral + n -= value + return out + + class VnPageNameInputValue(FilePageNameInputValue): + """The editable page name, whose default uses the Roman page number.""" + + def _default(self, page): + return __(self.pattern).format(vn_roman(int(page))) + + def get_text(self): + page = self.get_page() + if page in ("auto", "quick"): + return FilePageNameInputValue.get_text(self) + default = self._default(page) + rv = persistent._file_page_name.get(int(page), default) + if not rv.strip(): + current, active = renpy.get_editable_input_value() + if not ((current is self) and active): + rv = default + return rv + + def set_text(self, s): + page = self.get_page() + if page in ("auto", "quick"): + return + if s == self._default(page): + persistent._file_page_name.pop(int(page), None) + else: + persistent._file_page_name[int(page)] = s + + screen file_slots(title): - default page_name_value = FilePageNameInputValue(pattern=_("Page {}"), auto=_("Automatic saves"), quick=_("Quick saves")) + default page_name_value = VnPageNameInputValue(pattern=_("Page {}"), auto=_("Automatic saves"), quick=_("Quick saves")) + + $ loading = title != _("Save") use game_menu(title): @@ -640,7 +781,7 @@ screen file_slots(title): ## buttons do. order_reverse True - ## The page name, which can be edited by clicking on a button. + ## The page name, which can be edited by clicking on it. button: style "page_label" @@ -652,110 +793,227 @@ screen file_slots(title): style "page_label_text" value page_name_value - ## The grid of file slots. + ## The slots of this page, one entry per row. grid gui.file_slot_cols gui.file_slot_rows: style_prefix "slot" xalign 0.5 - yalign 0.5 + ypos 70 spacing gui.slot_spacing for i in range(gui.file_slot_cols * gui.file_slot_rows): $ slot = i + 1 + $ info = FileJson(slot) - button: - action FileAction(slot) + fixed: + style "slot_fixed" - has vbox + button: + action FileAction(slot) + if info is None: + style "slot_empty_button" - add FileScreenshot(slot) xalign 0.5 + hbox: + spacing 34 + yalign 0.5 - text FileTime(slot, format=_("{#file_time}%A, %B %d %Y, %H:%M"), empty=_("empty slot")): - style "slot_time_text" + frame: + style "slot_thumb_frame" + if info is None: + frame: + style "slot_thumb_blank" + text vn_diamond style "slot_thumb_empty" + else: + add Transform(FileScreenshot(slot), xysize=gui.vn_slot_thumb) - text FileSaveName(slot): - style "slot_name_text" + vbox: + yalign 0.5 + spacing 6 - key "save_delete" action FileDelete(slot) + if info is None: + text _("empty slot") style "slot_empty_text" + else: + text (info.get("vn_scene") or FileSaveName(slot) or _("Saved game")): + style "slot_scene_text" + if info.get("vn_line"): + hbox: + spacing 14 + if info.get("vn_who"): + text info["vn_who"] style "slot_who_text" + text ("«" + info["vn_line"] + "»") style "slot_line_text" + text FileTime(slot, format=_("{#vn_file_time}%A, %d/%m/%Y · %H:%M")): + style "slot_time_text" + + key "save_delete" action FileDelete(slot) + + if info is not None: + textbutton _("Delete"): + style "slot_delete_button" + action FileDelete(slot) ## Buttons to access other pages. - vbox: + hbox: style_prefix "page" xalign 0.5 yalign 1.0 + yoffset -6 + spacing gui.page_spacing - hbox: - xalign 0.5 - - spacing gui.page_spacing - - textbutton _("<") action FilePagePrevious() - key "save_page_prev" action FilePagePrevious() + textbutton "‹" action FilePagePrevious(auto=loading, quick=loading) text_style "page_arrow_text" + key "save_page_prev" action FilePagePrevious(auto=loading, quick=loading) + ## Saving into the automatic or quick slots makes no sense, so + ## those pages are only offered when loading. + if loading: if config.has_autosave: - textbutton _("{#auto_page}A") action FilePage("auto") + textbutton _("Autosaves") action FilePage("auto") if config.has_quicksave: - textbutton _("{#quick_page}Q") action FilePage("quick") + textbutton _("Quick saves") action FilePage("quick") - ## range(1, 10) gives the numbers from 1 to 9. - for page in range(1, 10): - textbutton "[page]" action FilePage(page) + text vn_diamond style "page_separator" - textbutton _(">") action FilePageNext() - key "save_page_next" action FilePageNext() + ## range(1, 10) gives the numbers from 1 to 9. + for page in range(1, 10): + textbutton vn_roman(page) action FilePage(page) - if config.has_sync: - if CurrentScreenName() == "save": - textbutton _("Upload Sync"): - action UploadSync() - xalign 0.5 - else: - textbutton _("Download Sync"): - action DownloadSync() - xalign 0.5 + textbutton "›" action FilePageNext(auto=loading, quick=loading) text_style "page_arrow_text" + key "save_page_next" action FilePageNext(auto=loading, quick=loading) +## Size of the slot thumbnails (config.thumbnail_* is the saved size). +define gui.vn_slot_thumb = (256, 144) + style page_label is gui_label style page_label_text is gui_label_text style page_button is gui_button style page_button_text is gui_button_text +style page_arrow_text is page_button_text +style page_separator is gui_text +style slot_fixed is fixed style slot_button is gui_button +style slot_empty_button is slot_button style slot_button_text is gui_button_text -style slot_time_text is slot_button_text -style slot_name_text is slot_button_text +style slot_thumb_frame is empty +style slot_thumb_blank is empty +style slot_thumb_empty is gui_text +style slot_scene_text is gui_text +style slot_who_text is gui_text +style slot_line_text is gui_text +style slot_time_text is gui_text +style slot_empty_text is gui_text +style slot_delete_button is gui_button +style slot_delete_button_text is gui_button_text style page_label: - xpadding 75 - ypadding 5 + xpadding 60 + ypadding 4 xalign 0.5 style page_label_text: textalign 0.5 layout "subtitle" + size 32 + italic True + kerning 2 + color gui.accent_color hover_color gui.hover_color style page_button: properties gui.button_properties("page_button") + yalign 0.5 style page_button_text: properties gui.text_properties("page_button") + size 28 + kerning 2 + +style page_arrow_text: + font "DejaVuSans.ttf" + size 40 + +style page_separator: + size 16 + color "#c9a25b90" + yalign 0.5 + xmargin 18 + +style slot_fixed: + xsize 1360 + ysize 156 style slot_button: - properties gui.button_properties("slot_button") + xfill True + yfill True + padding (18, 10, 18, 10) + background Frame("gui/vn/card_[prefix_]background.png", 12, 12) -style slot_button_text: - properties gui.text_properties("slot_button") +style slot_empty_button: + background Frame("gui/vn/card_empty.png", 12, 12) + hover_background Frame("gui/vn/card_hover_background.png", 12, 12) + +style slot_thumb_frame: + padding (2, 2) + background Solid("#c9a25b70") + yalign 0.5 + +style slot_thumb_blank: + xysize gui.vn_slot_thumb + background Solid("#0b0907") + +style slot_thumb_empty: + align (0.5, 0.5) + size 22 + color "#c9a25b60" + +style slot_scene_text: + size 30 + kerning 2 + color gui.accent_color + hover_color gui.hover_color + xmaximum 860 + +style slot_who_text: + size 23 + color "#efe6d290" + +style slot_line_text: + size 24 + italic True + color "#efe6d2" + xmaximum 760 + +style slot_time_text: + size 21 + color "#efe6d290" + +style slot_empty_text: + size 26 + italic True + color "#efe6d260" + hover_color gui.hover_color + +style slot_delete_button: + xalign 1.0 + yalign 0.5 + xoffset -28 + padding (14, 6) + +style slot_delete_button_text: + size 22 + kerning 1 + idle_color "#efe6d2a8" + hover_color "#e6866f" ## Preferences screen ########################################################## ## ## The preferences screen allows the player to configure the game to better suit -## themselves. +## themselves. Each group of choices sits on its own framed panel. ## ## https://www.renpy.org/doc/html/screen_special.html#preferences @@ -766,88 +1024,113 @@ screen preferences(): use game_menu(_("Preferences"), scroll="viewport"): vbox: + spacing 30 hbox: box_wrap True + spacing 30 + box_wrap_spacing 30 if renpy.variant("pc") or renpy.variant("web"): - vbox: - style_prefix "radio" - label _("Display") - textbutton _("Window") action Preference("display", "window") - textbutton _("Fullscreen") action Preference("display", "fullscreen") + frame: + style "pref_panel" + vbox: + style_prefix "radio" + label _("Display") + textbutton _("Window") action Preference("display", "window") + textbutton _("Fullscreen") action Preference("display", "fullscreen") - vbox: - style_prefix "check" - label _("Skip") - textbutton _("Unseen Text") action Preference("skip", "toggle") - textbutton _("After Choices") action Preference("after choices", "toggle") - textbutton _("Transitions") action InvertSelected(Preference("transitions", "toggle")) + frame: + style "pref_panel" + vbox: + style_prefix "check" + label _("Skip") + textbutton _("Unseen Text") action Preference("skip", "toggle") + textbutton _("After Choices") action Preference("after choices", "toggle") + textbutton _("Transitions") action InvertSelected(Preference("transitions", "toggle")) if len(vn_art_styles) > 1: - vbox: - style_prefix "radio" - label "@@ART_STYLE_TITLE@@" - for style_id, style_label in vn_art_styles: - textbutton style_label action SetField(persistent, "art_style", style_id) + frame: + style "pref_panel" + vbox: + style_prefix "radio" + label "@@ART_STYLE_TITLE@@" + for style_id, style_label in vn_art_styles: + textbutton style_label action SetField(persistent, "art_style", style_id) - ## Additional vboxes of type "radio_pref" or "check_pref" can be + if len(vn_languages) > 1: + + frame: + style "pref_panel" + vbox: + style_prefix "radio" + label _("Language") + ## Each language under its own name, so it can be found in any. + for lang, lang_label in vn_languages: + textbutton lang_label action [Function(vn_set_language, lang), Language(lang)] + + ## Additional panels of type "radio_pref" or "check_pref" can be ## added here, to add additional creator-defined preferences. - null height (4 * gui.pref_spacing) - hbox: style_prefix "slider" box_wrap True + spacing 30 + box_wrap_spacing 30 - vbox: + frame: + style "pref_panel" + vbox: - label _("Text Speed") + label _("Text Speed") - bar value Preference("text speed") + bar value Preference("text speed") - label _("Auto-Forward Time") + label _("Auto-Forward Time") - bar value Preference("auto-forward time") + bar value Preference("auto-forward time") - vbox: + frame: + style "pref_panel" + vbox: - if config.has_music: - label _("Music Volume") + if config.has_music: + label _("Music Volume") - hbox: - bar value Preference("music volume") + hbox: + bar value Preference("music volume") - if config.has_sound: + if config.has_sound: - label _("Sound Volume") + label _("Sound Volume") - hbox: - bar value Preference("sound volume") + hbox: + bar value Preference("sound volume") - if config.sample_sound: - textbutton _("Test") action Play("sound", config.sample_sound) + if config.sample_sound: + textbutton _("Test") action Play("sound", config.sample_sound) - if config.has_voice: - label _("Voice Volume") + if config.has_voice: + label _("Voice Volume") - hbox: - bar value Preference("voice volume") + hbox: + bar value Preference("voice volume") - if config.sample_voice: - textbutton _("Test") action Play("voice", config.sample_voice) + if config.sample_voice: + textbutton _("Test") action Play("voice", config.sample_voice) - if config.has_music or config.has_sound or config.has_voice: - null height gui.pref_spacing + if config.has_music or config.has_sound or config.has_voice: + null height gui.pref_spacing - textbutton _("Mute All"): - action Preference("all mute", "toggle") - style "mute_all_button" + textbutton _("Mute All"): + action Preference("all mute", "toggle") + style "mute_all_button" +style pref_panel is empty style pref_label is gui_label style pref_label_text is gui_label_text style pref_vbox is vbox @@ -874,15 +1157,22 @@ style slider_pref_vbox is pref_vbox style mute_all_button is check_button style mute_all_button_text is check_button_text +style pref_panel: + background Frame("gui/vn/card_background.png", 12, 12) + padding (30, 22, 30, 28) + style pref_label: top_margin gui.pref_spacing - bottom_margin 3 + bottom_margin 8 style pref_label_text: yalign 1.0 + size 28 + kerning 2 + color gui.accent_color style pref_vbox: - xsize 338 + xsize 370 style radio_vbox: spacing gui.pref_button_spacing @@ -916,14 +1206,13 @@ style slider_button_text: properties gui.text_properties("slider_button") style slider_vbox: - xsize 675 + xsize 580 ## History screen ############################################################## ## -## This is a screen that displays the dialogue history to the player. While -## there isn't anything special about this screen, it does have to access the -## dialogue history stored in _history_list. +## This is a screen that displays the dialogue history to the player, each entry +## under a faint rule. It accesses the dialogue history in _history_list. ## ## https://www.renpy.org/doc/html/history.html @@ -982,6 +1271,9 @@ style history_label_text is gui_label_text style history_window: xfill True ysize gui.history_height + top_padding 18 + bottom_padding 18 + background Frame("gui/vn/hairline.png", 0, 1, 0, 0) style history_name: xpos gui.history_name_xpos @@ -992,6 +1284,8 @@ style history_name: style history_name_text: min_width gui.history_name_width textalign gui.history_name_xalign + size 28 + kerning 1 style history_text: xpos gui.history_text_xpos @@ -1001,12 +1295,15 @@ style history_text: min_width gui.history_text_width textalign gui.history_text_xalign layout ("subtitle" if gui.history_text_xalign else "tex") + size 28 style history_label: xfill True style history_label_text: xalign 0.5 + italic True + color "#efe6d2a0" ## Help screen ################################################################# @@ -1026,9 +1323,11 @@ screen help(): style_prefix "help" vbox: - spacing 23 + spacing 16 hbox: + xalign 0.5 + spacing 20 textbutton _("Keyboard") action SetScreenVariable("device", "keyboard") textbutton _("Mouse") action SetScreenVariable("device", "mouse") @@ -1036,6 +1335,8 @@ screen help(): if GamepadExists(): textbutton _("Gamepad") action SetScreenVariable("device", "gamepad") + null height 10 + if device == "keyboard": use keyboard_help elif device == "mouse": @@ -1155,20 +1456,28 @@ style help_text is gui_text style help_button: properties gui.button_properties("help_button") - xmargin 12 + padding (26, 8, 20, 8) + background Frame("gui/vn/nav_[prefix_]background.png", 6, 0) style help_button_text: properties gui.text_properties("help_button") + size 30 + kerning 1 style help_label: - xsize 375 - right_padding 30 + xsize 420 + right_padding 36 style help_label_text: - size gui.text_size + size 28 + color gui.accent_color xalign 1.0 textalign 1.0 +style help_text: + size 28 + xmaximum 880 + ################################################################################ @@ -1179,7 +1488,7 @@ style help_label_text: ## Confirm screen ############################################################## ## ## The confirm screen is called when Ren'Py wants to ask the player a yes or no -## question. +## question: a framed plate between two gold rules. ## ## https://www.renpy.org/doc/html/screen_special.html#confirm @@ -1192,14 +1501,16 @@ screen confirm(message, yes_action, no_action): style_prefix "confirm" - add "gui/overlay/confirm.png" + add Solid("#000000b8") frame: vbox: xalign .5 yalign .5 - spacing 45 + spacing 36 + + add "vn_rule" xalign 0.5 label _(message): style "confirm_prompt" @@ -1207,7 +1518,7 @@ screen confirm(message, yes_action, no_action): hbox: xalign 0.5 - spacing 150 + spacing 120 textbutton _("Yes") action yes_action textbutton _("No") action no_action @@ -1223,20 +1534,27 @@ style confirm_button is gui_medium_button style confirm_button_text is gui_medium_button_text style confirm_frame: - background Frame([ "gui/confirm_frame.png", "gui/frame.png"], gui.confirm_frame_borders, tile=gui.frame_tile) - padding gui.confirm_frame_borders.padding + background Frame("gui/vn/card_background.png", 12, 12) + padding (90, 54, 90, 54) xalign .5 yalign .5 + xmaximum 1200 style confirm_prompt_text: textalign 0.5 layout "subtitle" + size 34 + color "#efe6d2" style confirm_button: properties gui.button_properties("confirm_button") + padding (40, 8) + background Frame("gui/vn/nav_[prefix_]background.png", 6, 0) style confirm_button_text: properties gui.text_properties("confirm_button") + size 36 + kerning 3 ## Skip indicator screen ####################################################### @@ -1282,12 +1600,15 @@ style skip_text is gui_text style skip_triangle is skip_text style skip_frame: + xpos 36 ypos gui.skip_ypos - background Frame("gui/skip.png", gui.skip_frame_borders, tile=gui.frame_tile) - padding gui.skip_frame_borders.padding + background Frame("gui/vn/card_background.png", 12, 12) + padding (28, 12, 28, 12) style skip_text: - size gui.notify_text_size + size 26 + kerning 2 + color gui.accent_color style skip_triangle: ## We have to use a font that has the BLACK RIGHT-POINTING SMALL TRIANGLE @@ -1308,7 +1629,10 @@ screen notify(message): style_prefix "notify" frame at notify_appear: - text "[message!tq]" + hbox: + spacing 16 + text vn_diamond style "notify_mark" + text "[message!tq]" timer 3.25 action Hide('notify') @@ -1323,15 +1647,23 @@ transform notify_appear: style notify_frame is empty style notify_text is gui_text +style notify_mark is notify_text style notify_frame: + xalign 0.5 ypos gui.notify_ypos - - background Frame("gui/notify.png", gui.notify_frame_borders, tile=gui.frame_tile) - padding gui.notify_frame_borders.padding + background Frame("gui/vn/card_background.png", 12, 12) + padding (36, 14, 40, 14) style notify_text: properties gui.text_properties("notify") + size 28 + color "#efe6d2" + +style notify_mark: + size 16 + color gui.accent_color + yalign 0.5 ## NVL screen ################################################################## @@ -1563,15 +1895,25 @@ screen quick_menu(): if quick_menu: - hbox: - style "quick_menu" - style_prefix "quick" + frame: + style "quick_frame" - textbutton _("Back") action Rollback() - textbutton _("Skip") action Skip() alternate Skip(fast=True, confirm=True) - textbutton _("Auto") action Preference("auto-forward", "toggle") - textbutton _("Menu") action ShowMenu() + hbox: + style "quick_menu" + style_prefix "quick" + textbutton _("Back") action Rollback() + textbutton _("Skip") action Skip() alternate Skip(fast=True, confirm=True) + textbutton _("Auto") action Preference("auto-forward", "toggle") + textbutton _("Menu") action ShowMenu() + + +## On touch screens the quick menu has bigger buttons: it goes to the top right +## corner, clear of the dialogue. +style quick_frame: + variant "touch" + xalign 1.0 + yalign 0.0 style window: variant "small" @@ -1589,30 +1931,116 @@ style nvl_window: variant "small" background "gui/phone/nvl.png" -style main_menu_frame: +style navigation_vbox: variant "small" - background "gui/phone/overlay/main_menu.png" + spacing 4 -style game_menu_outer_frame: +style navigation_button_text: variant "small" - background "gui/phone/overlay/game_menu.png" + size 40 + +style main_menu_vbox: + variant "small" + ypos 90 + +style main_nav_vbox: + variant "small" + ypos 500 + spacing 0 + +style main_nav_button_text: + variant "small" + size 46 style game_menu_navigation_frame: variant "small" - xsize 510 + xsize 440 + background Fixed(Solid("#0b0907d8"), Solid("#c9a25b50", xsize=1, ysize=960, xpos=439, ypos=60)) + +style game_menu_work_title: + variant "small" + xpos 220 + +style game_menu_work_rule: + variant "small" + xpos 220 + +style game_menu_title_vbox: + variant "small" + xpos 1190 + ypos 30 style game_menu_content_frame: variant "small" - top_margin 0 + xpos 500 + ypos 200 + xsize 1380 + ysize 840 -style game_menu_viewport: +style slot_fixed: variant "small" - xsize 1305 + ysize 206 + +style slot_scene_text: + variant "small" + size 40 + +style slot_who_text: + variant "small" + size 32 + +style slot_line_text: + variant "small" + size 32 + +style slot_time_text: + variant "small" + size 30 + +style slot_empty_text: + variant "small" + size 36 + +style slot_delete_button_text: + variant "small" + size 32 + +style page_button_text: + variant "small" + size 38 style pref_vbox: variant "small" xsize 600 +style pref_label_text: + variant "small" + size 40 + +style history_name_text: + variant "small" + size 36 + +style history_text: + variant "small" + size 36 + +style confirm_prompt_text: + variant "small" + size 46 + +style confirm_button_text: + variant "small" + size 50 + +style notify_text: + variant "small" + size 38 + +style about_text: + variant "small" + size 38 + style bar: variant "small" ysize gui.bar_size diff --git a/src/vnpipe/renpy_templates/game/styles.rpy b/src/vnpipe/renpy_templates/game/styles.rpy index b3c51bc..ecb1b47 100644 --- a/src/vnpipe/renpy_templates/game/styles.rpy +++ b/src/vnpipe/renpy_templates/game/styles.rpy @@ -33,6 +33,17 @@ screen vn_art_style_picker(): null height 40 + if len(vn_languages) > 1: + hbox: + xalign 0.5 + spacing 40 + for lang, lang_label in vn_languages: + textbutton lang_label: + style_prefix "vn_language" + action [Function(vn_set_language, lang), Language(lang)] + + null height 20 + for style_id, style_label in vn_art_styles: textbutton style_label: style_prefix "vn_picker" @@ -52,9 +63,21 @@ style vn_picker_button_text: xalign 0.5 text_align 0.5 -## Shown once, before the first scene, when there is a choice to make. +style vn_language_button is gui_button +style vn_language_button_text is gui_button_text + +style vn_language_button: + padding (16, 6) + +style vn_language_button_text: + size 32 + selected_color gui.accent_color + selected_underline True + +## Shown once, before the first scene, when there is a choice to make (an art style, and +## the language when the game has translations). label vn_pick_art_style: - if len(vn_art_styles) > 1 and not persistent.art_style_chosen: + if (len(vn_art_styles) > 1 or len(vn_languages) > 1) and not persistent.art_style_chosen: scene black $ quick_menu = False call screen vn_art_style_picker diff --git a/src/vnpipe/renpy_templates/tl/spanish/common.rpy b/src/vnpipe/renpy_templates/tl/spanish/common.rpy new file mode 100644 index 0000000..1231517 --- /dev/null +++ b/src/vnpipe/renpy_templates/tl/spanish/common.rpy @@ -0,0 +1,1121 @@ +## Ren'Py's own UI strings in Spanish (Spain): the Ren'Py SDK translation +## (launcher/game/tl/spanish/common.rpy, MIT licence) with corrections and the strings it +## lacks. Copied into game/tl/spanish/ by `vnpipe renpy` when [ui].language = "spanish". + +translate spanish strings: + + old "{#weekday}Monday" + new "Lunes" + + old "{#weekday}Tuesday" + new "Martes" + + old "{#weekday}Wednesday" + new "Miércoles" + + old "{#weekday}Thursday" + new "Jueves" + + old "{#weekday}Friday" + new "Viernes" + + old "{#weekday}Saturday" + new "Sábado" + + old "{#weekday}Sunday" + new "Domingo" + + old "{#weekday_short}Mon" + new "Lun." + + old "{#weekday_short}Tue" + new "Mar." + + old "{#weekday_short}Wed" + new "Mié." + + old "{#weekday_short}Thu" + new "Jue." + + old "{#weekday_short}Fri" + new "Vie." + + old "{#weekday_short}Sat" + new "Sab." + + old "{#weekday_short}Sun" + new "Dom." + + old "{#month}January" + new "Enero" + + old "{#month}February" + new "Febrero" + + old "{#month}March" + new "Marzo" + + old "{#month}April" + new "Abril" + + old "{#month}May" + new "Mayo" + + old "{#month}June" + new "Junio" + + old "{#month}July" + new "Julio" + + old "{#month}August" + new "Agosto" + + old "{#month}September" + new "Septiembre" + + old "{#month}October" + new "Octubre" + + old "{#month}November" + new "Noviembre" + + old "{#month}December" + new "Diciembre" + + old "{#month_short}Jan" + new "Ene." + + old "{#month_short}Feb" + new "Feb." + + old "{#month_short}Mar" + new "Mar." + + old "{#month_short}Apr" + new "Abr." + + old "{#month_short}May" + new "May." + + old "{#month_short}Jun" + new "Jun." + + old "{#month_short}Jul" + new "Jul." + + old "{#month_short}Aug" + new "Ago." + + old "{#month_short}Sep" + new "Sep." + + old "{#month_short}Oct" + new "Oct." + + old "{#month_short}Nov" + new "Nov." + + old "{#month_short}Dec" + new "Dic." + + old "%b %d, %H:%M" + new "%d de %b, %H:%M" + + old "Save slot %s: [text]" + new "Guardar ranura %s: [text]" + + old "Load slot %s: [text]" + new "Cargar ranura %s: [text]" + + old "Delete slot [text]" + new "Borrar partida [text]" + + old "File page auto" + new "Página de autoguardado" + + old "File page quick" + new "Página de guardado rápido" + + old "File page [text]" + new "Página [text]" + + old "Next file page." + new "Página siguiente." + + old "Previous file page." + new "Página anterior." + + old "Quick save complete." + new "Guardado rápido completado." + + old "Quick save." + new "Guardado rápido." + + old "Quick load." + new "Carga rápida." + + old "Language [text]" + new "Idioma [text]" + + old "The interactive director is not enabled here." + new "El director interactivo no está habilitado aquí." + + old "⬆" + new "⬆" + + old "⬇" + new "⬇" + + old "Done" + new "Hecho" + + old "(statement)" + new "(sentencia)" + + old "(tag)" + new "(etiqueta)" + + old "(attributes)" + new "(atributos)" + + old "(transform)" + new "(transformación)" + + old "(transition)" + new "(transición)" + + old "(channel)" + new "(canal)" + + old "(filename)" + new "(archivo)" + + old "Change" + new "Cambiar" + + old "Add" + new "Añadir" + + old "Cancel" + new "Cancelar" + + old "Remove" + new "Eliminar" + + old "Statement:" + new "Sentencia:" + + old "Tag:" + new "Etiqueta:" + + old "Attributes:" + new "Atributos:" + + old "Transforms:" + new "Transformaciones:" + + old "Behind:" + new "Detrás:" + + old "Transition:" + new "Transición:" + + old "Channel:" + new "Canal:" + + old "Audio Filename:" + new "Archivo de audio:" + + old "Are you sure?" + new "¿Seguro?" + + old "Are you sure you want to delete this save?" + new "¿Seguro que quieres borrar esta partida?" + + old "Are you sure you want to overwrite your save?" + new "¿Seguro que quieres sobrescribir esta partida?" + + old "Loading will lose unsaved progress.\nAre you sure you want to do this?" + new "Al cargar se perderá el progreso no guardado.\n¿Seguro que quieres continuar?" + + old "Are you sure you want to quit?" + new "¿Seguro que quieres salir?" + + old "Are you sure you want to return to the main menu?\nThis will lose unsaved progress." + new "¿Seguro que quieres volver al menú principal?\nSe perderá el progreso no guardado." + + old "Are you sure you want to end the replay?" + new "¿Seguro que quieres finalizar la repetición?" + + old "Are you sure you want to begin skipping?" + new "¿Seguro que quieres empezar a saltar?" + + old "Are you sure you want to skip to the next choice?" + new "¿Seguro que quieres saltar hasta la próxima elección?" + + old "Are you sure you want to skip unseen dialogue to the next choice?" + new "¿Seguro que quieres saltar el texto no leído hasta la próxima elección?" + + old "Failed to save screenshot as %s." + new "No se pudo guardar la captura de pantalla como %s." + + old "Saved screenshot as %s." + new "Captura de pantalla guardada como %s." + + old "Self-voicing disabled." + new "Lectura en voz alta desactivada." + + old "Clipboard voicing enabled. " + new "Lectura al portapapeles activada. " + + old "Self-voicing enabled. " + new "Lectura en voz alta activada. " + + old "bar" + new "bar" + + old "selected" + new "seleccionado" + + old "viewport" + new "viewport" + + old "horizontal scroll" + new "deslizamiento horizontal" + + old "vertical scroll" + new "deslizamiento vertical" + + old "activate" + new "activar" + + old "deactivate" + new "desactivar" + + old "increase" + new "aumentar" + + old "decrease" + new "disminuir" + + old "Skip Mode" + new "Saltando" + + old "This program contains free software under a number of licenses, including the MIT License and GNU Lesser General Public License. A complete list of software, including links to full source code, can be found {a=https://www.renpy.org/l/license}here{/a}." + new "Este programa contiene {i}software{/i} libre sujeto a diversas licencias que incluyen la licencia MIT y la {i}GNU Lesser General Public License{/i} (Licencia Pública General Reducida de GNU). Puedes encontrar la lista completa {i}de software{/i}, con enlaces al código fuente completo, {a=https://www.renpy.org/l/license}aquí (en inglés){/a}." + + old "display" + new "pantalla" + + old "transitions" + new "transiciones" + + old "skip transitions" + new "saltar transiciones" + + old "video sprites" + new "sprites de vídeo" + + old "show empty window" + new "muestra ventana vacía" + + old "text speed" + new "velocidad de texto" + + old "joystick" + new "joystick" + + old "joystick..." + new "joystick..." + + old "skip" + new "saltar" + + old "skip unseen [text]" + new "saltar no leído [text]" + + old "skip unseen text" + new "saltar texto no leído" + + old "begin skipping" + new "empezar a saltar" + + old "after choices" + new "tras elecciones" + + old "skip after choices" + new "saltar tras elecciones" + + old "auto-forward time" + new "tiempo autoavance" + + old "auto-forward" + new "autoavance" + + old "Auto forward" + new "Autoavance" + + old "auto-forward after click" + new "autoavanzar después del clic" + + old "automatic move" + new "movimiento automático" + + old "wait for voice" + new "espera la voz" + + old "voice sustain" + new "mantener voz" + + old "self voicing" + new "lectura en voz alta" + + old "clipboard voicing" + new "voz en clipboard" + + old "debug voicing" + new "depurar voz" + + old "emphasize audio" + new "enfatizar audio" + + old "rollback side" + new "lado de retroceso" + + old "gl powersave" + new "gl ahorro de energía" + + old "gl framerate" + new "gl cuadros por s." + + old "gl tearing" + new "gl tearing" + + old "music volume" + new "volumen música" + + old "sound volume" + new "volumen sonido" + + old "voice volume" + new "volumen voz" + + old "mute music" + new "silenciar música" + + old "mute sound" + new "silenciar sonido" + + old "mute voice" + new "silenciar voz" + + old "mute all" + new "silenciar todo" + + old "Clipboard voicing enabled. Press 'shift+C' to disable." + new "Lectura al portapapeles activada. Pulsa Mayús+C para desactivarla." + + old "Self-voicing would say \"[renpy.display.tts.last]\". Press 'alt+shift+V' to disable." + new "La lectura en voz alta diría \"[renpy.display.tts.last]\". Pulsa Alt+Mayús+V para desactivarla." + + old "Self-voicing enabled. Press 'v' to disable." + new "Lectura en voz alta activada. Pulsa V para desactivarla." + + old "Empty Slot." + new "Espacio libre." + + old "Previous" + new "Anterior" + + old "Next" + new "Siguiente" + + old "Joystick Mapping" + new "Mapeado del mando" + + old "Developer Menu" + new "Menú de desarrollo" + + old "Interactive Director (D)" + new "Director interactivo (D)" + + old "Reload Game (Shift+R)" + new "Reiniciar juego (Shift+R)" + + old "Console (Shift+O)" + new "Consola (Mayús.+O)" + + old "Variable Viewer" + new "Visor de variables" + + old "Image Location Picker" + new "Selector de posición en imágenes" + + old "Filename List" + new "Lista de archivos" + + old "Show Image Load Log (F4)" + new "Mostrar registro de carga de imagen (F4)" + + old "Hide Image Load Log (F4)" + new "Ocultar registro de carga de imagen (F4)" + + old "Image Attributes" + new "Image Attributes" + + old "[name] [attributes] (hidden)" + new "[name] [attributes] (hidden)" + + old "[name] [attributes]" + new "[name] [attributes]" + + old "Nothing to inspect." + new "Nada para inspeccionar." + + old "Hide deleted" + new "Hide deleted" + + old "Show deleted" + new "Show deleted" + + old "Return to the developer menu" + new "Volver al menú de desarrollo" + + old "Rectangle: %r" + new "Rectángulo: %r" + + old "Mouse position: %r" + new "Posición del ratón: %r" + + old "Right-click or escape to quit." + new "Clic-derecho o escape para salir." + + old "Rectangle copied to clipboard." + new "Rectángulo copiado al portapapeles." + + old "Position copied to clipboard." + new "Posición copiada al portapapeles." + + old "Type to filter: " + new "Escribe para filtrar: " + + old "Textures: [tex_count] ([tex_size_mb:.1f] MB)" + new "Texturas: [tex_count] ([tex_size_mb:.1f] MB)" + + old "Image cache: [cache_pct:.1f]% ([cache_size_mb:.1f] MB)" + new "Caché de imagen: [cache_pct:.1f]% ([cache_size_mb:.1f] MB)" + + old "✔ " + new "✔ " + + old "✘ " + new "✘ " + + old "\n{color=#cfc}✔ predicted image (good){/color}\n{color=#fcc}✘ unpredicted image (bad){/color}\n{color=#fff}Drag to move.{/color}" + new "\n{color=#cfc}✔ imagen prevista (correcto){/color}\n{color=#fcc}✘ imagen no prevista (fallido){/color}\n{color=#fff}Arrastra para mover.{/color}" + + old "Displayable Inspector" + new "Inspector de visualizables" + + old "Size" + new "Tamaño" + + old "Style" + new "Estilo" + + old "Location" + new "Ubicación" + + old "Inspecting Styles of [displayable_name!q]" + new "Inspeccionando estilos de [displayable_name!q]" + + old "displayable:" + new "visualizable:" + + old " (no properties affect the displayable)" + new " (no hay propiedades que afecten la visualización)" + + old " (default properties omitted)" + new " (propiedades por defecto omitidas)" + + old "" + new "" + + old "a" + new "a" + + old "q" + new "r" + + old "Contacting App Store\nPlease Wait..." + new "Contactando con la App Store\nEspera, por favor..." + + old "The Ren'Py Updater is not supported on mobile devices." + new "El Actualizador de Ren'Py no es compatible con dispositivos móviles." + + old "An error is being simulated." + new "Se simula un error." + + old "Either this project does not support updating, or the update status file was deleted." + new "O bien este proyecto no es compatible con la actualización o el archivo de estado de la actualización se ha eliminado." + + old "This account does not have permission to perform an update." + new "Esta cuenta no tiene permiso para realizar una actualización." + + old "This account does not have permission to write the update log." + new "Esta cuenta no tiene permiso para escribir en el registro de actualización." + + old "Could not verify update signature." + new "No se pudo verificar la actualización de firmas." + + old "The update file was not downloaded." + new "El archivo de actualización no se ha descargado." + + old "The update file does not have the correct digest - it may have been corrupted." + new "El archivo de actualización no tiene el 'digest' correcto - es posible que esté dañado." + + old "While unpacking {}, unknown type {}." + new "Tipo desconocido {1} al desempaquetar {0}." + + old "Updater" + new "Actualizador" + + old "An error has occurred:" + new "Ha sucedido un error:" + + old "Checking for updates." + new "Buscando actualizaciones." + + old "This program is up to date." + new "Este programa está actualizado." + + old "[u.version] is available. Do you want to install it?" + new "[u.version] está disponible. ¿Quieres instalarla?" + + old "Preparing to download the updates." + new "Preparando para descargar la actualización." + + old "Downloading the updates." + new "Descargando la actualización." + + old "Unpacking the updates." + new "Desempaquetando la actualización." + + old "Finishing up." + new "Finalizando." + + old "The updates have been installed. The program will restart." + new "La actualización ha sido instalada. El programa se reiniciará." + + old "The updates have been installed." + new "La actualización ha sido instalada." + + old "The updates were cancelled." + new "La actualización ha sido cancelada." + + old "Proceed" + new "Continuar" + + old "Image [index] of [count] locked." + new "Imagen [index] de [count] bloqueada." + + old "prev" + new "ant." + + old "next" + new "sig." + + old "slideshow" + new "presentación" + + old "return" + new "volver" + + old "Renderer" + new "Renderizador" + + old "Automatically Choose" + new "Escoger automáticamente" + + old "Force Angle/DirectX Renderer" + new "Forzar 'Angle/DirectX Renderer'" + + old "Force OpenGL Renderer" + new "Forzar renderizador OpenGL" + + old "Force Software Renderer" + new "Forzar renderizado por software" + + old "NPOT" + new "NPOT" + + old "Enable" + new "Activar" + + old "Disable" + new "Desactivar" + + old "Powersave" + new "Ahorro de energía" + + old "Framerate" + new "Cuadros por s." + + old "Screen" + new "Pantalla" + + old "60" + new "60" + + old "30" + new "30" + + old "Tearing" + new "Tearing" + + old "Changes will take effect the next time this program is run." + new "Los cambios se aplicarán la próxima vez que el programa se ejecute." + + old "Performance Warning" + new "Aviso de funcionamiento" + + old "This computer is using software rendering." + new "Este ordenador usa 'software rendering'." + + old "This computer is not using shaders." + new "Este ordenador no usa 'shaders'." + + old "This computer is displaying graphics slowly." + new "Este ordenador muestra los gráficos lentamente." + + old "This computer has a problem displaying graphics: [problem]." + new "Este ordenador tiene un problema mostrando los gráficos: [problem]." + + old "Its graphics drivers may be out of date or not operating correctly. This can lead to slow or incorrect graphics display. Updating DirectX could fix this problem." + new "Los controladores gráficos pueden estar obsoletos o no funcionar adecuadamente. Esto puede conllevar que los gráficos se muestren lenta o incorrectamente. Actualizar DirectX puede solucionar este problema." + + old "Its graphics drivers may be out of date or not operating correctly. This can lead to slow or incorrect graphics display." + new "Los controladores gráficos pueden estar obsoletos o no funcionar adecuadamente. Esto puede conllevar que los gráficos se muestren lenta o incorrectamente." + + old "Update DirectX" + new "Actualizar DirectX" + + old "Continue, Show this warning again" + new "Continuar. Mostrar este aviso de nuevo" + + old "Continue, Don't show warning again" + new "Continuar. No mostrar este aviso de nuevo" + + old "Updating DirectX." + new "Actualizando DirectX." + + old "DirectX web setup has been started. It may start minimized in the taskbar. Please follow the prompts to install DirectX." + new "La instalación web de DirectX ha comenzado. Puede haber iniciado minimizada en la barra de tareas. Siga las instrucciones para instalar DirectX." + + old "{b}Note:{/b} Microsoft's DirectX web setup program will, by default, install the Bing toolbar. If you do not want this toolbar, uncheck the appropriate box." + new "{b}Nota:{/b} El programa de instalación de DirectX de Microsoft instalará, por defecto, la barra Bing. Si no desea esta barra, desactive la casilla correspondiente." + + old "When setup finishes, please click below to restart this program." + new "Cuando la instalación acabe, haga clic abajo para reiniciar el programa." + + old "Restart" + new "Reiniciar" + + old "Select Gamepad to Calibrate" + new "Selecciona mando para calibrar" + + old "No Gamepads Available" + new "No hay mandos disponibles" + + old "Calibrating [name] ([i]/[total])" + new "Calibrando [name] ([i]/[total])" + + old "Press or move the [control!s] [kind]." + new "Pulsa o mueve: [control!s] [kind]." + + old "Skip (A)" + new "Salto (A)" + + old "Back (B)" + new "Atrás (B)" + + old "Open" + new "Abrir" + + old "Opens the traceback.txt file in a text editor." + new "Abre el archivo de rastreo 'traceback.txt' en un editor de texto." + + old "Copy" + new "Copiar" + + old "Copies the traceback.txt file to the clipboard." + new "Copiar el archivo traceback.txt al portapapeles." + + old "An exception has occurred." + new "Ha sucedido una excepción." + + old "Rollback" + new "Volver atrás" + + old "Attempts a roll back to a prior time, allowing you to save or choose a different choice." + new "Intenta volver a un momento anterior y permite guardar o escoger una opción diferente." + + old "Ignore" + new "Ignorar" + + old "Ignores the exception, allowing you to continue." + new "Ignora la excepción y permite continuar." + + old "Ignores the exception, allowing you to continue. This often leads to additional errors." + new "Ignora la excepción y permite continuar. Suele conllevar más errores." + + old "Reload" + new "Recargar" + + old "Reloads the game from disk, saving and restoring game state if possible." + new "Recarga el juego del disco, guardando y restaurando la partida si es posible." + + old "Console" + new "Consola" + + old "Opens a console to allow debugging the problem." + new "Abre una consola y permite depurar el problema." + + old "Quits the game." + new "Sale del juego." + + old "Parsing the script failed." + new "Error en el análisis del código." + + old "Opens the errors.txt file in a text editor." + new "Abre el archivo de errores, 'errors.txt', en un editor de texto." + + old "Copies the errors.txt file to the clipboard." + new "Copia el archivo errors.txt al portapapeles." + + old "Copy BBCode" + new "Copiar BBCode" + + old "Copies the traceback.txt file to the clipboard as BBcode for forums like https://lemmasoft.renai.us/." + new "Copia el archivo traceback.txt en el portapapeles como BBcode para foros como https://lemmasoft.renai.us/." + + old "Copy Markdown" + new "Copiar Markdown" + + old "Copies the traceback.txt file to the clipboard as Markdown for Discord." + new "Copia el archivo traceback.txt al portapapeles como Markdown para Discord." + + old "Copies the errors.txt file to the clipboard as BBcode for forums like https://lemmasoft.renai.us/." + new "Copia el archivo errors.txt en el portapapeles como BBcode para foros como https://lemmasoft.renai.us/." + + old "Copies the errors.txt file to the clipboard as Markdown for Discord." + new "Copia el archivo errors.txt al portapapeles como Markdown para Discord." + + old "Font Override" + new "Sobreescribir fuente" + + old "Default" + new "Por defecto" + + old "DejaVu Sans" + new "DejaVu Sans" + + old "Opendyslexic" + new "Opendyslexic" + + old "Text Size Scaling" + new "Escala del tamaño del texto" + + old "Reset" + new "Reiniciar" + + old "Line Spacing Scaling" + new "Escala del interlineado" + + old "Self-Voicing" + new "Lectura en voz alta" + + old "Off" + new "Apagado" + + old "Text-to-speech" + new "Texto a voz" + + old "Clipboard" + new "Portapapeles" + + old "Debug" + new "Depurar" + + old "font transform" + new "transformación de fuente" + + old "font size" + new "tamaño de fuente" + + old "font line spacing" + new "interlineado de la fuente" + + old "The options on this menu are intended to improve accessibility. They may not work with all games, and some combinations of options may render the game unplayable. This is not an issue with the game or engine. For the best results when changing fonts, try to keep the text size the same as it originally was." + new "Las opciones en este menú están destinadas a mejorar la accesibilidad. Es posible que no funcionen con todos los juegos, y algunas combinaciones de opciones pueden hacer que el juego no se pueda jugar. Esto no es un problema con el juego o el motor. Para obtener los mejores resultados al cambiar las fuentes, intente mantener el tamaño del texto igual al original." + + old "High Contrast Text" + new "Texto de alto contraste" + + old "Self-Voicing Volume Drop" + new "Bajada de volumen al leer en voz alta" + + old "self voicing volume drop" + new "bajada de volumen al leer en voz alta" + + old "system cursor" + new "cursor del sistema" + + old "renderer menu" + new "menú de renderizado" + + old "accessibility menu" + new "menú de accesibilidad" + + old "high contrast text" + new "texto de alto contraste" + + old "Force GL Renderer" + new "Forzar renderizador GL" + + old "Force ANGLE Renderer" + new "Forzar renderizador ANGLE" + + old "Force GLES Renderer" + new "Forzar renderizador GLES" + + old "Force GL2 Renderer" + new "Forzar renderizador GL2" + + old "Force ANGLE2 Renderer" + new "Forzar renderizador ANGLE2" + + old "Force GLES2 Renderer" + new "Forzar renderizador GLES2" + + old "Enable (No Blocklist)" + new "Habilitar (sin Blocklist)" + + old "This game requires use of GL2 that can't be initialised." + new "Este juego requiere el uso de GL2 que no se puede inicializar." + + old "The {a=edit:1:log.txt}log.txt{/a} file may contain information to help you determine what is wrong with your computer." + new "El archivo {a=edit:1:log.txt}log.txt{/a} puede contener información para ayudarte a encontrar el problema en tu ordenador." + + old "More details on how to fix this can be found in the {a=[url]}documentation{/a}." + new "Puede encontrar más detalles sobre cómo solucionar este problema en la {a=[url]} documentación {/a}." + + old "Change render options" + new "Cambiar las opciones de renderizado" + + old "Press or move the '[control!s]' [kind]." + new "Pulsa o mueve: '[control!s]' [kind]." + +# Strings missing from the Ren'Py SDK translation (Ren'Py 8.5), added by vnpipe. +translate spanish strings: + + old "Click to play the video." + new "Haz clic para reproducir el vídeo." + + old "Self-voicing support is limited when using a touch screen." + new "La lectura en voz alta es limitada con una pantalla táctil." + + old "Mono Audio" + new "Audio mono" + + old "Kerning" + new "Interletraje" + + old "Accessibility Menu. Use up and down arrows to navigate, and enter to activate buttons and bars." + new "Menú de accesibilidad. Usa las flechas arriba y abajo para moverte, e Intro para activar botones y barras." + + old "Self-Voicing and Audio" + new "Lectura en voz alta y audio" + + old "Text" + new "Texto" + + old "Open [text] directory." + new "Abrir la carpeta [text]." + + old "Click to toggle attribute, right click to toggle negative attribute." + new "Clic para alternar el atributo, clic derecho para alternar el atributo negativo." + + old "Click to set transform, right click to add to transform list." + new "Clic para fijar la transformación, clic derecho para añadirla a la lista." + + old "Customize director.transforms to add more transforms." + new "Modifica director.transforms para añadir más transformaciones." + + old "Click to set, right click to add to behind list." + new "Clic para fijar, clic derecho para añadir a la lista «behind»." + + old "Click to set." + new "Clic para fijar." + + old "Customize director.transitions to add more transitions." + new "Modifica director.transitions para añadir más transiciones." + + old "Customize director.audio_channels to add more channels." + new "Modifica director.audio_channels para añadir más canales." + + old "Are you sure you want to continue where you left off?" + new "¿Seguro que quieres continuar donde lo dejaste?" + + old "This save was created on a different device. Maliciously constructed save files can harm your computer. Do you trust this save's creator and everyone who could have changed the file?" + new "Esta partida se guardó en otro dispositivo. Un archivo de partida manipulado puede dañar tu ordenador. ¿Confías en quien la creó y en cualquiera que haya podido modificar el archivo?" + + old "Do you trust the device the save was created on? You should only choose yes if you are the device's sole user." + new "¿Confías en el dispositivo donde se guardó la partida? Elige «Sí» solo si eres su único usuario." + + old "self voicing enable" + new "activar lectura en voz alta" + + old "self voicing disable" + new "desactivar lectura en voz alta" + + old "clipboard voicing enable" + new "activar lectura al portapapeles" + + old "clipboard voicing disable" + new "desactivar lectura al portapapeles" + + old "debug voicing enable" + new "activar lectura de depuración" + + old "debug voicing disable" + new "desactivar lectura de depuración" + + old "audio when minimized" + new "audio con la ventana minimizada" + + old "audio when unfocused" + new "audio con la ventana en segundo plano" + + old "web cache preload" + new "precarga de la caché web" + + old "voice after game menu" + new "voz tras el menú del juego" + + old "restore window position" + new "restaurar la posición de la ventana" + + old "mono audio" + new "audio mono" + + old "font kerning" + new "interletraje de la fuente" + + old "reset" + new "restablecer" + + old "main volume" + new "volumen general" + + old "mute main" + new "silenciar el volumen general" + + old "Speech Bubble Editor" + new "Editor de bocadillos" + + old "(hide)" + new "(ocultar)" + + old "(clear retained bubbles)" + new "(borrar los bocadillos retenidos)" + + old "Sync downloaded." + new "Sincronización descargada." + + old "Could not connect to the Ren'Py Sync server." + new "No se pudo conectar con el servidor de Ren'Py Sync." + + old "The Ren'Py Sync server timed out." + new "El servidor de Ren'Py Sync no respondió a tiempo." + + old "An unknown error occurred while connecting to the Ren'Py Sync server." + new "Error desconocido al conectar con el servidor de Ren'Py Sync." + + old "The Ren'Py Sync server does not have a copy of this sync. The sync ID may be invalid, or it may have timed out." + new "El servidor de Ren'Py Sync no tiene esta sincronización. Puede que el ID no sea válido o que haya caducado." + + old "Please enter the sync ID you generated.\nNever enter a sync ID you didn't create yourself." + new "Introduce el ID de sincronización que generaste.\nNunca introduzcas un ID que no hayas creado tú." + + old "The sync ID is not in the correct format." + new "El ID de sincronización no tiene el formato correcto." + + old "The sync could not be decrypted." + new "No se pudo descifrar la sincronización." + + old "The sync belongs to a different game." + new "La sincronización pertenece a otro juego." + + old "The sync contains a file with an invalid name." + new "La sincronización contiene un archivo con un nombre no válido." + + old "This will upload your saves to the {a=https://sync.renpy.org}Ren'Py Sync Server{/a}.\nDo you want to continue?" + new "Tus partidas se subirán al {a=https://sync.renpy.org}servidor de Ren'Py Sync{/a}.\n¿Quieres continuar?" + + old "Enter Sync ID" + new "Introduce el ID de sincronización" + + old "This will contact the {a=https://sync.renpy.org}Ren'Py Sync Server{/a}." + new "Se contactará con el {a=https://sync.renpy.org}servidor de Ren'Py Sync{/a}." + + old "Sync Success" + new "Sincronización completada" + + old "The Sync ID is:" + new "El ID de sincronización es:" + + old "You can use this ID to download your save on another device.\nThis sync will expire in an hour.\nRen'Py Sync is supported by {a=https://www.renpy.org/sponsors.html}Ren'Py's Sponsors{/a}." + new "Puedes usar este ID para descargar tus partidas en otro dispositivo.\nLa sincronización caduca en una hora.\nRen'Py Sync existe gracias a los {a=https://www.renpy.org/sponsors.html}mecenas de Ren'Py{/a}." + + old "Continue" + new "Continuar" + + old "Sync Error" + new "Error de sincronización" + + old "Translation identifier: [identifier]" + new "Identificador de traducción: [identifier]" + + old " translates [tl.filename]:[tl.linenumber]" + new " traduce [tl.filename]:[tl.linenumber]" + + old "\n{color=#fff}Copied to clipboard.{/color}" + new "\n{color=#fff}Copiado al portapapeles.{/color}" + + old "No update methods found." + new "No se encontró ningún método de actualización." + + old "Could not download file list: " + new "No se pudo descargar la lista de archivos: " + + old "File list digest does not match." + new "La suma de comprobación de la lista de archivos no coincide." + + old "Preparing to download the game data." + new "Preparando la descarga de los datos del juego." + + old "Downloading the game data." + new "Descargando los datos del juego." + + old "The game data has been downloaded." + new "Los datos del juego se han descargado." + + old "An error occurred when trying to download game data:" + new "Se produjo un error al descargar los datos del juego:" + + old "This game cannot be run until the game data has been downloaded." + new "El juego no puede ejecutarse hasta que se descarguen sus datos." + + old "Retry" + new "Reintentar" diff --git a/src/vnpipe/renpy_templates/tl/spanish/screens.rpy b/src/vnpipe/renpy_templates/tl/spanish/screens.rpy new file mode 100644 index 0000000..e357d22 --- /dev/null +++ b/src/vnpipe/renpy_templates/tl/spanish/screens.rpy @@ -0,0 +1,247 @@ +## The strings of vnpipe's template screens (renpy_templates/game/*.rpy) in Spanish (Spain). +## Keep in step with the template: tests/test_renpy_gen.py checks every _("...") string. + +translate spanish strings: + + old "Back" + new "Atrás" + + old "History" + new "Historial" + + old "Skip" + new "Saltar" + + old "Auto" + new "Auto" + + old "Save" + new "Guardar" + + old "Q.Save" + new "Guardar rápido" + + old "Q.Load" + new "Cargar rápido" + + old "Prefs" + new "Opciones" + + old "Start" + new "Comenzar" + + old "Load" + new "Cargar" + + old "Preferences" + new "Opciones" + + old "End Replay" + new "Terminar la repetición" + + old "Main Menu" + new "Menú principal" + + old "About" + new "Acerca de" + + old "Help" + new "Ayuda" + + old "Quit" + new "Salir" + + old "Return" + new "Volver" + + old "Version [config.version!t]\n" + new "Versión [config.version!t]\n" + + old "Made with {a=https://www.renpy.org/}Ren'Py{/a} [renpy.version_only].\n\n[renpy.license!t]" + new "Hecho con {a=https://www.renpy.org/}Ren'Py{/a} [renpy.version_only].\n\n[renpy.license!t]" + + old "Page {}" + new "Página {}" + + old "Automatic saves" + new "Autoguardado" + + old "Quick saves" + new "Guardado rápido" + + old "empty slot" + new "Espacio libre" + + old "Saved game" + new "Partida guardada" + + old "{#vn_file_time}%A, %d/%m/%Y · %H:%M" + new "{#vn_file_time}%A, %d/%m/%Y · %H:%M" + + old "Delete" + new "Borrar" + + old "Autosaves" + new "Autoguardado" + + old "Display" + new "Pantalla" + + old "Window" + new "Ventana" + + old "Fullscreen" + new "Pantalla completa" + + old "Unseen Text" + new "Texto no leído" + + old "After Choices" + new "Tras las elecciones" + + old "Transitions" + new "Transiciones" + + old "Language" + new "Idioma" + + old "Text Speed" + new "Velocidad del texto" + + old "Auto-Forward Time" + new "Avance automático" + + old "Music Volume" + new "Volumen de la música" + + old "Sound Volume" + new "Volumen de los efectos" + + old "Test" + new "Probar" + + old "Voice Volume" + new "Volumen de las voces" + + old "Mute All" + new "Silenciar todo" + + old "The dialogue history is empty." + new "El historial está vacío." + + old "Keyboard" + new "Teclado" + + old "Mouse" + new "Ratón" + + old "Gamepad" + new "Mando" + + old "Enter" + new "Intro" + + old "Advances dialogue and activates the interface." + new "Avanza el diálogo y activa la interfaz." + + old "Space" + new "Espacio" + + old "Advances dialogue without selecting choices." + new "Avanza el diálogo sin elegir opciones." + + old "Arrow Keys" + new "Flechas" + + old "Navigate the interface." + new "Recorren la interfaz." + + old "Escape" + new "Esc" + + old "Accesses the game menu." + new "Abre el menú del juego." + + old "Ctrl" + new "Ctrl" + + old "Skips dialogue while held down." + new "Salta el diálogo mientras se mantiene pulsada." + + old "Tab" + new "Tab" + + old "Toggles dialogue skipping." + new "Activa o desactiva el salto del diálogo." + + old "Page Up" + new "Re Pág" + + old "Rolls back to earlier dialogue." + new "Vuelve al diálogo anterior." + + old "Page Down" + new "Av Pág" + + old "Rolls forward to later dialogue." + new "Avanza hasta el diálogo siguiente." + + old "Hides the user interface." + new "Oculta la interfaz." + + old "Takes a screenshot." + new "Hace una captura de pantalla." + + old "Toggles assistive {a=https://www.renpy.org/l/voicing}self-voicing{/a}." + new "Activa o desactiva la {a=https://www.renpy.org/l/voicing}lectura en voz alta{/a}." + + old "Opens the accessibility menu." + new "Abre el menú de accesibilidad." + + old "Left Click" + new "Clic izquierdo" + + old "Middle Click" + new "Clic central" + + old "Right Click" + new "Clic derecho" + + old "Mouse Wheel Up" + new "Rueda hacia arriba" + + old "Mouse Wheel Down" + new "Rueda hacia abajo" + + old "Right Trigger\nA/Bottom Button" + new "Gatillo derecho\nA/Botón inferior" + + old "Left Trigger\nLeft Shoulder" + new "Gatillo izquierdo\nBotón superior izquierdo" + + old "Right Shoulder" + new "Botón superior derecho" + + old "D-Pad, Sticks" + new "Cruceta, palancas" + + old "Start, Guide, B/Right Button" + new "Start, Guía, B/Botón derecho" + + old "Y/Top Button" + new "Y/Botón superior" + + old "Calibrate" + new "Calibrar" + + old "Yes" + new "Sí" + + old "No" + new "No" + + old "Skipping" + new "Saltando" + + old "Menu" + new "Menú" diff --git a/src/vnpipe/renpy_tl.py b/src/vnpipe/renpy_tl.py new file mode 100644 index 0000000..ecff1f0 --- /dev/null +++ b/src/vnpipe/renpy_tl.py @@ -0,0 +1,420 @@ +"""Ren'Py side of the translations: ``game/tl//`` from ``data/translations/.json``. + +Every say statement of the generated script carries an explicit ``id`` (its first line id), so +each translation writes ``translate :`` for every one of them: + +- the first box of a game unit that the mapping gave text shows that text, split into boxes + like the original (stanzas, at most 4 lines in ADV or 8 in NVL, long prose paragraphs at + sentence ends); +- every other box (the rest of the unit, or a unit grouped with an earlier one) is ``pass``. + +The voice clips are shared by every language: a clip that starts on a box of the group starts +on the first translated box of the same speaker, ``voice sustain`` keeps it going over the +following boxes of that speaker and over stage directions. + +Menu, card and credit strings go to ``translate strings:``; the credits, whose +entries differ per language, are a per-language list in ``menu_data.rpy``. +""" + +import hashlib +import re +from dataclasses import dataclass +from typing import Any + +from vnpipe.config import Work +from vnpipe.renpy_gen import ( + ADV_MAX_LINES, + ART_STYLE_LABELS, + NVL_MAX_LINES, + UI_LABELS, + BoxRecord, + _markup, + about_parts, + char_var, + credits_sections, + escape_text, + scene_menu_titles, + title_cards, +) +from vnpipe.translate import config_digest, load_translation, translations +from vnpipe.translate_align import game_units + +MAX_LINE_WORDS = 45 # a longer line (a prose paragraph) is split at sentence ends +SENTENCE_END_RE = re.compile(r"[.!?…][’”)]*\s+|[.!?]—") # where a long line may be cut + +# Native names of the languages a work or translation is written in. +LANGUAGE_NAMES = { + "de": "Deutsch", + "en": "English", + "es": "Español", + "fr": "Français", + "it": "Italiano", + "pt": "Português", +} + + +@dataclass +class Translation: + """One configured translation and its built mapping.""" + + code: str + language: str # Ren'Py language name (``english``) + label: str # shown in the language picker, in that language + cfg: dict[str, Any] + data: dict[str, Any] + + +def load_all(work: Work, annotated: dict[str, Any]) -> list[Translation]: + """The work's translations; an unbuilt or stale mapping is an error (the generated game + would silently show the wrong lines).""" + result = [] + annotated_file = work.path("data/annotated.json") + digest = ( + hashlib.sha256(annotated_file.read_bytes()).hexdigest() + if annotated_file.is_file() + else None + ) + for code, cfg in translations(work).items(): + data = load_translation(work, code) + if data is None: + raise ValueError(f"translation {code!r}: run `vnpipe translate build` first") + if digest is not None and data["annotated_sha256"] != digest: + raise ValueError( + f"translation {code!r} was built from another annotated.json: " + "run `vnpipe translate build` again" + ) + if data["config_sha256"] != config_digest(cfg): + raise ValueError( + f"translation {code!r} was built with another [translations.{code}] mapping " + "configuration: run `vnpipe translate build` again" + ) + ids = {ln["id"] for sc in annotated["scenes"] for ln in sc["lines"]} + for sid, scene in data["scenes"].items(): + unknown = [k for k in scene["units"] if k not in ids] + if unknown: + raise ValueError(f"translation {code!r}, {sid}: unknown line ids {unknown[:3]}") + result.append( + Translation( + code, + cfg["language"], + cfg.get("label") or LANGUAGE_NAMES.get(code, code), + cfg, + data, + ) + ) + return result + + +def languages(work: Work, tls: list[Translation]) -> list[tuple[str | None, str]]: + """(Ren'Py language, label) pairs; the work's own language first (the default).""" + ui = work.data.get("ui", {}) + lang = work.data["work"].get("language", "es") + own = (ui.get("language"), ui.get("language_label") or LANGUAGE_NAMES.get(lang, lang)) + return [own, *((t.language, t.label) for t in tls)] + + +# --- say blocks ------------------------------------------------------------------------------ + + +def _split_long(line: str) -> list[str]: + """A line over ``MAX_LINE_WORDS`` words as runs of whole sentences (the text unchanged).""" + if len(line.split()) <= MAX_LINE_WORDS: + return [line] + cuts = [0, *(m.end() for m in SENTENCE_END_RE.finditer(line)), len(line)] + pieces = [line[a:b] for a, b in zip(cuts, cuts[1:], strict=False) if b > a] + chunks: list[str] = [] + for piece in pieces: # slices of the line, so a chunk is always a verbatim substring + if chunks and len((chunks[-1] + piece).split()) <= MAX_LINE_WORDS: + chunks[-1] += piece + else: + chunks.append(piece) + return [c.strip() for c in chunks if c.strip()] + + +def item_boxes(item: dict[str, Any], limit: int) -> list[list[str]]: + """The boxes (lists of lines) of one translated item.""" + boxes: list[list[str]] = [] + if item["kind"] == "dir": + lines = [ln for st in item["stanzas"] for ln in st] + for line in lines: + parts = _split_long(line) + if len(parts) > 1 or not boxes or len(boxes[-1]) >= limit: + boxes.extend([p] for p in parts) + else: + boxes[-1].append(line) + return boxes + for stanza in item["stanzas"]: + box: list[str] = [] + for line in stanza: + parts = _split_long(line) + if len(parts) > 1: + if box: + boxes.append(box) + box = [] + boxes.extend([p] for p in parts) + continue + if len(box) >= limit: + boxes.append(box) + box = [] + box.append(line) + if box: + boxes.append(box) + return boxes + + +def assign_clips(clips: list[tuple[str, str]], says: list[str]) -> dict[int, str]: + """Place a group's voice clips (in order, with the Spanish box's speaker) on its translated + say boxes (their speakers, in order): each clip goes to the next box of the same speaker + when one is left (keeping room for the clips after it), else to the next box. Every clip + is placed; a group with more clips than say boxes is an error.""" + if len(clips) > len(says): + raise ValueError(f"{len(clips)} voice clips but only {len(says)} translated say boxes") + placed: dict[int, str] = {} + start = 0 + for k, (speaker, path) in enumerate(clips): + last = len(says) - (len(clips) - k) # leave a box for each later clip + at = next((i for i in range(start, last + 1) if says[i] == speaker), start) + placed[at] = path + start = at + 1 + return placed + + +class VoiceState: + """Which speaker's clip the translated boxes keep playing.""" + + def __init__(self) -> None: + self.active: str | None = None + + def statement(self, speaker: str, is_dir: bool, clip: str | None) -> str | None: + if clip is not None: + self.active = speaker + return f'voice "{clip}"' + if self.active is not None and (is_dir or speaker == self.active): + return "voice sustain" + self.active = None + return None + + +def render_scene_blocks( + tl: Translation, + scene: dict[str, Any], + records: list[BoxRecord], + lyric_voice: str, + cast: dict[str, Any], +) -> list[str]: + units = tl.data["scenes"][scene["id"]]["units"] + heads = {u.first_line for u in game_units(scene, lyric_voice)} + out: list[str] = [] + voice = VoiceState() + # groups: a box with text, then the boxes that show nothing until the next one + groups: list[list[BoxRecord]] = [] + for rec in records: + if rec.line_id in heads and rec.line_id in units or not groups: + groups.append([rec]) + else: + groups[-1].append(rec) + for group in groups: + head = group[0] + if not (head.line_id in heads and head.line_id in units): # nothing before any text + for rec in group: + out += [f"translate {tl.language} {rec.line_id}:", " pass", ""] + continue + if not head.sustain: + voice.active = None + clips = [(r.speaker, r.voice) for r in group if r.voice] + limit = NVL_MAX_LINES if head.nvl else ADV_MAX_LINES + boxes: list[tuple[str, bool, list[str]]] = [] + for item in units[head.line_id]: + speaker = item["speaker"] + if speaker != "narrator" and speaker not in cast: + raise ValueError(f"translation {tl.code!r}: unknown speaker {speaker!r}") + is_dir = item["kind"] == "dir" + boxes += [(speaker, is_dir, box) for box in item_boxes(item, limit)] + say_at = [i for i, (_, is_dir, _) in enumerate(boxes) if not is_dir] + try: + placed = assign_clips(clips, [boxes[i][0] for i in say_at]) + except ValueError as exc: + raise ValueError(f"translation {tl.code!r}, {head.line_id}: {exc}") from None + clip_at = {say_at[k]: path for k, path in placed.items()} + body: list[str] = [] + for i, (speaker, is_dir, box) in enumerate(boxes): + if head.nvl: + body.append("nvl clear") + statement = voice.statement(speaker, is_dir, clip_at.get(i)) + if statement: + body.append(statement) + text = "\\n".join(escape_text(line) for line in box) + body.append(f'{char_var(speaker, nvl=head.nvl)} "{text}"') + out.append(f"translate {tl.language} {head.line_id}:") + out += [f" {ln}" for ln in body] + out.append("") + for rec in group[1:]: + out += [f"translate {tl.language} {rec.line_id}:", " pass", ""] + return out + + +def render_tl_script( + tl: Translation, + annotated: dict[str, Any], + records: dict[str, list[BoxRecord]], + lyric_voice: str, + cast: dict[str, Any], +) -> str: + out = [ + "## Generated by `vnpipe renpy` from data/translations/" + f"{tl.code}.json. Do not edit: regenerate instead.", + "", + ] + for scene in annotated["scenes"]: + if scene["id"] not in tl.data["scenes"]: + raise ValueError(f"translation {tl.code!r} has no scene {scene['id']!r}") + out += render_scene_blocks(tl, scene, records.get(scene["id"], []), lyric_voice, cast) + return "\n".join(out) + + +# --- strings --------------------------------------------------------------------------------- + + +def string_literal(text: str) -> str: + """A Ren'Py string literal whose value is ``text`` exactly (already markup-escaped).""" + return '"' + text.replace("\\", "\\\\").replace('"', '\\"').replace("\n", "\\n") + '"' + + +def render_tl_strings(tl: Translation, pairs: list[tuple[str, str]]) -> str: + """``translate strings:`` for each (original, translation) pair; an original + may appear once only (a clash is an error: tag the original with ``{#...}``).""" + seen: dict[str, str] = {} + out = [ + "## Generated by `vnpipe renpy`. Do not edit: regenerate instead.", + "", + f"translate {tl.language} strings:", + "", + ] + for old, new in pairs: + if not old or old == new: + continue + if old in seen: + if seen[old] != new: + raise ValueError( + f"translation {tl.code!r}: {old!r} is both {seen[old]!r} and {new!r}" + ) + continue + seen[old] = new + out += [f" old {string_literal(old)}", f" new {string_literal(new)}", ""] + return "\n".join(out) + + +def _runtime(text: str) -> str: + """The value Ren'Py holds for a generated string (markup escaped, a trailing ``{#...}`` + tag kept).""" + match = re.search(r"\{#[^{}]*\}$", text) + if not match: + return _markup(text) + return _markup(text[: match.start()]) + match.group(0) + + +def translated_view( + work: Work, annotated: dict[str, Any], tl: Translation +) -> tuple[Work, dict[str, Any]]: + """The work and script as the translation names them: title, subtitle, translator, end + text, source, voice credits, scene headings and subtitles.""" + cfg = tl.cfg + info = {**work.data["work"], "language": tl.code} + for key in ("title", "subtitle", "translator", "end_text"): + if key in cfg: + info[key] = cfg[key] + sections = {s["scene"]: s for s in cfg.get("sections", [])} + scenes = [ + {**sc, "subtitle": sections.get(sc["id"], {}).get("subtitle")} + for sc in work.data.get("scenes", []) + ] + data = {**work.data, "work": info, "scenes": scenes} + if cfg.get("gutenberg_id"): + data["source"] = {**work.data.get("source", {}), "gutenberg_id": cfg["gutenberg_id"]} + if "voice" in work.data: + data["voice"] = {**work.data["voice"], "credits": cfg.get("voice_credits", [])} + ann = { + **annotated, + "scenes": [ + {**sc, "heading": tl.data["scenes"][sc["id"]]["title"]} for sc in annotated["scenes"] + ], + } + return Work(work.root, data), ann + + +def collision_tags(work: Work, annotated: dict[str, Any], tls: list[Translation]) -> dict[str, str]: + """Scene id -> tag id for scenes whose heading, subtitle or menu title is the same text as + another one but translated differently (``{#}`` on cards, ``{# menu}`` in the + scene list).""" + es_cards = title_cards(work, annotated) + es_menu = dict(scene_menu_titles(work, annotated)) + targets: dict[str, dict[str, set[str]]] = {} # original -> translation -> scene ids + for tl in tls: + tw, ta = translated_view(work, annotated, tl) + en_cards = title_cards(tw, ta) + en_menu = dict(scene_menu_titles(tw, ta)) + for sc in annotated["scenes"]: + sid = sc["id"] + name = f"card_{sid}" + pairs = list(zip(es_cards[name], en_cards[name], strict=True)) + pairs.append((es_menu[f"scene_{sid}"], en_menu[f"scene_{sid}"])) + for old, new in pairs: + if old: + targets.setdefault(old, {}).setdefault(new or "", set()).add(sid) + tags: dict[str, str] = {} + for by_new in targets.values(): + if len(by_new) > 1: + for sids in by_new.values(): + tags.update({sid: sid for sid in sids}) + return tags + + +def string_pairs( + work: Work, + annotated: dict[str, Any], + manifest: dict[str, Any] | None, + tl: Translation, + tags: dict[str, str], +) -> list[tuple[str, str]]: + """(original, translation) of every generated string the game shows outside dialogue.""" + tw, ta = translated_view(work, annotated, tl) + lang = work.data["work"].get("language", "es") + pairs: list[tuple[str, str]] = [] + names = tl.cfg.get("names", {}) + missing = [cid for cid, c in work.cast.items() if c.get("name") and cid not in names] + if missing: + raise ValueError(f"[translations.{tl.code}.names] lacks {missing}") + for cid, name in names.items(): + if cid not in work.cast: + raise ValueError(f"[translations.{tl.code}.names]: unknown cast id {cid!r}") + pairs.append((_markup(work.cast[cid].get("name") or ""), _markup(name))) + es_cards, en_cards = title_cards(work, annotated, tags), title_cards(tw, ta) + for name, card in es_cards.items(): + for old, new in zip(card, en_cards[name], strict=True): + if old and new: + pairs.append((_runtime(old), _markup(new))) + en_menu = dict(scene_menu_titles(tw, ta)) + pairs += [(old, en_menu[label]) for label, old in scene_menu_titles(work, annotated, tags)] + info, tinfo = work.data["work"], tw.data["work"] + pairs.append((_markup(info["title"]), _markup(tinfo["title"]))) + pairs.append((_markup(info.get("subtitle", "")), _markup(tinfo.get("subtitle", "")))) + pairs.append( + ( + "\n\n".join(_markup(p) for p in about_parts(work)), + "\n\n".join(_markup(p) for p in about_parts(tw)), + ) + ) + ui, tui = UI_LABELS.get(lang, UI_LABELS["en"]), UI_LABELS.get(tl.code, UI_LABELS["en"]) + pairs += [(ui[k], tui[k]) for k in ("scenes", "credits")] + art = ART_STYLE_LABELS.get(lang, ART_STYLE_LABELS["en"]) + tart = ART_STYLE_LABELS.get(tl.code, ART_STYLE_LABELS["en"]) + pairs += list(zip(art, tart, strict=True)) + pairs += [(_markup(k), _markup(v)) for k, v in tl.cfg.get("strings", {}).items()] + return pairs + + +def translated_credits( + work: Work, annotated: dict[str, Any], manifest: dict[str, Any] | None, tl: Translation +) -> list[tuple[str, list[str]]]: + tw, _ = translated_view(work, annotated, tl) + return credits_sections(tw, manifest) diff --git a/src/vnpipe/schemas/translation.schema.json b/src/vnpipe/schemas/translation.schema.json new file mode 100644 index 0000000..5409f15 --- /dev/null +++ b/src/vnpipe/schemas/translation.schema.json @@ -0,0 +1,51 @@ +{ + "$schema": "https://json-schema.org/draft/2020-12/schema", + "title": "Translation mapped onto the game text (data/translations/.json)", + "type": "object", + "required": ["version", "code", "language", "source_sha256", "annotated_sha256", "config_sha256", "scenes"], + "additionalProperties": false, + "properties": { + "version": {"const": 1}, + "code": {"type": "string"}, + "language": {"type": "string", "pattern": "^[a-z_]+$"}, + "source_sha256": {"type": "string", "pattern": "^[0-9a-f]{64}$"}, + "annotated_sha256": {"type": "string", "pattern": "^[0-9a-f]{64}$"}, + "config_sha256": {"type": "string", "pattern": "^[0-9a-f]{64}$"}, + "scenes": { + "type": "object", + "additionalProperties": { + "type": "object", + "required": ["title", "subtitle", "units", "stats"], + "additionalProperties": false, + "properties": { + "title": {"type": "string"}, + "subtitle": {"type": ["string", "null"]}, + "units": { + "description": "First line id of a game unit -> the source units it shows, in order. Game units absent here show nothing (their text is in their group's first unit).", + "type": "object", + "additionalProperties": { + "type": "array", + "minItems": 1, + "items": { + "type": "object", + "required": ["kind", "speaker", "src_line", "stanzas"], + "additionalProperties": false, + "properties": { + "kind": {"enum": ["say", "dir"]}, + "speaker": {"type": "string"}, + "src_line": {"type": "integer"}, + "stanzas": { + "type": "array", + "minItems": 1, + "items": {"type": "array", "minItems": 1, "items": {"type": "string"}} + } + } + } + } + }, + "stats": {"type": "object"} + } + } + } + } +} diff --git a/src/vnpipe/translate.py b/src/vnpipe/translate.py new file mode 100644 index 0000000..716b8c4 --- /dev/null +++ b/src/vnpipe/translate.py @@ -0,0 +1,348 @@ +"""Translations: show the play in another language, from a published public-domain translation. + +Stages (deterministic; see docs/translations.md): + fetch download the translation's text (a Project Gutenberg plain-text ebook) + build parse it into speeches and stage directions, map them onto the game's speeches by + speaker sequence -> data/translations/.json + status coverage per scene (worst first); ``--scene`` prints the alignment side by side + +``vnpipe renpy`` then writes ``game/tl//`` from the JSON. Nothing is machine +translated: every line comes verbatim from the configured translation. +""" + +import argparse +import hashlib +import json +from pathlib import Path +from typing import Any + +from vnpipe.config import Work, load_work +from vnpipe.schema import validate +from vnpipe.translate_align import ( + SETTING, + GameUnit, + Unit, + align_units, + find_section_lines, + game_units, + group_units, + parse_units, + strip_gutenberg, +) +from vnpipe.voice import download + +OUT_DIR = "data/translations" +SUSPECT_RATIO = 2.5 # a group whose size ratio is this far from the scene's is flagged +SUSPECT_WORDS = 25 # ... when it is at least this big (game + source words) + + +# --- configuration ------------------------------------------------------------------------- + + +def translations(work: Work) -> dict[str, dict[str, Any]]: + """``[translations.]`` tables, by code (e.g. ``en``).""" + return work.data.get("translations", {}) + + +def translation_cfg(work: Work, code: str) -> dict[str, Any]: + cfg = translations(work).get(code) + if cfg is None: + raise SystemExit(f"no [translations.{code}] table in work.toml") + return cfg + + +# The keys of [translations.] that change the mapping (the others, such as names and +# strings, are read by `vnpipe renpy` directly). +MAPPING_KEYS = ( + "text_file", + "sections", + "speakers", + "scene_speakers", + "direction_labels", + "ignore_lines", + "ensembles", + "overrides", +) + + +def config_digest(cfg: dict[str, Any]) -> str: + """Hash of the mapping configuration, stored in the JSON to detect a stale build.""" + picked = {k: cfg[k] for k in MAPPING_KEYS if k in cfg} + return hashlib.sha256(json.dumps(picked, sort_keys=True).encode("utf-8")).hexdigest() + + +def output_path(work: Work, code: str) -> Path: + return work.path(f"{OUT_DIR}/{code}.json") + + +def load_translation(work: Work, code: str) -> dict[str, Any] | None: + path = output_path(work, code) + if not path.is_file(): + return None + data = json.loads(path.read_text(encoding="utf-8")) + validate(data, "translation") + return data + + +def lyric_voice(work: Work) -> str: + return work.data["work"].get("lyric_voice", "poet_voice") + + +# --- build --------------------------------------------------------------------------------- + + +def find_override(source: list[Unit], quote: str, scene_id: str) -> int: + """Index of the source unit whose text starts with ``quote`` (verbatim, after markup + cleaning); exactly one must match.""" + hits = [u.index for u in source if u.text.startswith(quote)] + if len(hits) != 1: + raise SystemExit( + f"translate: override in {scene_id}: {len(hits)} source units start with {quote!r}" + ) + return hits[0] + + +def build_scene( + work: Work, + cfg: dict[str, Any], + scene: dict[str, Any], + section: dict[str, Any], + numbered: list[tuple[int, str]], +) -> dict[str, Any]: + """Map one scene; returns its entry of the translation file.""" + sid = scene["id"] + speakers = {**cfg.get("speakers", {}), **cfg.get("scene_speakers", {}).get(sid, {})} + cast = work.cast + for label, value in {**speakers, **cfg.get("direction_labels", {})}.items(): + for cid in value if isinstance(value, list) else [value]: + if cid and cid not in cast: + raise SystemExit(f"translate: label {label!r} maps to unknown cast id {cid!r}") + scene_cfg = next((s for s in work.data.get("scenes", []) if s["id"] == sid), {}) + source = parse_units( + numbered, + speakers, + default_speaker=section.get("default_speaker"), + prose=scene_cfg.get("format") == "prose", + ignore=frozenset(cfg.get("ignore_lines", [])), + direction_labels=cfg.get("direction_labels", {}), + ) + game = game_units(scene, lyric_voice(work)) + by_line = {u.first_line: u.index for u in game} + forced: dict[int, Unit] = {} + for ov in cfg.get("overrides", []): + if ov["scene"] != sid: + continue + if ov["game"] not in by_line: + raise SystemExit(f"translate: override {ov['game']!r} is not the start of a unit") + forced[by_line[ov["game"]]] = source[find_override(source, ov["source"], sid)] + # The setting (place and cast lines) is shown only where an override puts it. + used = {id(u) for u in forced.values()} + source = [u for u in source if u.label != SETTING or id(u) in used] + for k, u in enumerate(source): + u.index = k + anchors = {g: u.index for g, u in forced.items()} + ensembles = frozenset(cfg.get("ensembles", work.data.get("voice", {}).get("ensembles", []))) + pairs = align_units(game, source, ensembles, anchors) + carried = group_units(len(game), len(source), pairs) + units: dict[str, list[dict[str, Any]]] = {} + for g, sources in carried.items(): + units[game[g].first_line] = [ + { + "kind": source[s].kind, + "speaker": source[s].speaker or "narrator", + "src_line": source[s].src_line, + "stanzas": source[s].stanzas, + } + for s in sources + ] + return { + "title": section.get("title", section["heading"]), + "subtitle": section.get("subtitle"), + "units": units, + "stats": scene_stats(game, source, pairs, carried, set(anchors)), + } + + +def scene_stats( + game: list[GameUnit], + source: list[Unit], + pairs: dict[int, int], + carried: dict[int, list[int]], + forced: set[int], +) -> dict[str, Any]: + """Counts for ``status``, and the groups whose sizes look wrong (to review).""" + ratio = sum(u.words for u in game) / max(1, sum(u.words for u in source)) + heads = sorted(carried) + suspects = [] + for k, head in enumerate(heads): + end = heads[k + 1] if k + 1 < len(heads) else len(game) + g_words = sum(u.words for u in game[head:end]) + s_words = sum(source[s].words for s in carried[head]) + rel = (g_words / max(1, s_words)) / ratio + if g_words + s_words >= SUSPECT_WORDS and not (1 / SUSPECT_RATIO <= rel <= SUSPECT_RATIO): + suspects.append(game[head].first_line) + paired = len(pairs) + carrying = sum(1 for g in carried if g not in pairs) + return { + "game_units": len(game), + "paired": paired, + "carrying": carrying, + "grouped": len(game) - paired - carrying, + "source_units": len(source), + "source_attached": len(source) - paired, + "forced": len(forced), + "coverage": round((paired + carrying) / len(game), 3) if game else 1.0, + "complete": not game or 0 in carried, + "suspects": suspects, + } + + +def source_sections(work: Work, cfg: dict[str, Any]) -> tuple[str, dict[str, Any]]: + path = work.path(cfg["text_file"]) + if not path.is_file(): + raise SystemExit(f"translate: {path} missing; run `vnpipe translate fetch`") + raw = path.read_bytes() + text = strip_gutenberg(raw.decode("utf-8")) + sections = cfg["sections"] + found = find_section_lines(text, [s["heading"] for s in sections]) + return hashlib.sha256(raw).hexdigest(), { + s["scene"]: (s, lines) for s, lines in zip(sections, found, strict=True) + } + + +def build(work: Work, code: str) -> dict[str, Any]: + cfg = translation_cfg(work, code) + digest, sections = source_sections(work, cfg) + annotated = json.loads(work.path("data/annotated.json").read_text(encoding="utf-8")) + scenes = {} + for scene in annotated["scenes"]: + if scene["id"] not in sections: + raise SystemExit(f"translate: scene {scene['id']!r} has no [[sections]] entry") + section, numbered = sections[scene["id"]] + scenes[scene["id"]] = build_scene(work, cfg, scene, section, numbered) + data = { + "version": 1, + "code": code, + "language": cfg["language"], + "source_sha256": digest, + "annotated_sha256": hashlib.sha256( + work.path("data/annotated.json").read_bytes() + ).hexdigest(), + "config_sha256": config_digest(cfg), + "scenes": scenes, + } + validate(data, "translation") + return data + + +def write_json(path: Path, data: dict[str, Any]) -> None: + path.parent.mkdir(parents=True, exist_ok=True) + path.write_text( + json.dumps(data, ensure_ascii=False, indent=1) + "\n", encoding="utf-8", newline="\n" + ) + + +# --- status -------------------------------------------------------------------------------- + + +def status_lines(data: dict[str, Any]) -> list[str]: + """One line per scene, worst coverage first.""" + rows = sorted(data["scenes"].items(), key=lambda kv: (kv[1]["stats"]["coverage"], kv[0])) + out = [ + f"{'scene':<20} {'coverage':>8} {'paired':>7} {'carry':>6} {'grouped':>8} " + f"{'src':>5} {'attached':>8} {'forced':>6} suspects" + ] + for sid, sc in rows: + st = sc["stats"] + out.append( + f"{sid:<20} {st['coverage']:>8.1%} {st['paired']:>7} {st['carrying']:>6} " + f"{st['grouped']:>8} {st['source_units']:>5} {st['source_attached']:>8} " + f"{st['forced']:>6} {' '.join(st['suspects'])}" + ) + return out + + +def alignment_lines(work: Work, data: dict[str, Any], scene_id: str) -> list[str]: + """Side-by-side view of one scene: each game unit and the source text it shows.""" + annotated = json.loads(work.path("data/annotated.json").read_text(encoding="utf-8")) + scene = next(s for s in annotated["scenes"] if s["id"] == scene_id) + lines = {ln["id"]: ln for ln in scene["lines"]} + units = data["scenes"][scene_id]["units"] + suspects = set(data["scenes"][scene_id]["stats"]["suspects"]) + out = [] + for unit in game_units(scene, lyric_voice(work)): + first = lines[unit.first_line]["text"] + mark = "!" if unit.first_line in suspects else " " + out.append(f"{mark}{unit.first_line} [{unit.speaker or 'dir'} {unit.words}w] {first[:60]}") + for item in units.get(unit.first_line, []): + text = " / ".join(ln for st in item["stanzas"] for ln in st) + words = len(text.split()) + out.append(f" -> {item['speaker']} {words}w @{item['src_line']}: {text[:70]}") + if unit.first_line not in units: + out.append(" (grouped)") + return out + + +# --- CLI ----------------------------------------------------------------------------------- + + +def codes(work: Work, wanted: str | None) -> list[str]: + all_codes = list(translations(work)) + if not all_codes: + raise SystemExit("this work has no [translations.] table in work.toml") + picked = wanted.split(",") if wanted else all_codes + for code in picked: + translation_cfg(work, code) + return picked + + +def cmd_fetch(args: argparse.Namespace) -> int: + work = load_work(args.work) + for code in codes(work, args.lang): + cfg = translation_cfg(work, code) + dest = work.path(cfg["text_file"]) + if dest.exists(): + print(f"fetch: {dest} already present") + else: + download(cfg["text_url"], dest) + return 0 + + +def cmd_build(args: argparse.Namespace) -> int: + work = load_work(args.work) + for code in codes(work, args.lang): + data = build(work, code) + write_json(output_path(work, code), data) + print(f"build: wrote {output_path(work, code)}") + for line in status_lines(data): + print(line) + return 0 + + +def cmd_status(args: argparse.Namespace) -> int: + work = load_work(args.work) + for code in codes(work, args.lang): + data = load_translation(work, code) + if data is None: + raise SystemExit(f"status: {output_path(work, code)} missing; run `translate build`") + print(f"[{code}] {data['language']}") + lines = alignment_lines(work, data, args.scene) if args.scene else status_lines(data) + for line in lines: + print(line) + return 0 + + +def register(subparsers: argparse._SubParsersAction) -> None: + parser = subparsers.add_parser("translate", help="Map a published translation onto the game") + sub = parser.add_subparsers(dest="translate_command", required=True) + + def add(name: str, help_: str, handler: Any) -> argparse.ArgumentParser: + p = sub.add_parser(name, help=help_) + p.add_argument("--lang", help="Comma-separated translation codes (default: all)") + p.set_defaults(handler=handler) + return p + + add("fetch", "Download the translation text", cmd_fetch) + add("build", "Parse and map the translation -> data/translations/.json", cmd_build) + status = add("status", "Coverage per scene, worst first", cmd_status) + status.add_argument("--scene", help="Print one scene's alignment side by side") diff --git a/src/vnpipe/translate_align.py b/src/vnpipe/translate_align.py new file mode 100644 index 0000000..99911be --- /dev/null +++ b/src/vnpipe/translate_align.py @@ -0,0 +1,498 @@ +"""Translations, pure logic: parse a published translation of the play into speeches and stage +directions, and map them onto the game's speeches and directions by speaker sequence. + +The game text is never translated by vnpipe: every English (or other) line comes verbatim from +a public-domain translation. Where the two translations split or merge speeches differently, +the units are grouped: a group's text goes on its first game unit, the others show nothing. + +No I/O here; ``vnpipe.translate`` wires it to files and the CLI. +""" + +import math +import re +from dataclasses import dataclass, field +from typing import Any + +# --- source text ---------------------------------------------------------------------------- + +ILLUSTRATION_RE = re.compile(r"^\[Illustration[^\]]*\]?$", re.IGNORECASE) +ROMAN_RE = re.compile(r"^[IVXLC]+\.?$") +UPPER = "A-ZÀ-ÖØ-Þ" +# A speaker label: an upper-case name, optionally with a parenthetical note +# ("MEPHISTOPHELES (_to_ FAUST)", "FAUST _(passing by)_"). +LABEL_RE = re.compile( + rf"^(?P[{UPPER}][{UPPER}’'\-,.& ]*?[{UPPER}])\.?" + r"(?:\s*_?\((?P[^)]*)\)_?)?\.?$" +) +ITALIC_RE = re.compile(r"^_[^_]+_\W*$") # a paragraph wholly in italics +EXIT_RE = re.compile(r"^_?\[.*$") # "[_Exit_.", "[He sets the goblet to his mouth." +# "...the matter. _[Exit_.": an exit printed at the end of a verse line +TRAILING_EXIT_RE = re.compile(r"^(?P.*?\S)\s*(?P_?\[_?(?:Exit|Exeunt)(?![a-z]).*)$") +FOOTNOTE_RE = re.compile(r"(?<=[^\s\d])\s?\d{1,3}$") # "my stand.27": a note reference +SETTING = "setting" # label of the unit holding the place and cast lines before the first speech + + +def strip_gutenberg(text: str) -> str: + """The text between the Project Gutenberg start and end markers (header, footer and + licence removed); the whole text if the markers are missing.""" + lines = text.replace("\r\n", "\n").removeprefix("").split("\n") + start = next((i for i, ln in enumerate(lines) if ln.startswith("*** START OF")), -1) + end = next((i for i, ln in enumerate(lines) if ln.startswith("*** END OF")), len(lines)) + return "\n".join(lines[start + 1 : end]) + + +def find_section_lines(text: str, headings: list[str]) -> list[list[tuple[int, str]]]: + """Cut ``text`` at each heading line, searched in order: a whole line (not indented, so a + table of contents never matches) preceded by a blank line. Returns, per heading, the + numbered lines (1-based within ``text``) after it up to the next heading.""" + lines = text.split("\n") + starts: list[int] = [] + pos = 0 + for heading in headings: + for i in range(pos, len(lines)): + if lines[i] == heading and i > 0 and not lines[i - 1].strip(): + starts.append(i) + pos = i + 1 + break + else: + raise ValueError(f"heading {heading!r} not found in the translation") + bounds = [*starts, len(lines)] + return [ + [(n + 1, lines[n]) for n in range(a + 1, b)] + for a, b in zip(bounds, bounds[1:], strict=False) + ] + + +@dataclass +class Unit: + """A speech (or part of one, between stage directions) or a stage direction.""" + + index: int + kind: str # "say" or "dir" + speaker: str | None # cast id; None for a direction + label: str # speaker label as printed ("" for directions) + stanzas: list[list[str]] = field(default_factory=list) + src_line: int = 0 + + @property + def lines(self) -> list[str]: + return [ln for st in self.stanzas for ln in st] + + @property + def words(self) -> int: + return sum(len(ln.split()) for ln in self.lines) + + @property + def text(self) -> str: + return " ".join(self.lines) + + +def clean_markup(text: str) -> str: + """Drop italic/bold markers and collapse spaces.""" + text = re.sub(r"(? re.Match[str] | None: + if not stripped or stripped.startswith(("(", "[", "_")): + return None + match = LABEL_RE.match(stripped) + if match is None or not re.search(rf"[{UPPER}]{{2}}", match["name"]): + return None + return match + + +def _paragraph(rows: list[tuple[int, str]], i: int) -> str: + """The stripped, joined non-blank lines from index ``i``.""" + block = [] + while i < len(rows) and rows[i][1].strip(): + block.append(rows[i][1].strip()) + i += 1 + return " ".join(block) + + +def _whole_speech(rows: list[tuple[int, str]], i: int, after_label: bool) -> bool: + """An italic paragraph right after a label and followed by another label (or the end) is + the whole speech (a sung refrain, a Latin hymn line), not a stage direction.""" + if not after_label: + return False + while i < len(rows) and rows[i][1].strip(): + i += 1 + while i < len(rows) and not rows[i][1].strip(): + i += 1 + return i >= len(rows) or ( + not rows[i][1].startswith(" ") and _is_label(rows[i][1].strip()) is not None + ) + + +class UnknownLabel(ValueError): + """A speaker label of the translation has no cast id in the configuration.""" + + +def parse_units( + numbered: list[tuple[int, str]], + speakers: dict[str, str | list[str]], + default_speaker: str | None = None, + prose: bool = False, + ignore: frozenset[str] = frozenset(), + direction_labels: dict[str, str] | None = None, +) -> list[Unit]: + """Units of one section, in order. + + - Before the first speaker label (the setting): a ``(...)`` or ``_..._`` paragraph is a + direction; anything else (cast lists, place names) goes into one direction labelled + ``SETTING`` (one stanza per paragraph), which the mapper only uses when an override + names it (the game drops its own cast lines). + - ``(...)`` blocks, ``[_Exit_`` lines and ``_..._`` paragraphs are directions. + - An upper-case line followed by a blank line is a speaker label (indented only for a known + speaker: the chorus inside a song), mapped through + ``speakers`` (printed name without the note -> cast id); an unknown label directly + followed by another label is a cast list: dropped in the setting, a direction (an + entrance) after it. + - Everything else is verse (one line per printed line, stanzas split at blank lines) or, in + a ``prose`` section, paragraphs (one line each). + - A label listed in ``direction_labels`` ("PEASANTS, UNDER THE LINDEN-TREE") is printed as + a direction; the text after it is spoken by the cast id it maps to (none if empty). + - Lines in ``ignore`` (exact stripped text) and illustration markers are dropped; a + trailing Roman numeral (the next scene's number) is dropped, and so are footnote + reference numbers at the end of a line (the notes are not part of the play). + + A section with no speaker label is one speech by ``default_speaker``. + """ + direction_labels = direction_labels or {} + rows = [] + for n, t in numbered: + t = FOOTNOTE_RE.sub("", t.rstrip()) + match = TRAILING_EXIT_RE.match(t) + if match and not EXIT_RE.match(t.strip()): + parts = [(n, match["text"]), (n, match["exit"])] + if match["text"].lstrip().startswith("("): # "(_Enter_ X.) [_Exit_.": the exit + parts.reverse() # belongs to the speech before the entrance + rows += parts + else: + rows.append((n, t)) + rows = [ + (n, t) for n, t in rows if not ILLUSTRATION_RE.match(t.strip()) and t.strip() not in ignore + ] + while rows and (not rows[-1][1].strip() or ROMAN_RE.match(rows[-1][1].strip())): + rows.pop() + units: list[Unit] = [] + occurrences: dict[str, int] = {} + cur: Unit | None = None # the open speech + speaker: tuple[str, str] | None = None # (label, cast id) of the current speech + pending_blank = False + started = False + setting: Unit | None = None + has_labels = any( + _is_label(t.strip()) and t.strip() not in ignore and not t.startswith(" ") for _, t in rows + ) + + def new_dir(text: str, src: int) -> None: + nonlocal cur + cur = None + units.append(Unit(len(units), "dir", None, "", [[clean_markup(text)]], src)) + + def add_setting(text: str, src: int) -> None: + nonlocal setting + if setting is None: + setting = Unit(len(units), "dir", None, SETTING, [], src) + units.append(setting) + setting.stanzas.append([clean_markup(text)]) + + def add_line(text: str, src: int) -> None: + nonlocal cur, pending_blank + if cur is None: + if speaker is None: + if default_speaker is None: + raise ValueError(f"line {src}: text before any speaker label: {text!r}") + label, cast = "", default_speaker + else: + label, cast = speaker + cur = Unit(len(units), "say", cast, label, [[]], src) + units.append(cur) + elif pending_blank and cur.stanzas[-1]: + cur.stanzas.append([]) + pending_blank = False + cur.stanzas[-1].append(clean_markup(text)) + + i = 0 + while i < len(rows): + src, text = rows[i] + stripped = text.strip() + i += 1 + if not stripped: + pending_blank = True + continue + indented = text.startswith(" ") + if stripped.startswith("(") and indented and "_" not in stripped and cur is not None: + started = True # "(The witch's tricks)" inside an indented verse stanza + add_line(stripped, src) + continue + if stripped.startswith("("): + block = [stripped] + while " ".join(block).count("(") > " ".join(block).count(")"): + if i >= len(rows) or not rows[i][1].strip(): + raise ValueError(f"line {src}: unterminated stage direction") + block.append(rows[i][1].strip()) + i += 1 + joined = " ".join(block).rstrip("._ ") + if re.search(r"\)[,;:—–-]+$", joined): # "(These elements),—": verse + started = True + add_line(joined, src) + continue + if joined.endswith(")"): + joined = joined[1:-1] + if clean_markup(joined)[:1].islower() and cur is None and speaker is not None: + joined = ( + f"{speaker[0]} ({clean_markup(joined)})" # the label's note: "WITCH (declaims)" + ) + new_dir(joined, src) + pending_blank = False + continue + if EXIT_RE.match(stripped): + new_dir(clean_markup(stripped).lstrip("[").rstrip("]"), src) + continue + if stripped.startswith("_(") and stripped.rstrip("._").endswith(")"): + new_dir(stripped.rstrip("._ ").lstrip("_")[1:-1], src) + pending_blank = False + continue + if ( + not indented + and has_labels + and (i < 2 or not rows[i - 2][1].strip()) # starts a paragraph + and ITALIC_RE.match(_paragraph(rows, i - 1)) + and not _whole_speech(rows, i - 1, cur is None and speaker is not None) + ): + block = [stripped] + while i < len(rows) and rows[i][1].strip(): + block.append(rows[i][1].strip()) + i += 1 + new_dir(" ".join(block), src) + continue + match = _is_label(stripped) + if match is not None and indented: # only a known speaker, inside a song + known = match["name"].strip().rstrip(".,") in speakers + if not known or (i < len(rows) and rows[i][1].strip()): + match = None + if match is not None and match["name"].strip().rstrip(".,") not in speakers: + nxt = rows[i][1] if i < len(rows) else "" + if nxt.strip() and not nxt.startswith(" "): + match = None # caps text running on: not a label + if match is not None and has_labels: + name = match["name"].strip().rstrip(".,") + after = i + while after < len(rows) and not rows[after][1].strip(): + after += 1 + follow = rows[after][1].strip() if after < len(rows) else "" + if name in direction_labels: + new_dir(stripped, src) + cid = direction_labels[name] + speaker = (name, cid) if cid else None + started = True + continue + if not started and (not follow or _is_label(follow) or name not in speakers): + add_setting(stripped, src) # cast list or place line + continue + if name not in speakers and _is_label(follow): + new_dir(stripped, src) # an entrance: the names of who comes on + speaker = None + continue + if name not in speakers: + raise UnknownLabel(f"line {src}: unknown speaker label {name!r}") + cid = speakers[name] + if isinstance(cid, list): # one cast id per occurrence of the label, in order + seen = occurrences[name] = occurrences.get(name, 0) + 1 + if seen > len(cid): + raise UnknownLabel(f"line {src}: label {name!r} occurs more than {len(cid)}x") + cid = cid[seen - 1] + speaker = (name, cid) + cur = None + started = True + pending_blank = False + continue + if not started and has_labels: # cast list or place line of the setting + add_setting(_paragraph(rows, i - 1), src) + while i < len(rows) and rows[i][1].strip(): + i += 1 + continue + if prose and not indented: + block = [stripped] + while i < len(rows) and rows[i][1].strip() and not rows[i][1].startswith(" "): + block.append(rows[i][1].strip()) + i += 1 + add_line(" ".join(block), src) + pending_blank = True + continue + started = True + add_line(stripped, src) + for unit in units: + unit.stanzas = [st for st in unit.stanzas if st] + return [u for u in units if u.stanzas] + + +# --- game side ---------------------------------------------------------------------------- + + +def is_direction(line: dict[str, Any]) -> bool: + """Same rule as the Ren'Py generator: a direction line, or one annotated as such.""" + return line["kind"] == "direction" or line["ann"]["kind"] == "stage_direction" + + +@dataclass +class GameUnit: + """A run of game lines that starts a new box: a speech part or a stage direction.""" + + index: int + kind: str # "say" or "dir" + speaker: str | None + first_line: str + words: int = 0 + line_ids: list[str] = field(default_factory=list) + + +def game_units(scene: dict[str, Any], lyric_voice: str) -> list[GameUnit]: + """The scene's units: every stage direction line, and every run of lines with the same + (speaker, speech) between directions. Cast lines are skipped (they are never shown).""" + units: list[GameUnit] = [] + key: tuple[str, int] | None = None + for line in scene["lines"]: + if line["kind"] == "cast": + continue + words = len(line["text"].split()) + if is_direction(line): + units.append(GameUnit(len(units), "dir", None, line["id"], words, [line["id"]])) + key = None + continue + speaker = line["ann"]["speaker"] or lyric_voice + if key != (speaker, line["speech"]): + key = (speaker, line["speech"]) + units.append(GameUnit(len(units), "say", speaker, line["id"])) + units[-1].words += words + units[-1].line_ids.append(line["id"]) + return units + + +# --- mapping ------------------------------------------------------------------------------ + + +@dataclass +class Mapping: + """Result of mapping one scene: game unit index -> source unit indices it carries. + + ``pairs`` are the direct matches (same speaker, or two directions); ``carried`` lists, per + game unit, every source unit whose text it shows (its pair plus unmatched neighbours); + game units absent from ``carried`` show nothing (they belong to a group).""" + + pairs: dict[int, int] + carried: dict[int, list[int]] + forced: set[int] = field(default_factory=set) + + +def _pair_score(g: GameUnit, s: Unit, ratio: float, ensembles: frozenset[str]) -> float | None: + if g.kind != s.kind or s.label == SETTING: + return None + size = g.words / max(1, s.words) / ratio + penalty = min(3.0, abs(math.log2(max(size, 1e-3))) * 2) + if g.kind == "dir": + return 2.0 - penalty / 2 + if g.speaker != s.speaker: + if not (g.speaker in ensembles and s.speaker in ensembles): + return None + return 2.5 - penalty + return 4.0 - penalty + + +def align_units( + game: list[GameUnit], + source: list[Unit], + ensembles: frozenset[str] = frozenset(), + anchors: dict[int, int] | None = None, +) -> dict[int, int]: + """Global alignment of the two unit sequences (game index -> source index). + + Speeches pair only with speeches of the same speaker (or two crowd ids of ``ensembles``, + at a penalty), directions with directions; closer sizes (relative to the scene's overall + size ratio) score higher. ``anchors`` are forced pairs: the alignment runs separately + between them.""" + anchors = dict(sorted((anchors or {}).items())) + pairs: dict[int, int] = {} + prev_g = prev_s = 0 + for g_i, s_i in [*anchors.items(), (len(game), len(source))]: + if g_i < prev_g or s_i < prev_s: + raise ValueError("translation overrides are not in order") + pairs.update(_align_block(game, source, prev_g, g_i, prev_s, s_i, ensembles)) + if g_i < len(game): + pairs[g_i] = s_i + prev_g, prev_s = g_i + 1, s_i + 1 + return pairs + + +def _align_block( + game: list[GameUnit], + source: list[Unit], + g0: int, + g1: int, + s0: int, + s1: int, + ensembles: frozenset[str], +) -> dict[int, int]: + gs, ss = game[g0:g1], source[s0:s1] + g_words = sum(u.words for u in game) or 1 + s_words = sum(u.words for u in source) or 1 + ratio = g_words / s_words + n, m = len(gs), len(ss) + + def gap(unit: GameUnit | Unit) -> float: + return -0.4 if unit.kind == "dir" else -1.0 + + table = [[0.0] * (m + 1) for _ in range(n + 1)] + for i in range(1, n + 1): + table[i][0] = table[i - 1][0] + gap(gs[i - 1]) + for j in range(1, m + 1): + table[0][j] = table[0][j - 1] + gap(ss[j - 1]) + scores: dict[tuple[int, int], float] = {} + for i in range(1, n + 1): + for j in range(1, m + 1): + best = max(table[i - 1][j] + gap(gs[i - 1]), table[i][j - 1] + gap(ss[j - 1])) + s = _pair_score(gs[i - 1], ss[j - 1], ratio, ensembles) + if s is not None: + scores[i, j] = s + best = max(best, table[i - 1][j - 1] + s) + table[i][j] = best + pairs: dict[int, int] = {} + i, j = n, m + while i > 0 and j > 0: + s = scores.get((i, j)) + if s is not None and table[i][j] == table[i - 1][j - 1] + s: + pairs[g0 + i - 1] = s0 + j - 1 + i, j = i - 1, j - 1 + elif table[i][j] == table[i - 1][j] + gap(gs[i - 1]): + i -= 1 + else: + j -= 1 + return pairs + + +def group_units(n_game: int, n_source: int, pairs: dict[int, int]) -> dict[int, list[int]]: + """Which source units each game unit shows, so every source unit is shown once and in + order. Between two pairs, unmatched source units go to the first unmatched game unit of + the stretch, else to the preceding pair (or, before the first pair, to the next one).""" + carried: dict[int, list[int]] = {} + anchors = sorted(pairs.items()) + bounds = [(-1, -1), *anchors, (n_game, n_source)] + for (ga, sa), (gb, sb) in zip(bounds, bounds[1:], strict=False): + if gb < n_game: + carried.setdefault(gb, []).append(sb) + loose_s = list(range(sa + 1, sb)) + if not loose_s: + continue + loose_g = list(range(ga + 1, gb)) + if loose_g: + carried.setdefault(loose_g[0], []).extend(loose_s) + elif ga >= 0: + carried.setdefault(ga, []).extend(loose_s) + elif gb < n_game: + carried[gb] = loose_s + carried[gb] + elif n_game: # no pair at all: everything on the first game unit + carried.setdefault(0, []).extend(loose_s) + return {g: sorted(v) for g, v in sorted(carried.items())} diff --git a/tests/fixtures/mini_tl.toml b/tests/fixtures/mini_tl.toml new file mode 100644 index 0000000..46b349a --- /dev/null +++ b/tests/fixtures/mini_tl.toml @@ -0,0 +1,39 @@ + +[translations.en] +language = "english" +label = "English" +text_url = "https://example.org/mini.txt" +text_file = "data/raw/en.txt" +gutenberg_id = 1 +title = "Mini" +subtitle = "Fixture work" +translator = "E. Translator" +end_text = "To be continued…" +voice_credits = ["Voices: nobody."] + +[translations.en.speakers] +MANAGER = "director" +POET = "poet" +"THE LORD" = "lord" +VOICE = "poet_voice" + +[[translations.en.sections]] +scene = "lyric" +heading = "LYRIC" +default_speaker = "poet_voice" +subtitle = "Lyric · Dusk" + +[[translations.en.sections]] +scene = "talk" +heading = "TALK" +title = "CONVERSATION" + +[[translations.en.overrides]] +scene = "talk" +game = "talk_0010" +source = "Exit." + +[translations.en.names] +director = "Manager" +poet = "Poet" +lord = "The Lord" diff --git a/tests/fixtures/mini_tl_en.txt b/tests/fixtures/mini_tl_en.txt new file mode 100644 index 0000000..692bd21 --- /dev/null +++ b/tests/fixtures/mini_tl_en.txt @@ -0,0 +1,69 @@ +The Project Gutenberg eBook of Mini (a test fixture) + +*** START OF THE PROJECT GUTENBERG EBOOK MINI *** + +CONTENTS + + LYRIC + TALK + +LYRIC + +Again ye come, ye hovering Forms! I find ye, +As early to my clouded sight ye shone! +Shall I attempt, this once, to seize and bind ye? + +And dear ones rise, +Whom fortune stole. + +[Illustration] + +TALK + +A STAGE + +MANAGER. POET. + +MANAGER + +Ye two, who oft my help have been, +Say, what think ye? +I wish to please the crowd, +Who live and let me live. +Already there they sit, +With curious eyebrows raised. + +POET + +Away, profane! + +MANAGER (_softly_) + +Hush, he hears. [_Exit_. + +POET + +My breast is pressed +Beneath such weight.27 +(The evening comes),— + +THE LORD + +My servant! Tempt him. + +MANAGER + +Enough talk. + +VOICE + +The birds are still; +The night descends. + +POET + +I wake. + +*** END OF THE PROJECT GUTENBERG EBOOK MINI *** + +Licence text that must never be read. diff --git a/tests/test_renpy_gen.py b/tests/test_renpy_gen.py index d4729b0..92018aa 100644 --- a/tests/test_renpy_gen.py +++ b/tests/test_renpy_gen.py @@ -1,5 +1,6 @@ import json import os +import re import subprocess from pathlib import Path @@ -48,7 +49,8 @@ def scene_block(script: str, scene_id: str) -> list[str]: def say_lines(block: list[str]) -> list[str]: - return [ln for ln in block if ln.startswith("c_")] + """Say statements without their ``id`` clause.""" + return [re.sub(r" id \w+$", "", ln) for ln in block if ln.startswith("c_")] def test_escape_text(): @@ -115,10 +117,11 @@ def test_mode_switch_and_flash_shake(script): block = scene_block(script, "talk") i_nvl = block.index("# talk_0016") # nvl cue at 0016: sprites hidden (nothing changes the bg), director spoke in nvl mode - assert block[i_nvl + 1].startswith("c_director_nvl ") - assert "nvl clear" in block[i_nvl:] + # each nvl page is cleared before its say (so the clear joins the say's translate block) + assert block[i_nvl + 1] == "nvl clear" + assert block[i_nvl + 2].startswith("c_director_nvl ") # lyric voice lines in nvl are grouped into one page - pages = [ln for ln in block if ln.startswith("c_poet_voice_nvl")] + pages = [ln for ln in say_lines(block) if ln.startswith("c_poet_voice_nvl")] assert pages == ['c_poet_voice_nvl "Callan los pájaros;\\nla noche cae."'] # cue 3: leave nvl, flash + shake, tint reset i_cue = block.index("# talk_0019") @@ -275,7 +278,7 @@ def test_stage_direction_keeps_on_stage(work, annotated): direction = next(ln for ln in ann["scenes"][1]["lines"] if ln["id"] == "talk_0010") direction["ann"]["on_stage"] = [] block = scene_block(renpy_gen.render_script(work, ann), "talk") - i = block.index('c_narrator "Se aleja."') + i = block.index('c_narrator "Se aleja." id talk_0010') assert not any(ln.startswith("hide ") for ln in block[i - 3 : i]) @@ -434,22 +437,86 @@ def test_scan_and_copy_audio(work, tmp_path): assert "audio/scenes/x.ogg" in audio.files -def test_copy_translations_and_default_language(work, tmp_path): +def test_copy_translations(work, tmp_path): root = tmp_path / "w" (root / "tl/spanish").mkdir(parents=True) - (root / "tl/spanish/common.rpy").write_text("translate spanish strings:\n", encoding="utf-8") + work_common = "translate spanish strings:\n" + (root / "tl/spanish/common.rpy").write_text(work_common, encoding="utf-8") + (root / "tl/spanish/extra.rpy").write_text(work_common, encoding="utf-8") data = {**work.data, "ui": {**work.data.get("ui", {}), "language": "spanish"}} out = tmp_path / "out" copied = renpy_gen.copy_translations(type(work)(root=root, data=data), out) - assert (out / "game/tl/spanish/common.rpy").is_file() + tl = out / "game/tl/spanish" + # vnpipe's own translation ships; a work file with the same path replaces it + shipped = renpy_gen.TEMPLATE_DIR / "tl/spanish/screens.rpy" + assert (tl / "screens.rpy").read_bytes() == shipped.read_bytes() + assert (tl / "common.rpy").read_text(encoding="utf-8") == work_common + assert (tl / "extra.rpy").is_file() + assert tl / "screens.rpy" in copied + # the language is chosen in languages.rpy: a language.rpy left by an older build goes lang = out / "game/language.rpy" - assert lang in copied - assert lang.read_text(encoding="utf-8") == 'define config.default_language = "spanish"\n' - # Without [ui].language the stale file is removed. + lang.write_text("define config.language = 'spanish'\n", encoding="utf-8") renpy_gen.copy_translations(type(work)(root=tmp_path / "none", data=work.data), out) assert not lang.exists() +def test_languages_file_forces_the_work_language(project): + text = (project / "game/languages.rpy").read_text(encoding="utf-8") + # no translations: one language, the work's [ui].language (none in the fixture) + assert "define vn_languages = [(None, 'Español')]" in text + # config.language follows the player's choice only, never a stale preference + assert "config.language = persistent.vn_language" in text + assert "config.language = vn_languages[0][0]" in text + + +def _tl_strings(path: Path) -> list[str]: + return re.findall(r'^\s*old "((?:[^"\\]|\\.)*)"$', path.read_text(encoding="utf-8"), re.M) + + +def test_shipped_spanish_covers_every_template_string(): + """Every _("...") string of the template screens has exactly one Spanish translation.""" + template = "" + for path in sorted((renpy_gen.TEMPLATE_DIR / "game").glob("*.rpy")): + template += path.read_text(encoding="utf-8") + wanted = set(re.findall(r'(? 70 + olds = [] + for path in sorted((renpy_gen.TEMPLATE_DIR / "tl/spanish").glob("*.rpy")): + olds += _tl_strings(path) + assert len(olds) == len(set(olds)), "a string translated twice breaks Ren'Py" + assert sorted(wanted - set(olds)) == [] + + +def test_no_sync_buttons(project): + options = (project / "game/options.rpy").read_text(encoding="utf-8") + assert "define config.has_sync = False" in options + screens = (project / "game/screens.rpy").read_text(encoding="utf-8") + assert "UploadSync" not in screens and "DownloadSync" not in screens + + +def test_menu_ornaments_are_deterministic(): + a, b = renpy_gen.gui_extra_images(), renpy_gen.gui_extra_images() + assert a.keys() == b.keys() + assert all(a[k].tobytes() == b[k].tobytes() for k in a) + for name in ("card_background", "card_hover_background", "rule", "nav_selected_background"): + assert f"gui/vn/{name}.png" in a + assert "gui/phone/vn/rule.png" not in a # ornaments are not looked up per variant + rule = a["gui/vn/rule.png"] + mid = rule.height // 2 + # bright in the middle, faded at the ends + assert rule.getpixel((0, mid))[3] < 10 and rule.getpixel((rule.width // 3, mid))[3] == 255 + + +def test_save_metadata_and_slots(project): + menus = (project / "game/menus.rpy").read_text(encoding="utf-8") + assert "config.save_json_callbacks.append(vn_save_json)" in menus + assert "store.vn_current_scene = label" in menus + screens = (project / "game/screens.rpy").read_text(encoding="utf-8") + assert 'info.get("vn_scene")' in screens and 'info["vn_line"]' in screens + assert "FileDelete(slot)" in screens and "vn_roman(page)" in screens + + def test_mood_directory_is_a_playlist(work, annotated): block = scene_block(renpy_gen.render_script(work, annotated, _audio()), "lyric") assert _music_lines(block) == [ diff --git a/tests/test_translate.py b/tests/test_translate.py new file mode 100644 index 0000000..4a00429 --- /dev/null +++ b/tests/test_translate.py @@ -0,0 +1,312 @@ +import json +import os +import re +import shutil +import subprocess +from pathlib import Path + +import pytest + +from vnpipe import renpy_gen, renpy_tl, translate +from vnpipe.config import load_work +from vnpipe.renpy_gen import BoxRecord +from vnpipe.translate_align import ( + SETTING, + UnknownLabel, + find_section_lines, + group_units, + parse_units, + strip_gutenberg, +) + +FIXTURES = Path(__file__).parent / "fixtures" +ROOT = Path(__file__).resolve().parent.parent +SDK = Path(os.environ.get("RENPY_SDK") or ROOT / "tools/renpy-sdk") / "renpy.sh" +SPEAKERS = {"MANAGER": "director", "POET": "poet", "THE LORD": "lord", "VOICE": "poet_voice"} + + +@pytest.fixture +def tl_work(tmp_path): + """mini_work plus an English translation (fixture ebook) and its annotated script.""" + root = tmp_path / "w" + shutil.copytree(FIXTURES / "mini_work", root) + with (root / "work.toml").open("a", encoding="utf-8") as fh: + fh.write((FIXTURES / "mini_tl.toml").read_text(encoding="utf-8")) + (root / "data/raw").mkdir(parents=True) + shutil.copyfile(FIXTURES / "annotated_mini.json", root / "data/annotated.json") + shutil.copyfile(FIXTURES / "mini_tl_en.txt", root / "data/raw/en.txt") + return load_work(root) + + +def section(name: str) -> list[tuple[int, str]]: + text = strip_gutenberg((FIXTURES / "mini_tl_en.txt").read_text(encoding="utf-8")) + lyric, talk = find_section_lines(text, ["LYRIC", "TALK"]) + return {"lyric": lyric, "talk": talk}[name] + + +def test_strip_gutenberg_keeps_only_the_ebook_text(): + text = strip_gutenberg((FIXTURES / "mini_tl_en.txt").read_text(encoding="utf-8")) + assert "Project Gutenberg" not in text and "Licence" not in text + assert text.lstrip().startswith("CONTENTS") + + +def test_find_section_lines_skips_the_contents(): + text = strip_gutenberg((FIXTURES / "mini_tl_en.txt").read_text(encoding="utf-8")) + lyric, _ = find_section_lines(text, ["LYRIC", "TALK"]) + assert lyric[1][1].startswith("Again ye come") # not the indented contents entry + + +def test_parse_units_speeches_and_directions(): + units = parse_units(section("talk"), SPEAKERS) + kinds = [(u.kind, u.speaker, u.label) for u in units] + assert kinds == [ + ("dir", None, SETTING), # place line and cast list, kept apart + ("say", "director", "MANAGER"), + ("say", "poet", "POET"), + ("say", "director", "MANAGER"), + ("dir", None, ""), # "[_Exit_." at the end of a verse line + ("say", "poet", "POET"), + ("say", "lord", "THE LORD"), + ("say", "director", "MANAGER"), + ("say", "poet_voice", "VOICE"), + ("say", "poet", "POET"), + ] + assert units[0].stanzas == [["A STAGE"], ["MANAGER. POET."]] + assert units[3].lines == ["Hush, he hears."] + assert units[4].text == "Exit." + # footnote number dropped; a parenthesis inside a verse stays verse + assert units[5].lines == [ + "My breast is pressed", + "Beneath such weight.", + "(The evening comes),—", + ] + + +def test_a_speaker_list_maps_each_occurrence_of_a_label(): + speakers = {**SPEAKERS, "MANAGER": ["director", "lord", "poet"]} + units = parse_units(section("talk"), speakers) + assert [u.speaker for u in units if u.label == "MANAGER"] == ["director", "lord", "poet"] + with pytest.raises(UnknownLabel, match="more than 2x"): + parse_units(section("talk"), {**SPEAKERS, "MANAGER": ["director", "lord"]}) + + +def test_parse_units_without_labels_is_one_speech(): + units = parse_units(section("lyric"), SPEAKERS, default_speaker="poet_voice") + assert len(units) == 1 and units[0].speaker == "poet_voice" + assert [len(st) for st in units[0].stanzas] == [3, 2] # [Illustration] dropped + + +def test_group_units_shows_every_source_unit_once_in_order(): + # game 0..4, source 0..5; pairs 0-0, 2-3, 4-5: loose source units go to loose game units + carried = group_units(5, 6, {0: 0, 2: 3, 4: 5}) + assert carried == {0: [0], 1: [1, 2], 2: [3], 3: [4], 4: [5]} + assert sorted(s for v in carried.values() for s in v) == list(range(6)) + + +def test_build_maps_every_scene(tl_work): + data = translate.build(tl_work, "en") + talk = data["scenes"]["talk"] + assert talk["title"] == "CONVERSATION" + assert talk["stats"]["complete"] and talk["stats"]["forced"] == 1 + units = talk["units"] + assert units["talk_0002"][0]["stanzas"][0][0] == "Ye two, who oft my help have been," + assert units["talk_0010"] == [ + { + "kind": "dir", + "speaker": "narrator", + "src_line": units["talk_0010"][0]["src_line"], + "stanzas": [["Exit."]], + } + ] + assert units["talk_0017"][0]["speaker"] == "poet_voice" + assert "SETTING" not in json.dumps(data) # the unused setting is not shown + lyric = data["scenes"]["lyric"] + assert list(lyric["units"]) == ["lyric_0001"] + assert lyric["stats"]["coverage"] == 1.0 + # deterministic + assert json.dumps(translate.build(tl_work, "en")) == json.dumps(data) + + +def test_override_must_quote_exactly_one_unit(tl_work): + data = json.loads(json.dumps(tl_work.data)) + data["translations"]["en"]["overrides"][0]["source"] = "Nothing like this" + with pytest.raises(SystemExit, match="0 source units"): + translate.build(type(tl_work)(tl_work.root, data), "en") + + +def test_split_long_lines_keeps_the_text_verbatim(): + line = ("One two three four five six seven eight nine ten. " * 6).strip() + " End!—Next part" + chunks = renpy_tl._split_long(line) + assert len(chunks) > 1 + assert all(len(c.split()) <= renpy_tl.MAX_LINE_WORDS for c in chunks) + assert re.sub(r"\s+", "", "".join(chunks)) == re.sub(r"\s+", "", line) + + +def test_voice_follows_the_first_box_of_the_same_speaker(): + tl = renpy_tl.Translation( + "en", + "english", + "English", + {}, + { + "scenes": { + "s": { + "units": { + "s_0001": [ + {"kind": "say", "speaker": "poet", "src_line": 1, "stanzas": [["A"]]}, + { + "kind": "say", + "speaker": "lord", + "src_line": 2, + "stanzas": [["B"], ["C"]], + }, + { + "kind": "dir", + "speaker": "narrator", + "src_line": 3, + "stanzas": [["D"]], + }, + ], + } + } + }, + }, + ) + scene = { + "id": "s", + "lines": [ + { + "id": f"s_000{i}", + "kind": "verse", + "speech": i, + "text": "x", + "ann": {"speaker": who, "kind": "speech"}, + } + for i, who in ((1, "lord"), (2, "lord")) + ], + } + records = [ + BoxRecord("s_0001", "lord", False, voice="voice/a.ogg"), + BoxRecord("s_0002", "lord", False), + ] + cast = {"poet": {}, "lord": {}} + out = renpy_tl.render_scene_blocks(tl, scene, records, "poet_voice", cast) + assert out == [ + "translate english s_0001:", + ' c_poet "A"', + ' voice "voice/a.ogg"', + ' c_lord "B"', + " voice sustain", + ' c_lord "C"', + " voice sustain", + ' c_narrator "D"', + "", + "translate english s_0002:", + " pass", + "", + ] + + +def test_clips_follow_the_box_position_when_the_speaker_differs(): + # an ensemble line ("chorus") shown by a named source speaker, and a speaker mismatch + says = ["girl", "student", "girl"] + clips = [("chorus", "a.ogg"), ("student", "b.ogg"), ("burgher", "c.ogg")] + assert renpy_tl.assign_clips(clips, says) == {0: "a.ogg", 1: "b.ogg", 2: "c.ogg"} + # a later speaker match is skipped if it leaves no box for the clips after it + assert renpy_tl.assign_clips([("x", "a"), ("y", "b")], ["y", "x"]) == {0: "a", 1: "b"} + assert renpy_tl.assign_clips([("y", "a")], ["x", "y"]) == {1: "a"} + with pytest.raises(ValueError, match="2 voice clips"): + renpy_tl.assign_clips([("x", "a"), ("x", "b")], ["x"]) + + +def test_changed_mapping_config_is_an_error(tl_work, tmp_path): + translate.write_json(translate.output_path(tl_work, "en"), translate.build(tl_work, "en")) + annotated = json.loads(tl_work.path("data/annotated.json").read_text(encoding="utf-8")) + data = json.loads(json.dumps(tl_work.data)) + data["translations"]["en"]["names"]["lord"] = "God" # names need no rebuild + renpy_gen.generate(type(tl_work)(tl_work.root, data), annotated, tmp_path / "ok") + data["translations"]["en"]["speakers"]["POET"] = "director" + with pytest.raises(ValueError, match="mapping configuration"): + renpy_gen.generate(type(tl_work)(tl_work.root, data), annotated, tmp_path / "p") + + +@pytest.fixture +def tl_project(tl_work, tmp_path): + translate.write_json(translate.output_path(tl_work, "en"), translate.build(tl_work, "en")) + annotated = json.loads(tl_work.path("data/annotated.json").read_text(encoding="utf-8")) + out = tmp_path / "proj" + renpy_gen.generate(tl_work, annotated, out) + return out + + +def test_generate_writes_a_block_for_every_say(tl_project): + game = tl_project / "game" + script = (game / "script.rpy").read_text(encoding="utf-8") + tl = (game / "tl/english/script.rpy").read_text(encoding="utf-8") + ids = re.findall(r" id (\w+)$", script, re.M) + assert ids and ids == re.findall(r"^translate english (\w+):$", tl, re.M) + # the lyric scene is NVL: English pages cleared like the Spanish ones + lyric = tl.split("translate english lyric_0001:\n")[1].split("\n\n")[0].splitlines() + assert lyric == [ + " nvl clear", + ' c_poet_voice_nvl "Again ye come, ye hovering Forms! I find ye,\\n' + "As early to my clouded sight ye shone!\\n" + 'Shall I attempt, this once, to seize and bind ye?"', + " nvl clear", + ' c_poet_voice_nvl "And dear ones rise,\\nWhom fortune stole."', + ] + # director's 6 lines: 4 + 2 in ADV; the rest of his Spanish unit shows nothing + talk = tl.split("translate english talk_0002:\n")[1].split("\n\n")[0].splitlines() + assert [ln.count("\\n") for ln in talk] == [3, 1] + assert "translate english talk_0006:\n pass" in tl + + +def test_generate_translates_names_cards_and_menus(tl_project): + game = tl_project / "game" + strings = (game / "tl/english/strings.rpy").read_text(encoding="utf-8") + for old, new in ( + ("El Director", "Manager"), + ("CONVERSACIÓN", "CONVERSATION"), + ("Escenas", "Scenes"), + ("Estilo visual", "Visual style"), + ("Continuará…", "To be continued…"), + ): + assert f' old "{old}"\n new "{new}"' in strings + languages = (game / "languages.rpy").read_text(encoding="utf-8") + assert "define vn_languages = [(None, 'Español'), ('english', 'English')]" in languages + menu = (game / "menu_data.rpy").read_text(encoding="utf-8") + credits_tl = json.loads(re.search(r"^define vn_credits_tl = (.*)$", menu, re.M).group(1)) + text = dict(credits_tl["english"])["Text"] + assert "Translation: E. Translator" in text + assert dict(credits_tl["english"]).get("Voices") is None # no voice clips in the fixture + + +def test_missing_names_are_an_error(tl_work, tmp_path): + translate.write_json(translate.output_path(tl_work, "en"), translate.build(tl_work, "en")) + data = json.loads(json.dumps(tl_work.data)) + del data["translations"]["en"]["names"]["lord"] + annotated = json.loads(tl_work.path("data/annotated.json").read_text(encoding="utf-8")) + with pytest.raises(ValueError, match="lord"): + renpy_gen.generate(type(tl_work)(tl_work.root, data), annotated, tmp_path / "p") + + +def test_stale_translation_is_an_error(tl_work, tmp_path): + translate.write_json(translate.output_path(tl_work, "en"), translate.build(tl_work, "en")) + path = tl_work.path("data/annotated.json") + annotated = json.loads(path.read_text(encoding="utf-8")) + path.write_text(json.dumps(annotated, indent=2), encoding="utf-8") + with pytest.raises(ValueError, match="translate build"): + renpy_gen.generate(tl_work, annotated, tmp_path / "p") + + +@pytest.mark.skipif(not SDK.exists(), reason="Ren'Py SDK not found (set RENPY_SDK)") +def test_renpy_lint_with_translation(tl_project, tmp_path): + env = {**os.environ, "HOME": str(tmp_path / "home")} + (tmp_path / "home").mkdir() + result = subprocess.run( + [str(SDK), str(tl_project), "lint"], capture_output=True, text=True, env=env, timeout=300 + ) + report = result.stdout + result.stderr + assert result.returncode == 0, report + assert "Traceback" not in report and "error" not in report.lower(), report + assert "The english translation contains" in report