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}
93
94impl<S: Spec, A: App<Spec = S>> Runtime<S, A> {
95    /// Build the runtime and the app's handle (design §2.5). The app's
96    /// [`App::init`] runs once, before the first tick; its commands and
97    /// the config's startup windows land in the first tick's drain.
98    pub fn new(mut app: A, cfg: RuntimeConfig, waker: Waker) -> (Self, Handle<S>) {
99        let (tx, rx) = std::sync::mpsc::sync_channel(INBOX_CAP);
100        let snap = Arc::new(ArcSwap::from_pointee(VisualSnapshot::empty()));
101        let handle = Handle {
102            tx,
103            snap: Arc::clone(&snap),
104            waker,
105        };
106        let kernel = Kernel::new(&KernelConfig {
107            anim: cfg.anim,
108            layout: cfg.layout,
109            tokens: cfg.tokens,
110            dark: cfg.dark,
111            close: cfg.close,
112            tick: cfg.tick,
113        });
114        let mut cmds = Vec::new();
115        {
116            let mut cx = InitCx { out: &mut cmds };
117            app.init(&mut cx);
118        }
119        for spec in cfg.windows {
120            cmds.push(AppCommand::Window(WindowCmd::Open(spec)));
121        }
122        let runtime = Self {
123            app,
124            kernel,
125            rx,
126            snap,
127            inputs: Vec::new(),
128            cmds,
129            now: Seconds::ZERO,
130            last_pass_changed: false,
131        };
132        (runtime, handle)
133    }
134
135    /// Feed one host input event; the next tick routes it.
136    pub fn push_input(&mut self, input: InputEnvelope) {
137        self.inputs.push(input);
138    }
139
140    /// One tick (design §2.5): drain the inbox, phases 1-4 and 7, deliver
141    /// the intents (their commands feed the settle passes), then zero-input
142    /// settle passes until quiet, at most [`MAX_SETTLE`].
143    pub fn tick(&mut self, now: Seconds) -> TickOutput {
144        self.now = now;
145        while let Ok(cmd) = self.rx.try_recv() {
146            self.cmds.push(cmd);
147        }
148        let mut out = TickOutput::default();
149        self.pass(now, &mut out, true);
150        let mut settles = 0;
151        while (self.last_pass_changed || !self.cmds.is_empty()) && settles < MAX_SETTLE {
152            settles += 1;
153            self.pass(now, &mut out, false);
154        }
155        // Work outlived the settle budget: the loop must not sleep on it
156        // (the cadence hint only covers frames and timers).
157        if self.last_pass_changed || !self.cmds.is_empty() {
158            out.wake = Wake::Immediate;
159        }
160        out
161    }
162
163    /// One pass: phases 1-4, publish, intent delivery.
164    fn pass(&mut self, now: Seconds, out: &mut TickOutput, with_inputs: bool) {
165        let mut inputs = if with_inputs {
166            std::mem::take(&mut self.inputs)
167        } else {
168            Vec::new()
169        };
170        let mut cmds = std::mem::take(&mut self.cmds);
171        let before = self.kernel.engine_revisions();
172        self.kernel.step(now, &mut inputs, &mut cmds);
173        let published = self.kernel.publish(now);
174        out.window_commands.extend(published.window_commands);
175        out.frames.extend(published.frames);
176        out.wake = earliest(out.wake, published.wake);
177        if let Some(snapshot) = published.snapshot {
178            self.snap.store(Arc::new(snapshot));
179        }
180        // Intents deliver AFTER the publish of the same pass: an intent
181        // handler reading the handle sees the state the intent reports.
182        let intents = self.kernel.take_intents();
183        self.last_pass_changed = !intents.is_empty() || before != self.kernel.engine_revisions();
184        if !intents.is_empty() {
185            let snapshot = self.snap.load_full();
186            let mut answers = Vec::new();
187            for intent in intents {
188                let mut cx = IntentCx {
189                    view: &snapshot,
190                    out: &mut answers,
191                };
192                self.app.intent(intent, &mut cx);
193            }
194            self.cmds.extend(answers);
195        }
196    }
197
198    /// Paint one due frame request (phases 5-6 for its window). The
199    /// commands the hooks declare apply from the next tick's drain.
200    pub fn paint(&mut self, req: &FrameRequest, ctx: &mut dyn RenderContext) {
201        let out = self
202            .kernel
203            .compose(self.now, req.window, &mut self.app, ctx);
204        self.cmds.extend(out.commands);
205    }
206
207    /// The last published snapshot (same read as the handle's).
208    pub fn snapshot(&self) -> Arc<VisualSnapshot<S>> {
209        self.snap.load_full()
210    }
211
212    /// The published revision.
213    pub fn revision(&self) -> Revision {
214        self.snap.load().revision
215    }
216
217    /// The host should exit its loop (every window closed or `Shutdown`).
218    pub fn should_exit(&self) -> bool {
219        self.kernel.exit_requested()
220    }
221
222    /// The app, for hosts that drive app-level tools (tests).
223    pub fn app(&self) -> &A {
224        &self.app
225    }
226
227    /// The app, mutably, outside any hook (tests, host tools).
228    pub fn app_mut(&mut self) -> &mut A {
229        &mut self.app
230    }
231
232    /// The kernel (crate-internal: the §9.2 tests read the `RouteTrace`).
233    // Test doors (hop-count assertions in host::tests).
234    #[allow(dead_code)]
235    pub(crate) fn kernel(&self) -> &Kernel<S> {
236        &self.kernel
237    }
238}
239
240/// The earlier of two wakes (`Immediate` < `At(t)` < `Idle`).
241fn earliest(a: Wake, b: Wake) -> Wake {
242    match (a, b) {
243        (Wake::Immediate, _) | (_, Wake::Immediate) => Wake::Immediate,
244        (Wake::At(x), Wake::At(y)) => Wake::At(if x.get() <= y.get() { x } else { y }),
245        (Wake::At(t), Wake::Idle) | (Wake::Idle, Wake::At(t)) => Wake::At(t),
246        (Wake::Idle, Wake::Idle) => Wake::Idle,
247    }
248}