"""A host for a generated canvas-app package: it runs the handlers the way the canvas runtime would. Copied verbatim into every generated package as ``host.py``. Standard library only; it imports nothing but its sibling modules (``model`` and ``behaviour``), which it is given rather than importing itself. The generated ``model.py`` computes every pure property from a Context, and ``behaviour.py`` applies the steps of each ``On*`` formula to it. What neither does is what the canvas runtime does *between* formulas: - a control whose value the user has not set shows its ``Default`` property, and follows that property whenever its value changes (``Toggle.Value``, ``TextInput.Text``, ``Slider.Value`` and so on); - a Toggle or Checkbox runs ``OnCheck`` when its value becomes true and ``OnUncheck`` when it becomes false, which is how canvas apps chain behaviour through "trigger" variables bound to hidden toggles; - a Timer runs ``OnTimerEnd`` when it starts (``Start`` or ``AutoStart`` true) and, with ``Repeat``, again; - a screen runs ``OnVisible`` when ``Navigate`` reaches it (and the one it left runs ``OnHidden``); - ``Reset(control)`` returns a control to its Default and stops a timer; - ``Sort`` keeps rows with equal keys in their order, as the player's JavaScript sort does. Microsoft's .NET interpreter, the reconciliation's reference, does not (``Array.Sort`` is unstable), so the runtime follows the interpreter unless ``powerfx.SORT_STABLE`` is set, which the host does. An app whose formulas depend on tie order (a FEN built from a board sorted by rank, then by file) runs correctly only with the player's order. The host applies those rules after every event until nothing changes, and logs every handler it ran. Two simplifications are deliberate and named here rather than hidden: time is collapsed, so a timer fires as soon as it starts (its Duration is a wait, never a computation) and a repeating timer fires once per settle so a polling timer cannot spin; and toggles are taken to start false, so a trigger that is true after ``App.OnStart`` fires its ``OnCheck`` once the first screen shows. """ from __future__ import annotations from typing import Any, Callable #: An input property and the Default property it follows until the user sets it. DEFAULT_OF = {"Value": "Default", "Text": "Default", "Selected": "Default", "SelectedDate": "DefaultDate"} #: Control kinds whose Value changing runs OnCheck / OnUncheck. CHECKED_KINDS = {"Toggle", "Checkbox"} class Host: """Drive a generated package's model and handlers with the canvas runtime's rules. ``model`` and ``behaviour`` are the package's generated modules; ``ctx`` is a ``model.Context`` holding the inputs (data tables, external values such as ``User()``). ``muted`` names controls whose events the host must not fire (a polling timer that only talks to a server, say); ``max_rounds`` bounds a settle. """ def __init__(self, model: Any, behaviour: Any, ctx: Any, muted: set[str] | None = None, max_rounds: int = 200): self.model = model self.behaviour = behaviour self.ctx = ctx self.fx = model.fx self.muted = set(muted or ()) self.max_rounds = max_rounds self.controls: dict[str, tuple[str, str]] = dict(getattr(model, "CONTROLS", {})) self.events = behaviour.EVENTS self.toggles = [name for name, (screen, kind) in self.controls.items() if kind in CHECKED_KINDS and (f"{screen}/{name}.OnCheck" in self.events or f"{screen}/{name}.OnUncheck" in self.events)] self.timers = [name for name, (_, kind) in self.controls.items() if kind == "Timer"] self.log: list[dict[str, Any]] = [] self.settled = True self._toggle_state: dict[str, bool] = {name: False for name in self.toggles} self._running: dict[str, bool] = {} self._pinned: dict[tuple[str, str], Any] = {} # (control, prop) -> the Default the user's value was set against self._visible: str | None = None self._effects_seen = 0 ctx.input_fallback = self._default_value self.fx.SORT_STABLE = True # the player's tie order, see the module docstring ctx.invalidate() # anything computed before the host took over used the interpreter's rules # -- what the app shows -------------------------------------------------------------------------------- def screen_of(self, control: str) -> str | None: entry = self.controls.get(control) return entry[0] if entry else None def prop(self, source: str, this_item: Any = None) -> Any: """A translated property by source id, ``'Game Screen/LabelMessage.Text'``.""" return self.ctx.prop(source, this_item) def value(self, control: str, prop: str) -> Any: """What a control's input property holds: the user's value if set, else its Default.""" return self.ctx.control_input(control, prop) def property(self, control: str, prop: str) -> Any: """A control's property as the app computes it (``Start`` of a timer, ``Visible`` of a button), else its input value.""" screen = self.screen_of(control) source = f"{screen}/{control}.{prop}" if source in self.model.PROPERTIES: return self.ctx.prop(source) return self.ctx.control_input(control, prop) def _default_value(self, control: str, prop: str) -> Any: default_prop = DEFAULT_OF.get(prop) screen = self.screen_of(control) if default_prop is None or screen is None: return None source = f"{screen}/{control}.{default_prop}" if source not in self.model.PROPERTIES: return None return self.ctx.prop(source) def rows(self, source: str) -> list: """The rows of a gallery's Items (or any table property), empty when it is an error.""" value = self.ctx.prop(source) return value if isinstance(value, list) else [] # -- what the user does --------------------------------------------------------------------------------- def start(self) -> None: """Run ``App.OnStart``, show the first screen and settle.""" self._run("App.OnStart") if self.ctx.screen is None: start = self.ctx.prop("App.StartScreen") if "App.StartScreen" in self.model.PROPERTIES else None screens = list(getattr(self.model, "SCREENS", [])) self.ctx.screen = start if isinstance(start, str) and start in screens else (screens[0] if screens else None) self.settle() def select(self, control: str, this_item: Any = None) -> None: """The user selects a control (a button, a gallery row given as ``this_item``).""" screen = self.screen_of(control) self.run(f"{screen}/{control}.OnSelect", this_item) def change(self, control: str, prop: str, value: Any) -> None: """The user sets an input (``Text`` of a text input, ``Value`` of a toggle) and its ``OnChange`` runs.""" self._pinned[(control, prop)] = self.fx.json_ready(self._default_value(control, prop)) self.ctx.controls.setdefault(control, {})[prop] = value self.ctx.invalidate() screen = self.screen_of(control) source = f"{screen}/{control}.OnChange" if source in self.events: self.run(source) else: self.settle() def run(self, source: str, this_item: Any = None) -> None: """Run one event by source id, then settle.""" self._run(source, this_item) self.settle() def navigate(self, screen: str) -> None: self.ctx.navigate(screen) self.settle() # -- the canvas runtime's rules ------------------------------------------------------------------------- def settle(self) -> bool: """Apply the runtime rules until nothing changes; False when the round cap was hit.""" fired_timers: set[str] = set() for _ in range(self.max_rounds): if self._round(fired_timers): continue self.settled = True return True self.settled = False self.log.append({"unsettled": f"the state had not settled after {self.max_rounds} rounds"}) return False def _round(self, fired_timers: set[str]) -> bool: """One pass over the rules; True when something ran or changed.""" ctx = self.ctx if ctx.screen != self._visible: left, self._visible = self._visible, ctx.screen if left is not None and f"{left}.OnHidden" in self.events: self._run(f"{left}.OnHidden") if ctx.screen is not None and f"{ctx.screen}.OnVisible" in self.events: self._run(f"{ctx.screen}.OnVisible") return True if self._apply_effects(): return True if self._unpin_followers(): return True for name in self.toggles: if name in self.muted: continue now = self.fx.to_bool(self.value(name, "Value")) is True if now != self._toggle_state[name]: self._toggle_state[name] = now source = f"{self.screen_of(name)}/{name}.{'OnCheck' if now else 'OnUncheck'}" if source in self.events: self._run(source) return True for name in self.timers: if name in self.muted: continue screen = self.screen_of(name) started = self.fx.to_bool(self.property(name, "Start")) is True or self.fx.to_bool(self.property(name, "AutoStart")) is True running = self._running.get(name, False) if not started: if running: self._running[name] = False continue repeat = self.fx.to_bool(self.property(name, "Repeat")) is True if (not running or repeat) and name not in fired_timers: self._running[name] = True fired_timers.add(name) source = f"{screen}/{name}.OnTimerEnd" if source in self.events: self._run(source) return True return False def _apply_effects(self) -> bool: """Read the effects handlers logged since the last look: a Reset stops a timer.""" changed = False new = self.ctx.effects[self._effects_seen:] self._effects_seen = len(self.ctx.effects) for e in new: if e.get("effect") == "Reset": for name in e.get("args", []): if name in self.timers and self._running.get(name): self._running[name] = False changed = True self._pinned = {k: v for k, v in self._pinned.items() if k[0] != name} return changed def _unpin_followers(self) -> bool: """A user-set value is dropped when the Default it was set against has since changed (the control follows its Default).""" changed = False for (control, prop), default_then in list(self._pinned.items()): default_now = self.fx.json_ready(self._default_value(control, prop)) if default_now != default_then: self._pinned.pop((control, prop), None) props = self.ctx.controls.get(control) if props is not None and prop in props: del props[prop] changed = True if changed: self.ctx.invalidate() return changed def _run(self, source: str, this_item: Any = None) -> None: before = len(self.ctx.effects) error = None try: self.behaviour.run(self.ctx, source, this_item) except Exception as exc: # noqa: BLE001 - a crash in a handler is a finding for the log, and the host keeps running error = f"{type(exc).__name__}: {exc}" self.log.append({"event": source, "screen": self.ctx.screen, "effects": list(self.ctx.effects[before:]), "error": error}) # -- for a user interface ------------------------------------------------------------------------------- def notifications(self, since: int = 0) -> list[dict[str, Any]]: """``Notify`` effects logged since index ``since`` of ``ctx.effects``.""" return [e for e in self.ctx.effects[since:] if e.get("effect") == "Notify"] def on_screen(self, kind: str | None = None) -> list[str]: """Controls on the current screen, optionally of one kind.""" return [name for name, (screen, k) in self.controls.items() if screen == self.ctx.screen and (kind is None or k == kind)] def make_host(pkg: Any, raw_inputs: dict[str, Any], **kwargs: Any) -> Host: """A Host over a loaded package (``power_migrate.reconcile.load_package``) and inputs in the ``inputs.json`` layout.""" ctx = pkg.Context.from_dict(raw_inputs) return Host(pkg.model, pkg.behaviour, ctx, **kwargs) __all__ = ["CHECKED_KINDS", "DEFAULT_OF", "Host", "make_host"]