Cnass commited on
Commit
a182ff4
·
verified ·
1 Parent(s): 2233eca

Upload 4 files

Browse files
Files changed (4) hide show
  1. app/renpy/extract.py +12 -1
  2. app/renpy/rpyc.py +250 -17
  3. app/renpy/store.py +41 -2
  4. app/renpy/tl.py +34 -12
app/renpy/extract.py CHANGED
@@ -66,13 +66,24 @@ def is_skipped(relative: Path) -> bool:
66
 
67
 
68
  def iter_scripts(root: Path):
69
- """Yield every script under `root`, in a stable order."""
 
 
 
 
 
 
 
 
 
70
  for path in sorted(root.rglob("*")):
71
  if not path.is_file() or not is_script(path):
72
  continue
73
  relative = path.relative_to(root)
74
  if is_skipped(relative):
75
  continue
 
 
76
  yield path, relative
77
 
78
 
 
66
 
67
 
68
  def iter_scripts(root: Path):
69
+ """Yield every script under `root`, in a stable order.
70
+
71
+ A `.rpyc` is only read when it has no `.rpy` sibling. Where both exist,
72
+ Ren'Py itself always treats the `.rpy` as the source of truth and the
73
+ `.rpyc` as a disposable compiled cache, and this tool follows the same
74
+ rule - reading both would translate the same dialogue twice, and shipping
75
+ a `.rpy` we edited next to a `.rpyc` we cannot touch leaves a stale
76
+ compiled tree on disk that no longer matches the source next to it.
77
+ """
78
+ all_paths = {p.relative_to(root) for p in root.rglob("*") if p.is_file()}
79
  for path in sorted(root.rglob("*")):
80
  if not path.is_file() or not is_script(path):
81
  continue
82
  relative = path.relative_to(root)
83
  if is_skipped(relative):
84
  continue
85
+ if path.suffix.lower() == ".rpyc" and relative.with_suffix(".rpy") in all_paths:
86
+ continue
87
  yield path, relative
88
 
89
 
app/renpy/rpyc.py CHANGED
@@ -1,11 +1,38 @@
1
- """Read the dialogue out of a compiled .rpyc script.
2
-
3
- A .rpyc holds Ren'Py's parsed syntax tree, pickled and deflated. That is
4
- enough to *read* every line of dialogue, which is what makes it possible to
5
- translate a game that ships without its .rpy sources. It is not enough to write
6
- one back: the tree also encodes line numbers and file offsets that the engine
7
- checks, so translated text reaches these games through a generated translation
8
- file instead of an edit.
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
9
 
10
  Unpickling a file from a stranger normally means running their code - the
11
  pickle format can name any importable object and call it. This reader never
@@ -16,8 +43,10 @@ malicious .rpyc has nothing to reach for.
16
 
17
  from __future__ import annotations
18
 
 
19
  import io
20
  import pickle
 
21
  import struct
22
  import zlib
23
  from pathlib import Path
@@ -31,20 +60,84 @@ _MENU_NODES = {"Menu"}
31
  # part-translated game from being translated a second time.
32
  _TRANSLATE_NODES = {"Translate", "TranslateString", "TranslateBlock", "TranslatePython"}
33
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
34
  _MAX_NODES = 2_000_000
35
 
36
 
 
 
 
 
37
  class _Stand:
38
  """Inert stand-in for a class named inside the pickle."""
39
 
40
  __slots__ = ("__dict__",)
41
 
42
- def __init__(self, *args, **kwargs) -> None:
43
- # Ren'Py reconstructs most nodes through __setstate__, but a few are
44
- # built with positional arguments; keeping them lets the walker still
45
- # see any strings they carry.
 
 
46
  if args:
47
  self.__dict__["_args"] = args
 
 
 
 
48
 
49
  def __setstate__(self, state) -> None:
50
  if isinstance(state, dict):
@@ -85,6 +178,126 @@ class _SafeUnpickler(pickle.Unpickler):
85
  return None
86
 
87
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
88
  def _slots(blob: bytes) -> dict[int, bytes]:
89
  """Split an RPC2 container into its numbered slots."""
90
  slots: dict[int, bytes] = {}
@@ -100,6 +313,16 @@ def _slots(blob: bytes) -> dict[int, bytes]:
100
  return slots
101
 
102
 
 
 
 
 
 
 
 
 
 
 
103
  def _load_tree(path: Path):
104
  blob = path.read_bytes()
105
  if blob.startswith(_MAGIC):
@@ -109,17 +332,17 @@ def _load_tree(path: Path):
109
  payload = slots.get(1)
110
  if payload is None:
111
  raise ValueError("no syntax-tree slot in .rpyc")
112
- data = zlib.decompress(payload)
113
  else:
114
  # Ren'Py 6.17 and older: the whole file is one deflated pickle.
115
- data = zlib.decompress(blob)
116
  return _SafeUnpickler(io.BytesIO(data)).load()
117
 
118
 
119
  def _walk(node, sink, seen: set[int], budget: list[int]) -> None:
120
  """Collect dialogue from the object graph, depth first."""
121
  if budget[0] <= 0:
122
- return
123
  budget[0] -= 1
124
 
125
  if isinstance(node, (str, bytes, int, float, bool, type(None))):
@@ -154,6 +377,8 @@ def _walk(node, sink, seen: set[int], budget: list[int]) -> None:
154
 
155
  if kind in _SAY_NODES:
156
  what = fields.get("what")
 
 
157
  if isinstance(what, str):
158
  sink(what, "dialogue")
159
 
@@ -161,8 +386,16 @@ def _walk(node, sink, seen: set[int], budget: list[int]) -> None:
161
  items = fields.get("items")
162
  if isinstance(items, (list, tuple)):
163
  for item in items:
164
- if isinstance(item, (list, tuple)) and item and isinstance(item[0], str):
165
- sink(item[0], "menu")
 
 
 
 
 
 
 
 
166
 
167
  for value in fields.values():
168
  _walk(value, sink, seen, budget)
 
1
+ """Read the player-visible text out of a compiled .rpyc script.
2
+
3
+ A .rpyc holds Ren'Py's parsed syntax tree, pickled and deflated. Mobile builds
4
+ routinely ship without any .rpy sources, so this is the only way to reach
5
+ their text at all - it is a first-class path here, not a fallback.
6
+
7
+ Two kinds of text come out, and they are found very differently:
8
+
9
+ * **Dialogue and menu choices** are stored in the tree as plain strings. Say
10
+ text is never evaluated as code, only substituted (`[var]`) at display time,
11
+ so `Say.what` and a `Menu` item's label can simply be read.
12
+
13
+ * **Screen text** - `text`, `textbutton`, `label`, `tooltip` inside a `screen`
14
+ block - is not stored as a string at all. Ren'Py compiles *every* screen
15
+ argument, including a plain `"Continue"`, into a `PyExpr` holding Python
16
+ source, and the label sits in exactly the same position as a style name, an
17
+ action or a variable. So a label cannot be recognised by position; it has to
18
+ be recognised by *shape*. Each argument's source is parsed and accepted only
19
+ when it is a bare string literal or an explicit `_()` / `__()` translation
20
+ marker - never a name, attribute or call. That is what keeps
21
+ `Preference("text speed")`, `gui.main_menu_background`, `i.caption` and
22
+ `SideImage()` out, while letting `_("Options")` and `"Fonlar: [fon]"`
23
+ through.
24
+
25
+ Two traps are worth naming, because both are real strings that look
26
+ translatable and are not. `key "K_F5"` puts a keysym in the same slot a
27
+ label would occupy - excluded because a `key` statement has no text style.
28
+ And Ren'Py's own help screen writes its key names as bare `"H"` / `"Shift+A"`
29
+ while wrapping every description beside them in `_()`; translating a key
30
+ name renames a control the player then cannot find.
31
+
32
+ It is not enough to write a translation back into the .rpyc: the tree also
33
+ encodes line numbers and file offsets that the engine checks, so translated
34
+ text reaches these games through a generated translation file instead of an
35
+ edit - see `tl.py`.
36
 
37
  Unpickling a file from a stranger normally means running their code - the
38
  pickle format can name any importable object and call it. This reader never
 
43
 
44
  from __future__ import annotations
45
 
46
+ import ast
47
  import io
48
  import pickle
49
+ import re
50
  import struct
51
  import zlib
52
  from pathlib import Path
 
60
  # part-translated game from being translated a second time.
61
  _TRANSLATE_NODES = {"Translate", "TranslateString", "TranslateBlock", "TranslatePython"}
62
 
63
+ # Screen-language nodes carrying player-visible text.
64
+ #
65
+ # `SLDisplayable.style` names the *built-in* style of the widget, which is set
66
+ # by which statement created it and is not changed by a `style "foo"` keyword
67
+ # override. That makes it a reliable statement identifier:
68
+ #
69
+ # text "..." -> style "text"
70
+ # textbutton "..." -> style "button"
71
+ # label "..." -> style "label"
72
+ #
73
+ # Everything else is deliberately excluded, and the exclusions matter as much
74
+ # as the inclusions: `key "K_F5"`, `add gui.main_menu_background` and
75
+ # `imagebutton auto="..."` all carry string arguments that are keysyms, asset
76
+ # names or style prefixes rather than text, and they arrive with a style of
77
+ # None or one not listed here.
78
+ _TEXT_STYLES = {"text", "button", "label"}
79
+
80
+ # Keyword arguments that hold text rather than configuration. Kept to the two
81
+ # Ren'Py documents as player-facing; `action`, `style`, `value` and `hovered`
82
+ # routinely hold string literals that are code or style names.
83
+ _TEXT_KEYWORDS = {"tooltip", "alt"}
84
+
85
+ _SL_DISPLAYABLE_NODES = {"SLDisplayable"}
86
+ _SL_USE_NODES = {"SLUse"}
87
+
88
+ # Bare (not `_()`-wrapped) literals matching these are input bindings, not
89
+ # prose. Ren'Py's own help screen is the reason this exists: it writes the key
90
+ # names as plain strings - "H", "S", "Shift+A" - while wrapping every
91
+ # description beside them in `_()`. Translating a key name renames a control
92
+ # the player then cannot find.
93
+ # Ren'Py's disambiguation tag: `{#auto_page}A` displays as just "A", the tag
94
+ # existing only to keep two otherwise identical strings apart in a translation
95
+ # file. It has to stay in the key verbatim, but it must not hide a one-letter
96
+ # control label from the shortcut check above.
97
+ _DISAMBIGUATION_RE = re.compile(r"\{#[^}]*\}")
98
+
99
+ _SHORTCUT_RE = re.compile(
100
+ r"""^(?:
101
+ [A-Za-z0-9] # one key: H, S, 1
102
+ | K_[A-Za-z0-9_]+ # Ren'Py keysym: K_F5
103
+ | F\d{1,2} # F1 .. F12
104
+ | (?:Shift|Ctrl|Control|Alt|Cmd|Meta|Super) # modifier combinations
105
+ (?:\s*\+\s*[A-Za-z0-9_]+)+
106
+ | (?:mouse|joy|pad)_[A-Za-z0-9_]+ # input device ids
107
+ )$""",
108
+ re.VERBOSE,
109
+ )
110
+
111
+ # Depth-first node budget. Real scripts need a few AST objects per line of
112
+ # dialogue, so a script with tens of thousands of lines stays orders of
113
+ # magnitude under this - it exists to bound a pathological or corrupted file,
114
+ # not real games. If it is ever exhausted, the file is reported as unreadable
115
+ # rather than silently returning a partial scan: a game that is missing lines
116
+ # with no warning is worse than one flagged for a manual look.
117
  _MAX_NODES = 2_000_000
118
 
119
 
120
+ class BudgetExceeded(Exception):
121
+ """The node walk hit `_MAX_NODES` - the file may not be fully read."""
122
+
123
+
124
  class _Stand:
125
  """Inert stand-in for a class named inside the pickle."""
126
 
127
  __slots__ = ("__dict__",)
128
 
129
+ def __new__(cls, *args, **kwargs):
130
+ # Overridden (rather than relying on the default object.__new__)
131
+ # specifically so positional constructor arguments are captured no
132
+ # matter which pickle opcode built this object - NEWOBJ reconstructs
133
+ # via __new__ alone and never calls __init__.
134
+ self = object.__new__(cls)
135
  if args:
136
  self.__dict__["_args"] = args
137
+ return self
138
+
139
+ def __init__(self, *args, **kwargs) -> None:
140
+ pass
141
 
142
  def __setstate__(self, state) -> None:
143
  if isinstance(state, dict):
 
178
  return None
179
 
180
 
181
+ def _expr_source(node) -> str | None:
182
+ """The Python source behind a compiled screen argument.
183
+
184
+ Ren'Py stores every screen-language argument as a PyExpr - a str subclass
185
+ carrying the expression's source plus its origin. Reconstructed through the
186
+ inert stand-in above, that source is the first constructor argument.
187
+ """
188
+ if type(node).__name__ != "PyExpr":
189
+ return None
190
+ args = getattr(node, "__dict__", {}).get("_args")
191
+ if args and isinstance(args[0], str):
192
+ return args[0]
193
+ return None
194
+
195
+
196
+ def _literal_from_expr(source: str) -> tuple[str, bool] | None:
197
+ """Pull a translatable literal out of one screen argument.
198
+
199
+ Returns `(text, explicitly_marked)`, or None when the argument is anything
200
+ other than a plain string. This is the whole safety story for screen text:
201
+ a screen argument is an arbitrary Python expression, and `title`,
202
+ `i.caption`, `SideImage()` and `Preference("text speed")` all sit in the
203
+ same position as the label the player reads. Parsing the source and
204
+ accepting only a literal - never a name, attribute or call - is what keeps
205
+ a style name or an action from being handed to a translator.
206
+
207
+ `explicitly_marked` is True for `_("...")` and `__("...")`, Ren'Py's own
208
+ "this string is shown to a human" marker. It is the difference between a
209
+ caption and a keysym in Ren'Py's own screens, so callers hold bare literals
210
+ to a stricter standard.
211
+ """
212
+ try:
213
+ parsed = ast.parse(source.strip(), mode="eval").body
214
+ except (SyntaxError, ValueError, MemoryError, RecursionError):
215
+ return None
216
+
217
+ if isinstance(parsed, ast.Constant) and isinstance(parsed.value, str):
218
+ return parsed.value, False
219
+
220
+ if (
221
+ isinstance(parsed, ast.Call)
222
+ and isinstance(parsed.func, ast.Name)
223
+ and parsed.func.id in ("_", "__")
224
+ and len(parsed.args) == 1
225
+ and not parsed.keywords
226
+ and isinstance(parsed.args[0], ast.Constant)
227
+ and isinstance(parsed.args[0].value, str)
228
+ ):
229
+ return parsed.args[0].value, True
230
+
231
+ return None
232
+
233
+
234
+ def _screen_text(node, sink) -> None:
235
+ """Collect the player-visible strings from one screen-language node."""
236
+ fields = node.__dict__
237
+ kind = type(node).__name__
238
+
239
+ if kind in _SL_DISPLAYABLE_NODES:
240
+ if fields.get("style") in _TEXT_STYLES:
241
+ positional = fields.get("positional")
242
+ if isinstance(positional, (list, tuple)) and positional:
243
+ # The visible text is always the first positional argument;
244
+ # anything after it is configuration.
245
+ source = _expr_source(positional[0])
246
+ if source is not None:
247
+ _emit_literal(source, sink)
248
+
249
+ for entry in fields.get("keyword") or ():
250
+ if not isinstance(entry, (list, tuple)) or len(entry) != 2:
251
+ continue
252
+ name, value = entry
253
+ if name in _TEXT_KEYWORDS:
254
+ source = _expr_source(value)
255
+ if source is not None:
256
+ _emit_literal(source, sink)
257
+
258
+ elif kind in _SL_USE_NODES:
259
+ # `use game_menu(_("Options"))` - a screen's title is passed in rather
260
+ # than written inside it. Only positional arguments are read, and only
261
+ # explicitly marked ones: a bare literal in this position is far more
262
+ # often a configuration value (`scroll="viewport"`) than a caption.
263
+ args = getattr(fields.get("args"), "__dict__", {}).get("arguments")
264
+ for entry in args or ():
265
+ if not isinstance(entry, (list, tuple)) or len(entry) != 2:
266
+ continue
267
+ name, value = entry
268
+ if name is not None:
269
+ continue
270
+ source = _expr_source(value)
271
+ if source is None:
272
+ continue
273
+ found = _literal_from_expr(source)
274
+ if found and found[1]:
275
+ sink(found[0], "ui")
276
+
277
+
278
+ def _emit_literal(source: str, sink) -> None:
279
+ found = _literal_from_expr(source)
280
+ if found is None:
281
+ return
282
+ text, explicit = found
283
+ visible = _DISAMBIGUATION_RE.sub("", text).strip()
284
+
285
+ # A label whose whole visible content is one character is a glyph, not
286
+ # prose - the "A" and "Q" on Ren'Py's auto-page and quick-page buttons.
287
+ # These carry a disambiguation tag precisely *because* a bare "A" is
288
+ # meaningless to a translator, and they sit in fixed-width square buttons.
289
+ # There is nothing to gain by translating one and a layout to lose if the
290
+ # model answers with a word, so they are skipped even when explicitly
291
+ # marked with _().
292
+ if len(visible) <= 1:
293
+ return
294
+
295
+ if not explicit and _SHORTCUT_RE.match(visible):
296
+ return
297
+
298
+ sink(text, "ui")
299
+
300
+
301
  def _slots(blob: bytes) -> dict[int, bytes]:
302
  """Split an RPC2 container into its numbered slots."""
303
  slots: dict[int, bytes] = {}
 
313
  return slots
314
 
315
 
316
+ def _inflate(payload: bytes) -> bytes:
317
+ try:
318
+ return zlib.decompress(payload)
319
+ except zlib.error:
320
+ # Every RPC2 slot shipped by every Ren'Py release so far is deflated,
321
+ # but the fallback costs nothing and means a future format change
322
+ # degrades to "read the raw pickle" instead of an outright failure.
323
+ return payload
324
+
325
+
326
  def _load_tree(path: Path):
327
  blob = path.read_bytes()
328
  if blob.startswith(_MAGIC):
 
332
  payload = slots.get(1)
333
  if payload is None:
334
  raise ValueError("no syntax-tree slot in .rpyc")
335
+ data = _inflate(payload)
336
  else:
337
  # Ren'Py 6.17 and older: the whole file is one deflated pickle.
338
+ data = _inflate(blob)
339
  return _SafeUnpickler(io.BytesIO(data)).load()
340
 
341
 
342
  def _walk(node, sink, seen: set[int], budget: list[int]) -> None:
343
  """Collect dialogue from the object graph, depth first."""
344
  if budget[0] <= 0:
345
+ raise BudgetExceeded
346
  budget[0] -= 1
347
 
348
  if isinstance(node, (str, bytes, int, float, bool, type(None))):
 
377
 
378
  if kind in _SAY_NODES:
379
  what = fields.get("what")
380
+ if isinstance(what, bytes):
381
+ what = what.decode("utf-8", errors="replace")
382
  if isinstance(what, str):
383
  sink(what, "dialogue")
384
 
 
386
  items = fields.get("items")
387
  if isinstance(items, (list, tuple)):
388
  for item in items:
389
+ if not isinstance(item, (list, tuple)) or not item:
390
+ continue
391
+ label = item[0]
392
+ if isinstance(label, bytes):
393
+ label = label.decode("utf-8", errors="replace")
394
+ if isinstance(label, str):
395
+ sink(label, "menu")
396
+
397
+ elif kind in _SL_DISPLAYABLE_NODES or kind in _SL_USE_NODES:
398
+ _screen_text(node, sink)
399
 
400
  for value in fields.values():
401
  _walk(value, sink, seen, budget)
app/renpy/store.py CHANGED
@@ -215,12 +215,36 @@ def purge_expired() -> list[str]:
215
  return removed
216
 
217
 
218
- def build_output(project_id: str, meta: dict) -> Path:
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
219
  """Package the translated scripts.
220
 
221
  Only files that actually changed go in the zip. A Ren'Py game folder is
222
  mostly art and audio, and shipping it back unchanged would turn a few
223
  hundred kilobytes of script into a download the size of the game.
 
 
 
224
  """
225
  from . import inject, tl
226
 
@@ -245,6 +269,18 @@ def build_output(project_id: str, meta: dict) -> Path:
245
  if slot.writable
246
  }
247
 
 
 
 
 
 
 
 
 
 
 
 
 
248
  generated = tl.write_runtime_translation(staging, units, translations, lang)
249
 
250
  output = base / "translated.zip"
@@ -256,5 +292,8 @@ def build_output(project_id: str, meta: dict) -> Path:
256
  zf.write(path, name)
257
  for path in generated:
258
  zf.write(path, path.relative_to(staging).as_posix())
 
 
 
259
  shutil.rmtree(staging, ignore_errors=True)
260
- return output
 
215
  return removed
216
 
217
 
218
+ _STALE_NOTICE_NAME = "HYMT_DELETE_THESE_RPYC_FIRST.txt"
219
+
220
+ _STALE_NOTICE_HEADER = """\
221
+ Before copying the files from this zip into your game, delete these exact
222
+ files from your game folder (they will NOT be deleted by extracting this zip
223
+ - zip extraction only adds/overwrites files, it never removes anything):
224
+
225
+ """
226
+
227
+ _STALE_NOTICE_FOOTER = """
228
+
229
+ Why: your project ships a precompiled .rpyc next to each .rpy. Ren'Py treats
230
+ the .rpy as the source of truth and the .rpyc as a disposable cache, but a
231
+ .rpyc left over from BEFORE translation no longer matches the .rpy you are
232
+ about to install - and Ren'Py running that stale compiled version against the
233
+ new source is what produces crashes like "must return a Text object" the
234
+ moment a translated line is reached. Deleting the .rpyc removes the mismatch:
235
+ Ren'Py recompiles a fresh one from the translated .rpy on next launch.
236
+ """
237
+
238
+
239
+ def build_output(project_id: str, meta: dict) -> tuple[Path, list[str]]:
240
  """Package the translated scripts.
241
 
242
  Only files that actually changed go in the zip. A Ren'Py game folder is
243
  mostly art and audio, and shipping it back unchanged would turn a few
244
  hundred kilobytes of script into a download the size of the game.
245
+
246
+ Returns the zip path and the list of stale sibling .rpyc files the caller
247
+ still has on disk from before translation - see `_STALE_NOTICE_FOOTER`.
248
  """
249
  from . import inject, tl
250
 
 
269
  if slot.writable
270
  }
271
 
272
+ # A .rpy we just edited may still have an untouched .rpyc sibling sitting
273
+ # in the user's own game folder from before translation - never inside
274
+ # this zip (extract() never reads it once a .rpy sibling exists), but
275
+ # still on their disk, and now stale relative to the file we are about to
276
+ # hand them.
277
+ source = source_dir(project_id)
278
+ stale_rpyc = sorted(
279
+ name[:-4] + ".rpyc"
280
+ for name in changed
281
+ if name.endswith(".rpy") and (source / (name[:-4] + ".rpyc")).is_file()
282
+ )
283
+
284
  generated = tl.write_runtime_translation(staging, units, translations, lang)
285
 
286
  output = base / "translated.zip"
 
292
  zf.write(path, name)
293
  for path in generated:
294
  zf.write(path, path.relative_to(staging).as_posix())
295
+ if stale_rpyc:
296
+ notice = _STALE_NOTICE_HEADER + "\n".join(stale_rpyc) + _STALE_NOTICE_FOOTER
297
+ zf.writestr(_STALE_NOTICE_NAME, notice)
298
  shutil.rmtree(staging, ignore_errors=True)
299
+ return output, stale_rpyc
app/renpy/tl.py CHANGED
@@ -133,15 +133,33 @@ def write_runtime_translation(
133
  Returns the files created, which is empty when the project had no compiled
134
  scripts.
135
  """
136
- mapping: dict[str, str] = {}
 
 
 
 
 
 
 
 
 
 
 
 
 
 
137
  for unit in units:
138
  translated = translations.get(unit.source)
139
  if translated is None or translated == unit.source:
140
  continue
141
- if any(not slot.writable for slot in unit.slots):
142
- mapping[unit.source] = translated
 
 
 
 
143
 
144
- if not mapping:
145
  return []
146
 
147
  lang = language_name(target_lang)
@@ -149,19 +167,23 @@ def write_runtime_translation(
149
  tl_dir = root / "tl" / lang
150
  tl_dir.mkdir(parents=True, exist_ok=True)
151
 
152
- json_path = tl_dir / _JSON_NAME
153
- json_path.write_text(
154
- json.dumps(mapping, ensure_ascii=False, indent=1), encoding="utf-8"
155
- )
156
 
157
- hook_path = root / _HOOK_NAME
158
- hook_path.write_text(_render_hook(lang), encoding="utf-8")
 
 
 
 
 
 
159
 
160
  # dict keys are unique by construction, so no `old` can repeat - the
161
  # condition Ren'Py refuses to start on.
162
- pairs = sorted(mapping.items())
163
  assert len({source for source, _ in pairs}) == len(pairs)
164
  strings_path = tl_dir / _STRINGS_NAME
165
  strings_path.write_text(_render_strings(lang, pairs), encoding="utf-8")
 
166
 
167
- return [json_path, hook_path, strings_path]
 
133
  Returns the files created, which is empty when the project had no compiled
134
  scripts.
135
  """
136
+ # Two delivery routes, because Ren'Py exposes two different hooks and each
137
+ # one only sees its own kind of text:
138
+ #
139
+ # say/menu text -> config.say_menu_text_filter, keyed on the untranslated
140
+ # line. The filter is never handed screen text, so
141
+ # putting interface strings in its map would only bloat
142
+ # a file that is read at launch.
143
+ # screen text -> `translate <lang> strings:`, the table Ren'Py's own
144
+ # string translation consults. This is the same shape
145
+ # the launcher's "Generate Translations" produces, so it
146
+ # is the route the engine already expects these in.
147
+ #
148
+ # Everything goes in the strings block; only dialogue also goes in the map.
149
+ dialogue: dict[str, str] = {}
150
+ strings: dict[str, str] = {}
151
  for unit in units:
152
  translated = translations.get(unit.source)
153
  if translated is None or translated == unit.source:
154
  continue
155
+ compiled = [slot for slot in unit.slots if not slot.writable]
156
+ if not compiled:
157
+ continue
158
+ strings[unit.source] = translated
159
+ if any(slot.kind in ("dialogue", "menu") for slot in compiled):
160
+ dialogue[unit.source] = translated
161
 
162
+ if not strings:
163
  return []
164
 
165
  lang = language_name(target_lang)
 
167
  tl_dir = root / "tl" / lang
168
  tl_dir.mkdir(parents=True, exist_ok=True)
169
 
170
+ written: list[Path] = []
 
 
 
171
 
172
+ if dialogue:
173
+ json_path = tl_dir / _JSON_NAME
174
+ json_path.write_text(
175
+ json.dumps(dialogue, ensure_ascii=False, indent=1), encoding="utf-8"
176
+ )
177
+ hook_path = root / _HOOK_NAME
178
+ hook_path.write_text(_render_hook(lang), encoding="utf-8")
179
+ written += [json_path, hook_path]
180
 
181
  # dict keys are unique by construction, so no `old` can repeat - the
182
  # condition Ren'Py refuses to start on.
183
+ pairs = sorted(strings.items())
184
  assert len({source for source, _ in pairs}) == len(pairs)
185
  strings_path = tl_dir / _STRINGS_NAME
186
  strings_path.write_text(_render_strings(lang, pairs), encoding="utf-8")
187
+ written.append(strings_path)
188
 
189
+ return written