@native-sdk/cli 0.5.3 → 0.6.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (172) hide show
  1. package/build/app.zig +91 -2
  2. package/build.zig +756 -5
  3. package/build.zig.zon +7 -0
  4. package/native-sdk.d.ts +19 -1
  5. package/package.json +9 -9
  6. package/packages/core/package-lock.json +2 -2
  7. package/packages/core/package.json +1 -1
  8. package/packages/core/rt/rt.zig +416 -9
  9. package/packages/core/sdk/core.ts +706 -5
  10. package/packages/core/sdk/events.ts +17 -8
  11. package/packages/core/src/checker.ts +305 -2
  12. package/packages/core/src/diagnostics.ts +12 -0
  13. package/packages/core/src/emitter.ts +3187 -264
  14. package/packages/core/src/typed_ast.ts +51 -4
  15. package/packages/core/src/types.ts +34 -1
  16. package/skill-data/native-ui/SKILL.md +42 -4
  17. package/skill-data/ts-core/SKILL.md +13 -3
  18. package/src/app_runner/root.zig +112 -10
  19. package/src/app_runner/ts_core_main.zig +4 -0
  20. package/src/automation/layout_fingerprint.zig +160 -0
  21. package/src/automation/protocol.zig +82 -33
  22. package/src/automation/root.zig +1 -0
  23. package/src/automation/server.zig +1 -1
  24. package/src/automation/snapshot.zig +68 -9
  25. package/src/automation/watcher.zig +1 -1
  26. package/src/embed/host.zig +5 -0
  27. package/src/embed/tests.zig +119 -1
  28. package/src/embed/ui_host.zig +13 -0
  29. package/src/platform/linux/gtk_host.c +639 -16
  30. package/src/platform/linux/gtk_host.h +25 -0
  31. package/src/platform/linux/root.zig +351 -7
  32. package/src/platform/macos/appkit_host.h +152 -8
  33. package/src/platform/macos/appkit_host.m +1816 -100
  34. package/src/platform/macos/cef_host.mm +372 -11
  35. package/src/platform/macos/root.zig +379 -11
  36. package/src/platform/null_platform.zig +696 -9
  37. package/src/platform/null_platform_tests.zig +35 -0
  38. package/src/platform/root.zig +42 -0
  39. package/src/platform/types.zig +524 -18
  40. package/src/platform/windows/root.zig +432 -9
  41. package/src/platform/windows/webview2_host.cpp +482 -45
  42. package/src/primitives/app_manifest/comptime_scene.zig +5 -0
  43. package/src/primitives/app_manifest/root.zig +1 -0
  44. package/src/primitives/app_manifest/types.zig +32 -0
  45. package/src/primitives/app_manifest/validation.zig +18 -0
  46. package/src/primitives/canvas/a11y_audit.zig +33 -11
  47. package/src/primitives/canvas/a11y_audit_tests.zig +20 -0
  48. package/src/primitives/canvas/drawing.zig +25 -0
  49. package/src/primitives/canvas/equality.zig +8 -0
  50. package/src/primitives/canvas/events.zig +103 -16
  51. package/src/primitives/canvas/frame.zig +125 -1
  52. package/src/primitives/canvas/layout_audit.zig +22 -5
  53. package/src/primitives/canvas/markdown_hostile_tests.zig +8 -4
  54. package/src/primitives/canvas/render_tests.zig +13 -10
  55. package/src/primitives/canvas/root.zig +48 -0
  56. package/src/primitives/canvas/terminal_box.zig +471 -0
  57. package/src/primitives/canvas/terminal_grid.zig +978 -0
  58. package/src/primitives/canvas/terminal_grid_tests.zig +1093 -0
  59. package/src/primitives/canvas/test_support.zig +1 -0
  60. package/src/primitives/canvas/tests.zig +2 -0
  61. package/src/primitives/canvas/text_tests.zig +39 -4
  62. package/src/primitives/canvas/tokens.zig +115 -12
  63. package/src/primitives/canvas/ui.zig +535 -12
  64. package/src/primitives/canvas/ui_markup.zig +253 -36
  65. package/src/primitives/canvas/ui_markup_binary.zig +4 -1
  66. package/src/primitives/canvas/ui_markup_compiled.zig +195 -9
  67. package/src/primitives/canvas/ui_markup_compiled_tests.zig +188 -8
  68. package/src/primitives/canvas/ui_markup_contract.zig +89 -6
  69. package/src/primitives/canvas/ui_markup_contract_tests.zig +65 -1
  70. package/src/primitives/canvas/ui_markup_huge_document_tests.zig +154 -0
  71. package/src/primitives/canvas/ui_markup_huge_model_tests.zig +1 -0
  72. package/src/primitives/canvas/ui_markup_reflect.zig +75 -24
  73. package/src/primitives/canvas/ui_markup_tests.zig +178 -9
  74. package/src/primitives/canvas/ui_markup_view.zig +220 -11
  75. package/src/primitives/canvas/ui_markup_view_tests.zig +553 -28
  76. package/src/primitives/canvas/ui_schema.zig +110 -17
  77. package/src/primitives/canvas/ui_schema_tests.zig +18 -10
  78. package/src/primitives/canvas/ui_tests.zig +141 -9
  79. package/src/primitives/canvas/widget_access.zig +28 -2
  80. package/src/primitives/canvas/widget_anchored_tests.zig +48 -0
  81. package/src/primitives/canvas/widget_invalidation.zig +81 -1
  82. package/src/primitives/canvas/widget_layout.zig +59 -11
  83. package/src/primitives/canvas/widget_layout_tests.zig +125 -4
  84. package/src/primitives/canvas/widget_render.zig +272 -18
  85. package/src/primitives/canvas/widget_render_scroll.zig +108 -27
  86. package/src/primitives/canvas/widget_routing.zig +59 -7
  87. package/src/primitives/canvas/widget_runtime.zig +23 -0
  88. package/src/primitives/canvas/widget_runtime_tests.zig +149 -0
  89. package/src/primitives/canvas/widget_semantics.zig +119 -11
  90. package/src/primitives/canvas/widget_semantics_tests.zig +409 -0
  91. package/src/primitives/canvas/widget_tree.zig +17 -0
  92. package/src/primitives/canvas/widgets.zig +132 -0
  93. package/src/root.zig +23 -0
  94. package/src/runtime/api.zig +76 -5
  95. package/src/runtime/automation_commands.zig +20 -1
  96. package/src/runtime/automation_snapshot.zig +25 -1
  97. package/src/runtime/automation_widget_dispatch.zig +73 -8
  98. package/src/runtime/bridge_payload.zig +8 -0
  99. package/src/runtime/bridge_responses.zig +5 -0
  100. package/src/runtime/builtin_bridge.zig +9 -4
  101. package/src/runtime/canvas_font_tests.zig +439 -2
  102. package/src/runtime/canvas_fonts.zig +61 -6
  103. package/src/runtime/canvas_frame.zig +62 -7
  104. package/src/runtime/canvas_frame_animation_tests.zig +5 -4
  105. package/src/runtime/canvas_frame_helpers.zig +190 -1
  106. package/src/runtime/canvas_frame_invalidation_tests.zig +531 -0
  107. package/src/runtime/canvas_frame_patch_tests.zig +161 -10
  108. package/src/runtime/canvas_frame_retained_tests.zig +5 -2
  109. package/src/runtime/canvas_image_tests.zig +195 -0
  110. package/src/runtime/canvas_images.zig +45 -12
  111. package/src/runtime/canvas_widget_accessibility_tests.zig +1 -1
  112. package/src/runtime/canvas_widget_clipboard_tests.zig +40 -0
  113. package/src/runtime/canvas_widget_context_menu.zig +269 -32
  114. package/src/runtime/canvas_widget_context_menu_tests.zig +640 -14
  115. package/src/runtime/canvas_widget_display.zig +1 -1
  116. package/src/runtime/canvas_widget_event_tests.zig +1823 -0
  117. package/src/runtime/canvas_widget_events.zig +240 -24
  118. package/src/runtime/canvas_widget_runtime.zig +213 -29
  119. package/src/runtime/canvas_widget_scroll_driver_tests.zig +170 -7
  120. package/src/runtime/canvas_widget_scroll_drivers.zig +151 -17
  121. package/src/runtime/canvas_widget_scroll_tests.zig +435 -23
  122. package/src/runtime/canvas_widget_state.zig +6 -0
  123. package/src/runtime/canvas_widget_text_tests.zig +1 -1
  124. package/src/runtime/core.zig +131 -13
  125. package/src/runtime/effects.zig +8136 -180
  126. package/src/runtime/effects_channel_tests.zig +3519 -0
  127. package/src/runtime/effects_fetch_tests.zig +89 -1
  128. package/src/runtime/effects_file_tests.zig +41 -1
  129. package/src/runtime/effects_image_tests.zig +1304 -0
  130. package/src/runtime/effects_pty_tests.zig +1362 -0
  131. package/src/runtime/effects_tests.zig +167 -9
  132. package/src/runtime/effects_video_tests.zig +3609 -0
  133. package/src/runtime/flow.zig +42 -4
  134. package/src/runtime/gpu_surface_events.zig +473 -13
  135. package/src/runtime/media_surface.zig +116 -11
  136. package/src/runtime/media_surface_tests.zig +61 -0
  137. package/src/runtime/pty.zig +1252 -0
  138. package/src/runtime/pty_windows.zig +1780 -0
  139. package/src/runtime/root.zig +36 -0
  140. package/src/runtime/runtime_event_tests.zig +20 -1
  141. package/src/runtime/session_blobs.zig +689 -0
  142. package/src/runtime/session_journal.zig +432 -62
  143. package/src/runtime/session_record.zig +43 -2
  144. package/src/runtime/session_replay.zig +556 -20
  145. package/src/runtime/session_tests.zig +2087 -1
  146. package/src/runtime/shell_layout.zig +7 -0
  147. package/src/runtime/terminal_session.zig +1569 -0
  148. package/src/runtime/terminal_session_tests.zig +450 -0
  149. package/src/runtime/terminal_vt_ghostty.zig +15 -0
  150. package/src/runtime/terminal_vt_stub.zig +13 -0
  151. package/src/runtime/testdata/fonts/NotoSansSC-Receipt.ttf +0 -0
  152. package/src/runtime/testdata/fonts/OFL.txt +93 -0
  153. package/src/runtime/tests.zig +8 -0
  154. package/src/runtime/ts_core_host.zig +1320 -45
  155. package/src/runtime/ts_core_host_tests.zig +1100 -1
  156. package/src/runtime/ts_ui_app.zig +23 -5
  157. package/src/runtime/ui_app.zig +2444 -69
  158. package/src/runtime/ui_app_tests.zig +3171 -744
  159. package/src/runtime/ui_app_virtual_variable_tests.zig +4 -2
  160. package/src/runtime/ui_app_window_tests.zig +736 -0
  161. package/src/runtime/view.zig +190 -2
  162. package/src/runtime/view_widget_scroll.zig +218 -68
  163. package/src/runtime/view_widget_text.zig +11 -2
  164. package/src/runtime/view_widget_tree.zig +111 -3
  165. package/src/runtime/window_command_bridge_tests.zig +117 -0
  166. package/src/runtime/window_storage.zig +77 -2
  167. package/src/runtime/window_view_runtime.zig +34 -2
  168. package/src/runtime/window_views.zig +62 -1
  169. package/src/terminal_session_tests_root.zig +15 -0
  170. package/src/tooling/manifest.zig +75 -0
  171. package/src/tooling/raw_manifest.zig +2 -0
  172. package/src/tooling/templates.zig +244 -8
@@ -38,6 +38,7 @@ const canvas_frame = @import("canvas_frame.zig");
38
38
  const canvas_limits = @import("canvas_limits.zig");
39
39
  const launch_timing = @import("launch_timing.zig");
40
40
  const runtime_effects = @import("effects.zig");
41
+ const terminal_session = @import("terminal_session.zig");
41
42
  const ui_app_provenance = @import("ui_app_provenance.zig");
42
43
 
43
44
  const Runtime = core.Runtime;
@@ -49,6 +50,14 @@ const ui_app_log = std.log.scoped(.zero_ui_app);
49
50
  /// Maximum number of webview panes a `UiApp` can drive (`Options.web_panes`).
50
51
  pub const max_web_panes: usize = 4;
51
52
 
53
+ /// One queued `on-terminal` dispatch: the terminal widget's id and the
54
+ /// post-change view state the reconcile produced (see
55
+ /// `applyTerminalLayout`). `id == 0` marks an empty slot.
56
+ const PendingTerminalState = struct {
57
+ id: canvas.ObjectId = 0,
58
+ state: canvas.TerminalState = .{},
59
+ };
60
+
52
61
  /// Approach-end hysteresis for `on_reach_end`, in viewports from the
53
62
  /// content end: fire when the offset comes within one viewport, re-arm
54
63
  /// only past one and a half — so the fire and re-arm boundaries never
@@ -176,14 +185,25 @@ pub fn UiAppWithFeatures(comptime ModelT: type, comptime MsgT: type, comptime fe
176
185
 
177
186
  pub const ChromeOptions = struct {
178
187
  /// Number of chrome commands preserved in front of the
179
- /// widget-generated commands.
188
+ /// widget-generated commands. With `variable_prefix`, the
189
+ /// BUDGET instead: `build` may emit any count up to it.
180
190
  prefix_commands: usize,
181
191
  /// Number of chrome commands preserved after the
182
- /// widget-generated commands.
192
+ /// widget-generated commands. Always exact.
183
193
  suffix_commands: usize = 0,
194
+ /// The prefix length is whatever `build` emitted this
195
+ /// rebuild (minus the fixed suffix) rather than an exact
196
+ /// pin — for chrome whose command count is model-derived
197
+ /// (a terminal grid, a data plot). The runtime re-learns
198
+ /// the split at every install, so its internal widget-span
199
+ /// regenerations keep preserving the right commands; the
200
+ /// exact-count default stays the teaching check for
201
+ /// fixed-shape chrome, where a drifted count is a bug.
202
+ variable_prefix: bool = false,
184
203
  /// Builds the chrome display-list commands: exactly
185
204
  /// `prefix_commands` commands followed by `suffix_commands`
186
- /// commands.
205
+ /// commands (up to `prefix_commands` under
206
+ /// `variable_prefix`).
187
207
  build: *const fn (model: *const ModelT, builder: *canvas.Builder, size: geometry.SizeF, tokens: canvas.DesignTokens) anyerror!void,
188
208
  };
189
209
 
@@ -478,6 +498,11 @@ pub fn UiAppWithFeatures(comptime ModelT: type, comptime MsgT: type, comptime fe
478
498
  /// Optional mapping from shell command events (menus, shortcuts,
479
499
  /// native controls) into messages.
480
500
  on_command: ?*const fn (name: []const u8) ?MsgT = null,
501
+ /// Optional mapping from app lifecycle events into messages.
502
+ /// A single-window app can use activate/deactivate as its
503
+ /// keyboard-focus signal for custom canvas chrome whose
504
+ /// pixels live outside the widget focus register.
505
+ on_lifecycle: ?*const fn (event: core.LifecycleEvent) ?MsgT = null,
481
506
  /// Model-driven selection for declared platform chrome
482
507
  /// (`scene.chrome.tabs`): returns the id of the tab the
483
508
  /// model currently selects (one of the declared tab ids, or
@@ -537,6 +562,26 @@ pub fn UiAppWithFeatures(comptime ModelT: type, comptime MsgT: type, comptime fe
537
562
  /// can never steal typing — a fallback that yields to every
538
563
  /// consuming widget can carry them safely.
539
564
  on_key: ?*const fn (keyboard: canvas.WidgetKeyboardEvent) ?MsgT = null,
565
+ /// Deliver `.key_up` phases through `on_key` too. OFF by
566
+ /// default: most key consumers act on presses alone, and a
567
+ /// release arriving unexpectedly would double-fire a
568
+ /// name-gated action. A terminal-class consumer opts in to
569
+ /// forward key releases to the child (the kitty keyboard
570
+ /// protocol's event reporting); consumers that opt in MUST
571
+ /// branch on `keyboard.phase`.
572
+ key_release_events: bool = false,
573
+ /// Optional mapping from unclaimed COMMITTED TEXT into
574
+ /// messages — `on_key`'s typing sibling for apps that
575
+ /// consume text themselves without a text-entry widget
576
+ /// focused (a terminal grid). Delivered for `.text_input`
577
+ /// phases only, after the same widget-precedence routing
578
+ /// `on_key` yields to: a focused editable widget keeps its
579
+ /// typing, and only unclaimed text falls through. The
580
+ /// event's `text` carries the committed UTF-8 (IME
581
+ /// composition results included), so consumers stay
582
+ /// layout- and input-method-correct — key names never
583
+ /// reconstruct text.
584
+ on_text: ?*const fn (keyboard: canvas.WidgetKeyboardEvent) ?MsgT = null,
540
585
  /// Optional mapping from trackpad pinch gestures into
541
586
  /// messages — the app-level gesture channel (the `on_key`
542
587
  /// shape). Pinch deliberately bypasses the widget pipeline:
@@ -557,6 +602,14 @@ pub fn UiAppWithFeatures(comptime ModelT: type, comptime MsgT: type, comptime fe
557
602
  /// a pinch source emit these (macOS today); everywhere else
558
603
  /// the channel simply never fires.
559
604
  on_pinch: ?*const fn (pinch: platform.PinchEvent) ?MsgT = null,
605
+ /// Optional mapping from wheel/trackpad scrolls over a gpu
606
+ /// surface into messages — the pinch channel's sibling, for
607
+ /// apps whose content scrolls without a scroll-region
608
+ /// widget (a terminal's scrollback). Delivered for every
609
+ /// raw `.scroll` input on a focused gpu surface; apps that
610
+ /// also declare canvas scroll regions should leave this
611
+ /// null (regions consume wheel input themselves).
612
+ on_wheel: ?*const fn (wheel: platform.WheelEvent) ?MsgT = null,
560
613
  /// Optional mapping from runtime timer events (started via
561
614
  /// `runtime.startTimer`) into messages. Framework-reserved timer
562
615
  /// ids (>= `platform.reserved_timer_id_base`) are handled
@@ -690,6 +743,20 @@ pub fn UiAppWithFeatures(comptime ModelT: type, comptime MsgT: type, comptime fe
690
743
  window_id: platform.WindowId = 0,
691
744
  on_close: ?MsgT = null,
692
745
  installed: bool = false,
746
+ /// This slot's handler-tree currency (the per-slot half of
747
+ /// `main_tree_current`): false only between handing the
748
+ /// runtime this window's new layout and adopting the
749
+ /// matching tree — so one window's failed publication never
750
+ /// poisons its siblings, and this window's own next
751
+ /// successful rebuild (a frame-driven retry included)
752
+ /// restores it.
753
+ tree_current: bool = true,
754
+ /// The `<video src>` declaration the in-flight build pass
755
+ /// recorded (arena-borrowed; consumed by
756
+ /// `rebuildWindowSlot` immediately after the pass succeeds
757
+ /// and the tree installs — a failed layout's declaration
758
+ /// never reaches the reconciler).
759
+ pending_video_declaration: ?Ui.VideoDeclaration = null,
693
760
  canvas_size: geometry.SizeF = .{ .width = 1, .height = 1 },
694
761
  /// The device scale of THIS window's surface, adopted from
695
762
  /// its own frame and resize events. Secondary windows can sit
@@ -739,6 +806,16 @@ pub fn UiAppWithFeatures(comptime ModelT: type, comptime MsgT: type, comptime fe
739
806
  /// register would then fail `FontIdInUse` and bury the real
740
807
  /// error).
741
808
  fonts_registered: bool = false,
809
+ /// The runtime's registered-font count the installed trees last
810
+ /// measured against. Registration is permanent with no
811
+ /// unregister, so the count IS the runtime's fonts generation:
812
+ /// a mismatch on a presented frame means a face joined the
813
+ /// registry AFTER the trees were built (late registration
814
+ /// through `runtime.registerCanvasFont` — `Options.fonts` lands
815
+ /// before the installing build), and every installed surface
816
+ /// must rebuild so layout re-measures with the new face
817
+ /// (`rebuildForRegisteredFonts`).
818
+ fonts_built_count: usize = 0,
742
819
  /// Exactly-once guard for `Options.init_fx`, independent of
743
820
  /// `installed` so a failed install rebuild cannot rerun it.
744
821
  init_fx_ran: bool = false,
@@ -854,6 +931,75 @@ pub fn UiAppWithFeatures(comptime ModelT: type, comptime MsgT: type, comptime fe
854
931
  hold_view_label_storage: [app_manifest.max_view_label_bytes]u8 = undefined,
855
932
  hold_view_label_len: usize = 0,
856
933
  hold_window_id: platform.WindowId = 1,
934
+ /// Hover-Msg delivery mirror: the containment chain — and which
935
+ /// view it belongs to — as the app last HEARD it. The runtime
936
+ /// owns the STANDING chain per view (derived from journaled
937
+ /// input at the same seams the hover wash resolves through);
938
+ /// this mirror is the dispatch bookkeeping, and the diff
939
+ /// between the two is exactly the enter/leave Msgs owed. One
940
+ /// pointer, one standing mirror (the hold-arming shape). Leave
941
+ /// Msgs are captured when their enter dispatches (the
942
+ /// context-menu snapshot's capture-at-presentation rule), so a
943
+ /// widget unmounted mid-hover still delivers the paired leave
944
+ /// the live tree can no longer resolve — no enter without its
945
+ /// eventual leave. Captures are DEEP copies: payload slices are
946
+ /// duplicated into the slot's own bytes below, because a
947
+ /// standing hover outlives the build-arena pair's two-build
948
+ /// lifetime and a by-value capture of a `ui.fmt` payload would
949
+ /// dangle into a reset arena.
950
+ hover_msg_window_id: platform.WindowId = 1,
951
+ hover_msg_view_label_storage: [app_manifest.max_view_label_bytes]u8 = undefined,
952
+ hover_msg_view_label_len: usize = 0,
953
+ hover_msg_chain: [canvas.max_widget_depth]canvas.ObjectId = undefined,
954
+ hover_msg_chain_len: usize = 0,
955
+ /// Capture SLOT per mirror chain position (`hover_msg_slot_none`
956
+ /// = no capture): containment is per LISTENER, so when an outer
957
+ /// listener unbinds while an inner one stands, the retained
958
+ /// entry keeps its slot — and its captured leave — while only
959
+ /// the departed id's edges dispatch. Slots decouple capture
960
+ /// ownership from chain position so retained entries never need
961
+ /// their captures moved or re-taken.
962
+ hover_msg_slots: [canvas.max_widget_depth]u8 = undefined,
963
+ hover_msg_slot_used: [hover_msg_slot_count]bool = [_]bool{false} ** hover_msg_slot_count,
964
+ /// Captured leave Msgs BY SLOT (see `hover_msg_slots`).
965
+ hover_msg_leave_msgs: [hover_msg_slot_count]?MsgT = undefined,
966
+ /// Per-SLOT arenas owning the captured leave Msgs' payload
967
+ /// bytes (see `captureHoverLeave`): reset when the slot
968
+ /// releases or re-captures, freed at deinit. Arena-backed so a
969
+ /// payload of any size can be owned — a fixed budget would turn
970
+ /// a large `ui.fmt` payload into a silently unpaired leave.
971
+ hover_msg_leave_arenas: [hover_msg_slot_count]std.heap.ArenaAllocator = undefined,
972
+ /// Re-entrancy guard for `drainHoverMsgs`: the drain's own
973
+ /// dispatches must not drain recursively through `dispatch`'s
974
+ /// tail.
975
+ hover_msg_draining: bool = false,
976
+ /// Handler-tree currency for hover-Msg delivery — the shared
977
+ /// invariant over every rebuild/error seam, PER TREE FAMILY: a
978
+ /// flag holds while its last rebuild attempt fully succeeded,
979
+ /// so a failed build — or a failed publication that left a
980
+ /// tree pointing at a build the runtime never adopted — defers
981
+ /// entering edges into that tree instead of resolving them
982
+ /// through a stale handler table or consuming them as absent.
983
+ /// Two flags because the families recover independently: a
984
+ /// main-only rebuild (a resize, a frame path) must never
985
+ /// restore currency for a secondary-window tree whose
986
+ /// publication failed — only a clean pass over the slots does.
987
+ /// `build_generation` ticks on every successful rebuild, so
988
+ /// standing captures refresh exactly when handler bindings can
989
+ /// have moved and never otherwise. Captured leaves dispatch
990
+ /// regardless: their Msgs are owned bytes, not tree lookups.
991
+ main_tree_current: bool = true,
992
+ build_generation: u64 = 0,
993
+ /// The `build_generation` the mirror's captures were last
994
+ /// refreshed against.
995
+ hover_msg_captured_generation: u64 = 0,
996
+ /// Nonzero while `eventFn` is on the stack: `dispatch` and
997
+ /// `drainEffects` tails drain hover edges only for DIRECT
998
+ /// callers (embedders, command handlers, tests) — inside a
999
+ /// runtime event, draining belongs to the event's own tail so
1000
+ /// hover dispatches can never rebuild a view out from under the
1001
+ /// input cycle's pending scroll/resize/change observations.
1002
+ hover_msg_event_depth: u32 = 0,
857
1003
  /// Context-menu presentation fallback state: the widget whose
858
1004
  /// declared menu is mounted as an anchored canvas surface because
859
1005
  /// the platform could not present it natively. Set by
@@ -865,6 +1011,41 @@ pub fn UiAppWithFeatures(comptime ModelT: type, comptime MsgT: type, comptime fe
865
1011
  context_menu_fallback_window_id: platform.WindowId = 1,
866
1012
  context_menu_fallback_label_storage: [app_manifest.max_view_label_bytes]u8 = undefined,
867
1013
  context_menu_fallback_label_len: usize = 0,
1014
+ /// The secondary click's pointer location from the request event
1015
+ /// (view-local canvas points): threaded to `Ui.finalize` so the
1016
+ /// synthesized surface anchors at the click, not the target's
1017
+ /// edge.
1018
+ context_menu_fallback_point: geometry.PointF = .{},
1019
+ /// The presented native menu's selection snapshot: the per-item
1020
+ /// dispatch Msgs captured (by value) at present time, keyed by
1021
+ /// the request's token. Native presentation is asynchronous (a
1022
+ /// GTK popover outlives its presenting dispatch), so a rebuild
1023
+ /// while the menu is open — a timer reordering conditional
1024
+ /// items, an effect re-mapping captured messages — must never
1025
+ /// redirect the visible selection: `handleContextMenu` resolves
1026
+ /// a token-matching selection HERE, never through the live
1027
+ /// tree. 0 = no snapshot armed (then the live tree is the shown
1028
+ /// menu: the fallback surface and the automation verb both
1029
+ /// validate against it directly).
1030
+ context_menu_shown_token: u64 = 0,
1031
+ context_menu_shown_count: usize = 0,
1032
+ context_menu_shown_msgs: [platform.max_context_menu_items]?MsgT = undefined,
1033
+ /// The build-arena generation PINNED under the presented menu.
1034
+ /// A snapshot Msg may carry build-arena slices (the documented
1035
+ /// payload shape — `ui.fmt` strings and allocator-form
1036
+ /// bindings), and the open menu outlives the arena pair's
1037
+ /// two-build lifetime, so while the snapshot is armed the arena
1038
+ /// that built the presented tree is exempt from the rebuild
1039
+ /// reset: rebuilds landing on its turn allocate on top instead
1040
+ /// (growth is bounded by the menu's open span; the next reset
1041
+ /// after release reclaims it). The dispatched Msg is therefore
1042
+ /// the ORIGINAL value — same bytes, same pointers as the
1043
+ /// fallback surface and the automation verb dispatch. Released
1044
+ /// on selection, dismissal (the runtime's dismissed notice),
1045
+ /// supersession by the next presentation, and teardown. Markup
1046
+ /// payloads need nothing more: they are path-only — model
1047
+ /// storage or this same build arena, never document literals.
1048
+ context_menu_pin: ?ContextMenuPin = null,
868
1049
  /// The windowed virtual lists the LAST build declared
869
1050
  /// (`Ui.virtualList` records): scroll events on these regions
870
1051
  /// re-derive the view even without an app `on_scroll` binding,
@@ -873,10 +1054,13 @@ pub fn UiAppWithFeatures(comptime ModelT: type, comptime MsgT: type, comptime fe
873
1054
  virtual_windows: [canvas.max_virtual_windows]canvas.VirtualWindowRecord = [_]canvas.VirtualWindowRecord{.{}} ** canvas.max_virtual_windows,
874
1055
  virtual_window_count: usize = 0,
875
1056
  /// Scroll regions whose `on_reach_end` fired and has not re-armed
876
- /// (the approach-end hysteresis state, keyed by widget id).
877
- reach_end_fired_ids: [canvas.max_virtual_windows]canvas.ObjectId = [_]canvas.ObjectId{0} ** canvas.max_virtual_windows,
1057
+ /// (the approach-end hysteresis state, keyed by widget id AND the
1058
+ /// axis the reach was measured on: a region whose primary axis
1059
+ /// changes — content growing sideways after a vertical fire —
1060
+ /// must not have the stale axis's latch suppress the fresh one).
1061
+ reach_end_fired: [max_reach_latches]ReachLatch = [_]ReachLatch{.{}} ** max_reach_latches,
878
1062
  /// The approach-START mirror (`on_reach_start` hysteresis).
879
- reach_start_fired_ids: [canvas.max_virtual_windows]canvas.ObjectId = [_]canvas.ObjectId{0} ** canvas.max_virtual_windows,
1063
+ reach_start_fired: [max_reach_latches]ReachLatch = [_]ReachLatch{.{}} ** max_reach_latches,
880
1064
  /// Retained offset tables for VARIABLE-extent virtual lists,
881
1065
  /// claimed per list identity during builds (`Ui.virtualWindow`
882
1066
  /// through the extent source) and patched by the post-layout
@@ -885,6 +1069,95 @@ pub fn UiAppWithFeatures(comptime ModelT: type, comptime MsgT: type, comptime fe
885
1069
  /// slots drops the excess to estimate-only math with a debug
886
1070
  /// warning.
887
1071
  virtual_extent_tables: [canvas.max_virtual_windows]canvas.VirtualExtentTable = [_]canvas.VirtualExtentTable{.{}} ** canvas.max_virtual_windows,
1072
+ /// The `<video src>` declaration the LAST main-canvas build
1073
+ /// recorded (`Ui.video_declaration`), captured by the build pass
1074
+ /// for the post-rebuild reconcile; the src slice lives in that
1075
+ /// build's arena, valid until the next rebuild.
1076
+ video_build_declaration: ?VideoBuildDeclaration = null,
1077
+ /// The in-flight rebuild's capture, committed into
1078
+ /// `video_build_declaration` only once the rebuild INSTALLS
1079
+ /// (the `self.tree` assignment): a build that fails after the
1080
+ /// capture never mounted, and the retained tree on the glass
1081
+ /// still shows the old declaration — a later reconcile (a
1082
+ /// secondary window's close) acting on the unmounted build's
1083
+ /// capture would stop or replace a playback the presented tree
1084
+ /// still declares. Seeded from the committed value at each
1085
+ /// rebuild's start, so a failed rebuild changes nothing.
1086
+ video_build_staged: ?VideoBuildDeclaration = null,
1087
+ video_build_staged_src_buffer: [1024]u8 = undefined,
1088
+ /// The load identity of the playback the declarative
1089
+ /// reconciler started (`Effects.videoOwnerToken` right after
1090
+ /// its own loadVideo; 0 = owns nothing): the ownership proof
1091
+ /// for the stop and flag-delta paths. The derived key alone
1092
+ /// is not one — it is a pure function of the source string,
1093
+ /// and a manual load could carry the same key.
1094
+ video_declared_token: u64 = 0,
1095
+ /// Recursion bound for the post-reconcile chrome repass in
1096
+ /// `rebuild` (see the call site): the repass reconciles an
1097
+ /// unchanged declaration, so the mirrors are already a fixed
1098
+ /// point — this guard just makes one level a hard guarantee.
1099
+ video_chrome_repass: bool = false,
1100
+ /// Backing bytes for `video_build_declaration.src`, copied out
1101
+ /// of the build arena at capture (the slot captures' rule): the
1102
+ /// declaration outlives the pass that recorded it — a later
1103
+ /// FAILED rebuild resets the arena it would otherwise borrow
1104
+ /// from, and the reconcile can run from a window close before
1105
+ /// the next successful build.
1106
+ video_build_src_buffer: [1024]u8 = undefined,
1107
+ /// The video mirrors as the LAST main-canvas build rendered
1108
+ /// them (stamped at build time, before the post-build reconcile
1109
+ /// can move them): `drainEffects` compares against the live
1110
+ /// snapshot so a Msg-less mirror move — a handler-less
1111
+ /// declarative playback's synchronous failure delivering its
1112
+ /// staged terminal — still re-renders the house chrome instead
1113
+ /// of leaving controls painted for a playback that is gone.
1114
+ video_rendered_snapshot: Effects.VideoSnapshot = .{},
1115
+ /// Applied declarative-video state: whether a declared src owns
1116
+ /// the playback right now, the src it loaded (so an unchanged
1117
+ /// declaration never reloads — loadVideo replaces the playback
1118
+ /// whole), and the applied loop/muted flags for delta updates.
1119
+ video_declared: bool = false,
1120
+ video_declared_src_buffer: [1024]u8 = undefined,
1121
+ video_declared_src_len: usize = 0,
1122
+ video_declared_loop: bool = false,
1123
+ video_declared_muted: bool = false,
1124
+ /// The last declared src the video loader REFUSED (see
1125
+ /// `applyVideoDeclaration`): remembered so an unchanged bad
1126
+ /// declaration is taught once, not re-attempted every rebuild —
1127
+ /// and kept OUT of the applied-src tracking above, so the
1128
+ /// playback the reconciler actually owns stays stoppable.
1129
+ video_refused_src_buffer: [1024]u8 = undefined,
1130
+ video_refused_src_len: usize = 0,
1131
+ /// The `<video src>` declarations SECONDARY windows' builds
1132
+ /// recorded, one retained entry per declaring window, copied
1133
+ /// out of the slot arenas (slot builds and the main build
1134
+ /// interleave, so a borrowed slice could die under the
1135
+ /// reconciler). `Ui.video` promises that declaring the element
1136
+ /// IS the playback in every window's tree; the main canvas
1137
+ /// build wins when it declares (one player, one owner), and
1138
+ /// among slots the current owner keeps the player until it
1139
+ /// stops declaring or closes — at which point the next
1140
+ /// RETAINED declaration promotes immediately, no rebuild
1141
+ /// required (`slotVideoDeclaration`).
1142
+ video_slot_declarations: [max_ui_windows]SlotVideoDeclaration = @splat(.{}),
1143
+ /// The slot window currently owning the declarative playback
1144
+ /// (0 while none does).
1145
+ video_slot_owner: platform.WindowId = 0,
1146
+ /// The framework-owned terminal sessions behind `<terminal
1147
+ /// pty={key}>` (see `terminal_session.zig`): the emulator store
1148
+ /// the builder's grid lookup resolves through, fed by the
1149
+ /// effects channel's pty tap. Compiles to inert no-ops when the
1150
+ /// `terminal_vt` seam carries the stub.
1151
+ terminal_sessions: terminal_session.TerminalSessions,
1152
+ /// `on-terminal` states the last rebuild's view-state reconcile
1153
+ /// produced (a resize the layout derived, an applied scrollback
1154
+ /// echo): dispatched at the rebuild's tail, one bounded pass —
1155
+ /// the nested rebuild each dispatch runs reconciles to the same
1156
+ /// state and produces nothing new (`terminal_state_draining`
1157
+ /// makes that one level a hard guarantee).
1158
+ terminal_state_pending: [terminal_session.max_sessions]PendingTerminalState = @splat(.{}),
1159
+ terminal_state_pending_count: usize = 0,
1160
+ terminal_state_draining: bool = false,
888
1161
  /// Live model-declared secondary windows (`Options.windows_fn`),
889
1162
  /// keyed by window label.
890
1163
  window_slots: [max_ui_windows]WindowSlot,
@@ -916,10 +1189,19 @@ pub fn UiAppWithFeatures(comptime ModelT: type, comptime MsgT: type, comptime fe
916
1189
  },
917
1190
  .window_slots = windowSlotsInit(backing),
918
1191
  .markup_fragment_slots = if (comptime fragment_watch_enabled) markupFragmentSlotsInit(backing) else {},
1192
+ .hover_msg_leave_arenas = hoverMsgLeaveArenasInit(backing),
919
1193
  .effects = Effects.init(backing),
1194
+ .terminal_sessions = terminal_session.TerminalSessions.init(backing),
920
1195
  };
921
1196
  }
922
1197
 
1198
+ /// One arena per hover-capture slot, over the backing allocator.
1199
+ fn hoverMsgLeaveArenasInit(backing: std.mem.Allocator) [hover_msg_slot_count]std.heap.ArenaAllocator {
1200
+ var arenas: [hover_msg_slot_count]std.heap.ArenaAllocator = undefined;
1201
+ for (&arenas) |*arena| arena.* = std.heap.ArenaAllocator.init(backing);
1202
+ return arenas;
1203
+ }
1204
+
923
1205
  /// Heap-allocate the app and construct every field — the
924
1206
  /// Model included — in place, so nothing app-sized ever rides
925
1207
  /// the stack. The Model starts as its default value; set fields
@@ -972,7 +1254,9 @@ pub fn UiAppWithFeatures(comptime ModelT: type, comptime MsgT: type, comptime fe
972
1254
  },
973
1255
  .window_slots = windowSlotsInit(backing),
974
1256
  .markup_fragment_slots = if (comptime fragment_watch_enabled) markupFragmentSlotsInit(backing) else {},
1257
+ .hover_msg_leave_arenas = hoverMsgLeaveArenasInit(backing),
975
1258
  .effects = Effects.init(backing),
1259
+ .terminal_sessions = terminal_session.TerminalSessions.init(backing),
976
1260
  };
977
1261
  }
978
1262
 
@@ -993,6 +1277,7 @@ pub fn UiAppWithFeatures(comptime ModelT: type, comptime MsgT: type, comptime fe
993
1277
  // services binding there, so this second call frees app-side
994
1278
  // memory only and never touches the dead platform.
995
1279
  self.effects.deinit();
1280
+ self.terminal_sessions.deinit();
996
1281
  self.arenas[0].deinit();
997
1282
  self.arenas[1].deinit();
998
1283
  self.markup_arenas[0].deinit();
@@ -1007,6 +1292,7 @@ pub fn UiAppWithFeatures(comptime ModelT: type, comptime MsgT: type, comptime fe
1007
1292
  slot.arenas[0].deinit();
1008
1293
  slot.arenas[1].deinit();
1009
1294
  }
1295
+ for (&self.hover_msg_leave_arenas) |*arena| arena.deinit();
1010
1296
  if (self.pixel_buffer.len > 0) self.backing.free(self.pixel_buffer);
1011
1297
  if (self.pixel_scratch.len > 0) self.backing.free(self.pixel_scratch);
1012
1298
  self.pixel_buffer = &.{};
@@ -1049,14 +1335,45 @@ pub fn UiAppWithFeatures(comptime ModelT: type, comptime MsgT: type, comptime fe
1049
1335
  self.effects.bindServices(&runtime.options.platform.services);
1050
1336
  self.effects.bindEnviron(runtime.options.environ);
1051
1337
  self.effects.bindImages(runtime.canvasImageRegistryBinding());
1338
+ self.effects.bindMediaSurfaces(runtime.mediaSurfaceBinding());
1052
1339
  self.effects.bindWindowActions(.{
1053
1340
  .context = runtime,
1054
1341
  .close_fn = effectsCloseWindowByLabel,
1055
1342
  .minimize_fn = effectsMinimizeWindowByLabel,
1343
+ .show_fn = effectsShowWindowByLabel,
1344
+ .quit_fn = effectsQuitApp,
1056
1345
  });
1057
1346
  if (runtime.options.session_recorder) |recorder| {
1058
1347
  self.effects.bindJournal(recorder.effectJournal());
1059
1348
  }
1349
+ // The terminal-session seams (no-ops on stub builds): the
1350
+ // pty tap feeds every delivered event into the store, and
1351
+ // the gateway routes the store's outbound bytes (keystrokes,
1352
+ // emulator query answers) and grid sizes back through the
1353
+ // JOURNALED pty verbs. Idempotent, like every bind here.
1354
+ if (comptime terminal_session.enabled) {
1355
+ self.effects.pty_tap = .{ .context = @ptrCast(self), .notify = terminalPtyTap };
1356
+ self.terminal_sessions.setGateway(.{
1357
+ .context = @ptrCast(self),
1358
+ .write = terminalGatewayWrite,
1359
+ .resize = terminalGatewayResize,
1360
+ });
1361
+ }
1362
+ }
1363
+
1364
+ fn terminalPtyTap(context: *anyopaque, event: *const runtime_effects.EffectPtyEvent) void {
1365
+ const self: *Self = @ptrCast(@alignCast(context));
1366
+ self.terminal_sessions.notePtyEvent(event);
1367
+ }
1368
+
1369
+ fn terminalGatewayWrite(context: *anyopaque, key: u64, bytes: []const u8) bool {
1370
+ const self: *Self = @ptrCast(@alignCast(context));
1371
+ return self.effects.ptyWrite(key, bytes);
1372
+ }
1373
+
1374
+ fn terminalGatewayResize(context: *anyopaque, key: u64, cols: u16, rows: u16) void {
1375
+ const self: *Self = @ptrCast(@alignCast(context));
1376
+ self.effects.ptyResize(key, cols, rows);
1060
1377
  }
1061
1378
 
1062
1379
  /// Session-replay control (`App.replay_fn`): arm the effects
@@ -1090,6 +1407,67 @@ pub fn UiAppWithFeatures(comptime ModelT: type, comptime MsgT: type, comptime fe
1090
1407
  // envMsgs dispatch consumes the queue on the
1091
1408
  // replayed installing frame (zero env reads).
1092
1409
  .env => try self.effects.pushReplayEnv(record.stderr_tail, record.payload),
1410
+ // `.image` records deliver the RECORDED terminal
1411
+ // verbatim (byte-identical Msg stream on any host)
1412
+ // and re-register the journaled source bytes —
1413
+ // resolved from the blob store into `payload` by
1414
+ // the replayer — best-effort for presentation.
1415
+ // Loop-side validation rejections never reach here
1416
+ // (marked by `exit_reason == .rejected`, they
1417
+ // regenerate and are skipped); a worker-origin
1418
+ // `.rejected` terminal feeds like any failure class.
1419
+ .image => try self.effects.feedImageResult(
1420
+ record.key,
1421
+ record.image_outcome,
1422
+ record.image_width,
1423
+ record.image_height,
1424
+ record.status,
1425
+ record.payload,
1426
+ ),
1427
+ // `.channel` records deliver the RECORDED event
1428
+ // verbatim through the channel the replayed
1429
+ // dispatch opened — the source thread never re-runs
1430
+ // at replay, so the journaled events are the whole
1431
+ // stream. Admission `.rejected` records never reach
1432
+ // here (marked by `exit_reason == .rejected`, they
1433
+ // regenerate and are skipped); an executor-truth
1434
+ // rejection feeds and retires the parked slot.
1435
+ .channel => try self.effects.feedChannelEvent(
1436
+ record.key,
1437
+ record.channel_kind,
1438
+ record.payload,
1439
+ record.dropped,
1440
+ record.channel_dropped_total,
1441
+ ),
1442
+ // `.pty` records deliver the RECORDED session:
1443
+ // output batches (resolved from the blob store
1444
+ // into `payload` by the replayer) feed the parked
1445
+ // spawn byte-identically — no shell ever runs —
1446
+ // and the exit retires it. Admission `.rejected`
1447
+ // records never reach here (they regenerate and
1448
+ // are skipped); executor-truth start failures feed
1449
+ // and retire the park at the spawn's dispatch
1450
+ // position.
1451
+ .pty => switch (record.pty_kind) {
1452
+ .output => try self.effects.feedPtyOutput(record.key, record.payload),
1453
+ .exit => try self.effects.feedPtyExit(
1454
+ record.key,
1455
+ record.code,
1456
+ record.pty_signal,
1457
+ record.exit_reason,
1458
+ record.pty_dropped_writes,
1459
+ ),
1460
+ // Write-admission verdicts are executor truth
1461
+ // (whether the FIFO had room depends on how fast
1462
+ // the child was reading): queue each — WITH the
1463
+ // pty key it was recorded against — for the
1464
+ // replayed dispatch's own `ptyWrite` calls, which
1465
+ // consume them in call order against the same
1466
+ // key (the clock feed's shape, keyed: the same
1467
+ // count and results against a different session
1468
+ // is still divergent input).
1469
+ .write => try self.effects.pushReplayPtyWriteVerdict(record.key, record.code == 1),
1470
+ },
1093
1471
  // Spectrum records feed through the band-carrying
1094
1472
  // helper so replay repaints identical bars; every
1095
1473
  // other audio kind rides the plain shape.
@@ -1097,8 +1475,38 @@ pub fn UiAppWithFeatures(comptime ModelT: type, comptime MsgT: type, comptime fe
1097
1475
  try self.effects.feedAudioSpectrum(record.audio_bands, record.audio_position_ms, record.audio_duration_ms)
1098
1476
  else
1099
1477
  try self.effects.feedAudioEventBuffering(record.audio_kind, record.audio_position_ms, record.audio_duration_ms, record.audio_playing, record.audio_buffering),
1478
+ // `.video` records feed the whole journaled shape —
1479
+ // dimensions included — routed by the journaled
1480
+ // load identity (`video_token`), so replay delivers
1481
+ // the identical Msg stream with NO producer and NO
1482
+ // platform player behind it, even when the record's
1483
+ // load was replaced or stopped by the very dispatch
1484
+ // that produced it (see `feedVideoRecord`).
1485
+ .video => try self.effects.feedVideoRecord(
1486
+ record.key,
1487
+ record.video_token,
1488
+ record.video_handled,
1489
+ record.video_kind,
1490
+ record.video_position_ms,
1491
+ record.video_duration_ms,
1492
+ record.video_playing,
1493
+ record.video_buffering,
1494
+ record.video_width,
1495
+ record.video_height,
1496
+ ),
1497
+ // `.video_load` records carry the recording host's
1498
+ // cascade resolution — which source the load
1499
+ // actually played — because the replayed fake load
1500
+ // cannot probe the filesystem. Queued, not applied:
1501
+ // the record precedes the event whose dispatch
1502
+ // issues the load (see `pushReplayVideoSource`).
1503
+ .video_load => self.effects.pushReplayVideoSource(record.key, record.video_token, record.video_source, record.video_kind == .failed),
1100
1504
  .timer => {},
1101
1505
  },
1506
+ .finish => {
1507
+ try self.effects.finishReplay();
1508
+ try self.effects.settleReplayFeeds();
1509
+ },
1102
1510
  }
1103
1511
  }
1104
1512
 
@@ -1118,8 +1526,28 @@ pub fn UiAppWithFeatures(comptime ModelT: type, comptime MsgT: type, comptime fe
1118
1526
  // events land before the first frame on every launch, so it
1119
1527
  // used to cost a full view build on the launch path.
1120
1528
  if (!self.installed) return;
1121
- try self.rebuild(runtime, self.canvas_window_id);
1122
- try self.rebuildWindowSlots(runtime);
1529
+ // Hover edges the rebuilds produce (an unmounted hovered
1530
+ // element's leave, an adoption re-hit-test's handoff)
1531
+ // settle at this tail for DIRECT callers — command
1532
+ // handlers, embedders, tests — without waiting for the
1533
+ // next platform event, and on the REBUILD-ERROR path too:
1534
+ // a failed secondary-window rebuild must not strand the
1535
+ // leave the main rebuild already produced. Inside a runtime
1536
+ // event the event's own tail drains instead, and the
1537
+ // drain's own dispatches re-enter here guarded.
1538
+ var rebuild_error: ?anyerror = null;
1539
+ self.rebuild(runtime, self.canvas_window_id) catch |err| {
1540
+ rebuild_error = err;
1541
+ };
1542
+ if (rebuild_error == null) self.rebuildWindowSlots(runtime) catch |err| {
1543
+ rebuild_error = err;
1544
+ };
1545
+ if (self.hover_msg_event_depth == 0 and !self.hover_msg_draining) {
1546
+ self.drainHoverMsgs(runtime) catch |err| {
1547
+ if (rebuild_error == null) rebuild_error = err;
1548
+ };
1549
+ }
1550
+ if (rebuild_error) |err| return err;
1123
1551
  // A Msg dispatched FROM a secondary window still rebuilt the
1124
1552
  // main canvas above (one model, every window's view derives
1125
1553
  // from it); `window_id` names the dispatch origin for apps
@@ -1149,15 +1577,53 @@ pub fn UiAppWithFeatures(comptime ModelT: type, comptime MsgT: type, comptime fe
1149
1577
  self.bindEffectsChannel(runtime);
1150
1578
  self.syncModel(runtime, self.canvas_window_id);
1151
1579
  var dispatched = false;
1152
- while (self.effects.takeMsg()) |msg| {
1580
+ // One pass consumes only completions that existed when it
1581
+ // began: a load started by an update handler in THIS pass
1582
+ // that finishes while the pass still runs waits for the wake
1583
+ // its producer already nudged. That keeps the session
1584
+ // journal's event boundaries causal — every result recorded
1585
+ // ahead of this wake's event record answers a request from
1586
+ // an earlier dispatch, so replay's file-order feed always
1587
+ // finds the parked request (see Effects.DrainBoundary).
1588
+ var boundary = self.effects.drainBoundary();
1589
+ while (self.effects.takeMsgWithin(&boundary)) |msg| {
1153
1590
  self.applyMsg(msg);
1154
1591
  dispatched = true;
1155
1592
  }
1156
1593
  self.publishAudioState(runtime);
1594
+ var rebuild_error: ?anyerror = null;
1157
1595
  if (dispatched) {
1158
- try self.rebuild(runtime, self.canvas_window_id);
1159
- try self.rebuildWindowSlots(runtime);
1596
+ self.rebuild(runtime, self.canvas_window_id) catch |err| {
1597
+ rebuild_error = err;
1598
+ };
1599
+ if (rebuild_error == null) self.rebuildWindowSlots(runtime) catch |err| {
1600
+ rebuild_error = err;
1601
+ };
1602
+ } else if (self.installed and
1603
+ !std.meta.eql(self.video_rendered_snapshot, self.effects.videoSnapshot()))
1604
+ {
1605
+ // A drained Msg-less video terminal (a handler-less
1606
+ // declarative playback's synchronous failure) moved
1607
+ // the mirrors after the last build rendered them:
1608
+ // re-render the chrome so its controls never keep
1609
+ // advertising a playback that is gone.
1610
+ self.rebuild(runtime, self.canvas_window_id) catch |err| {
1611
+ rebuild_error = err;
1612
+ };
1613
+ if (rebuild_error == null) self.rebuildWindowSlots(runtime) catch |err| {
1614
+ rebuild_error = err;
1615
+ };
1160
1616
  }
1617
+ // Same tail as `dispatch`, same error-path duty: effect-
1618
+ // driven rebuilds settle the hover edges they produced
1619
+ // (this path is also public — host-pumped embeds call it
1620
+ // directly).
1621
+ if (self.hover_msg_event_depth == 0 and !self.hover_msg_draining) {
1622
+ self.drainHoverMsgs(runtime) catch |err| {
1623
+ if (rebuild_error == null) rebuild_error = err;
1624
+ };
1625
+ }
1626
+ if (rebuild_error) |err| return err;
1161
1627
  }
1162
1628
 
1163
1629
  /// Mirror the effects channel's audio playback state into the
@@ -1176,6 +1642,27 @@ pub fn UiAppWithFeatures(comptime ModelT: type, comptime MsgT: type, comptime fe
1176
1642
  runtime.audio_duration_ms = audio.duration_ms;
1177
1643
  runtime.audio_spectrum_bands = audio.spectrum_bands;
1178
1644
  runtime.audio_spectrum_events = audio.spectrum_events;
1645
+ self.publishVideoState(runtime);
1646
+ }
1647
+
1648
+ /// The video channel's mirror publication, riding every
1649
+ /// `publishAudioState` call site — the same "wherever a
1650
+ /// dispatch or drain may have moved playback" contract, one
1651
+ /// seam instead of two at each site.
1652
+ fn publishVideoState(self: *Self, runtime: *Runtime) void {
1653
+ const video = self.effects.videoSnapshot();
1654
+ runtime.video_active = video.active;
1655
+ runtime.video_key = video.key;
1656
+ runtime.video_surface_id = video.surface;
1657
+ runtime.video_playing = video.playing;
1658
+ runtime.video_buffering = video.buffering;
1659
+ runtime.video_looping = video.looping;
1660
+ runtime.video_muted = video.muted;
1661
+ runtime.video_source = video.source;
1662
+ runtime.video_position_ms = video.position_ms;
1663
+ runtime.video_duration_ms = video.duration_ms;
1664
+ runtime.video_width = video.width;
1665
+ runtime.video_height = video.height;
1179
1666
  }
1180
1667
 
1181
1668
  /// The design tokens for the next rebuild: the model-derived
@@ -1250,14 +1737,20 @@ pub fn UiAppWithFeatures(comptime ModelT: type, comptime MsgT: type, comptime fe
1250
1737
  /// Whether a rebuild must push its tokens into the runtime's
1251
1738
  /// stored copy. Derived tokens can change with any model or
1252
1739
  /// appearance input, so they always re-emit. Static tokens are
1253
- /// fixed by the app, but the runtime stamps the surface scale
1254
- /// onto them (`effectiveTokens`), so a stored copy holding a
1255
- /// stale scale re-emits too — hairlines re-snap after a move
1256
- /// between monitors — while ordinary rebuilds keep skipping the
1257
- /// redundant emission.
1740
+ /// fixed by the app, but the runtime stamps two live values onto
1741
+ /// them: the surface scale (`effectiveTokens` — a stored copy
1742
+ /// holding a stale scale re-emits so hairlines re-snap after a
1743
+ /// move between monitors) and the text-measure provider
1744
+ /// (`tokensWithTextMeasure` — the FIRST font registration binds
1745
+ /// the runtime's font-aware provider on platforms without host
1746
+ /// measurement, and a stored copy still measuring with the
1747
+ /// estimator would keep display-list text layout on
1748
+ /// pre-registration metrics). Ordinary rebuilds keep skipping
1749
+ /// the redundant emission.
1258
1750
  fn rebuildEmitsTokens(self: *const Self, runtime: *Runtime, window_id: platform.WindowId, canvas_label: []const u8, tokens: canvas.DesignTokens) bool {
1259
1751
  if (self.derivesTokens()) return true;
1260
1752
  const stored = runtime.canvasWidgetDesignTokens(window_id, canvas_label) catch return true;
1753
+ if (!std.meta.eql(stored.text_measure, tokens.text_measure)) return true;
1261
1754
  return stored.pixel_snap.scale != tokens.pixel_snap.scale;
1262
1755
  }
1263
1756
 
@@ -1300,12 +1793,35 @@ pub fn UiAppWithFeatures(comptime ModelT: type, comptime MsgT: type, comptime fe
1300
1793
  }
1301
1794
  }
1302
1795
  var tokens = runtime.tokensWithTextMeasure(self.effectiveTokens());
1303
- const next_index = self.arena_index ^ 1;
1796
+ // Stamp the mirrors this build renders BEFORE building:
1797
+ // the post-build reconcile (`applyVideoDeclaration`) can
1798
+ // move them, and `drainEffects` uses the stamp to know the
1799
+ // published chrome no longer matches (see
1800
+ // `video_rendered_snapshot`).
1801
+ self.video_rendered_snapshot = self.effects.videoSnapshot();
1802
+ const next_index = self.contextMenuRebuildIndex(null, self.arena_index);
1304
1803
  // Widget layout is inset by the runtime's viewport chrome
1305
1804
  // (safe areas + keyboard on mobile, zero on desktop); the
1306
1805
  // canvas itself stays surface-sized so chrome and the clear
1307
1806
  // color still paint edge to edge under notches and bars.
1308
1807
  const bounds = geometry.RectF.fromSize(self.canvas_size).deflate(self.layoutViewportInsets(runtime, window_id));
1808
+ // Under an open menu's pin, consecutive rebuilds route into
1809
+ // the LIVE tree's arena (`contextMenuRebuildIndex` freezes
1810
+ // the pinned side): the pass below resets that arena, so a
1811
+ // failure anywhere before the assignments would leave
1812
+ // `self.tree` dangling into reset, partially rewritten
1813
+ // storage. Drop the reference instead — handlers go quiet
1814
+ // until the next successful rebuild, and a stale-arena Msg
1815
+ // can never dispatch. The pinned snapshot is untouched: the
1816
+ // presented menu still resolves.
1817
+ var live_tree_reset = next_index == self.arena_index;
1818
+ errdefer if (live_tree_reset) {
1819
+ self.tree = null;
1820
+ };
1821
+ // Seed the staged video capture from the committed one, so
1822
+ // a pass that fails before capturing (or an over-long
1823
+ // declaration) leaves the committed state untouched.
1824
+ self.stageVideoDeclarationFromCommitted();
1309
1825
  var built = try self.buildLayoutPass(runtime, window_id, bounds, tokens, next_index);
1310
1826
  // Window-control clearance is a one-retry pass like the
1311
1827
  // virtual-window coverage retry inside the build: only when
@@ -1326,10 +1842,22 @@ pub fn UiAppWithFeatures(comptime ModelT: type, comptime MsgT: type, comptime fe
1326
1842
  const layout = built.layout;
1327
1843
  launch_timing.lapOnce("first_view_built");
1328
1844
 
1845
+ // The INSTALL WINDOW: from the moment the runtime ADOPTS
1846
+ // the new layout until the matching handler tree is adopted
1847
+ // below, the pair disagrees — the one place the main tree
1848
+ // goes stale (see `main_tree_current`; the stamp sits right
1849
+ // AFTER each `setCanvasWidgetLayout`, whose rejection is
1850
+ // validated-then-atomic — `validateWidgetLayoutPoolBudgets`
1851
+ // keeps the previous tree applied — so every failure before
1852
+ // adoption leaves the old, still-matching pair current). A
1853
+ // failure AFTER the window — animation scheduling, web
1854
+ // panes, the status item — leaves a genuinely current pair,
1855
+ // so hover enters keep flowing even when an idle app
1856
+ // performs no further rebuild.
1329
1857
  if (self.options.chrome) |chrome| {
1330
1858
  try self.installChromeDisplayList(runtime, window_id, chrome, layout, tokens);
1331
1859
  } else {
1332
- _ = try runtime.setCanvasWidgetLayout(window_id, self.options.canvas_label, layout);
1860
+ try self.publishWidgetLayoutTracked(runtime, window_id, self.options.canvas_label, layout, &self.main_tree_current);
1333
1861
  if (self.installed and self.rebuildEmitsTokens(runtime, window_id, self.options.canvas_label, tokens)) {
1334
1862
  _ = try runtime.emitCanvasWidgetDisplayList(window_id, self.options.canvas_label, tokens);
1335
1863
  }
@@ -1337,6 +1865,20 @@ pub fn UiAppWithFeatures(comptime ModelT: type, comptime MsgT: type, comptime fe
1337
1865
 
1338
1866
  self.tree = tree;
1339
1867
  self.arena_index = next_index;
1868
+ live_tree_reset = false;
1869
+ self.main_tree_current = true;
1870
+ self.build_generation +%= 1;
1871
+ // Captures track EVERY tree transition (see
1872
+ // refreshHoverLeaveCaptures) — a transient failure is
1873
+ // retried at the next commit or drain and lands in the
1874
+ // dispatch-error ring (the rebuild itself already
1875
+ // committed; erroring it here would lie about the tree).
1876
+ if (self.refreshHoverLeaveCaptures()) |refresh_err| {
1877
+ runtime.recordDispatchError("hover_leave_capture", refresh_err);
1878
+ }
1879
+ // The build INSTALLED: its video declaration now speaks
1880
+ // for what the glass shows.
1881
+ self.commitStagedVideoDeclaration();
1340
1882
  // The fallback menu's target vanished from this build (the
1341
1883
  // model dropped the row, or its menu emptied): the open state
1342
1884
  // has nothing to present, so it closes.
@@ -1346,10 +1888,127 @@ pub fn UiAppWithFeatures(comptime ModelT: type, comptime MsgT: type, comptime fe
1346
1888
  try self.scheduleAnimations(runtime, window_id);
1347
1889
  try self.scheduleLayoutTweens(runtime, window_id);
1348
1890
  self.applyWebPanes(runtime, window_id, layout);
1891
+ try self.applyTerminalLayout(runtime, window_id, layout, tokens);
1349
1892
  self.applyStatusItem(runtime);
1893
+ self.applyVideoDeclaration(runtime);
1894
+ // The reconcile can move the playback this very build
1895
+ // rendered (a src change loading an autoplaying
1896
+ // replacement): the just-installed chrome would advertise
1897
+ // the OLD transport state until a platform event arrived,
1898
+ // and its control would act on the new one — Play on the
1899
+ // label, pause in effect. One repass renders the chrome
1900
+ // from the moved mirrors; it reconciles the SAME
1901
+ // declaration (unchanged src reloads nothing), so the
1902
+ // mirrors are a fixed point and the repass ends the
1903
+ // recursion — the guard makes that a hard bound.
1904
+ if (!self.video_chrome_repass and
1905
+ !std.meta.eql(self.video_rendered_snapshot, self.effects.videoSnapshot()))
1906
+ {
1907
+ self.video_chrome_repass = true;
1908
+ defer self.video_chrome_repass = false;
1909
+ try self.rebuild(runtime, window_id);
1910
+ return;
1911
+ }
1350
1912
  self.applyWindows(runtime);
1351
1913
  self.applyChromeSelection();
1352
1914
  self.applyChromeNavigation();
1915
+ // Deliver the `on-terminal` states this rebuild's view-state
1916
+ // reconcile produced. Each dispatch rebuilds, and the nested
1917
+ // reconcile finds an already-applied state (nothing new
1918
+ // queues), so one guarded pass is the whole drain.
1919
+ try self.drainTerminalStates(runtime, window_id);
1920
+ }
1921
+
1922
+ /// The `<terminal>` view-state reconcile against the freshly
1923
+ /// laid-out tree: derive each bound terminal's cols/rows from
1924
+ /// its frame (the painter's own sizing seam, so painted cells
1925
+ /// and the pty grid can never disagree), apply a CHANGED
1926
+ /// declared scrollback (source wins), resize the emulator and
1927
+ /// push `ptyResize`, and queue the post-change state for the
1928
+ /// widget's `on-terminal`. A no-op on stub builds and for trees
1929
+ /// without a bound terminal.
1930
+ fn applyTerminalLayout(self: *Self, runtime: *Runtime, window_id: platform.WindowId, layout: canvas.WidgetLayoutTree, tokens: canvas.DesignTokens) anyerror!void {
1931
+ if (comptime !terminal_session.enabled) return;
1932
+ var applied = false;
1933
+ for (layout.nodes) |node| {
1934
+ if (node.widget.kind != .terminal) continue;
1935
+ const pty = node.widget.terminal.pty;
1936
+ if (pty == 0) continue;
1937
+ const frame = node.frame.normalized();
1938
+ if (frame.width <= 0 or frame.height <= 0) continue;
1939
+ // The grid text region sits inside the widget's own
1940
+ // padding (the house inset when none is declared) — the
1941
+ // exact rule the widget painter applies, so the derived
1942
+ // grid is the one the cells paint into.
1943
+ const padding = node.widget.layout.padding;
1944
+ const declared = padding.left + padding.top + padding.right + padding.bottom > 0;
1945
+ const inset: geometry.InsetsF = if (declared) padding else geometry.InsetsF.all(8);
1946
+ const content_width = @max(0, frame.width - inset.left - inset.right);
1947
+ const content_height = @max(0, frame.height - inset.top - inset.bottom);
1948
+ const metrics = canvas.terminalCellMetrics(tokens);
1949
+ if (metrics.width <= 0 or metrics.height <= 0) continue;
1950
+ const proposed = canvas.clampTerminalGrid(
1951
+ @intFromFloat(@max(2, @floor(content_width / metrics.width))),
1952
+ @intFromFloat(@max(2, @floor(content_height / metrics.height))),
1953
+ );
1954
+ const state = self.terminal_sessions.reconcile(
1955
+ pty,
1956
+ node.widget.terminal.scrollback,
1957
+ proposed.x,
1958
+ proposed.y,
1959
+ ) orelse continue;
1960
+ applied = true;
1961
+ if (self.terminal_state_pending_count < self.terminal_state_pending.len) {
1962
+ self.terminal_state_pending[self.terminal_state_pending_count] = .{
1963
+ .id = node.widget.id,
1964
+ .state = state,
1965
+ };
1966
+ self.terminal_state_pending_count += 1;
1967
+ }
1968
+ }
1969
+ // An applied change moved the published snapshot AFTER this
1970
+ // rebuild handed its layout over: refresh the retained
1971
+ // display list so the glass shows the post-reconcile grid
1972
+ // this frame (the widget diff always reports bound terminal
1973
+ // grids paint-dirty, and the refresh is batch-aware).
1974
+ if (applied and self.installed) {
1975
+ if (runtime.findViewIndex(window_id, self.options.canvas_label)) |view_index| {
1976
+ _ = try runtime.refreshCanvasWidgetDisplayListIfOwned(view_index);
1977
+ }
1978
+ }
1979
+ }
1980
+
1981
+ /// Repaint after INPUT moved a terminal's published snapshot (a
1982
+ /// scrollback snap on typing, a wheel scroll): dirty snapshots
1983
+ /// rebuild in place first, so the retained tree's borrowed grid
1984
+ /// pointers paint current state. A no-op when nothing is dirty.
1985
+ fn repaintTerminals(self: *Self, runtime: *Runtime, window_id: platform.WindowId) anyerror!void {
1986
+ if (comptime !terminal_session.enabled) return;
1987
+ if (!self.terminal_sessions.refreshDirty()) return;
1988
+ if (!self.installed) return;
1989
+ if (runtime.findViewIndex(window_id, self.options.canvas_label)) |view_index| {
1990
+ _ = try runtime.refreshCanvasWidgetDisplayListIfOwned(view_index);
1991
+ }
1992
+ }
1993
+
1994
+ /// Dispatch the queued `on-terminal` states (see the rebuild
1995
+ /// tail). Guarded to one level: the nested rebuild each dispatch
1996
+ /// runs reconciles to the same applied state and queues nothing.
1997
+ fn drainTerminalStates(self: *Self, runtime: *Runtime, window_id: platform.WindowId) anyerror!void {
1998
+ if (comptime !terminal_session.enabled) return;
1999
+ if (self.terminal_state_draining) return;
2000
+ if (self.terminal_state_pending_count == 0) return;
2001
+ self.terminal_state_draining = true;
2002
+ defer self.terminal_state_draining = false;
2003
+ while (self.terminal_state_pending_count > 0) {
2004
+ self.terminal_state_pending_count -= 1;
2005
+ const pending = self.terminal_state_pending[self.terminal_state_pending_count];
2006
+ self.terminal_state_pending[self.terminal_state_pending_count] = .{};
2007
+ const tree = self.tree orelse continue;
2008
+ if (tree.msgForTerminal(pending.id, pending.state)) |msg| {
2009
+ try self.dispatch(runtime, window_id, msg);
2010
+ }
2011
+ }
1353
2012
  }
1354
2013
 
1355
2014
  const BuiltLayout = struct {
@@ -1357,6 +2016,18 @@ pub fn UiAppWithFeatures(comptime ModelT: type, comptime MsgT: type, comptime fe
1357
2016
  layout: canvas.WidgetLayoutTree,
1358
2017
  };
1359
2018
 
2019
+ /// One build's `<video src>` declaration as the reconcile
2020
+ /// consumes it (`Ui.VideoDeclaration` minus the chrome flag,
2021
+ /// which is a view concern). The src slice borrows the build
2022
+ /// arena — valid until the next rebuild, longer than the
2023
+ /// reconcile needs.
2024
+ const VideoBuildDeclaration = struct {
2025
+ src: []const u8,
2026
+ autoplay: bool,
2027
+ loop: bool,
2028
+ muted: bool,
2029
+ };
2030
+
1360
2031
  /// One view-build + flex-layout pass of `rebuild`, including the
1361
2032
  /// windowed-virtual-list coverage retry: builds the tree into the
1362
2033
  /// next arena and lays it out against `bounds` with `tokens`.
@@ -1380,13 +2051,27 @@ pub fn UiAppWithFeatures(comptime ModelT: type, comptime MsgT: type, comptime fe
1380
2051
  var layout: canvas.WidgetLayoutTree = undefined;
1381
2052
  var pass: usize = 0;
1382
2053
  while (true) {
2054
+ // `contextMenuRebuildIndex` never routes a rebuild into
2055
+ // the pinned generation, so the reset is unconditional.
2056
+ std.debug.assert(if (self.context_menu_pin) |pin| pin.window_id != null or pin.arena_index != next_index else true);
1383
2057
  _ = self.arenas[next_index].reset(.retain_capacity);
1384
2058
  var ui = Ui.init(self.arenas[next_index].allocator());
2059
+ // The house video chrome renders the channel's honest
2060
+ // snapshot, stamped before the view fn runs — the model
2061
+ // carries none of it.
2062
+ ui.video_state = self.uiVideoState();
2063
+ // The terminal grid lookup (null on stub builds): each
2064
+ // `<terminal pty={key}>` resolves its session's published
2065
+ // snapshot during finalize, with THIS build's tokens
2066
+ // driving the palette's theme mapping.
2067
+ self.terminal_sessions.beginBuild(tokens);
2068
+ ui.terminal_lookup = self.terminal_sessions.lookup();
1385
2069
  ui.virtual_window_context = @ptrCast(&window_source);
1386
2070
  ui.virtual_window_source = VirtualWindowResolver.resolve;
1387
2071
  ui.virtual_extent_context = @ptrCast(self);
1388
2072
  ui.virtual_extent_source = virtualExtentResolve;
1389
2073
  ui.context_menu_fallback_target = self.contextMenuFallbackTargetForLabel(self.options.canvas_label);
2074
+ if (ui.context_menu_fallback_target != 0) ui.context_menu_fallback_point = self.context_menu_fallback_point;
1390
2075
  self.armUiFragmentHost(&ui);
1391
2076
  if (comptime features.runtime_markup) {
1392
2077
  if (self.markup_view != null and runtime.options.automation != null) {
@@ -1418,6 +2103,30 @@ pub fn UiAppWithFeatures(comptime ModelT: type, comptime MsgT: type, comptime fe
1418
2103
  };
1419
2104
  runtime.frame_profile.end(.layout, layout_begin);
1420
2105
 
2106
+ // Capture the build's `<video src>` declaration for the
2107
+ // post-rebuild reconcile (last pass wins — each pass
2108
+ // resets the arena and re-records), COPIED out of the
2109
+ // build arena (`video_build_staged_src_buffer`):
2110
+ // borrowing the arena would dangle after a later failed
2111
+ // rebuild reset it. STAGED, not committed: the rebuild
2112
+ // commits at install (`commitStagedVideoDeclaration`),
2113
+ // so a build that fails downstream never speaks for the
2114
+ // tree still on the glass. Over-long sources are not
2115
+ // tracked and keep the previous capture — the slot
2116
+ // captures' rule (`captureSlotVideoDeclaration`).
2117
+ if (ui.video_declaration) |declaration| {
2118
+ if (declaration.src.len > 0 and declaration.src.len <= self.video_build_staged_src_buffer.len) {
2119
+ @memcpy(self.video_build_staged_src_buffer[0..declaration.src.len], declaration.src);
2120
+ self.video_build_staged = .{
2121
+ .src = self.video_build_staged_src_buffer[0..declaration.src.len],
2122
+ .autoplay = declaration.autoplay,
2123
+ .loop = declaration.loop,
2124
+ .muted = declaration.muted,
2125
+ };
2126
+ }
2127
+ } else {
2128
+ self.video_build_staged = null;
2129
+ }
1421
2130
  self.rememberVirtualWindows(&ui);
1422
2131
  // Measure the mounted rows of every variable-extent
1423
2132
  // list against the fresh layout and patch the retained
@@ -1686,6 +2395,36 @@ pub fn UiAppWithFeatures(comptime ModelT: type, comptime MsgT: type, comptime fe
1686
2395
  return false;
1687
2396
  }
1688
2397
 
2398
+ /// One (id, axis) hysteresis latch: the axis rides along so a
2399
+ /// region whose primary axis changes re-arms honestly. Two
2400
+ /// slots per declarable window — the (id, axis) key space is
2401
+ /// twice the id space.
2402
+ const max_reach_latches = canvas.max_virtual_windows * 2;
2403
+
2404
+ const ReachLatch = struct {
2405
+ id: canvas.ObjectId = 0,
2406
+ axis: canvas.ScrollAxis = .vertical,
2407
+ };
2408
+
2409
+ const ReachAxis = struct {
2410
+ state: canvas.ScrollAxisState,
2411
+ axis: canvas.ScrollAxis,
2412
+ };
2413
+
2414
+ /// The axis reach-end/reach-start measure: the vertical axis
2415
+ /// wherever it has scrollable range (every pre-axis region, so
2416
+ /// existing apps see identical behavior), otherwise the
2417
+ /// horizontal one — a horizontal timeline's `on-reach-end` is
2418
+ /// its right edge. One rule for both signals so "the end" and
2419
+ /// "the start" always name the same axis.
2420
+ fn reachAxisState(scroll_state: canvas.ScrollState) ReachAxis {
2421
+ const vertical = scroll_state.axis(.vertical);
2422
+ if (vertical.maxOffset() > 0) return .{ .state = vertical, .axis = .vertical };
2423
+ const horizontal = scroll_state.axis(.horizontal);
2424
+ if (horizontal.maxOffset() > 0) return .{ .state = horizontal, .axis = .horizontal };
2425
+ return .{ .state = vertical, .axis = .vertical };
2426
+ }
2427
+
1689
2428
  /// Approach-end hysteresis (`on_reach_end`): fire when a scroll
1690
2429
  /// lands within `reach_end_fire_ratio` viewports of the content
1691
2430
  /// end and the region is armed; re-arm once the offset sits more
@@ -1694,37 +2433,43 @@ pub fn UiAppWithFeatures(comptime ModelT: type, comptime MsgT: type, comptime fe
1694
2433
  /// under the unchanged offset. One Msg per approach, never a
1695
2434
  /// fetch storm from a user riding the end of the list.
1696
2435
  fn reachEndShouldFire(self: *Self, id: canvas.ObjectId, scroll_state: canvas.ScrollState) bool {
1697
- if (id == 0 or scroll_state.viewport_extent <= 0) return false;
1698
- const remaining = scroll_state.content_extent - scroll_state.viewport_extent - scroll_state.offset;
1699
- if (remaining > scroll_state.viewport_extent * reach_end_rearm_ratio) {
1700
- self.clearReachEndFired(id);
2436
+ const reach = reachAxisState(scroll_state);
2437
+ const axis_state = reach.state;
2438
+ if (id == 0 or axis_state.viewport_extent <= 0) return false;
2439
+ const remaining = axis_state.content_extent - axis_state.viewport_extent - axis_state.offset;
2440
+ if (remaining > axis_state.viewport_extent * reach_end_rearm_ratio) {
2441
+ self.clearReachEndFired(id, reach.axis);
1701
2442
  return false;
1702
2443
  }
1703
- if (remaining > scroll_state.viewport_extent * reach_end_fire_ratio) return false;
1704
- if (self.reachEndFired(id)) return false;
1705
- self.markReachEndFired(id);
1706
- return true;
2444
+ if (remaining > axis_state.viewport_extent * reach_end_fire_ratio) return false;
2445
+ if (self.reachEndFired(id, reach.axis)) return false;
2446
+ // Fire only when the latch STORES: an unstorable latch
2447
+ // (table full — a degenerate tree) would otherwise fire on
2448
+ // every observation, the exact storm the hysteresis exists
2449
+ // to prevent. Silence is the safer failure.
2450
+ return self.markReachEndFired(id, reach.axis);
1707
2451
  }
1708
2452
 
1709
- fn reachEndFired(self: *const Self, id: canvas.ObjectId) bool {
1710
- for (self.reach_end_fired_ids) |fired| {
1711
- if (fired == id) return true;
2453
+ fn reachEndFired(self: *const Self, id: canvas.ObjectId, axis: canvas.ScrollAxis) bool {
2454
+ for (self.reach_end_fired) |fired| {
2455
+ if (fired.id == id and fired.axis == axis) return true;
1712
2456
  }
1713
2457
  return false;
1714
2458
  }
1715
2459
 
1716
- fn markReachEndFired(self: *Self, id: canvas.ObjectId) void {
1717
- for (&self.reach_end_fired_ids) |*slot| {
1718
- if (slot.* == 0 or slot.* == id) {
1719
- slot.* = id;
1720
- return;
2460
+ fn markReachEndFired(self: *Self, id: canvas.ObjectId, axis: canvas.ScrollAxis) bool {
2461
+ for (&self.reach_end_fired) |*slot| {
2462
+ if (slot.id == 0 or (slot.id == id and slot.axis == axis)) {
2463
+ slot.* = .{ .id = id, .axis = axis };
2464
+ return true;
1721
2465
  }
1722
2466
  }
2467
+ return false;
1723
2468
  }
1724
2469
 
1725
- fn clearReachEndFired(self: *Self, id: canvas.ObjectId) void {
1726
- for (&self.reach_end_fired_ids) |*slot| {
1727
- if (slot.* == id) slot.* = 0;
2470
+ fn clearReachEndFired(self: *Self, id: canvas.ObjectId, axis: canvas.ScrollAxis) void {
2471
+ for (&self.reach_end_fired) |*slot| {
2472
+ if (slot.id == id and slot.axis == axis) slot.* = .{};
1728
2473
  }
1729
2474
  }
1730
2475
 
@@ -1739,37 +2484,40 @@ pub fn UiAppWithFeatures(comptime ModelT: type, comptime MsgT: type, comptime fe
1739
2484
  /// only moves on scroll OBSERVATIONS, so a programmatic jump out
1740
2485
  /// of the band re-arms on the next user scroll, not instantly.
1741
2486
  fn reachStartShouldFire(self: *Self, id: canvas.ObjectId, scroll_state: canvas.ScrollState) bool {
1742
- if (id == 0 or scroll_state.viewport_extent <= 0) return false;
1743
- const remaining = scroll_state.offset;
1744
- if (remaining > scroll_state.viewport_extent * reach_start_rearm_ratio) {
1745
- self.clearReachStartFired(id);
2487
+ const reach = reachAxisState(scroll_state);
2488
+ const axis_state = reach.state;
2489
+ if (id == 0 or axis_state.viewport_extent <= 0) return false;
2490
+ const remaining = axis_state.offset;
2491
+ if (remaining > axis_state.viewport_extent * reach_start_rearm_ratio) {
2492
+ self.clearReachStartFired(id, reach.axis);
1746
2493
  return false;
1747
2494
  }
1748
- if (remaining > scroll_state.viewport_extent * reach_start_fire_ratio) return false;
1749
- if (self.reachStartFired(id)) return false;
1750
- self.markReachStartFired(id);
1751
- return true;
2495
+ if (remaining > axis_state.viewport_extent * reach_start_fire_ratio) return false;
2496
+ if (self.reachStartFired(id, reach.axis)) return false;
2497
+ // Fire only when the latch stores (the reach-end rule).
2498
+ return self.markReachStartFired(id, reach.axis);
1752
2499
  }
1753
2500
 
1754
- fn reachStartFired(self: *const Self, id: canvas.ObjectId) bool {
1755
- for (self.reach_start_fired_ids) |fired| {
1756
- if (fired == id) return true;
2501
+ fn reachStartFired(self: *const Self, id: canvas.ObjectId, axis: canvas.ScrollAxis) bool {
2502
+ for (self.reach_start_fired) |fired| {
2503
+ if (fired.id == id and fired.axis == axis) return true;
1757
2504
  }
1758
2505
  return false;
1759
2506
  }
1760
2507
 
1761
- fn markReachStartFired(self: *Self, id: canvas.ObjectId) void {
1762
- for (&self.reach_start_fired_ids) |*slot| {
1763
- if (slot.* == 0 or slot.* == id) {
1764
- slot.* = id;
1765
- return;
2508
+ fn markReachStartFired(self: *Self, id: canvas.ObjectId, axis: canvas.ScrollAxis) bool {
2509
+ for (&self.reach_start_fired) |*slot| {
2510
+ if (slot.id == 0 or (slot.id == id and slot.axis == axis)) {
2511
+ slot.* = .{ .id = id, .axis = axis };
2512
+ return true;
1766
2513
  }
1767
2514
  }
2515
+ return false;
1768
2516
  }
1769
2517
 
1770
- fn clearReachStartFired(self: *Self, id: canvas.ObjectId) void {
1771
- for (&self.reach_start_fired_ids) |*slot| {
1772
- if (slot.* == id) slot.* = 0;
2518
+ fn clearReachStartFired(self: *Self, id: canvas.ObjectId, axis: canvas.ScrollAxis) void {
2519
+ for (&self.reach_start_fired) |*slot| {
2520
+ if (slot.id == id and slot.axis == axis) slot.* = .{};
1773
2521
  }
1774
2522
  }
1775
2523
 
@@ -1931,6 +2679,11 @@ pub fn UiAppWithFeatures(comptime ModelT: type, comptime MsgT: type, comptime fe
1931
2679
  /// the model already knows).
1932
2680
  fn closeWindowSlot(self: *Self, runtime: *Runtime, index: usize) void {
1933
2681
  const window_id = self.window_slots[index].window_id;
2682
+ self.releaseContextMenuSnapshotForWindow(window_id);
2683
+ // The reconcile-closed window's video declaration dies with
2684
+ // it, exactly as in `handleWindowClosed`.
2685
+ self.captureSlotVideoDeclaration(window_id, null);
2686
+ self.applyVideoDeclaration(runtime);
1934
2687
  const last = self.window_slot_count - 1;
1935
2688
  var removed = self.window_slots[index];
1936
2689
  self.window_slots[index] = self.window_slots[last];
@@ -1946,6 +2699,7 @@ pub fn UiAppWithFeatures(comptime ModelT: type, comptime MsgT: type, comptime fe
1946
2699
  /// Drop a slot whose runtime window is ALREADY gone (the user
1947
2700
  /// closed it): bookkeeping only, no platform call.
1948
2701
  fn forgetWindowSlot(self: *Self, index: usize) ?MsgT {
2702
+ self.releaseContextMenuSnapshotForWindow(self.window_slots[index].window_id);
1949
2703
  const on_close = self.window_slots[index].on_close;
1950
2704
  const last = self.window_slot_count - 1;
1951
2705
  var removed = self.window_slots[index];
@@ -1971,8 +2725,16 @@ pub fn UiAppWithFeatures(comptime ModelT: type, comptime MsgT: type, comptime fe
1971
2725
  fn rebuildWindowSlot(self: *Self, runtime: *Runtime, slot: *WindowSlot) anyerror!void {
1972
2726
  if (self.options.window_view == null) return;
1973
2727
  var tokens = runtime.tokensWithTextMeasure(self.slotEffectiveTokens(slot));
1974
- const next_index = slot.arena_index ^ 1;
2728
+ const next_index = self.contextMenuRebuildIndex(slot.window_id, slot.arena_index);
1975
2729
  const bounds = geometry.RectF.fromSize(slot.canvas_size).deflate(runtime.viewportInsetsForWindow(slot.window_id));
2730
+ // Same live-arena guard as the main canvas rebuild: under
2731
+ // this window's pin the build routes into the slot's LIVE
2732
+ // arena, so a failing pass must drop `slot.tree` rather
2733
+ // than leave it dangling into the reset storage.
2734
+ var live_tree_reset = next_index == slot.arena_index;
2735
+ errdefer if (live_tree_reset) {
2736
+ slot.tree = null;
2737
+ };
1976
2738
  var built = try self.buildWindowSlotPass(slot, bounds, tokens, next_index);
1977
2739
  // The same one-retry window-control clearance the main
1978
2740
  // rebuild runs (see `rebuild`): a secondary hidden-inset
@@ -1986,16 +2748,103 @@ pub fn UiAppWithFeatures(comptime ModelT: type, comptime MsgT: type, comptime fe
1986
2748
  }
1987
2749
  const tree = built.tree;
1988
2750
  const layout = built.layout;
1989
- _ = try runtime.setCanvasWidgetLayout(slot.window_id, slot.canvasLabel(), layout);
2751
+ // The slot's install window — the per-slot mirror of the
2752
+ // main rebuild's stamp: stale only from the runtime's
2753
+ // ADOPTION of the new layout (whose rejection is atomic, so
2754
+ // earlier failures keep the old pair current) until the
2755
+ // matching handler tree lands below, wherever the rebuild
2756
+ // was driven from (the full pass or a direct resize/install
2757
+ // site).
2758
+ try self.publishWidgetLayoutTracked(runtime, slot.window_id, slot.canvasLabel(), layout, &slot.tree_current);
1990
2759
  if (slot.installed and self.rebuildEmitsTokens(runtime, slot.window_id, slot.canvasLabel(), tokens)) {
1991
2760
  _ = try runtime.emitCanvasWidgetDisplayList(slot.window_id, slot.canvasLabel(), tokens);
1992
2761
  }
1993
2762
  slot.tree = tree;
1994
2763
  slot.arena_index = next_index;
2764
+ live_tree_reset = false;
2765
+ slot.tree_current = true;
2766
+ self.build_generation +%= 1;
2767
+ // Same per-transition capture refresh as the main rebuild,
2768
+ // same dispatch-error-ring surfacing.
2769
+ if (self.refreshHoverLeaveCaptures()) |refresh_err| {
2770
+ runtime.recordDispatchError("hover_leave_capture", refresh_err);
2771
+ }
1995
2772
  // Same close-on-vanish rule as the main canvas rebuild.
1996
2773
  if (self.contextMenuFallbackTargetForLabel(slot.canvasLabel()) != 0 and tree.context_menu_fallback == null) {
1997
2774
  self.clearContextMenuFallback();
1998
2775
  }
2776
+ // Reconcile the video declaration THIS build recorded or
2777
+ // withdrew (a no-op when nothing changed — the reconciler
2778
+ // diffs the applied src), captured only now that the tree
2779
+ // really installed. The main rebuild already ran it, but
2780
+ // slot builds run after, so a slot-declared video must not
2781
+ // wait a cycle to load.
2782
+ self.captureSlotVideoDeclaration(slot.window_id, slot.pending_video_declaration);
2783
+ const rendered = self.effects.videoSnapshot();
2784
+ self.applyVideoDeclaration(runtime);
2785
+ // The reconcile can activate (or move) the playback this
2786
+ // slot's build rendered — a first mount of an autoplaying
2787
+ // declaration builds its chrome from the still-inactive
2788
+ // snapshot — so one guarded repass renders it from the
2789
+ // moved mirrors, the main rebuild's rule: the repass
2790
+ // reconciles an unchanged declaration, so the mirrors are
2791
+ // a fixed point and the guard makes one level a hard
2792
+ // bound.
2793
+ if (!self.video_chrome_repass and !std.meta.eql(rendered, self.effects.videoSnapshot())) {
2794
+ self.video_chrome_repass = true;
2795
+ defer self.video_chrome_repass = false;
2796
+ try self.rebuildWindowSlot(runtime, slot);
2797
+ }
2798
+ }
2799
+
2800
+ /// One retained secondary-window `<video src>` declaration
2801
+ /// (see `video_slot_declarations`): the window's latest build
2802
+ /// output, kept even while another window owns the player so
2803
+ /// the owner's close or withdrawal promotes it without waiting
2804
+ /// for the declaring window's next rebuild.
2805
+ const SlotVideoDeclaration = struct {
2806
+ used: bool = false,
2807
+ window_id: platform.WindowId = 0,
2808
+ src_buffer: [1024]u8 = undefined,
2809
+ src_len: usize = 0,
2810
+ autoplay: bool = false,
2811
+ loop: bool = false,
2812
+ muted: bool = false,
2813
+ };
2814
+
2815
+ /// Record (or withdraw) a secondary window's `<video src>`
2816
+ /// declaration, copied out of the slot build's arena — one
2817
+ /// retained entry per window (the table matches the window
2818
+ /// budget, so an upsert always finds room). Over-long and
2819
+ /// empty sources are not tracked (`loadVideo` would reject
2820
+ /// them, and tracking one would reload every rebuild).
2821
+ fn captureSlotVideoDeclaration(self: *Self, window_id: platform.WindowId, declaration: ?Ui.VideoDeclaration) void {
2822
+ if (declaration) |decl| {
2823
+ if (decl.src.len == 0 or decl.src.len > 1024) return;
2824
+ const entry = blk: {
2825
+ for (&self.video_slot_declarations) |*candidate| {
2826
+ if (candidate.used and candidate.window_id == window_id) break :blk candidate;
2827
+ }
2828
+ for (&self.video_slot_declarations) |*candidate| {
2829
+ if (!candidate.used) break :blk candidate;
2830
+ }
2831
+ return;
2832
+ };
2833
+ @memcpy(entry.src_buffer[0..decl.src.len], decl.src);
2834
+ entry.src_len = decl.src.len;
2835
+ entry.window_id = window_id;
2836
+ entry.autoplay = decl.autoplay;
2837
+ entry.loop = decl.loop;
2838
+ entry.muted = decl.muted;
2839
+ entry.used = true;
2840
+ return;
2841
+ }
2842
+ for (&self.video_slot_declarations) |*candidate| {
2843
+ if (candidate.used and candidate.window_id == window_id) {
2844
+ candidate.* = .{};
2845
+ }
2846
+ }
2847
+ if (self.video_slot_owner == window_id) self.video_slot_owner = 0;
1999
2848
  }
2000
2849
 
2001
2850
  /// One view-build + flex-layout pass of `rebuildWindowSlot`,
@@ -2011,12 +2860,33 @@ pub fn UiAppWithFeatures(comptime ModelT: type, comptime MsgT: type, comptime fe
2011
2860
  next_index: usize,
2012
2861
  ) anyerror!BuiltLayout {
2013
2862
  const window_view = self.options.window_view.?;
2863
+ // `contextMenuRebuildIndex` never routes a rebuild into the
2864
+ // pinned generation, so the reset is unconditional.
2865
+ std.debug.assert(if (self.context_menu_pin) |pin| pin.window_id != slot.window_id or pin.arena_index != next_index else true);
2014
2866
  _ = slot.arenas[next_index].reset(.retain_capacity);
2015
2867
  var ui = Ui.init(slot.arenas[next_index].allocator());
2868
+ // Window views render the same honest video chrome state,
2869
+ // and their `<video src>` declarations reconcile the channel
2870
+ // too — `Ui.video` promises that declaring the element IS
2871
+ // the playback in every window's tree. The main canvas
2872
+ // build's declaration wins when both declare (one player,
2873
+ // one owner); the capture below records this slot's claim.
2874
+ ui.video_state = self.uiVideoState();
2875
+ // Window views resolve terminal bindings through the same
2876
+ // session store as the main canvas — one emulator per pty
2877
+ // key, whichever tree binds it.
2878
+ self.terminal_sessions.beginBuild(tokens);
2879
+ ui.terminal_lookup = self.terminal_sessions.lookup();
2016
2880
  ui.context_menu_fallback_target = self.contextMenuFallbackTargetForLabel(slot.canvasLabel());
2881
+ if (ui.context_menu_fallback_target != 0) ui.context_menu_fallback_point = self.context_menu_fallback_point;
2017
2882
  self.armUiFragmentHost(&ui);
2018
2883
  const node = window_view(&ui, &self.model, slot.label());
2019
2884
  const tree = try ui.finalizeWithTokens(node, tokens);
2885
+ // The declaration is captured by `rebuildWindowSlot` AFTER
2886
+ // the pass (and its clearance retry) succeeds and the tree
2887
+ // installs: a build whose layout errors never displays, so
2888
+ // its declaration must not steer the playback either.
2889
+ slot.pending_video_declaration = ui.video_declaration;
2020
2890
  const layout = canvas.layoutWidgetTreeWithTokens(tree.root, bounds, tokens, &self.layout_nodes) catch |err| {
2021
2891
  if (err == error.WidgetLayoutListFull) {
2022
2892
  ui_app_log.warn(
@@ -2138,20 +3008,31 @@ pub fn UiAppWithFeatures(comptime ModelT: type, comptime MsgT: type, comptime fe
2138
3008
  var chrome_builder = canvas.Builder.init(&chrome_commands);
2139
3009
  try chrome.build(&self.model, &chrome_builder, self.canvas_size, tokens);
2140
3010
  const chrome_list = chrome_builder.displayList();
2141
- if (chrome_list.commands.len != chrome.prefix_commands + chrome.suffix_commands) {
3011
+ if (chrome.variable_prefix) {
3012
+ if (chrome_list.commands.len < chrome.suffix_commands or
3013
+ chrome_list.commands.len - chrome.suffix_commands > chrome.prefix_commands)
3014
+ {
3015
+ return error.InvalidChromeCommandCount;
3016
+ }
3017
+ } else if (chrome_list.commands.len != chrome.prefix_commands + chrome.suffix_commands) {
2142
3018
  return error.InvalidChromeCommandCount;
2143
3019
  }
3020
+ const prefix_len = chrome_list.commands.len - chrome.suffix_commands;
2144
3021
 
2145
3022
  var commands: [canvas_limits.max_canvas_commands_per_view]canvas.CanvasCommand = undefined;
2146
3023
  var builder = canvas.Builder.init(&commands);
2147
- for (chrome_list.commands[0..chrome.prefix_commands]) |command| try builder.append(command);
3024
+ for (chrome_list.commands[0..prefix_len]) |command| try builder.append(command);
2148
3025
  try layout.emitDisplayList(&builder, tokens);
2149
- for (chrome_list.commands[chrome.prefix_commands..]) |command| try builder.append(command);
3026
+ for (chrome_list.commands[prefix_len..]) |command| try builder.append(command);
2150
3027
 
2151
3028
  _ = try runtime.setCanvasDisplayList(window_id, self.options.canvas_label, builder.displayList());
2152
- _ = try runtime.setCanvasWidgetLayout(window_id, self.options.canvas_label, layout);
3029
+ // The main install window opens at the layout's true
3030
+ // adoption inside the tracked publication (see `rebuild`)
3031
+ // and closes when the caller adopts the matching handler
3032
+ // tree.
3033
+ try self.publishWidgetLayoutTracked(runtime, window_id, self.options.canvas_label, layout, &self.main_tree_current);
2153
3034
  _ = try runtime.emitCanvasWidgetDisplayListWithChrome(window_id, self.options.canvas_label, tokens, .{
2154
- .prefix_command_count = chrome.prefix_commands,
3035
+ .prefix_command_count = prefix_len,
2155
3036
  .suffix_command_count = chrome.suffix_commands,
2156
3037
  });
2157
3038
  }
@@ -2729,6 +3610,223 @@ pub fn UiAppWithFeatures(comptime ModelT: type, comptime MsgT: type, comptime fe
2729
3610
  }
2730
3611
  }
2731
3612
 
3613
+ /// The video channel snapshot in the builder's chrome shape
3614
+ /// (`Ui.VideoPlaybackState`), stamped onto every Ui before its
3615
+ /// view fn runs.
3616
+ fn uiVideoState(self: *const Self) Ui.VideoPlaybackState {
3617
+ const snap = self.effects.videoSnapshot();
3618
+ return .{
3619
+ .active = snap.active,
3620
+ .playing = snap.playing,
3621
+ .buffering = snap.buffering,
3622
+ .completed = snap.completed,
3623
+ .position_ms = snap.position_ms,
3624
+ .duration_ms = snap.duration_ms,
3625
+ // The surface + reported stream dimensions drive the
3626
+ // video surface's CONTAIN fit: the builder stamps the
3627
+ // fitted-draw geometry on whichever media surface this
3628
+ // playback feeds (Ui.stampVideoSurfaceFit).
3629
+ .surface = snap.surface,
3630
+ .width = snap.width,
3631
+ .height = snap.height,
3632
+ };
3633
+ }
3634
+
3635
+ /// Whether a `<video src>` names an http(s) stream — the
3636
+ /// `loadVideo` cascade's scheme split; everything else is a
3637
+ /// local app-assets path.
3638
+ fn videoSrcIsUrl(src: []const u8) bool {
3639
+ return std.ascii.startsWithIgnoreCase(src, "http://") or
3640
+ std.ascii.startsWithIgnoreCase(src, "https://");
3641
+ }
3642
+
3643
+ /// Reconcile the build's `<video src>` declaration into the
3644
+ /// video playback channel — the windows/tray pattern: presence
3645
+ /// IS playback. A new or changed src loads (loadVideo's replace
3646
+ /// semantics — one player is the whole surface, keyed by the
3647
+ /// src hash so identical declarations share identity); an
3648
+ /// unchanged src applies only loop/muted deltas; a build with
3649
+ /// no declaration while one was applied stops the playback (the
3650
+ /// element left the view; declarative ownership ends it).
3651
+ /// Deterministic under replay: only fx verbs, which regenerate
3652
+ /// from the replayed rebuilds — never a journal write of its
3653
+ /// own.
3654
+ /// The secondary-window declaration as the reconciler consumes
3655
+ /// it — the current owner window's retained entry while it
3656
+ /// still declares, otherwise the first retained declaration
3657
+ /// PROMOTES on the spot (the previous owner closed or stopped
3658
+ /// declaring; a mounted video in another window must not wait
3659
+ /// for an unrelated rebuild to start). Null when no slot
3660
+ /// declares. The src borrows the app struct's own copy, stable
3661
+ /// across builds.
3662
+ fn slotVideoDeclaration(self: *Self) ?VideoBuildDeclaration {
3663
+ const entry = blk: {
3664
+ if (self.video_slot_owner != 0) {
3665
+ for (&self.video_slot_declarations) |*candidate| {
3666
+ if (candidate.used and candidate.window_id == self.video_slot_owner) break :blk candidate;
3667
+ }
3668
+ }
3669
+ for (&self.video_slot_declarations) |*candidate| {
3670
+ if (candidate.used) break :blk candidate;
3671
+ }
3672
+ self.video_slot_owner = 0;
3673
+ return null;
3674
+ };
3675
+ self.video_slot_owner = entry.window_id;
3676
+ return .{
3677
+ .src = entry.src_buffer[0..entry.src_len],
3678
+ .autoplay = entry.autoplay,
3679
+ .loop = entry.loop,
3680
+ .muted = entry.muted,
3681
+ };
3682
+ }
3683
+
3684
+ /// Seed the in-flight rebuild's staged capture from the
3685
+ /// committed declaration (see `video_build_staged`).
3686
+ fn stageVideoDeclarationFromCommitted(self: *Self) void {
3687
+ if (self.video_build_declaration) |committed| {
3688
+ @memcpy(self.video_build_staged_src_buffer[0..committed.src.len], committed.src);
3689
+ self.video_build_staged = .{
3690
+ .src = self.video_build_staged_src_buffer[0..committed.src.len],
3691
+ .autoplay = committed.autoplay,
3692
+ .loop = committed.loop,
3693
+ .muted = committed.muted,
3694
+ };
3695
+ } else {
3696
+ self.video_build_staged = null;
3697
+ }
3698
+ }
3699
+
3700
+ /// Commit the installed build's staged capture (see
3701
+ /// `video_build_staged`).
3702
+ fn commitStagedVideoDeclaration(self: *Self) void {
3703
+ if (self.video_build_staged) |staged| {
3704
+ @memcpy(self.video_build_src_buffer[0..staged.src.len], staged.src);
3705
+ self.video_build_declaration = .{
3706
+ .src = self.video_build_src_buffer[0..staged.src.len],
3707
+ .autoplay = staged.autoplay,
3708
+ .loop = staged.loop,
3709
+ .muted = staged.muted,
3710
+ };
3711
+ } else {
3712
+ self.video_build_declaration = null;
3713
+ }
3714
+ }
3715
+
3716
+ fn applyVideoDeclaration(self: *Self, runtime: *Runtime) void {
3717
+ const declaration = self.video_build_declaration orelse self.slotVideoDeclaration() orelse {
3718
+ if (self.video_declared) {
3719
+ self.video_declared = false;
3720
+ const declared_key = std.hash.Wyhash.hash(0x76696465, self.video_declared_src_buffer[0..self.video_declared_src_len]) | 1;
3721
+ self.video_declared_src_len = 0;
3722
+ // Stop ONLY the playback this reconciler started:
3723
+ // an update handler may have replaced it with its
3724
+ // own load (a different key) between rebuilds, and
3725
+ // declarative ownership must never kill a playback
3726
+ // it does not own.
3727
+ const snapshot = self.effects.videoSnapshot();
3728
+ if (snapshot.active and snapshot.key == declared_key and
3729
+ self.effects.videoOwnerToken() == self.video_declared_token)
3730
+ {
3731
+ self.effects.stopVideo();
3732
+ }
3733
+ self.video_declared_token = 0;
3734
+ self.publishAudioState(runtime);
3735
+ }
3736
+ return;
3737
+ };
3738
+ // The installing rebuild can reach here before any dispatch
3739
+ // bound the channel (first-bind-sticks, so this is free
3740
+ // afterwards); the load below needs the platform services.
3741
+ self.bindEffectsChannel(runtime);
3742
+ const src = declaration.src;
3743
+ if (src.len > self.video_declared_src_buffer.len) {
3744
+ // Longer than the platform source bound: loadVideo
3745
+ // would reject it; refusing to track it here keeps an
3746
+ // over-long declaration from reloading every rebuild.
3747
+ return;
3748
+ }
3749
+ const applied = self.video_declared_src_buffer[0..self.video_declared_src_len];
3750
+ if (!self.video_declared or !std.mem.eql(u8, applied, src)) {
3751
+ const options: Effects.LoadVideoOptions = .{
3752
+ // Key from the src (nonzero by construction): the
3753
+ // declaration IS the playback's identity.
3754
+ .key = std.hash.Wyhash.hash(0x76696465, src) | 1,
3755
+ .surface = canvas.video_playback_surface_id,
3756
+ .path = if (videoSrcIsUrl(src)) "" else src,
3757
+ .url = if (videoSrcIsUrl(src)) src else "",
3758
+ .autoplay = declaration.autoplay,
3759
+ .loop = declaration.loop,
3760
+ .muted = declaration.muted,
3761
+ };
3762
+ // Validate BEFORE committing: a source the engine's own
3763
+ // deterministic gates refuse (a malformed URL, say)
3764
+ // must not take over the tracked ownership — the
3765
+ // engine keeps the CURRENT playback on a rejected
3766
+ // load, and tracking the refused src would make a
3767
+ // later element removal hash the refused source
3768
+ // instead of the playback still running, stranding it
3769
+ // forever. The refused src is remembered separately so
3770
+ // an unchanged bad declaration is not re-attempted
3771
+ // (and re-taught) every rebuild.
3772
+ if (Effects.videoLoadRejected(options)) {
3773
+ const refused = self.video_refused_src_buffer[0..self.video_refused_src_len];
3774
+ if (src.len <= self.video_refused_src_buffer.len and !std.mem.eql(u8, refused, src)) {
3775
+ @memcpy(self.video_refused_src_buffer[0..src.len], src);
3776
+ self.video_refused_src_len = src.len;
3777
+ ui_app_log.warn(
3778
+ "declared <video src> was refused by the video loader (empty or over-long source, or a non-http(s) URL): the declaration is ignored and the current playback, if any, keeps running",
3779
+ .{},
3780
+ );
3781
+ }
3782
+ return;
3783
+ }
3784
+ self.video_refused_src_len = 0;
3785
+ @memcpy(self.video_declared_src_buffer[0..src.len], src);
3786
+ self.video_declared_src_len = src.len;
3787
+ self.video_declared = true;
3788
+ self.video_declared_loop = declaration.loop;
3789
+ self.video_declared_muted = declaration.muted;
3790
+ self.effects.loadVideo(options);
3791
+ self.video_declared_token = self.effects.videoOwnerToken();
3792
+ self.publishAudioState(runtime);
3793
+ return;
3794
+ }
3795
+ // Same src: apply flag deltas in place — a reload would
3796
+ // restart the playback the declaration did not change. Only
3797
+ // while the declared playback still OWNS the channel: an
3798
+ // update handler that replaced it (its own key) took the
3799
+ // single player over, and the reconciler yields until the
3800
+ // declaration itself changes.
3801
+ // Ownership is the TOKEN of the load this reconciler
3802
+ // issued, not the derived key: the key is a pure function
3803
+ // of the source string, and an update's manual load could
3804
+ // carry the same one — the reconciler must never stop or
3805
+ // mutate a playback it did not start.
3806
+ const declared_key = std.hash.Wyhash.hash(0x76696465, src) | 1;
3807
+ const snapshot = self.effects.videoSnapshot();
3808
+ if (!snapshot.active or snapshot.key != declared_key or
3809
+ self.effects.videoOwnerToken() != self.video_declared_token) return;
3810
+ var moved = false;
3811
+ if (declaration.loop != self.video_declared_loop) {
3812
+ self.video_declared_loop = declaration.loop;
3813
+ self.effects.setVideoLoop(declaration.loop);
3814
+ moved = true;
3815
+ }
3816
+ if (declaration.muted != self.video_declared_muted) {
3817
+ self.video_declared_muted = declaration.muted;
3818
+ self.effects.setVideoMuted(declaration.muted);
3819
+ moved = true;
3820
+ }
3821
+ // A flag delta moves the channel mirrors without any
3822
+ // dispatch or drain behind it, so the runtime mirror
3823
+ // republishes here exactly like the load and removal paths
3824
+ // — an automation snapshot taken after a <video muted> or
3825
+ // <video loop> flip must report the new value, not the one
3826
+ // published before the reconcile.
3827
+ if (moved) self.publishAudioState(runtime);
3828
+ }
3829
+
2732
3830
  fn sceneFn(context: *anyopaque) anyerror!app_manifest.ShellConfig {
2733
3831
  const self: *Self = @ptrCast(@alignCast(context));
2734
3832
  return self.options.scene;
@@ -2736,7 +3834,73 @@ pub fn UiAppWithFeatures(comptime ModelT: type, comptime MsgT: type, comptime fe
2736
3834
 
2737
3835
  fn eventFn(context: *anyopaque, runtime: *Runtime, event_value: Event) anyerror!void {
2738
3836
  const self: *Self = @ptrCast(@alignCast(context));
3837
+ self.hover_msg_event_depth += 1;
3838
+ defer self.hover_msg_event_depth -= 1;
3839
+ // Hover enter/leave delivery rides the tail of runtime
3840
+ // events: the standing chain moves during pointer routing,
3841
+ // scroll reconciles (wheel, kinetic, drivers, keyboard),
3842
+ // dismissals, and any rebuild the dispatches above
3843
+ // performed — the drain seam catches them all, and replay
3844
+ // re-runs the same events through the same seam. The drain
3845
+ // runs on the handler's ERROR path too (the degraded-error
3846
+ // doctrine): a failing handler must not strand edges the
3847
+ // event already produced — a closed window's leave, a
3848
+ // failed rebuild's prune — until some later event happens
3849
+ // by. Mid-cycle DERIVED widget events skip the drain (see
3850
+ // `hoverDrainsAfterEvent`): their input cycle's terminal
3851
+ // `gpu_surface_input` dispatch drains after the cycle's
3852
+ // pending scroll/resize/change observations were delivered,
3853
+ // so a hover Msg's rebuild can never unmount a view whose
3854
+ // promised observation is still queued.
3855
+ handleRuntimeEvent(self, runtime, event_value) catch |err| {
3856
+ if (hoverDrainsAfterEvent(event_value)) self.drainHoverMsgs(runtime) catch {};
3857
+ return err;
3858
+ };
3859
+ if (hoverDrainsAfterEvent(event_value)) try self.drainHoverMsgs(runtime);
3860
+ }
3861
+
3862
+ /// Whether the hover drain runs at this event's tail. Derived
3863
+ /// widget events that only occur INSIDE a gpu-surface input
3864
+ /// cycle defer to the cycle's terminal `gpu_surface_input`
3865
+ /// dispatch — which always follows them, after the pending
3866
+ /// scroll/resize/change drains. Scroll/resize/change events also
3867
+ /// arrive standalone from the native-driver and kinetic paths;
3868
+ /// those defer at most one frame (both paths run under an
3869
+ /// actively pumping frame channel), which is the price of never
3870
+ /// rebuilding mid-cycle. Dismiss events DO drain: the
3871
+ /// automation/accessibility dismiss verb dispatches one
3872
+ /// standalone, and a dismissal's own Msg rebuild already runs
3873
+ /// before the cycle's pending drains, so draining here adds no
3874
+ /// new hazard class. Everything else — commands, timers, wakes,
3875
+ /// frames, the terminal input dispatch, native menu selections —
3876
+ /// drains immediately.
3877
+ fn hoverDrainsAfterEvent(event_value: Event) bool {
3878
+ return switch (event_value) {
3879
+ // Keyboard events usually ride an input cycle (their
3880
+ // terminal dispatch drains); the standalone ones —
3881
+ // accessibility selection edits, context-menu
3882
+ // cut/paste/select-all — have no cycle and drain here.
3883
+ .canvas_widget_keyboard => |keyboard_event| keyboard_event.standalone,
3884
+ .canvas_widget_pointer,
3885
+ .canvas_widget_drag,
3886
+ .canvas_widget_file_drop,
3887
+ .canvas_widget_context_press,
3888
+ .canvas_widget_context_menu_request,
3889
+ .canvas_widget_context_menu_shown,
3890
+ .canvas_widget_scroll,
3891
+ .canvas_widget_resize,
3892
+ .canvas_widget_change,
3893
+ => false,
3894
+ else => true,
3895
+ };
3896
+ }
3897
+
3898
+ fn handleRuntimeEvent(self: *Self, runtime: *Runtime, event_value: Event) anyerror!void {
2739
3899
  switch (event_value) {
3900
+ .lifecycle => |lifecycle| {
3901
+ const map = self.options.on_lifecycle orelse return;
3902
+ if (map(lifecycle)) |msg| try self.dispatch(runtime, self.canvas_window_id, msg);
3903
+ },
2740
3904
  .command => |command| {
2741
3905
  const map = self.options.on_command orelse return;
2742
3906
  if (map(command.name)) |msg| {
@@ -2776,6 +3940,22 @@ pub fn UiAppWithFeatures(comptime ModelT: type, comptime MsgT: type, comptime fe
2776
3940
  .audio => |audio_event| if (self.effects.takeAudioMsg(audio_event)) |msg| {
2777
3941
  try self.dispatch(runtime, self.canvas_window_id, msg);
2778
3942
  },
3943
+ // Platform video reports route the same way: through
3944
+ // the effects channel into the app's `on_event` Msg,
3945
+ // journaled at the delivery boundary. Without an app
3946
+ // Msg the report still moved the channel mirrors, and
3947
+ // the house `<video controls>` chrome renders those —
3948
+ // so publish and rebuild anyway (window slots included:
3949
+ // a secondary window's tree consumes the same
3950
+ // snapshot), keeping the transport live with no model
3951
+ // plumbing (position ticks arrive at the platform's
3952
+ // coarse ~2 Hz cadence, so the extra rebuilds stay
3953
+ // cheap).
3954
+ .video => |video_event| if (self.effects.takeVideoMsg(video_event)) |msg| {
3955
+ try self.dispatch(runtime, self.canvas_window_id, msg);
3956
+ } else if (self.installed) {
3957
+ try self.rebuildVideoChrome(runtime);
3958
+ },
2779
3959
  .effects_wake => try self.drainEffects(runtime),
2780
3960
  .gpu_surface_frame => |frame_event| try self.handleFrame(runtime, frame_event),
2781
3961
  .gpu_surface_resized => |resize_event| try self.handleResize(runtime, resize_event),
@@ -2783,6 +3963,8 @@ pub fn UiAppWithFeatures(comptime ModelT: type, comptime MsgT: type, comptime fe
2783
3963
  .canvas_widget_keyboard => |keyboard_event| try self.handleKeyboard(runtime, keyboard_event),
2784
3964
  .canvas_widget_scroll => |scroll_event| try self.handleScroll(runtime, scroll_event),
2785
3965
  .canvas_widget_context_menu => |menu_event| try self.handleContextMenu(runtime, menu_event),
3966
+ .canvas_widget_context_menu_shown => |shown_event| try self.handleContextMenuShown(runtime, shown_event),
3967
+ .canvas_widget_context_menu_dismissed => |dismissed_event| try self.handleContextMenuDismissed(runtime, dismissed_event),
2786
3968
  .canvas_widget_context_menu_request => |request_event| try self.handleContextMenuRequest(runtime, request_event),
2787
3969
  .canvas_widget_dismiss => |dismiss_event| try self.handleDismiss(runtime, dismiss_event),
2788
3970
  .canvas_widget_context_press => |press_event| try self.handleContextPress(runtime, press_event),
@@ -2793,7 +3975,15 @@ pub fn UiAppWithFeatures(comptime ModelT: type, comptime MsgT: type, comptime fe
2793
3975
  // Raw gpu-surface input stays runtime-internal EXCEPT the
2794
3976
  // pinch kinds, which surface through the app-level pinch
2795
3977
  // channel (widget routing never claims a pinch).
2796
- .gpu_surface_input => |input_event| try self.handlePinch(runtime, input_event),
3978
+ .gpu_surface_input => |input_event| {
3979
+ try self.handlePinch(runtime, input_event);
3980
+ // A wheel over a bound terminal is the widget's
3981
+ // scrollback gesture and consumes the event before
3982
+ // the app-level wheel seam (widget precedence).
3983
+ if (!(try self.handleTerminalWheel(runtime, input_event))) {
3984
+ try self.handleWheel(runtime, input_event);
3985
+ }
3986
+ },
2797
3987
  else => {},
2798
3988
  }
2799
3989
  }
@@ -2806,6 +3996,12 @@ pub fn UiAppWithFeatures(comptime ModelT: type, comptime MsgT: type, comptime fe
2806
3996
  /// next rebuild (source wins), exactly like a dismissed surface.
2807
3997
  fn handleWindowClosed(self: *Self, runtime: *Runtime, closed: core.WindowClosedEvent) anyerror!void {
2808
3998
  const index = self.windowSlotIndexByWindowId(closed.window_id) orelse return;
3999
+ // A closed window's video declaration dies with it: withdraw
4000
+ // its retained entry and reconcile — an owning window's
4001
+ // playback stops (or the next retained declaration promotes
4002
+ // in its place), a non-owner just drops out of the table.
4003
+ self.captureSlotVideoDeclaration(closed.window_id, null);
4004
+ self.applyVideoDeclaration(runtime);
2809
4005
  const on_close = self.forgetWindowSlot(index);
2810
4006
  if (on_close) |msg| {
2811
4007
  try self.dispatch(runtime, self.canvas_window_id, msg);
@@ -2949,6 +4145,12 @@ pub fn UiAppWithFeatures(comptime ModelT: type, comptime MsgT: type, comptime fe
2949
4145
  _ = try runtime.emitCanvasWidgetDisplayList(frame_event.window_id, self.options.canvas_label, runtime.tokensWithTextMeasure(self.effectiveTokens()));
2950
4146
  }
2951
4147
  self.installed = true;
4148
+ // The installing rebuild measured with everything the
4149
+ // registry holds right now (declared fonts registered
4150
+ // above, embedder registrations before install): adopt
4151
+ // the count so only faces joining AFTER this build
4152
+ // trigger the late-registration rebuild.
4153
+ self.fonts_built_count = runtime.registeredCanvasFontCount();
2952
4154
  self.startMarkupWatch(runtime);
2953
4155
  self.installStatusItem(runtime);
2954
4156
  } else if (@abs(self.pixel_snap_scale - scale) > 0.001) {
@@ -2977,6 +4179,17 @@ pub fn UiAppWithFeatures(comptime ModelT: type, comptime MsgT: type, comptime fe
2977
4179
  // job.
2978
4180
  self.canvas_size = frame_event.size;
2979
4181
  try self.rebuild(runtime, frame_event.window_id);
4182
+ } else if (runtime.registeredCanvasFontCount() != self.fonts_built_count) {
4183
+ // A face joined the registry after install (late
4184
+ // registration through the runtime seam). The runtime
4185
+ // already invalidated measurement caches and requested
4186
+ // frames for every open surface (noteCanvasFontsChanged),
4187
+ // but repainting retained geometry only re-inks text
4188
+ // measured with the OLD seam answers: honoring the fonts
4189
+ // doc's promise — every open surface re-measures — means
4190
+ // rebuilding so layout and the re-emitted display lists
4191
+ // charge the registered face's advances.
4192
+ try self.rebuildForRegisteredFonts(runtime);
2980
4193
  } else if (self.options.web_panes != null) {
2981
4194
  // Re-snap the webview panes each presented frame: a shell
2982
4195
  // relayout that stomped a pane frame also invalidated the
@@ -2986,6 +4199,15 @@ pub fn UiAppWithFeatures(comptime ModelT: type, comptime MsgT: type, comptime fe
2986
4199
  self.applyWebPanes(runtime, frame_event.window_id, layout);
2987
4200
  } else |_| {}
2988
4201
  }
4202
+ // Terminal outbound pacing: a child that read without
4203
+ // echoing freed stdin-FIFO room no output event announces,
4204
+ // so pending session bytes (a retained query reply, a paste
4205
+ // tail) flush on the presented-frame clock — journaled
4206
+ // write verdicts on a journaled event, so replay drains
4207
+ // identically. A no-op when nothing is pending.
4208
+ if (comptime terminal_session.enabled) {
4209
+ _ = self.terminal_sessions.flushPending();
4210
+ }
2989
4211
  try self.presentFrame(runtime, frame_event, self.options.canvas_label, installing);
2990
4212
  if (installing) return;
2991
4213
  const on_frame = self.options.on_frame orelse return;
@@ -3031,10 +4253,39 @@ pub fn UiAppWithFeatures(comptime ModelT: type, comptime MsgT: type, comptime fe
3031
4253
  // stale bounds.
3032
4254
  slot.canvas_size = frame_event.size;
3033
4255
  try self.rebuildWindowSlot(runtime, slot);
4256
+ } else if (runtime.registeredCanvasFontCount() != self.fonts_built_count) {
4257
+ // Late registration, first observed on a secondary
4258
+ // window's frame (registration requests frames for every
4259
+ // open surface, and arrival order is the platform's):
4260
+ // the same all-surfaces rebuild as the main canvas —
4261
+ // the count is app-level, so whichever surface's frame
4262
+ // lands first re-measures all of them.
4263
+ try self.rebuildForRegisteredFonts(runtime);
3034
4264
  }
3035
4265
  try self.presentFrame(runtime, frame_event, slot.canvasLabel(), installing);
3036
4266
  }
3037
4267
 
4268
+ /// A face joined the runtime's font registry after this app's
4269
+ /// trees were built: rebuild EVERY installed surface — main
4270
+ /// canvas and declared secondary windows — so widget frames and
4271
+ /// baked text runs re-measure against the registered face, then
4272
+ /// adopt the count. Rebuild re-emits each surface's display list
4273
+ /// (`rebuildEmitsTokens` treats a text-measure provider change
4274
+ /// as an emit reason), so the repaint the runtime already
4275
+ /// requested draws re-measured geometry, not re-inked stale
4276
+ /// frames.
4277
+ fn rebuildForRegisteredFonts(self: *Self, runtime: *Runtime) anyerror!void {
4278
+ try self.rebuildAllViews(runtime);
4279
+ // Adopt the count only AFTER the rebuild succeeded:
4280
+ // production dispatch degrades errors, so a failed rebuild
4281
+ // (widget budget, allocator pressure, a secondary window's
4282
+ // emit) that had already adopted the count would mark stale
4283
+ // layouts as font-current and never retry. Left unadopted,
4284
+ // the error leaves the count mismatched and the next
4285
+ // presented frame retries the rebuild.
4286
+ self.fonts_built_count = runtime.registeredCanvasFontCount();
4287
+ }
4288
+
3038
4289
  /// Present the planned canvas frame: GPU packet when the platform
3039
4290
  /// has a packet presenter (macOS/Metal — unchanged), otherwise the
3040
4291
  /// CPU reference-rendered pixel path (`presentGpuSurfacePixels`,
@@ -3206,6 +4457,55 @@ pub fn UiAppWithFeatures(comptime ModelT: type, comptime MsgT: type, comptime fe
3206
4457
  return map(chrome);
3207
4458
  }
3208
4459
 
4460
+ /// Route primary pointer selection into a bound terminal before
4461
+ /// ordinary press dispatch. The layout query supplies the
4462
+ /// terminal's resolved frame; coordinates are translated into
4463
+ /// the same padded content box the painter and size reconcile
4464
+ /// use, then Ghostty owns cell snapping and tracked selection
4465
+ /// pins. Returns whether an active selection should suppress a
4466
+ /// release-time `on_press`.
4467
+ fn handleTerminalPointer(self: *Self, runtime: *Runtime, pointer_event: core.CanvasWidgetPointerEvent) anyerror!bool {
4468
+ if (comptime !terminal_session.enabled) return false;
4469
+ switch (pointer_event.pointer.phase) {
4470
+ .down, .move, .up, .cancel => {},
4471
+ .hover, .wheel => return false,
4472
+ }
4473
+ if (pointer_event.pointer.phase == .down and pointer_event.pointer.button != 0) return false;
4474
+ const target = pointer_event.target orelse return false;
4475
+ const layout = runtime.canvasWidgetLayout(pointer_event.window_id, pointer_event.view_label) catch return false;
4476
+ var terminal_node: ?canvas.WidgetLayoutNode = null;
4477
+ for (layout.nodes) |node| {
4478
+ if (node.widget.id != target.id) continue;
4479
+ if (node.widget.kind != .terminal or node.widget.terminal.pty == 0) return false;
4480
+ terminal_node = node;
4481
+ break;
4482
+ }
4483
+ const node = terminal_node orelse return false;
4484
+ if (!self.terminal_sessions.hasSession(node.widget.terminal.pty)) return false;
4485
+
4486
+ const frame = node.frame.normalized();
4487
+ const padding = node.widget.layout.padding;
4488
+ const declared = padding.left + padding.top + padding.right + padding.bottom > 0;
4489
+ const inset: geometry.InsetsF = if (declared) padding else geometry.InsetsF.all(8);
4490
+ const content = geometry.RectF.init(
4491
+ frame.x + inset.left,
4492
+ frame.y + inset.top,
4493
+ @max(0, frame.width - inset.left - inset.right),
4494
+ @max(0, frame.height - inset.top - inset.bottom),
4495
+ );
4496
+ if (content.isEmpty()) return false;
4497
+ const result = self.terminal_sessions.pointerSelection(node.widget.terminal.pty, .{
4498
+ .phase = pointer_event.pointer.phase,
4499
+ .x = pointer_event.pointer.point.x - content.x,
4500
+ .y = pointer_event.pointer.point.y - content.y,
4501
+ .width = content.width,
4502
+ .height = content.height,
4503
+ .click_count = pointer_event.pointer.click_count,
4504
+ });
4505
+ if (result.changed) try self.repaintTerminals(runtime, pointer_event.window_id);
4506
+ return pointer_event.pointer.phase == .up and result.selection_active;
4507
+ }
4508
+
3209
4509
  /// Typed press dispatch resolves through the press target — the
3210
4510
  /// deepest widget on the hit path that claims presses — so a press
3211
4511
  /// on a pressable row's plain text children lands on the row's
@@ -3216,6 +4516,7 @@ pub fn UiAppWithFeatures(comptime ModelT: type, comptime MsgT: type, comptime fe
3216
4516
  /// Msg), and any release/cancel disarms it.
3217
4517
  fn handlePointer(self: *Self, runtime: *Runtime, pointer_event: core.CanvasWidgetPointerEvent) anyerror!void {
3218
4518
  const tree = self.treeForViewLabel(pointer_event.view_label) orelse return;
4519
+ const terminal_selected = try self.handleTerminalPointer(runtime, pointer_event);
3219
4520
  switch (pointer_event.pointer.phase) {
3220
4521
  .down => {
3221
4522
  self.disarmHold(runtime);
@@ -3253,6 +4554,9 @@ pub fn UiAppWithFeatures(comptime ModelT: type, comptime MsgT: type, comptime fe
3253
4554
  }
3254
4555
  }
3255
4556
  }
4557
+ // A selection gesture owns the release the way a static
4558
+ // text drag does: keep its highlight and dispatch no press.
4559
+ if (terminal_selected) return;
3256
4560
  const target = pointer_event.press_target orelse return;
3257
4561
  // A released press on a synthesized fallback menu item is a
3258
4562
  // context-menu selection, not an ordinary press: it resolves
@@ -3260,6 +4564,17 @@ pub fn UiAppWithFeatures(comptime ModelT: type, comptime MsgT: type, comptime fe
3260
4564
  // closes the surface.
3261
4565
  if (pointer_event.pointer.phase == .up) {
3262
4566
  if (try self.dispatchContextMenuFallbackItem(runtime, tree, pointer_event.window_id, target.id)) return;
4567
+ // House video chrome is runtime-consumed: a release on
4568
+ // the transport's play/pause control drives the video
4569
+ // channel directly (no app Msg exists to resolve), and
4570
+ // the rebuild re-renders the chrome from the moved
4571
+ // mirrors.
4572
+ if (tree.findWidget(target.id)) |widget| {
4573
+ if (widget.video_control == .toggle) {
4574
+ try self.toggleVideoControl(runtime);
4575
+ return;
4576
+ }
4577
+ }
3263
4578
  }
3264
4579
  // The click count rides the release into typed dispatch: a
3265
4580
  // double-click's second release resolves the target's
@@ -3271,6 +4586,688 @@ pub fn UiAppWithFeatures(comptime ModelT: type, comptime MsgT: type, comptime fe
3271
4586
  }
3272
4587
  }
3273
4588
 
4589
+ /// Cap on hover-Msg drain passes per runtime event: each pass
4590
+ /// delivers one coalesced containment transition, and the Msgs
4591
+ /// it dispatches can rebuild the tree and move the standing
4592
+ /// chain again (an enter handler that unmounts the hovered
4593
+ /// element owes an immediate leave — the second pass delivers
4594
+ /// it). The cap exists ONLY as a flap guard (an app whose enter
4595
+ /// mounts and whose leave unmounts, forever), sized far past
4596
+ /// any honest cascade — even one where every enter replaces the
4597
+ /// listener under a stationary pointer — so a finite sequence
4598
+ /// always settles within one drain; residue past the cap
4599
+ /// delivers on the next event's drain.
4600
+ const hover_msg_drain_passes: usize = 64;
4601
+
4602
+ /// Refresh every standing capture from the mirror view's live
4603
+ /// tree when the trees moved underneath: called at EVERY
4604
+ /// rebuild commit — two dispatches in one cycle (payload A to
4605
+ /// B, then unmount) must deliver B, so the refresh cannot wait
4606
+ /// for drain time and see only the final tree — and again
4607
+ /// defensively at drain time. UPSERT only (an unbound leave
4608
+ /// keeps the last capture). Returns the first TRANSIENT failure
4609
+ /// (allocation) after attempting every entry, leaving the
4610
+ /// generation behind so the next commit or drain retries.
4611
+ fn refreshHoverLeaveCaptures(self: *Self) ?anyerror {
4612
+ if (self.hover_msg_chain_len == 0) return null;
4613
+ if (self.hover_msg_captured_generation == self.build_generation) return null;
4614
+ if (!self.hoverTreeCurrentFor(self.hover_msg_window_id, self.hoverMsgViewLabel())) return null;
4615
+ const mirror_tree = self.hoverTreeFor(self.hover_msg_window_id, self.hoverMsgViewLabel()) orelse return null;
4616
+ var first_error: ?anyerror = null;
4617
+ var refreshed = true;
4618
+ for (0..self.hover_msg_chain_len) |position| {
4619
+ // A refused entry's pair is disabled (its enter never
4620
+ // dispatched); a rebind only takes effect on re-entry.
4621
+ if (self.hover_msg_slots[position] == hover_msg_slot_refused) continue;
4622
+ const leave_msg = mirror_tree.msgFor(self.hover_msg_chain[position], .hover_leave) orelse continue;
4623
+ // Copy-then-swap: the replacement lands in a FRESH slot
4624
+ // (the pool sizing guarantees one is free) and the old
4625
+ // capture releases only after it succeeded — a failed
4626
+ // allocation must never destroy the still-valid capture
4627
+ // it was refreshing.
4628
+ const fresh = self.claimHoverSlot() orelse {
4629
+ refreshed = false;
4630
+ ui_app_log.warn("hover-leave capture refresh failed: no free capture slot - retrying at the next rebuild or drain", .{});
4631
+ if (first_error == null) first_error = error.OutOfMemory;
4632
+ continue;
4633
+ };
4634
+ self.captureHoverLeave(fresh, leave_msg) catch |err| {
4635
+ self.releaseHoverSlot(fresh);
4636
+ switch (err) {
4637
+ error.OutOfMemory => {
4638
+ // Transient: keep the old capture, retry at
4639
+ // the next commit or drain — the generation
4640
+ // stays behind — and surface the failure
4641
+ // LOUD: if the element unmounts before a
4642
+ // retry lands, its refreshed leave is lost,
4643
+ // and that must never be silent.
4644
+ refreshed = false;
4645
+ ui_app_log.warn("hover-leave capture refresh failed: {t} - retrying at the next rebuild or drain; an unmount before a successful retry loses the newly bound leave", .{err});
4646
+ if (first_error == null) first_error = err;
4647
+ },
4648
+ error.HoverCapturePayloadUnsupported => {
4649
+ // A rebind to an unownable payload. An
4650
+ // entry with a standing capture keeps it
4651
+ // quietly (the promise the enter earned);
4652
+ // an entry that never had one — entered
4653
+ // with no leave bound, then given one no
4654
+ // copy can own — is marked so the
4655
+ // degradation is WARNED once, not silent,
4656
+ // and not re-warned every generation.
4657
+ if (self.hover_msg_slots[position] == hover_msg_slot_none) {
4658
+ self.hover_msg_slots[position] = hover_msg_slot_unowned;
4659
+ ui_app_log.warn("on_hover_leave rebind cannot be owned (a single-item pointer): the standing element's leave degrades to live-tree resolution, and an unmount loses it - bind a slice or scalar payload instead", .{});
4660
+ }
4661
+ },
4662
+ }
4663
+ continue;
4664
+ };
4665
+ self.releaseHoverSlot(self.hover_msg_slots[position]);
4666
+ self.hover_msg_slots[position] = fresh;
4667
+ }
4668
+ if (refreshed) self.hover_msg_captured_generation = self.build_generation;
4669
+ return first_error;
4670
+ }
4671
+
4672
+ /// The mirror-view adoption count for the tracked publication
4673
+ /// below (0 when the view is not found — then no adoption can
4674
+ /// have happened either).
4675
+ fn canvasWidgetLayoutAdoptions(runtime: *Runtime, window_id: platform.WindowId, label: []const u8) u64 {
4676
+ for (runtime.views[0..runtime.view_count]) |*view| {
4677
+ if (view.window_id == window_id and std.mem.eql(u8, view.label, label)) return view.canvas_widget_layout_adoptions;
4678
+ }
4679
+ return 0;
4680
+ }
4681
+
4682
+ /// Publish a widget layout with the hover-currency stamp at the
4683
+ /// TRUE adoption boundary: `setCanvasWidgetLayout` adopts the
4684
+ /// layout partway through its pipeline (validated-then-atomic)
4685
+ /// and runs more fallible work after — source-text copies, host
4686
+ /// scroll/drag syncs, display refresh — so a failure THERE must
4687
+ /// still mark the pair stale, while a pre-adoption rejection
4688
+ /// must not. The view's adoption counter is the witness.
4689
+ fn publishWidgetLayoutTracked(self: *Self, runtime: *Runtime, window_id: platform.WindowId, label: []const u8, layout: canvas.WidgetLayoutTree, current_flag: *bool) anyerror!void {
4690
+ _ = self;
4691
+ const adoptions_before = canvasWidgetLayoutAdoptions(runtime, window_id, label);
4692
+ _ = runtime.setCanvasWidgetLayout(window_id, label, layout) catch |err| {
4693
+ if (canvasWidgetLayoutAdoptions(runtime, window_id, label) != adoptions_before) current_flag.* = false;
4694
+ return err;
4695
+ };
4696
+ current_flag.* = false;
4697
+ }
4698
+
4699
+ /// The handler tree behind a hover mirror's VIEW IDENTITY —
4700
+ /// window id AND canvas label, never label alone: a replacement
4701
+ /// window can reuse a closed window's canvas label (and even
4702
+ /// rebuild the same structural ids), and resolving the old
4703
+ /// window's captures through the new window's tree would
4704
+ /// dispatch the wrong message under the old window id.
4705
+ fn hoverTreeFor(self: *Self, window_id: platform.WindowId, view_label: []const u8) ?*const Ui.Tree {
4706
+ if (std.mem.eql(u8, view_label, self.options.canvas_label)) {
4707
+ if (window_id != self.canvas_window_id) return null;
4708
+ return if (self.tree) |*tree| tree else null;
4709
+ }
4710
+ if (self.windowSlotByCanvasLabel(view_label)) |slot| {
4711
+ if (slot.window_id != window_id) return null;
4712
+ return if (slot.tree) |*tree| tree else null;
4713
+ }
4714
+ return null;
4715
+ }
4716
+
4717
+ /// The currency flag governing hover-Msg resolution through the
4718
+ /// handler tree behind the view identity (see
4719
+ /// `main_tree_current`): the main canvas keys on the main flag,
4720
+ /// every secondary window on ITS OWN slot's — one window's
4721
+ /// failed publication never defers hover into its siblings, and
4722
+ /// a same-label replacement window never answers for its
4723
+ /// predecessor. An unknown identity has no tree at all; the
4724
+ /// null-tree checks own that case.
4725
+ fn hoverTreeCurrentFor(self: *Self, window_id: platform.WindowId, view_label: []const u8) bool {
4726
+ if (std.mem.eql(u8, view_label, self.options.canvas_label)) return self.main_tree_current;
4727
+ if (self.windowSlotByCanvasLabel(view_label)) |slot| {
4728
+ if (slot.window_id != window_id) return true;
4729
+ return slot.tree_current;
4730
+ }
4731
+ return true;
4732
+ }
4733
+
4734
+ /// The capture-slot pool covers BOTH populations a transition
4735
+ /// can hold at once — the departing chain's captures (released
4736
+ /// only after each leave Msg is consumed) and the standing
4737
+ /// mirror's (a mid-batch rebuild's refresh can fill every
4738
+ /// entry before the first leave releases) — plus one in-flight
4739
+ /// swap slot, so a legitimate deep handoff between disjoint
4740
+ /// branches can never exhaust it. `claimHoverSlot` still
4741
+ /// degrades like an allocation failure rather than trapping if
4742
+ /// the accounting is ever wrong.
4743
+ const hover_msg_slot_count: usize = canvas.max_widget_depth * 2 + 1;
4744
+
4745
+ /// The "no capture slot" sentinel in `hover_msg_slots` (the slot
4746
+ /// space is `hover_msg_slot_count`, far below it).
4747
+ const hover_msg_slot_none: u8 = 0xFF;
4748
+
4749
+ /// The "pair disabled" marker: this standing entry's leave
4750
+ /// payload cannot be owned (a single-item pointer only a Zig
4751
+ /// view could construct), so its ENTER was refused too — no
4752
+ /// enter without a deliverable leave. Permanent while the entry
4753
+ /// stands (re-hovering after a rebind retries); refused
4754
+ /// entries dispatch nothing on exit and are skipped by the
4755
+ /// capture refresh.
4756
+ const hover_msg_slot_refused: u8 = 0xFE;
4757
+
4758
+ /// The "entered, but the leave rebind is unownable" marker: the
4759
+ /// enter already dispatched (with no leave bound, or an ownable
4760
+ /// one), then a rebuild bound a payload no copy can own. The
4761
+ /// leave degrades to live-tree resolution — silence on unmount
4762
+ /// — warned ONCE at the rebind; the refresh keeps re-attempting
4763
+ /// it, so a later ownable rebind upgrades to a real capture.
4764
+ const hover_msg_slot_unowned: u8 = 0xFD;
4765
+
4766
+ /// Capture a leave Msg for later delivery into `slot`: a DEEP
4767
+ /// copy whose payload slices live in the slot's own arena (any
4768
+ /// size — a budget here would turn a large payload into an
4769
+ /// unpaired leave). Allocation failure PROPAGATES so the caller
4770
+ /// can defer the enter instead of dispatching one whose paired
4771
+ /// leave is already lost; the one non-transient refusal — a
4772
+ /// payload shape that cannot be owned (a single-item pointer
4773
+ /// only a Zig view could construct) — degrades to an empty
4774
+ /// capture with a debug note, and delivery falls back to the
4775
+ /// live tree while the element stands.
4776
+ fn captureHoverLeave(self: *Self, slot: u8, msg: MsgT) error{ OutOfMemory, HoverCapturePayloadUnsupported }!void {
4777
+ _ = self.hover_msg_leave_arenas[slot].reset(.free_all);
4778
+ self.hover_msg_leave_msgs[slot] = deepCopyMsgValue(MsgT, msg, self.hover_msg_leave_arenas[slot].allocator(), 0) catch |err| {
4779
+ // A refused capture holds no bytes either: the partial
4780
+ // copy is released with the arena before the verdict.
4781
+ // OutOfMemory is transient (callers defer and retry);
4782
+ // HoverCapturePayloadUnsupported is permanent (callers
4783
+ // disable the pair — no enter without a deliverable
4784
+ // leave).
4785
+ _ = self.hover_msg_leave_arenas[slot].reset(.free_all);
4786
+ self.hover_msg_leave_msgs[slot] = null;
4787
+ return err;
4788
+ };
4789
+ }
4790
+
4791
+ /// Claim a free capture slot, or null when none is free — the
4792
+ /// pool is sized so that never happens for legitimate
4793
+ /// transitions (see `hover_msg_slot_count`), and callers treat
4794
+ /// null exactly like a transient allocation failure: defer and
4795
+ /// retry, never trap.
4796
+ fn claimHoverSlot(self: *Self) ?u8 {
4797
+ for (&self.hover_msg_slot_used, 0..) |*used, slot| {
4798
+ if (used.*) continue;
4799
+ used.* = true;
4800
+ return @intCast(slot);
4801
+ }
4802
+ return null;
4803
+ }
4804
+
4805
+ /// Release a slot: reset its arena (the captured Msg was already
4806
+ /// consumed — dispatch is synchronous) and free it, so a retired
4807
+ /// slot never retains a large payload copy until some later
4808
+ /// hover happens to reuse it.
4809
+ fn releaseHoverSlot(self: *Self, slot: u8) void {
4810
+ if (slot >= hover_msg_slot_count) return;
4811
+ self.hover_msg_leave_msgs[slot] = null;
4812
+ _ = self.hover_msg_leave_arenas[slot].reset(.free_all);
4813
+ self.hover_msg_slot_used[slot] = false;
4814
+ }
4815
+
4816
+ /// Recursively copy a Msg value so it owns every byte it
4817
+ /// references: scalars ride through, slices are duplicated into
4818
+ /// `allocator` (element-wise, so nested slices copy too), and
4819
+ /// payload shapes that cannot be owned (single-item pointers,
4820
+ /// untagged unions) refuse rather than alias.
4821
+ /// Pointer-indirection bound for one captured Msg: a run of
4822
+ /// nested slices deeper than this is either a cyclic value
4823
+ /// graph (which no copy terminates) or data no Msg payload has
4824
+ /// business carrying — both refuse as unsupported instead of
4825
+ /// recursing toward exhaustion. Structs and arrays add no
4826
+ /// depth; only slice hops count.
4827
+ const hover_msg_capture_max_indirections: usize = 64;
4828
+
4829
+ fn deepCopyMsgValue(comptime T: type, value: T, allocator: std.mem.Allocator, indirections: usize) error{ OutOfMemory, HoverCapturePayloadUnsupported }!T {
4830
+ return switch (@typeInfo(T)) {
4831
+ .void, .int, .float, .bool, .@"enum", .vector, .error_set => value,
4832
+ .optional => |info| if (value) |inner| try deepCopyMsgValue(info.child, inner, allocator, indirections) else null,
4833
+ .error_union => |info| if (value) |payload| @as(T, try deepCopyMsgValue(info.payload, payload, allocator, indirections)) else |err| @as(T, err),
4834
+ .array => |info| blk: {
4835
+ var out: T = undefined;
4836
+ for (0..info.len) |index| out[index] = try deepCopyMsgValue(info.child, value[index], allocator, indirections);
4837
+ // A sentinel-terminated array carries one element
4838
+ // past its length: stamp it, never leave it
4839
+ // undefined.
4840
+ if (comptime std.meta.sentinel(T)) |sentinel| out[info.len] = sentinel;
4841
+ break :blk out;
4842
+ },
4843
+ .@"struct" => |info| blk: {
4844
+ var out = value;
4845
+ inline for (info.fields) |field| {
4846
+ @field(out, field.name) = try deepCopyMsgValue(field.type, @field(value, field.name), allocator, indirections);
4847
+ }
4848
+ break :blk out;
4849
+ },
4850
+ .@"union" => |info| if (comptime info.tag_type == null) error.HoverCapturePayloadUnsupported else switch (value) {
4851
+ inline else => |payload, tag| @unionInit(T, @tagName(tag), try deepCopyMsgValue(@TypeOf(payload), payload, allocator, indirections)),
4852
+ },
4853
+ .pointer => |info| blk: {
4854
+ if (info.size != .slice) return error.HoverCapturePayloadUnsupported;
4855
+ if (indirections >= hover_msg_capture_max_indirections) return error.HoverCapturePayloadUnsupported;
4856
+ // The copy preserves the slice type's OWN alignment
4857
+ // and sentinel, so over-aligned payloads
4858
+ // (`[]align(64) const u8`) and sentinel slices
4859
+ // type-check and round-trip.
4860
+ const alignment: ?std.mem.Alignment = comptime align_blk: {
4861
+ const declared = info.alignment orelse break :align_blk null;
4862
+ if (declared == @alignOf(info.child)) break :align_blk null;
4863
+ break :align_blk std.mem.Alignment.fromByteUnits(declared);
4864
+ };
4865
+ const out = try allocator.allocWithOptions(info.child, value.len, alignment, comptime std.meta.sentinel(T));
4866
+ for (value, 0..) |element, index| out[index] = try deepCopyMsgValue(info.child, element, allocator, indirections + 1);
4867
+ break :blk out;
4868
+ },
4869
+ else => error.HoverCapturePayloadUnsupported,
4870
+ };
4871
+ }
4872
+
4873
+ fn hoverMsgViewLabel(self: *const Self) []const u8 {
4874
+ return self.hover_msg_view_label_storage[0..self.hover_msg_view_label_len];
4875
+ }
4876
+
4877
+ /// Deliver hover enter/leave Msgs owed since the last drain:
4878
+ /// diff the runtime's standing containment chain against the
4879
+ /// delivered mirror and dispatch the edges — leaves innermost
4880
+ /// first, then enters outermost first (the DOM's
4881
+ /// mouseleave/mouseenter order). Intermediate flickers within
4882
+ /// one event coalesce away: only the settled containment
4883
+ /// dispatches, which is what "discrete edges, never per-move"
4884
+ /// means under a fast pointer.
4885
+ fn drainHoverMsgs(self: *Self, runtime: *Runtime) anyerror!void {
4886
+ if (!self.installed) return;
4887
+ if (self.hover_msg_draining) return;
4888
+ self.hover_msg_draining = true;
4889
+ defer self.hover_msg_draining = false;
4890
+ // A pass's error degrades WITHOUT aborting the drain: its
4891
+ // mirror commit already happened, and the containment its
4892
+ // dispatches moved (an enter handler that unmounted itself)
4893
+ // still owes edges only a further pass can deliver. The
4894
+ // first error propagates after the loop, into the same
4895
+ // degraded handling every event handler gets.
4896
+ var first_error: ?anyerror = null;
4897
+ var passes: usize = 0;
4898
+ while (passes < hover_msg_drain_passes) : (passes += 1) {
4899
+ const progressed = self.stepHoverMsgs(runtime) catch |err| blk: {
4900
+ if (first_error == null) first_error = err;
4901
+ break :blk true;
4902
+ };
4903
+ if (!progressed) break;
4904
+ }
4905
+ if (first_error) |err| return err;
4906
+ }
4907
+
4908
+ /// One drain pass: resolve the view whose standing chain is
4909
+ /// live, compare it to the mirror, and — when they differ —
4910
+ /// dispatch the owed edges and commit the mirror. Returns
4911
+ /// whether it dispatched anything (the drain loop re-checks:
4912
+ /// a dispatched Msg's rebuild may have moved the chain again).
4913
+ ///
4914
+ /// One pointer means at most one view should hold a standing
4915
+ /// chain; if a host ever leaves two populated (a missing
4916
+ /// pointer-cancel on window switch), the mirror's own view
4917
+ /// wins while it stands — deterministic, never flapping.
4918
+ fn stepHoverMsgs(self: *Self, runtime: *Runtime) anyerror!bool {
4919
+ var standing_index: ?usize = null;
4920
+ for (runtime.views[0..runtime.view_count], 0..) |*view, index| {
4921
+ if (view.kind != .gpu_surface) continue;
4922
+ if (view.canvas_widget_hover_msg_chain_len == 0) continue;
4923
+ const is_mirror = view.window_id == self.hover_msg_window_id and
4924
+ std.mem.eql(u8, view.label, self.hoverMsgViewLabel());
4925
+ if (is_mirror) {
4926
+ standing_index = index;
4927
+ break;
4928
+ }
4929
+ if (standing_index == null) standing_index = index;
4930
+ }
4931
+
4932
+ // The standing chain and the view identity it belongs to
4933
+ // (the mirror's own view when nothing stands anywhere:
4934
+ // its entries owe leaves against that view's tree). The
4935
+ // label is COPIED out of runtime view storage: the
4936
+ // dispatches below can close windows and compact the view
4937
+ // array, and a lookup through a reused label slice could
4938
+ // resolve another view's tree.
4939
+ var standing_window: platform.WindowId = self.hover_msg_window_id;
4940
+ var standing_label_storage: [app_manifest.max_view_label_bytes]u8 = undefined;
4941
+ var standing_label_len: usize = @min(self.hover_msg_view_label_len, standing_label_storage.len);
4942
+ @memcpy(standing_label_storage[0..standing_label_len], self.hover_msg_view_label_storage[0..standing_label_len]);
4943
+ var standing_chain: [canvas.max_widget_depth]canvas.ObjectId = undefined;
4944
+ var standing_len: usize = 0;
4945
+ if (standing_index) |index| {
4946
+ const view = &runtime.views[index];
4947
+ standing_window = view.window_id;
4948
+ standing_label_len = @min(view.label.len, standing_label_storage.len);
4949
+ @memcpy(standing_label_storage[0..standing_label_len], view.label[0..standing_label_len]);
4950
+ standing_len = view.canvas_widget_hover_msg_chain_len;
4951
+ @memcpy(standing_chain[0..standing_len], view.canvas_widget_hover_msg_chain[0..standing_len]);
4952
+ }
4953
+ const standing_label: []const u8 = standing_label_storage[0..standing_label_len];
4954
+
4955
+ const same_view = standing_window == self.hover_msg_window_id and
4956
+ std.mem.eql(u8, standing_label, self.hoverMsgViewLabel());
4957
+ const mirror_len = self.hover_msg_chain_len;
4958
+
4959
+ // Handler bindings move with rebuilds: when the trees
4960
+ // changed since the standing captures were taken, refresh
4961
+ // every mirror entry's capture from its live tree — a leave
4962
+ // handler ADDED while the listener already stood must be
4963
+ // captured before an unmount needs it, and a changed
4964
+ // payload delivers its latest value. UPSERT only: an
4965
+ // element whose leave binding VANISHED keeps the previously
4966
+ // captured Msg (the standing enter was promised its pair;
4967
+ // unbinding never un-promises it). Runs before the settled
4968
+ // fast path below, which compares ids and would never see a
4969
+ // binding-only change.
4970
+ var first_error: ?anyerror = self.refreshHoverLeaveCaptures();
4971
+
4972
+ // The diff is a SET diff over listener ids, not a positional
4973
+ // one: containment is per listener, so an outer listener
4974
+ // unbinding (or binding) while an inner one stands must
4975
+ // dispatch edges for the changed id ONLY — the retained
4976
+ // entry keeps standing, its capture untouched in its slot.
4977
+ // A view change retains nothing (one pointer, one view).
4978
+ var retained_slots: [canvas.max_widget_depth]u8 = undefined;
4979
+ var entering_at: [canvas.max_widget_depth]bool = undefined;
4980
+ var entering_any = false;
4981
+ var identical = same_view and standing_len == mirror_len;
4982
+ for (standing_chain[0..standing_len], 0..) |id, position| {
4983
+ var slot: u8 = hover_msg_slot_none;
4984
+ var retained = false;
4985
+ if (same_view) {
4986
+ for (self.hover_msg_chain[0..mirror_len], 0..) |mirror_id, mirror_position| {
4987
+ if (mirror_id != id) continue;
4988
+ slot = self.hover_msg_slots[mirror_position];
4989
+ retained = true;
4990
+ if (mirror_position != position) identical = false;
4991
+ break;
4992
+ }
4993
+ }
4994
+ retained_slots[position] = slot;
4995
+ entering_at[position] = !retained;
4996
+ if (!retained) {
4997
+ entering_any = true;
4998
+ identical = false;
4999
+ }
5000
+ }
5001
+ if (identical) {
5002
+ if (first_error) |err| return err;
5003
+ return false;
5004
+ }
5005
+
5006
+ // Entering edges resolve through the DESTINATION view's
5007
+ // handler tree, and only a CURRENT one (`hoverTreeCurrentFor`): a
5008
+ // failed rebuild may have cleared it, or — worse — left a
5009
+ // tree standing whose build the runtime never adopted, and
5010
+ // resolving through that dispatches stale handlers or
5011
+ // consumes enters as absent. When it is not ready, the
5012
+ // enters DEFER (the standing chain keeps carrying them, so
5013
+ // the drain after the next successful rebuild retries)
5014
+ // while the leaves this transition owes still dispatch
5015
+ // below — their Msgs are owned captures, not tree lookups,
5016
+ // and a broken destination must never withhold them.
5017
+ const destination_ready = !entering_any or
5018
+ (self.hoverTreeCurrentFor(standing_window, standing_label) and self.hoverTreeFor(standing_window, standing_label) != null);
5019
+ if (!destination_ready) {
5020
+ var any_leaving = false;
5021
+ for (self.hover_msg_chain[0..mirror_len]) |id| {
5022
+ const still_standing = same_view and blk: {
5023
+ for (standing_chain[0..standing_len]) |candidate| {
5024
+ if (candidate == id) break :blk true;
5025
+ }
5026
+ break :blk false;
5027
+ };
5028
+ if (!still_standing) {
5029
+ any_leaving = true;
5030
+ break;
5031
+ }
5032
+ }
5033
+ // Nothing deliverable now: enters wait for a current
5034
+ // tree, retained entries stay put.
5035
+ if (!any_leaving) return false;
5036
+ }
5037
+
5038
+ // The leaves this pass owes — mirror ids absent from the
5039
+ // standing chain — innermost-first. Their captured Msgs own
5040
+ // their payload bytes (see `captureHoverLeave`), so the
5041
+ // rebuilds the dispatches below perform cannot invalidate
5042
+ // them. Ids and the OLD view identity ride along so a
5043
+ // capture that could not be owned can still resolve from
5044
+ // the live tree while its element stands.
5045
+ const leave_window = self.hover_msg_window_id;
5046
+ var leave_label_storage: [app_manifest.max_view_label_bytes]u8 = undefined;
5047
+ const leave_label_len = self.hover_msg_view_label_len;
5048
+ @memcpy(leave_label_storage[0..leave_label_len], self.hover_msg_view_label_storage[0..leave_label_len]);
5049
+ var leave_ids: [canvas.max_widget_depth]canvas.ObjectId = undefined;
5050
+ var leave_slots: [canvas.max_widget_depth]u8 = undefined;
5051
+ var leave_count: usize = 0;
5052
+ var index = mirror_len;
5053
+ while (index > 0) {
5054
+ index -= 1;
5055
+ const id = self.hover_msg_chain[index];
5056
+ const still_standing = same_view and blk: {
5057
+ for (standing_chain[0..standing_len]) |candidate| {
5058
+ if (candidate == id) break :blk true;
5059
+ }
5060
+ break :blk false;
5061
+ };
5062
+ if (still_standing) continue;
5063
+ leave_ids[leave_count] = id;
5064
+ leave_slots[leave_count] = self.hover_msg_slots[index];
5065
+ leave_count += 1;
5066
+ }
5067
+
5068
+ // Commit the mirror before dispatching so a mid-dispatch
5069
+ // error can never re-deliver the same edges: standing ids in
5070
+ // standing order, retained entries keeping their slots,
5071
+ // entering entries slotless until their enter actually
5072
+ // dispatches below. The identity rewrite only runs on a view
5073
+ // CHANGE — when the view stood, `standing_label` was copied
5074
+ // from the mirror's own storage.
5075
+ if (!same_view) {
5076
+ self.hover_msg_window_id = standing_window;
5077
+ const label_len = @min(standing_label.len, self.hover_msg_view_label_storage.len);
5078
+ @memcpy(self.hover_msg_view_label_storage[0..label_len], standing_label[0..label_len]);
5079
+ self.hover_msg_view_label_len = label_len;
5080
+ }
5081
+ @memcpy(self.hover_msg_chain[0..standing_len], standing_chain[0..standing_len]);
5082
+ @memcpy(self.hover_msg_slots[0..standing_len], retained_slots[0..standing_len]);
5083
+ self.hover_msg_chain_len = standing_len;
5084
+ // A deferred entering side stays OUT of the mirror: the
5085
+ // standing chain still carries those ids, so the drain
5086
+ // after the next successful rebuild sees them entering and
5087
+ // delivers then.
5088
+ if (!destination_ready) self.unwindHoverEnters(&entering_at, 0);
5089
+
5090
+ // Deliver: leaves innermost-first, then enters
5091
+ // outermost-first; retained ids dispatch nothing. Each
5092
+ // dispatch degrades PER EDGE — an error is remembered and
5093
+ // the remaining edges still deliver (the mirror is already
5094
+ // committed, so an aborted batch could never be retried;
5095
+ // one failed rebuild must not swallow its siblings' edges)
5096
+ // — and the first error propagates after the batch, into
5097
+ // the same degraded handling every event handler gets.
5098
+ for (leave_ids[0..leave_count], leave_slots[0..leave_count]) |id, slot| {
5099
+ // A refused entry never entered: it owes nothing on
5100
+ // exit.
5101
+ if (slot == hover_msg_slot_refused) continue;
5102
+ // The capture wins (leave answers what enter announced);
5103
+ // an unowned capture falls back to the live tree while
5104
+ // its element still stands there.
5105
+ const captured: ?MsgT = if (slot >= hover_msg_slot_count) null else self.hover_msg_leave_msgs[slot];
5106
+ const msg = captured orelse blk: {
5107
+ if (!self.hoverTreeCurrentFor(leave_window, leave_label_storage[0..leave_label_len])) break :blk null;
5108
+ const live = self.hoverTreeFor(leave_window, leave_label_storage[0..leave_label_len]) orelse break :blk null;
5109
+ break :blk live.msgFor(id, .hover_leave);
5110
+ } orelse {
5111
+ self.releaseHoverSlot(slot);
5112
+ continue;
5113
+ };
5114
+ self.dispatch(runtime, leave_window, msg) catch |err| {
5115
+ if (first_error == null) first_error = err;
5116
+ };
5117
+ // The leave Msg was consumed synchronously: its slot
5118
+ // releases now instead of holding a payload copy until
5119
+ // some later hover reuses it.
5120
+ self.releaseHoverSlot(slot);
5121
+ }
5122
+ for (standing_chain[0..standing_len], 0..) |id, position| {
5123
+ if (!destination_ready) break;
5124
+ if (!entering_at[position]) continue;
5125
+ if (!self.hoverTreeCurrentFor(standing_window, standing_label)) {
5126
+ // An earlier edge's failed rebuild left this tree
5127
+ // stale mid-batch: the same deferral as above — drop
5128
+ // the unentered tail from the mirror and retry after
5129
+ // a rebuild lands.
5130
+ self.unwindHoverEnters(&entering_at, position);
5131
+ break;
5132
+ }
5133
+ // Resolve from the LIVE tree per edge: an earlier edge
5134
+ // in this batch may have rebuilt the view (payload
5135
+ // bytes are only promised for their own dispatch), and
5136
+ // its update may even have unmounted this element — a
5137
+ // vanished handler then dispatches no enter and owes no
5138
+ // leave. The paired leave is captured BEFORE the enter
5139
+ // dispatches, from the same tree that resolved it, so
5140
+ // an enter whose own handler unmounts the element still
5141
+ // has its leave to deliver.
5142
+ const live = self.hoverTreeFor(standing_window, standing_label) orelse {
5143
+ // A failed rebuild cleared the tree mid-batch: drop
5144
+ // the not-yet-entered ids from the mirror so the
5145
+ // next drain retries them once the tree returns (the
5146
+ // entering-with-no-tree deferral above then holds
5147
+ // the line instead of consuming enters as silence).
5148
+ self.unwindHoverEnters(&entering_at, position);
5149
+ break;
5150
+ };
5151
+ const enter_msg = live.msgFor(id, .hover_enter);
5152
+ if (live.msgFor(id, .hover_leave)) |leave_msg| {
5153
+ const slot = self.claimHoverSlot() orelse {
5154
+ // Pool pressure degrades like allocation
5155
+ // pressure: defer this id and the entering tail
5156
+ // to the next drain.
5157
+ self.unwindHoverEnters(&entering_at, position);
5158
+ if (first_error == null) first_error = error.OutOfMemory;
5159
+ break;
5160
+ };
5161
+ self.captureHoverLeave(slot, leave_msg) catch |err| switch (err) {
5162
+ error.OutOfMemory => {
5163
+ // Transient: an enter whose paired leave
5164
+ // cannot be owned must not dispatch — defer
5165
+ // this id and the rest of the entering tail
5166
+ // to the next drain instead of breaking the
5167
+ // pairing guarantee.
5168
+ self.releaseHoverSlot(slot);
5169
+ self.unwindHoverEnters(&entering_at, position);
5170
+ if (first_error == null) first_error = error.OutOfMemory;
5171
+ break;
5172
+ },
5173
+ error.HoverCapturePayloadUnsupported => {
5174
+ // Permanent: no copy can own this payload
5175
+ // (a single-item pointer), so the PAIR is
5176
+ // disabled — the enter is refused too,
5177
+ // once, loudly, and the entry settles as
5178
+ // refused instead of retrying every drain.
5179
+ self.releaseHoverSlot(slot);
5180
+ self.releaseHoverSlot(self.hover_msg_slots[position]);
5181
+ self.hover_msg_slots[position] = hover_msg_slot_refused;
5182
+ ui_app_log.warn("on_hover_leave payload cannot be owned (a single-item pointer): the hover pair is disabled for this element - bind a slice or scalar payload instead", .{});
5183
+ continue;
5184
+ },
5185
+ };
5186
+ // A mid-batch rebuild's capture refresh can have
5187
+ // filled this position's slot already (an earlier
5188
+ // edge's dispatch rebuilt): release it before the
5189
+ // fresh assignment so no slot ever leaks.
5190
+ self.releaseHoverSlot(self.hover_msg_slots[position]);
5191
+ self.hover_msg_slots[position] = slot;
5192
+ } else {
5193
+ self.releaseHoverSlot(self.hover_msg_slots[position]);
5194
+ self.hover_msg_slots[position] = hover_msg_slot_none;
5195
+ }
5196
+ if (enter_msg) |msg| {
5197
+ self.dispatch(runtime, standing_window, msg) catch |err| {
5198
+ if (first_error == null) first_error = err;
5199
+ };
5200
+ }
5201
+ }
5202
+ if (first_error) |err| return err;
5203
+ return true;
5204
+ }
5205
+
5206
+ /// Drop the not-yet-entered entering ids (positions >= `from`
5207
+ /// with `entering_at` set) from the committed mirror, compacting
5208
+ /// ids and slots in lockstep: the standing chain still carries
5209
+ /// them, so a later drain — once the tree (or memory) is back —
5210
+ /// sees them as entering again and retries. Their positions hold
5211
+ /// no capture slots yet, so nothing needs releasing.
5212
+ fn unwindHoverEnters(self: *Self, entering_at: *const [canvas.max_widget_depth]bool, from: usize) void {
5213
+ var kept: usize = 0;
5214
+ for (0..self.hover_msg_chain_len) |position| {
5215
+ if (position >= from and entering_at[position]) {
5216
+ // A mid-batch capture refresh can have filled this
5217
+ // never-entered position's slot: release it so an
5218
+ // unwound enter never leaks its claim.
5219
+ self.releaseHoverSlot(self.hover_msg_slots[position]);
5220
+ continue;
5221
+ }
5222
+ self.hover_msg_chain[kept] = self.hover_msg_chain[position];
5223
+ self.hover_msg_slots[kept] = self.hover_msg_slots[position];
5224
+ kept += 1;
5225
+ }
5226
+ self.hover_msg_chain_len = kept;
5227
+ }
5228
+
5229
+ /// Re-render the house video chrome from the moved channel
5230
+ /// mirrors, everywhere it shows: the main canvas rebuilds
5231
+ /// against ITS window (never a control event's origin window —
5232
+ /// the main canvas label resolves only there), and the window
5233
+ /// slots rebuild after it, so a `<video controls>` declared in
5234
+ /// a secondary window's tree repaints too — `dispatch`'s exact
5235
+ /// rebuild discipline, minus the Msg.
5236
+ fn rebuildVideoChrome(self: *Self, runtime: *Runtime) anyerror!void {
5237
+ self.publishAudioState(runtime);
5238
+ try self.rebuild(runtime, self.canvas_window_id);
5239
+ try self.rebuildWindowSlots(runtime);
5240
+ }
5241
+
5242
+ /// Activate the house transport's play/pause control — the
5243
+ /// runtime-consumed action both the pointer release and the
5244
+ /// keyboard control intent (Enter/Space on the focused button)
5245
+ /// resolve to: no app Msg exists, the video channel is driven
5246
+ /// directly and the chrome re-renders from the moved mirrors.
5247
+ fn toggleVideoControl(self: *Self, runtime: *Runtime) anyerror!void {
5248
+ const snapshot = self.effects.videoSnapshot();
5249
+ if (snapshot.playing) {
5250
+ self.effects.pauseVideo();
5251
+ } else if (snapshot.completed) {
5252
+ // The natural end retired the player, so play would
5253
+ // refuse with one `.failed` — a broken answer to a
5254
+ // valid control. Play on a finished playback means
5255
+ // from-the-start: a fresh load of the same source. The
5256
+ // restart mints a fresh load identity, so declarative
5257
+ // ownership re-captures it (`video_declared_token`) —
5258
+ // the reconciler must keep recognizing the playback it
5259
+ // started, or removal and flag deltas would go dead
5260
+ // after a replay-from-end.
5261
+ const declared = self.video_declared_token != 0 and
5262
+ self.effects.videoOwnerToken() == self.video_declared_token;
5263
+ self.effects.restartVideo();
5264
+ if (declared) self.video_declared_token = self.effects.videoOwnerToken();
5265
+ } else {
5266
+ self.effects.playVideo();
5267
+ }
5268
+ try self.rebuildVideoChrome(runtime);
5269
+ }
5270
+
3274
5271
  fn disarmHold(self: *Self, runtime: *Runtime) void {
3275
5272
  if (self.hold_armed_id != 0 and !self.hold_fired) runtime.cancelTimer(press_hold_timer_id) catch {};
3276
5273
  self.hold_armed_id = 0;
@@ -3362,13 +5359,138 @@ pub fn UiAppWithFeatures(comptime ModelT: type, comptime MsgT: type, comptime fe
3362
5359
  }
3363
5360
  if (tree.findWidget(target.id)) |widget| {
3364
5361
  if (!widget.state.disabled) {
5362
+ // A focused BOUND terminal owns its keys the way
5363
+ // an editable text widget owns typing: specials
5364
+ // and chords encode through the session's
5365
+ // emulator toward the pty; consumed either way so
5366
+ // the app-level key fallback can never fire while
5367
+ // the user is driving the terminal. An ended
5368
+ // session declines, and the key falls through
5369
+ // (an app may bind a restart chord).
5370
+ if (widget.kind == .terminal and widget.terminal.pty != 0) {
5371
+ // Focus traversal/spatial navigation routes
5372
+ // the arriving key to the NEW target. That
5373
+ // key moved focus; it is not terminal input
5374
+ // (Tabbing into a terminal must not also
5375
+ // complete at the shell prompt). Once the
5376
+ // terminal already owns focus, the focus pass
5377
+ // leaves Tab in place and this flag is false,
5378
+ // so Tab/Shift+Tab encode normally below.
5379
+ if (keyboard_event.keyboard.focus_moved) return;
5380
+ // The runtime clipboard pass already copied
5381
+ // this emulator selection. Do not forward the
5382
+ // same Cmd/Ctrl+C chord to the child (where
5383
+ // Ctrl+C would be an interrupt).
5384
+ const copy_chord = (keyboard_event.keyboard.phase == .key_down or keyboard_event.keyboard.phase == .key_up) and
5385
+ keyboard_event.keyboard.modifiers.hasCommandModifier() and
5386
+ !keyboard_event.keyboard.modifiers.alt and
5387
+ !keyboard_event.keyboard.modifiers.shift and
5388
+ std.ascii.eqlIgnoreCase(keyboard_event.keyboard.key, "c");
5389
+ if (copy_chord) {
5390
+ if (widget.terminal.grid) |grid| {
5391
+ if (grid.selection_active) return;
5392
+ }
5393
+ }
5394
+ if (self.terminal_sessions.keyEvent(widget.terminal.pty, keyboard_event.keyboard)) {
5395
+ try self.repaintTerminals(runtime, keyboard_event.window_id);
5396
+ return;
5397
+ }
5398
+ }
3365
5399
  if (canvas.isWidgetTextEntry(widget)) return;
3366
- if (canvas.widgetKeyboardControlIntent(widget, keyboard_event.keyboard) != null) return;
5400
+ if (canvas.widgetKeyboardControlIntent(widget, keyboard_event.keyboard)) |intent| {
5401
+ // Keyboard activation of the house video
5402
+ // transport's play/pause control drives the
5403
+ // channel exactly like the pointer release
5404
+ // — the control advertises Play/Pause to
5405
+ // focus and accessibility, so Enter/Space
5406
+ // must act, not be consumed silently.
5407
+ if (widget.video_control == .toggle and intent.kind == .press) {
5408
+ try self.toggleVideoControl(runtime);
5409
+ }
5410
+ // The seek slider's keyboard and assistive
5411
+ // steps land here as set_value intents —
5412
+ // no widget change event exists on these
5413
+ // paths — so the step maps its fraction
5414
+ // onto the duration and drives the channel,
5415
+ // the pointer scrub's exact rule; consuming
5416
+ // it silently would move the thumb
5417
+ // optimistically and let the next tick
5418
+ // snap it back.
5419
+ if (widget.video_control == .scrub and intent.kind == .set_value) {
5420
+ if (intent.value) |fraction| {
5421
+ const snap = self.effects.videoSnapshot();
5422
+ if (snap.duration_ms > 0) {
5423
+ self.effects.seekVideo(@intFromFloat(std.math.clamp(@as(f64, fraction), 0, 1) * @as(f64, @floatFromInt(snap.duration_ms))));
5424
+ }
5425
+ try self.rebuildVideoChrome(runtime);
5426
+ }
5427
+ }
5428
+ return;
5429
+ }
3367
5430
  }
3368
5431
  }
3369
5432
  }
5433
+ if (keyboard_event.keyboard.phase == .text_input) {
5434
+ // A focused BOUND terminal consumes committed text ahead
5435
+ // of the app-level `on_text` seam — the typing channel
5436
+ // the terminal element promises (IME results included;
5437
+ // the runtime already gates this dispatch to committed
5438
+ // insertions). Text arrives TARGET-LESS here because the
5439
+ // terminal deliberately stays out of the TextBuffer
5440
+ // pipeline; the stamped focused id names it.
5441
+ if (comptime terminal_session.enabled) {
5442
+ if (keyboard_event.keyboard.focused_id) |focused_id| {
5443
+ if (tree.findWidget(focused_id)) |widget| {
5444
+ if (widget.kind == .terminal and widget.terminal.pty != 0) {
5445
+ const edit = keyboard_event.keyboard.textEditEvent() orelse return;
5446
+ if (edit != .insert_text) return;
5447
+ if (keyboard_event.terminal_paste) {
5448
+ // Clipboard paste is provenance-
5449
+ // sensitive terminal input: the
5450
+ // session must apply bracketed-paste
5451
+ // framing and paste sanitization.
5452
+ // Consume it even when the session
5453
+ // ended between presentation and
5454
+ // dispatch; clipboard bytes addressed
5455
+ // to a terminal must never leak to the
5456
+ // app-level `on_text` fallback.
5457
+ if (self.terminal_sessions.pasteInput(widget.terminal.pty, edit.insert_text)) {
5458
+ try self.repaintTerminals(runtime, keyboard_event.window_id);
5459
+ }
5460
+ return;
5461
+ }
5462
+ if (self.terminal_sessions.textInput(widget.terminal.pty, edit.insert_text)) {
5463
+ try self.repaintTerminals(runtime, keyboard_event.window_id);
5464
+ return;
5465
+ }
5466
+ }
5467
+ }
5468
+ }
5469
+ }
5470
+ // A provenance-tagged terminal paste is terminal-addressed
5471
+ // even when no enabled emulator is wired in this build.
5472
+ // Never leak its clipboard bytes to app-level `on_text`.
5473
+ if (keyboard_event.terminal_paste) return;
5474
+ const text_map = self.options.on_text orelse return;
5475
+ // COMMITTED text only. An IME preedit (`set_composition`)
5476
+ // or a cancel is provisional and must never reach a
5477
+ // consumer with no editor state (a terminal) — otherwise
5478
+ // a composition-in-progress routed through a focused
5479
+ // non-text widget would type bytes the user has not
5480
+ // committed and cannot retract. `insert_text` is the
5481
+ // committed insertion (a plain text_input, or the
5482
+ // resolved commit the host delivers as text); every
5483
+ // other edit kind is skipped here.
5484
+ const edit = keyboard_event.keyboard.textEditEvent() orelse return;
5485
+ if (edit != .insert_text) return;
5486
+ if (text_map(keyboard_event.keyboard)) |msg| {
5487
+ try self.dispatch(runtime, keyboard_event.window_id, msg);
5488
+ }
5489
+ return;
5490
+ }
3370
5491
  const map = self.options.on_key orelse return;
3371
- if (keyboard_event.keyboard.phase != .key_down) return;
5492
+ const release = keyboard_event.keyboard.phase == .key_up and self.options.key_release_events;
5493
+ if (keyboard_event.keyboard.phase != .key_down and !release) return;
3372
5494
  if (map(keyboard_event.keyboard)) |msg| {
3373
5495
  try self.dispatch(runtime, keyboard_event.window_id, msg);
3374
5496
  }
@@ -3401,6 +5523,70 @@ pub fn UiAppWithFeatures(comptime ModelT: type, comptime MsgT: type, comptime fe
3401
5523
  }
3402
5524
  }
3403
5525
 
5526
+ /// Wheel scrollback over a bound `<terminal>`: natural
5527
+ /// direction, like every terminal — the gesture belongs to the
5528
+ /// widget under the pointer, so it consumes the event ahead of
5529
+ /// the app-level `on_wheel` seam (widget precedence). The
5530
+ /// applied position reports through `on-terminal` like every
5531
+ /// runtime-applied view-state change, and the Msg rides the
5532
+ /// same journaled input event, so a recorded scroll replays to
5533
+ /// the identical viewport. Returns whether a terminal consumed
5534
+ /// the wheel.
5535
+ fn handleTerminalWheel(self: *Self, runtime: *Runtime, input_event: platform.GpuSurfaceInputEvent) anyerror!bool {
5536
+ if (comptime !terminal_session.enabled) return false;
5537
+ if (input_event.kind != .scroll) return false;
5538
+ if (input_event.delta_y == 0) return false;
5539
+ const layout = runtime.canvasWidgetLayout(input_event.window_id, input_event.label) catch return false;
5540
+ const point = geometry.PointF.init(input_event.x, input_event.y);
5541
+ // The TOPMOST bound terminal under the pointer (later nodes
5542
+ // paint over earlier ones).
5543
+ var target: ?canvas.WidgetLayoutNode = null;
5544
+ for (layout.nodes) |node| {
5545
+ if (node.widget.kind != .terminal) continue;
5546
+ if (node.widget.terminal.pty == 0) continue;
5547
+ if (!node.frame.normalized().containsPoint(point)) continue;
5548
+ target = node;
5549
+ }
5550
+ const node = target orelse return false;
5551
+ if (!self.terminal_sessions.hasSession(node.widget.terminal.pty)) return false;
5552
+ if (self.terminal_sessions.wheel(node.widget.terminal.pty, input_event.delta_y)) {
5553
+ try self.repaintTerminals(runtime, input_event.window_id);
5554
+ if (self.terminal_sessions.currentState(node.widget.terminal.pty)) |state| {
5555
+ if (self.treeForViewLabel(input_event.label)) |tree| {
5556
+ if (tree.msgForTerminal(node.widget.id, state)) |msg| {
5557
+ try self.dispatch(runtime, input_event.window_id, msg);
5558
+ }
5559
+ }
5560
+ }
5561
+ }
5562
+ // Over a bound terminal the gesture is the terminal's even
5563
+ // when the viewport is already pinned — the app wheel seam
5564
+ // must not double-consume it.
5565
+ return true;
5566
+ }
5567
+
5568
+ /// Wheel/trackpad scrolls reach the app as the pinch channel's
5569
+ /// sibling (`Options.on_wheel`): the raw `.scroll` kind of the
5570
+ /// gpu-surface input surface, for apps whose content scrolls
5571
+ /// without a scroll-region widget (a terminal's scrollback).
5572
+ /// The Msg dispatch rides the same journaled input event, so a
5573
+ /// recorded scroll replays to the identical model.
5574
+ fn handleWheel(self: *Self, runtime: *Runtime, input_event: platform.GpuSurfaceInputEvent) anyerror!void {
5575
+ const map = self.options.on_wheel orelse return;
5576
+ if (input_event.kind != .scroll) return;
5577
+ if (map(.{
5578
+ .window_id = input_event.window_id,
5579
+ .label = input_event.label,
5580
+ .delta_x = input_event.delta_x,
5581
+ .delta_y = input_event.delta_y,
5582
+ .x = input_event.x,
5583
+ .y = input_event.y,
5584
+ .modifiers = input_event.modifiers,
5585
+ })) |msg| {
5586
+ try self.dispatch(runtime, input_event.window_id, msg);
5587
+ }
5588
+ }
5589
+
3404
5590
  /// Split-fraction changes route through the split's `on_resize`
3405
5591
  /// constructor. The payload is the fraction the runtime already
3406
5592
  /// applied, so a model that stores it and echoes it back into
@@ -3421,6 +5607,22 @@ pub fn UiAppWithFeatures(comptime ModelT: type, comptime MsgT: type, comptime fe
3421
5607
  /// on it, the same contract keyboard slider steps follow.
3422
5608
  fn handleWidgetChange(self: *Self, runtime: *Runtime, change_event: core.CanvasWidgetChangeEvent) anyerror!void {
3423
5609
  const tree = self.treeForViewLabel(change_event.view_label) orelse return;
5610
+ // House video chrome is runtime-consumed: a change on the
5611
+ // transport's seek slider maps its 0..1 fraction onto the
5612
+ // playback's duration and seeks the channel directly (no
5613
+ // app Msg exists to resolve). A duration-less playback (not
5614
+ // loaded yet) seeks nowhere honestly.
5615
+ if (tree.findWidget(change_event.id)) |widget| {
5616
+ if (widget.video_control == .scrub) {
5617
+ const snap = self.effects.videoSnapshot();
5618
+ if (snap.duration_ms > 0) {
5619
+ const fraction: f64 = std.math.clamp(change_event.value, 0, 1);
5620
+ self.effects.seekVideo(@intFromFloat(fraction * @as(f64, @floatFromInt(snap.duration_ms))));
5621
+ }
5622
+ try self.rebuildVideoChrome(runtime);
5623
+ return;
5624
+ }
5625
+ }
3424
5626
  if (tree.msgForChange(change_event.id, change_event.value)) |msg| {
3425
5627
  try self.dispatch(runtime, change_event.window_id, msg);
3426
5628
  }
@@ -3465,16 +5667,156 @@ pub fn UiAppWithFeatures(comptime ModelT: type, comptime MsgT: type, comptime fe
3465
5667
  }
3466
5668
  }
3467
5669
 
3468
- /// A native context-menu selection: resolve the selected
3469
- /// item's declared `Msg` through the tree's handler table.
5670
+ /// The runtime handed a widget's declared menu to the native
5671
+ /// presenter: capture the shown items' dispatch Msgs (by value)
5672
+ /// keyed by the request's token, and PIN the build-arena
5673
+ /// generation the presented tree was built from — the payloads'
5674
+ /// slices stay valid, at their original addresses, however many
5675
+ /// rebuilds the open menu outlives (`context_menu_pin`).
5676
+ /// Selection resolves from this snapshot, so the user always
5677
+ /// gets the item they SAW even when the tree rebuilds under the
5678
+ /// open menu. A new presentation supersedes the previous pin.
5679
+ fn handleContextMenuShown(self: *Self, runtime: *Runtime, shown_event: core.CanvasWidgetContextMenuShownEvent) anyerror!void {
5680
+ // A pinned rebuild failure may have dropped the live tree
5681
+ // while the previous menu was open. This shown event
5682
+ // PROMISES a snapshot for the replacement menu, so restore
5683
+ // the tree first — silently arming nothing would leave the
5684
+ // presented menu's selection to fall through a null tree
5685
+ // and dispatch no message.
5686
+ if (self.treeForViewLabel(shown_event.view_label) == null) try self.restoreMissingTree(runtime);
5687
+ const tree = self.treeForViewLabel(shown_event.view_label) orelse return;
5688
+ const count = @min(shown_event.item_count, self.context_menu_shown_msgs.len);
5689
+ for (0..count) |item_index| {
5690
+ self.context_menu_shown_msgs[item_index] = tree.msgForContextMenu(shown_event.target_id, item_index);
5691
+ }
5692
+ self.context_menu_shown_token = shown_event.token;
5693
+ self.context_menu_shown_count = count;
5694
+ self.context_menu_pin = if (std.mem.eql(u8, shown_event.view_label, self.options.canvas_label))
5695
+ .{ .window_id = null, .arena_index = self.arena_index }
5696
+ else if (self.windowSlotByCanvasLabel(shown_event.view_label)) |slot|
5697
+ .{ .window_id = slot.window_id, .arena_index = slot.arena_index }
5698
+ else
5699
+ null;
5700
+ }
5701
+
5702
+ /// The arena index this canvas's next rebuild must use:
5703
+ /// normally the pair alternates, but while the presented menu's
5704
+ /// pin holds one generation of THIS canvas (matched by stable
5705
+ /// window identity, null = the main canvas), every rebuild
5706
+ /// routes through the partner arena instead — consecutive
5707
+ /// builds reset and reuse one side while the pinned side stays
5708
+ /// frozen, exactly the cadence the clearance-retry pass already
5709
+ /// runs within a single rebuild. Memory under an open menu is
5710
+ /// therefore bounded at two trees, however many rebuilds occur.
5711
+ fn contextMenuRebuildIndex(self: *const Self, window_id: ?platform.WindowId, current_index: usize) usize {
5712
+ const natural = current_index ^ 1;
5713
+ const pin = self.context_menu_pin orelse return natural;
5714
+ if (pin.arena_index != natural) return natural;
5715
+ const matches = if (pin.window_id) |pin_window|
5716
+ (window_id orelse return natural) == pin_window
5717
+ else
5718
+ window_id == null;
5719
+ return if (matches) natural ^ 1 else natural;
5720
+ }
5721
+
5722
+ /// Window teardown for the pin's owner: the slot's arenas are
5723
+ /// about to deinit (and another slot swap-moves into its index),
5724
+ /// so a snapshot presented from this window must disarm NOW —
5725
+ /// a stale pin would otherwise keep steering the reused slot's
5726
+ /// rebuild cadence around a generation that no longer exists.
5727
+ fn releaseContextMenuSnapshotForWindow(self: *Self, window_id: platform.WindowId) void {
5728
+ const pin = self.context_menu_pin orelse return;
5729
+ const pin_window = pin.window_id orelse return;
5730
+ if (pin_window == window_id) self.releaseContextMenuSnapshot();
5731
+ }
5732
+
5733
+ /// Disarm the presented-menu snapshot and release the pinned
5734
+ /// build generation. Every way a request ends comes through
5735
+ /// here: selection (after its dispatch), the runtime's
5736
+ /// dismissed notice, an out-of-range selection swallow, and the
5737
+ /// pin-owning window's teardown.
5738
+ fn releaseContextMenuSnapshot(self: *Self) void {
5739
+ self.context_menu_shown_token = 0;
5740
+ self.context_menu_shown_count = 0;
5741
+ self.context_menu_pin = null;
5742
+ }
5743
+
5744
+ /// The presented menu closed without a selection: a stale
5745
+ /// token's notice is ignored (a superseding presentation
5746
+ /// already replaced the snapshot and the pin).
5747
+ fn handleContextMenuDismissed(self: *Self, runtime: *Runtime, dismissed_event: core.CanvasWidgetContextMenuDismissedEvent) anyerror!void {
5748
+ if (dismissed_event.token == 0 or dismissed_event.token != self.context_menu_shown_token) return;
5749
+ self.releaseContextMenuSnapshot();
5750
+ try self.restoreMissingTree(runtime);
5751
+ }
5752
+
5753
+ /// A pinned rebuild failure dropped a live tree (`rebuild`'s
5754
+ /// live-arena guard) while its menu stayed on the glass, and
5755
+ /// the request just resolved WITHOUT a Msg dispatch (dismissal,
5756
+ /// an out-of-range swallow, an unmapped item): restore the tree
5757
+ /// now. No Msg-driven rebuild is coming, and with no handler
5758
+ /// table every pointer, keyboard, and scroll event silently
5759
+ /// no-ops until an unrelated resize, timer, or effect happens
5760
+ /// to rebuild.
5761
+ fn restoreMissingTree(self: *Self, runtime: *Runtime) anyerror!void {
5762
+ if (!self.installed) return;
5763
+ var missing = self.tree == null;
5764
+ for (self.window_slots[0..self.window_slot_count]) |*slot| {
5765
+ if (slot.installed and slot.tree == null) missing = true;
5766
+ }
5767
+ if (missing) try self.rebuildAllViews(runtime);
5768
+ }
5769
+
5770
+ /// A native context-menu selection: resolve the selected item's
5771
+ /// declared `Msg`. A selection carrying the presented snapshot's
5772
+ /// token resolves from the snapshot (what the user saw); only a
5773
+ /// snapshot-less dispatch — the automation verb, which validates
5774
+ /// against the live tree itself — resolves through the tree's
5775
+ /// handler table.
3470
5776
  fn handleContextMenu(self: *Self, runtime: *Runtime, menu_event: core.CanvasWidgetContextMenuEvent) anyerror!void {
3471
- const tree = self.treeForViewLabel(menu_event.view_label) orelse return;
3472
5777
  // A selection on this menu closes it whatever the source: an
3473
5778
  // automation-invoked selection while the fallback surface is
3474
5779
  // open must not leave the surface mounted.
3475
5780
  if (self.context_menu_fallback_target == menu_event.target_id) {
3476
5781
  self.clearContextMenuFallback();
3477
5782
  }
5783
+ if (menu_event.token != 0 and menu_event.token == self.context_menu_shown_token) {
5784
+ const count = self.context_menu_shown_count;
5785
+ // The request is consumed on every path out of this
5786
+ // block — resolved, out-of-range, or a failed dispatch.
5787
+ defer self.releaseContextMenuSnapshot();
5788
+ if (menu_event.item_index < count) {
5789
+ if (self.context_menu_shown_msgs[menu_event.item_index]) |msg| {
5790
+ // The Msg is stored by value and its pinned-arena
5791
+ // payload slices are consumed by `update` itself;
5792
+ // the rebuild that follows reads only the model.
5793
+ // Release the pin BEFORE the dispatch: nothing
5794
+ // resets the pinned arena until the rebuild, and
5795
+ // the rebuild then routes into the partner arena
5796
+ // naturally — so a Msg whose update pushes the
5797
+ // model past a build budget fails the rebuild
5798
+ // WITHOUT resetting the live arena underneath it.
5799
+ // Input keeps working on the previous tree, and
5800
+ // the app's controls can recover the model —
5801
+ // production's degraded-error contract.
5802
+ self.releaseContextMenuSnapshot();
5803
+ try self.dispatch(runtime, menu_event.window_id, msg);
5804
+ return;
5805
+ }
5806
+ }
5807
+ // Swallowed without a Msg (out of range, or an item the
5808
+ // presented tree never mapped): no dispatch rebuilds, so
5809
+ // restore a live tree a failed pinned rebuild dropped.
5810
+ try self.restoreMissingTree(runtime);
5811
+ return;
5812
+ }
5813
+ // Snapshot-less resolution (the automation verb, or a menu
5814
+ // whose shown event could not arm — its restore attempt
5815
+ // failed while the model was unbuildable): the model may
5816
+ // have recovered since, so restore a dropped tree before
5817
+ // resolving rather than silently dispatching nothing.
5818
+ if (self.treeForViewLabel(menu_event.view_label) == null) try self.restoreMissingTree(runtime);
5819
+ const tree = self.treeForViewLabel(menu_event.view_label) orelse return;
3478
5820
  if (tree.msgForContextMenu(menu_event.target_id, menu_event.item_index)) |msg| {
3479
5821
  try self.dispatch(runtime, menu_event.window_id, msg);
3480
5822
  }
@@ -3491,6 +5833,7 @@ pub fn UiAppWithFeatures(comptime ModelT: type, comptime MsgT: type, comptime fe
3491
5833
  self.context_menu_fallback_label_len = label_len;
3492
5834
  self.context_menu_fallback_window_id = request_event.window_id;
3493
5835
  self.context_menu_fallback_target = request_event.target_id;
5836
+ self.context_menu_fallback_point = request_event.point;
3494
5837
  try self.rebuildAllViews(runtime);
3495
5838
  }
3496
5839
 
@@ -3570,3 +5913,35 @@ fn effectsMinimizeWindowByLabel(context: *anyopaque, window_label: []const u8) b
3570
5913
  runtime.minimizeWindow(window_id) catch return false;
3571
5914
  return true;
3572
5915
  }
5916
+
5917
+ fn effectsShowWindowByLabel(context: *anyopaque, window_label: []const u8) bool {
5918
+ const runtime: *Runtime = @ptrCast(@alignCast(context));
5919
+ // A policy-hidden window keeps `open` true, so the same live-window
5920
+ // resolution close/minimize use finds it.
5921
+ const window_id = effectsWindowIdByLabel(runtime, window_label) orelse return false;
5922
+ runtime.showWindow(window_id) catch return false;
5923
+ return true;
5924
+ }
5925
+
5926
+ fn effectsQuitApp(context: *anyopaque) bool {
5927
+ const runtime: *Runtime = @ptrCast(@alignCast(context));
5928
+ runtime.quitApp() catch return false;
5929
+ return true;
5930
+ }
5931
+
5932
+ /// The build storage pinned under a presented native context menu:
5933
+ /// which canvas's arena pair and which generation (index) of that pair
5934
+ /// built the presented tree. The canvas is named by STABLE window
5935
+ /// identity (`window_id` null = the main canvas), never by slot index —
5936
+ /// removing a window swap-moves another slot into its place, and an
5937
+ /// index-keyed pin would start protecting the wrong arena. While set,
5938
+ /// rebuilds of that canvas route through the PARTNER arena
5939
+ /// (`contextMenuRebuildIndex`), so the pinned generation stays
5940
+ /// untouched — the snapshot's Msg payloads keep their original storage
5941
+ /// and pointer identity — and memory holds at two trees (the pinned
5942
+ /// one plus the partner, reset on its normal cadence) however long the
5943
+ /// menu stays open.
5944
+ const ContextMenuPin = struct {
5945
+ window_id: ?platform.WindowId,
5946
+ arena_index: usize,
5947
+ };