# The Sin Within 0.5.1 + URM 2.6.2 / Ren'Py 8.5.2 compatibility (v4). # Install this one file in game/ and fully restart the game. # URM attaches its textbox hook at priority 999. This MUST run afterward. # Keep the say_arguments_callback customization; restore only the engine # function URM replaced. Normal empty-say-screen transitions are restored. init 1000 python hide: import renpy as _engine import pickle as _pickle _screen = _engine.display.screen _exported = _engine.exports.show_screen _urm = getattr(_engine.store, "x52URM", None) _textbox = getattr(_urm, "TextBox", None) _original = getattr(_textbox, "_m1_textbox__originalShowScreen", None) _capture = getattr(_textbox, "_m1_textbox__captureSayScreen", None) if _screen.show_screen is _exported: _status = "already canonical" elif (_original is _exported and _original is not None and _screen.show_screen == _capture): _screen.show_screen = _original _status = "restored after URM initialization" else: raise RuntimeError( "URM Sandbox save fix: unexpected show_screen hook. " "The compatibility patch could not safely restore it." ) # Verify the actual runtime function, rather than silently skipping. if _pickle.loads(_pickle.dumps(_exported)) is not _exported: raise RuntimeError("URM Sandbox save fix: function identity check failed.") # URM uses the old location after Apply/Cancel returns from its preview. # Alias the real exception: do not swallow errors or skip context restart. if not hasattr(_engine.game, "RestartContext"): _engine.game.RestartContext = _engine.execution.RestartContext _engine.exports.log("URM compatibility v4: " + _status + "; pickle check passed; context restart compatibility ready.") # Replace only the obsolete incompatibility warning, after game screens load. # Main_UI continues to use this screen normally; the replacement draws nothing. init 1001: screen URMWARNING(): null # Compatibility helpers live in a constant store, outside saved game state. init 1000 python in _urm_compat: _constant = True import re import ast from collections.abc import Mapping import renpy as engine def resolve(path): """Resolve character paths without executing saved rule text as Python.""" def walk(node): if isinstance(node, ast.Name): return getattr(engine.store, node.id) if isinstance(node, ast.Attribute): return getattr(walk(node.value), node.attr) if isinstance(node, ast.Subscript) and isinstance(node.slice, ast.Constant): return walk(node.value)[node.slice.value] raise ValueError("Unsupported character path") try: return walk(ast.parse(path, mode="eval").body) except (AttributeError, KeyError, IndexError, TypeError, ValueError, SyntaxError): return None def rule_for(original): rule = engine.store.x52URM.TextRepl.store.get(original) if not isinstance(rule, Mapping) or not original: return None path = rule.get("characterVar") if path and not isinstance(resolve(path), engine.character.ADVCharacter): return None # A removed or not-yet-created character is not game code. return rule def plain(text, original, rule): # Treat replacement values literally, including regex backslashes. replacement = str(rule.get("replacement", "")).replace("{", "{{") flags = re.IGNORECASE if rule.get("caseInsensitive") else 0 pattern = re.escape(original) if not rule.get("replacePartialWords"): pattern = r"\b" + pattern + r"(?!\w)" pattern = re.compile(pattern, flags) # Keep tag names, parameters, image paths and hyperlinks intact. parts = re.split(r"(\{\{|\{[^{}]*\})", text) return "".join(part if i % 2 else pattern.sub(lambda match: replacement, part) for i, part in enumerate(parts)) def value(current, original, conversion=""): """Apply a rule to a resolved value, never to its Python expression.""" rule = rule_for(original) if rule is None: return current if isinstance(current, engine.character.ADVCharacter): if rule.get("characterVar") and resolve(rule["characterVar"]) is current: return str(rule.get("replacement", "")).replace("{", "{{") return current if not isinstance(current, str): return current # Preserve numbers and objects for Ren'Py formatting. result = plain(current, original, rule) if "i" in conversion and result != current: result = result.replace("[", "[[") return result def replace(self, text, original): rule = rule_for(original) if rule is None or not isinstance(text, str): return text output = [] for literal, expression, conversion, formatting in engine.substitutions.parse(text): output.append(plain(literal, original, rule).replace("[", "[[")) if expression is None: continue # Explicit [variable] replacement remains supported. if original == "[" + expression + "]" and conversion is None and formatting is None: output.append(str(rule.get("replacement", "")).replace("[", "[[").replace("{", "{{")) continue # Keep Python names/indexes intact, and rename only their resulting text. # Do not wrap debug expressions (expr=), whose original spelling is displayed. if expression.rstrip().endswith("="): wrapped = expression else: wrapped = "_urm_compat.value(({}), {!r}, {!r})".format(expression, original, conversion or "") output.append("[" + wrapped + ("!" + conversion if conversion is not None else "") + (":" + formatting if formatting is not None else "") + "]") return "".join(output) def say_filter(self, who, *args, **kwargs): previous = self._m1_textrepl__defaultSayFilter if previous: args, kwargs = previous(who, *args, **kwargs) for original, rule in self.store.items(): if not isinstance(rule, Mapping) or not rule.get("characterVar"): continue target = resolve(rule["characterVar"]) if target is None or not (target is who or isinstance(who, str) and who == original): continue name = str(rule.get("replacement", "")).replace("[", "[[").replace("{", "{{") kwargs["name"] = repr(name) if getattr(who, "dynamic", False) else name break return args, kwargs def character_init(self, varName): if not isinstance(resolve(varName), engine.character.ADVCharacter): raise ValueError("Not a character: " + str(varName)) self.varName = varName self._m1_Characters__substituionErrorLogged = False def character_who(self): return resolve(self.varName) def characters_reload(self): urm = engine.store.x52URM found = [] # This game's Sandbox keeps dialogue Characters inside NPC/MC objects. owner_types = tuple(t for t in (getattr(engine.store, "NPC", None), getattr(engine.store, "MC", None)) if isinstance(t, type)) for key, obj in list(engine.store.__dict__.items()): if isinstance(obj, engine.character.ADVCharacter): if isinstance(obj.name, str): found.append(urm.Character(key)) elif owner_types and isinstance(obj, owner_types): for attr, child in vars(obj).items(): if isinstance(child, engine.character.ADVCharacter) and isinstance(child.name, str): found.append(urm.Character(key + "." + attr)) self._m1_Characters__characters = found def preview_get(self): who = resolve(self.previewCharacterVarName) if self.previewCharacterVarName else None return who if isinstance(who, engine.character.ADVCharacter) else self.demoCharacter def preview_set(self, path): self.previewCharacterVarName = path if isinstance(resolve(path), engine.character.ADVCharacter) else None def settings_for_character(self, char): if isinstance(char, str) and char in self.store: return self.store[char] if isinstance(char, engine.character.ADVCharacter): for path in self.store: if path != "None" and resolve(path) is char: return self.store[path] return self.store.get("None") def list_changes(self, oldList, newList): # Preserve set-like membership semantics while supporting lists/dicts. def unique(items): result = [] for item in items: if item not in result: result.append(item) return result old, new = unique(oldList), unique(newList) return ([{"type": "Added", "val": item} for item in new if item not in old] + [{"type": "Removed", "val": item} for item in old if item not in new]) def settings_init(self, char=None): # Apply/remove/import can change a rule without changing the character. cls = engine.store.x52URM.TextBoxSettings cls._m1_textbox__tempValues = None cls._m1_textbox__values = self._m1_textbox__getSettingsForChar(char) cls._m1_textbox__valuesChar = char api_original_fetch = None def api_fetch(self, url, onSuccess, onError, body=None, headers=None): # URM's Updates screen passes this no-argument callback to an API # that supplies response/error data. Adapt only that known mismatch. def adapt(callback): if callback is engine.exports.restart_interaction: return lambda *unused: engine.exports.restart_interaction() return callback return api_original_fetch(self, url, adapt(onSuccess), adapt(onError), body, headers) def install(): global api_original_fetch urm = getattr(engine.store, "x52URM", None) if urm is None: return # Install class methods before the existing bound callbacks are invoked. urm.TextReplacementsClass._m1_textrepl__replace = replace # The filter already captured a bound method: update that method's code # in its original globals, preserving callback identity and chain order. original = urm.TextReplacementsClass._m1_textrepl__sayFilter original.__globals__["_urm_compat"] = engine.store._urm_compat original.__code__ = say_dispatch.__code__ urm.SnapshotsClass.findListChanges = list_changes urm.Character.__init__ = character_init urm.Character.who = property(character_who) urm.CharactersClass.reload = characters_reload # Refresh on access: Sandbox creation/load can replace NPC instances. urm.CharactersClass.all = property(characters_all) urm.TextBoxClass.previewCharacter = property(preview_get, preview_set) urm.TextBoxSettings._m1_textbox__getSettingsForChar = settings_for_character urm.TextBoxSettings.__init__ = settings_init if api_original_fetch is None: api_original_fetch = urm.x52API.fetch urm.x52API.fetch = api_fetch engine.exports.log("URM compatibility v4: expression-safe replacements and nested-character support installed.") def characters_all(self): self.reload() return self._m1_Characters__characters def say_dispatch(self, who, *args, **kwargs): return _urm_compat.say_filter(self, who, *args, **kwargs) init 1001 python hide: renpy.store._urm_compat.install()