Skip to main content

uzor_framework/
runtime.rs

1//! ROLE runtime (shell): the tick loop around the kernel (design §2.5).
2//!
3//! The runtime owns the app, the kernel and the two channel ends; it runs
4//! `tick` (kernel phases 1-4 and 7, intent delivery, settle passes) and
5//! `paint` (phases 5-6 per due frame request). Hosts drive it; the app
6//! never sees it (ban F8 — the app reaches on-screen state only through
7//! the [`Handle`] and the hook contexts).
8
9use std::sync::mpsc::Receiver;
10use std::sync::Arc;
11
12use arc_swap::ArcSwap;
13use uzor::render::{RenderContext, TickRate};
14use uzor::tokens::Tokens;
15
16use crate::handle::{App, Handle, InitCx, IntentCx, Waker, INBOX_CAP};
17use crate::kernel::{Kernel, KernelConfig};
18use crate::types::anim::AnimPolicy;
19use crate::types::bus::InputEnvelope;
20use crate::types::command::{AppCommand, LayoutPolicy, WindowCmd};
21use crate::types::frame::{FrameRequest, Wake};
22use crate::types::ids::{Revision, Seconds, WindowId};
23use crate::types::snapshot::VisualSnapshot;
24use crate::types::spec::Spec;
25use crate::types::window::{ClosePolicy, WindowCommand, WindowSpec};
26
27/// Settle passes a tick runs at most after the main pass (design §2.5
28/// `MAX_SETTLE`): effects that feed back into commands or intents get
29/// zero-input passes of phases 1, 3-4 and 7 until the tick is quiet.
30pub const MAX_SETTLE: usize = 4;
31
32/// Everything a tick hands to the host (design §2.5 `TickOutput`).
33#[derive(Default)]
34pub struct TickOutput {
35    /// Host-bound window commands, in the order the engines enqueued them.
36    pub window_commands: Vec<(WindowId, WindowCommand)>,
37    /// Due frame requests; the host paints each with [`Runtime::paint`].
38    pub frames: Vec<FrameRequest>,
39    /// When the host should tick again.
40    pub wake: Wake,
41}
42
43/// Runtime construction parameters (design §2.5 `RuntimeConfig`).
44pub struct RuntimeConfig {
45    /// Windows to open at startup (the app can open more from
46    /// [`App::init`]).
47    pub windows: Vec<WindowSpec>,
48    /// Default repaint cadence of a window whose spec sets none.
49    pub tick: TickRate,
50    /// Animator durations.
51    pub anim: AnimPolicy,
52    /// Splitter / drag-out / expand behaviour.
53    pub layout: LayoutPolicy,
54    /// App-wide theme.
55    pub tokens: Arc<Tokens>,
56    /// Dark theme active.
57    pub dark: bool,
58    /// What happens when the user asks to close a window.
59    pub close: ClosePolicy,
60}
61
62impl Default for RuntimeConfig {
63    fn default() -> Self {
64        Self {
65            windows: Vec::new(),
66            tick: TickRate::default(),
67            anim: AnimPolicy::default(),
68            layout: LayoutPolicy::default(),
69            tokens: Tokens::builtin(uzor::tokens::BuiltinSet::Dark),
70            dark: true,
71            close: ClosePolicy::default(),
72        }
73    }
74}
75
76/// The tick loop around the kernel. `S` is the app's vocabulary, `A` the
77/// app itself.
78pub struct Runtime<S: Spec, A: App<Spec = S>> {
79    app: A,
80    kernel: Kernel<S>,
81    rx: Receiver<AppCommand<S>>,
82    snap: Arc<ArcSwap<VisualSnapshot<S>>>,
83    /// Inputs pushed since the last tick.
84    inputs: Vec<InputEnvelope>,
85    /// Commands waiting for the next pass: handle dispatches, hook and
86    /// intent answers, startup commands.
87    cmds: Vec<AppCommand<S>>,
88    /// Host clock of the last tick (paints stamp their frames with it).
89    now: Seconds,
90    /// The last pass moved an engine revision or produced intents.
91    last_pass_changed: bool,
92    /// A paint asked for another tick (see [`Runtime::take_paint_wants_tick`]).
93    paint_wants_tick: bool,
94}
95
96impl<S: Spec, A: App<Spec = S>> Runtime<S, A> {
97    /// Build the runtime and the app's handle (design §2.5). The app's
98    /// [`App::init`] runs once, before the first tick; its commands and
99    /// the config's startup windows land in the first tick's drain.
100    pub fn new(mut app: A, cfg: RuntimeConfig, waker: Waker) -> (Self, Handle<S>) {
101        let (tx, rx) = std::sync::mpsc::sync_channel(INBOX_CAP);
102        let snap = Arc::new(ArcSwap::from_pointee(VisualSnapshot::empty()));
103        let handle = Handle {
104            tx,
105            snap: Arc::clone(&snap),
106            waker,
107        };
108        let kernel = Kernel::new(&KernelConfig {
109            anim: cfg.anim,
110            layout: cfg.layout,
111            tokens: cfg.tokens,
112            dark: cfg.dark,
113            close: cfg.close,
114            tick: cfg.tick,
115        });
116        let mut cmds = Vec::new();
117        {
118            let mut cx = InitCx { out: &mut cmds, handle: &handle };
119            app.init(&mut cx);
120        }
121        for spec in cfg.windows {
122            cmds.push(AppCommand::Window(WindowCmd::Open(spec)));
123        }
124        let runtime = Self {
125            app,
126            kernel,
127            rx,
128            snap,
129            inputs: Vec::new(),
130            cmds,
131            now: Seconds::ZERO,
132            last_pass_changed: false,
133            paint_wants_tick: false,
134        };
135        (runtime, handle)
136    }
137
138    /// Feed one host input event; the next tick routes it.
139    pub fn push_input(&mut self, input: InputEnvelope) {
140        self.inputs.push(input);
141    }
142
143    /// One tick (design §2.5): drain the inbox, phases 1-4 and 7, deliver
144    /// the intents (their commands feed the settle passes), then zero-input
145    /// settle passes until quiet, at most [`MAX_SETTLE`].
146    pub fn tick(&mut self, now: Seconds) -> TickOutput {
147        self.now = now;
148        while let Ok(cmd) = self.rx.try_recv() {
149            self.cmds.push(cmd);
150        }
151        let mut out = TickOutput::default();
152        self.pass(now, &mut out, true);
153        let mut settles = 0;
154        while (self.last_pass_changed || !self.cmds.is_empty()) && settles < MAX_SETTLE {
155            settles += 1;
156            self.pass(now, &mut out, false);
157        }
158        // Work outlived the settle budget: the loop must not sleep on it
159        // (the cadence hint only covers frames and timers).
160        if self.last_pass_changed || !self.cmds.is_empty() {
161            out.wake = Wake::Immediate;
162        }
163        out
164    }
165
166    /// One pass: phases 1-4, publish, intent delivery.
167    fn pass(&mut self, now: Seconds, out: &mut TickOutput, with_inputs: bool) {
168        let mut inputs = if with_inputs {
169            std::mem::take(&mut self.inputs)
170        } else {
171            Vec::new()
172        };
173        let mut cmds = std::mem::take(&mut self.cmds);
174        let before = self.kernel.engine_revisions();
175        self.kernel.step(now, &mut inputs, &mut cmds);
176        let published = self.kernel.publish(now);
177        out.window_commands.extend(published.window_commands);
178        out.frames.extend(published.frames);
179        out.wake = earliest(out.wake, published.wake);
180        if let Some(snapshot) = published.snapshot {
181            self.snap.store(Arc::new(snapshot));
182        }
183        // Intents deliver AFTER the publish of the same pass: an intent
184        // handler reading the handle sees the state the intent reports.
185        let intents = self.kernel.take_intents();
186        self.last_pass_changed = !intents.is_empty() || before != self.kernel.engine_revisions();
187        if !intents.is_empty() {
188            let snapshot = self.snap.load_full();
189            let mut answers = Vec::new();
190            for intent in intents {
191                let mut cx = IntentCx {
192                    view: &snapshot,
193                    out: &mut answers,
194                };
195                self.app.intent(intent, &mut cx);
196            }
197            self.cmds.extend(answers);
198        }
199    }
200
201    /// Paint one due frame request (phases 5-6 for its window). The
202    /// commands the hooks declare apply from the next tick's drain.
203    pub fn paint(&mut self, req: &FrameRequest, ctx: &mut dyn RenderContext) {
204        let out = self
205            .kernel
206            .compose(self.now, req.window, &mut self.app, ctx);
207        self.paint_wants_tick |= out.wants_frame || !out.commands.is_empty();
208        self.cmds.extend(out.commands);
209    }
210
211    /// A paint since the last call asked for more work (a hook's
212    /// `request_frame`, declared commands, clicks to deliver). The tick's
213    /// `wake` predates the paint, so hosts check this after painting and
214    /// tick again instead of going idle.
215    pub fn take_paint_wants_tick(&mut self) -> bool {
216        std::mem::take(&mut self.paint_wants_tick)
217    }
218
219    /// The last published snapshot (same read as the handle's).
220    pub fn snapshot(&self) -> Arc<VisualSnapshot<S>> {
221        self.snap.load_full()
222    }
223
224    /// The accessibility tree of `win`'s last composed frame (empty before one).
225    pub fn a11y_tree(&self, win: crate::types::ids::WindowId) -> uzor::a11y::A11yTree {
226        self.kernel.a11y_tree(win)
227    }
228
229    /// Every widget registered in `win`'s last composed frame.
230    pub fn widget_snapshot(&self, win: crate::types::ids::WindowId) -> Vec<uzor::input::core::WidgetInfo> {
231        self.kernel.widget_snapshot(win)
232    }
233
234    /// The published revision.
235    pub fn revision(&self) -> Revision {
236        self.snap.load().revision
237    }
238
239    /// The host should exit its loop (every window closed or `Shutdown`).
240    pub fn should_exit(&self) -> bool {
241        self.kernel.exit_requested()
242    }
243
244    /// The app, for hosts that drive app-level tools (tests).
245    pub fn app(&self) -> &A {
246        &self.app
247    }
248
249    /// The app, mutably, outside any hook (tests, host tools).
250    pub fn app_mut(&mut self) -> &mut A {
251        &mut self.app
252    }
253
254    /// The kernel (crate-internal: the §9.2 tests read the `RouteTrace`).
255    // Test doors (hop-count assertions in host::tests).
256    #[allow(dead_code)]
257    pub(crate) fn kernel(&self) -> &Kernel<S> {
258        &self.kernel
259    }
260}
261
262/// The earlier of two wakes (`Immediate` < `At(t)` < `Idle`).
263fn earliest(a: Wake, b: Wake) -> Wake {
264    match (a, b) {
265        (Wake::Immediate, _) | (_, Wake::Immediate) => Wake::Immediate,
266        (Wake::At(x), Wake::At(y)) => Wake::At(if x.get() <= y.get() { x } else { y }),
267        (Wake::At(t), Wake::Idle) | (Wake::Idle, Wake::At(t)) => Wake::At(t),
268        (Wake::Idle, Wake::Idle) => Wake::Idle,
269    }
270}