Skip to main content

uzor_framework/handle/
app.rs

1//! The [`App`] contract and the narrow hook contexts (design §6.3).
2//!
3//! An app implements [`App`] once. The kernel calls its hooks with contexts
4//! that reach exactly one frame's worth of on-screen truth and nothing
5//! else: no engine, no kernel, no runtime, no inbox (ban F8). Effects a
6//! hook asks for are declared through [`HookOps`] and applied by the next
7//! settle pass; intents arrive through [`App::intent`] with an
8//! [`IntentCx`] that answers with commands.
9
10use uzor::app_context::StateRegistry;
11use uzor::input::{InputCoordinator, LayerId};
12use uzor::layout::docking::LeafId;
13use uzor::render::RenderContext;
14use uzor::tokens::Tokens;
15use uzor::{Rect, WidgetId};
16
17use crate::types::command::{AppCommand, ChromeModel};
18use crate::types::ids::{Seconds, WindowId};
19use crate::types::intent::Intent;
20use crate::types::overlay_model::OverlayModel;
21use crate::types::snapshot::VisualSnapshot;
22use crate::types::spec::Spec;
23
24/// The application: view-model declarations, content hooks and the intent
25/// sink. One value drives any number of windows.
26///
27/// All hooks run on the runtime's thread inside the tick (`intent`,
28/// `shutdown`) or the compose phase (`chrome_model`, `overlay_model`,
29/// `panel`, `overlay_body`). Business state stays behind the app's own
30/// back-office handle; nothing back-office crosses into this crate
31/// (design §6.5).
32pub trait App: 'static {
33    /// The app's vocabulary (panels, overlays, actions).
34    type Spec: Spec;
35
36    /// Startup: enqueue the initial windows, keymap bindings and default
37    /// layout as commands. Runs once before the first tick.
38    fn init(&mut self, cx: &mut InitCx<'_, Self::Spec>) {
39        let _ = cx;
40    }
41
42    /// What the kernel draws as this window's chrome strip, declared per
43    /// frame. Compose diffs it against the layout engine's model and
44    /// applies a `SetChromeModel` on change (the engine stays the single
45    /// writer; hit-testing reads the same model the kernel draws).
46    fn chrome_model(&self, win: WindowId) -> ChromeModel {
47        let _ = win;
48        ChromeModel::default()
49    }
50
51    /// What the kernel draws around one open overlay's body, declared per
52    /// frame. The body itself is drawn by [`App::overlay_body`].
53    fn overlay_model(&self, win: WindowId, id: <Self::Spec as Spec>::Overlay) -> OverlayModel;
54
55    /// Draw one visible dock leaf's content with library widget functions,
56    /// once per frame per leaf. The kernel gives the content rect (inside
57    /// the leaf's frame and tab strip) and a scoped registration layer.
58    fn panel(&mut self, cx: &mut PanelCx<'_, Self::Spec>);
59
60    /// Draw one open overlay's body into the rect the frame leaves, once
61    /// per frame per open overlay.
62    fn overlay_body(&mut self, cx: &mut OverlayCx<'_, Self::Spec>);
63
64    /// One typed intent produced by the tick, in production order. Answer
65    /// with visual effects via [`IntentCx::command`]; send business effects
66    /// through the app's own back-office handle.
67    fn intent(&mut self, intent: Intent<Self::Spec>, cx: &mut IntentCx<'_, Self::Spec>);
68
69    /// The runtime is shutting down (last window closed or
70    /// `AppCommand::Shutdown`).
71    fn shutdown(&mut self) {}
72}
73
74/// Startup door: commands only.
75pub struct InitCx<'a, S: Spec> {
76    pub(crate) out: &'a mut Vec<AppCommand<S>>,
77    pub(crate) handle: &'a super::Handle<S>,
78}
79
80impl<'a, S: Spec> InitCx<'a, S> {
81    /// Enqueue a command, applied from the first tick on.
82    pub fn command(&mut self, cmd: AppCommand<S>) {
83        self.out.push(cmd);
84    }
85
86    /// The app's own [`Handle`](super::Handle): keep a clone to dispatch
87    /// commands or [`request_repaint`](super::Handle::request_repaint) from
88    /// background work on any host (native, web, headless).
89    pub fn handle(&self) -> super::Handle<S> {
90        self.handle.clone()
91    }
92}
93
94/// Intent hook door: the published snapshot (read-only) plus commands.
95pub struct IntentCx<'a, S: Spec> {
96    /// The snapshot published at the end of this tick (already includes
97    /// every change the intent reports).
98    pub view: &'a VisualSnapshot<S>,
99    pub(crate) out: &'a mut Vec<AppCommand<S>>,
100}
101
102impl<'a, S: Spec> IntentCx<'a, S> {
103    /// Enqueue a command, applied in the next settle pass of this tick.
104    pub fn command(&mut self, cmd: AppCommand<S>) {
105        self.out.push(cmd);
106    }
107}
108
109/// Effects a content hook may declare; nothing else crosses (design §6.3).
110pub enum HookOp<S: Spec> {
111    /// Repaint this window next frame (animation, live data).
112    RequestFrame,
113    /// Tell the OS where the text caret is (IME candidate window).
114    ImeArea(Rect),
115    /// A visual command, applied in the next settle pass.
116    Command(AppCommand<S>),
117}
118
119/// The sink a hook writes its declared effects into.
120pub struct HookOps<S: Spec> {
121    pub(crate) ops: Vec<HookOp<S>>,
122}
123
124impl<S: Spec> Default for HookOps<S> {
125    fn default() -> Self {
126        Self { ops: Vec::new() }
127    }
128}
129
130impl<S: Spec> HookOps<S> {
131    /// Repaint this window next frame.
132    pub fn request_frame(&mut self) {
133        self.ops.push(HookOp::RequestFrame);
134    }
135
136    /// Report the text caret rect (window-local logical pixels) to the OS.
137    pub fn ime_area(&mut self, rect: Rect) {
138        self.ops.push(HookOp::ImeArea(rect));
139    }
140
141    /// Enqueue a visual command for the next settle pass.
142    pub fn command(&mut self, cmd: AppCommand<S>) {
143        self.ops.push(HookOp::Command(cmd));
144    }
145}
146
147/// Wall-clock facts of this frame; both values come from the host clock
148/// the runtime was given, never read inside the crate.
149#[derive(Clone, Copy, Debug, Default, PartialEq)]
150pub struct FrameTime {
151    /// Host clock of the tick.
152    pub now: Seconds,
153    /// Seconds since the previous painted frame of this window.
154    pub dt: f64,
155}
156
157/// Read-only per-window truth of this frame, built at the start of the
158/// compose phase (design §5.2, read path a).
159///
160/// Owned, not borrowed: the compose phase mutates the input engine
161/// (registrations) while hooks hold the view, so the engine views cannot
162/// be lent out; the copied state is exactly what the engines reported at
163/// phase start, which is the same-tick truth the design asks the view to
164/// be. Clicks are the last evaluated frame's (a release is evaluated by
165/// the `EndFrame` of the compose that saw it and read back from the next
166/// compose on — one frame of latency, like every retained-registration
167/// immediate-mode UI).
168pub struct VisualView<S: Spec> {
169    pub(crate) hovered: Option<WidgetId>,
170    pub(crate) pressed: Option<WidgetId>,
171    pub(crate) focused: Option<WidgetId>,
172    pub(crate) clicked: Vec<(WidgetId, u8)>,
173    pub(crate) scroll: (f64, f64),
174    pub(crate) captured: bool,
175    pub(crate) open_overlays: Vec<S::Overlay>,
176}
177
178// Manual impl: a derive would demand `S: Default` of the marker type.
179impl<S: Spec> Default for VisualView<S> {
180    fn default() -> Self {
181        Self {
182            hovered: None,
183            pressed: None,
184            focused: None,
185            clicked: Vec::new(),
186            scroll: (0.0, 0.0),
187            captured: false,
188            open_overlays: Vec::new(),
189        }
190    }
191}
192
193impl<S: Spec> VisualView<S> {
194    /// The widget under the pointer, if any.
195    pub fn hovered(&self) -> Option<&WidgetId> {
196        self.hovered.as_ref()
197    }
198
199    /// `id` is under the pointer.
200    pub fn is_hovered(&self, id: &WidgetId) -> bool {
201        self.hovered.as_ref() == Some(id)
202    }
203
204    /// The widget being pressed, if any.
205    pub fn pressed(&self) -> Option<&WidgetId> {
206        self.pressed.as_ref()
207    }
208
209    /// `id` is being pressed.
210    pub fn is_pressed(&self, id: &WidgetId) -> bool {
211        self.pressed.as_ref() == Some(id)
212    }
213
214    /// The widget with keyboard focus, if any.
215    pub fn focused(&self) -> Option<&WidgetId> {
216        self.focused.as_ref()
217    }
218
219    /// `id` has keyboard focus.
220    pub fn is_focused(&self, id: &WidgetId) -> bool {
221        self.focused.as_ref() == Some(id)
222    }
223
224    /// `id` was clicked in the last evaluated frame (single, double or
225    /// triple — see [`VisualView::click_count`]).
226    pub fn clicked(&self, id: &WidgetId) -> bool {
227        self.click_count(id) > 0
228    }
229
230    /// The click count `id` was last clicked with (0 = not clicked,
231    /// 1 single, 2 double, 3 triple).
232    pub fn click_count(&self, id: &WidgetId) -> u8 {
233        self.clicked
234            .iter()
235            .find_map(|(w, n)| (w == id).then_some(*n))
236            .unwrap_or(0)
237    }
238
239    /// Every widget clicked in the last evaluated frame, with counts.
240    pub fn clicks(&self) -> &[(WidgetId, u8)] {
241        &self.clicked
242    }
243
244    /// Scroll delta accumulated for this frame, in lines.
245    pub fn scroll(&self) -> (f64, f64) {
246        self.scroll
247    }
248
249    /// The pointer is captured by a widget or an engine.
250    pub fn captured(&self) -> bool {
251        self.captured
252    }
253
254    /// This overlay is open in the window.
255    pub fn overlay_open(&self, id: S::Overlay) -> bool {
256        self.open_overlays.contains(&id)
257    }
258
259    /// Every open overlay of the window, bottom to top.
260    pub fn open_overlays(&self) -> &[S::Overlay] {
261        &self.open_overlays
262    }
263}
264
265/// Widget registration face a hook draws against: the window's coordinator
266/// (library L1 `register_*` fns take it), the per-widget typed state store
267/// and the layer the hook's widgets register into.
268///
269/// The coordinator's state-mutating driver methods are deliberately not
270/// reachable here (one writer of focus / hover / capture, design §6.3);
271/// lib brief L6 makes that mechanical.
272pub struct Widgets<'a> {
273    /// The window's input coordinator (widget registration only).
274    pub coord: &'a mut InputCoordinator,
275    /// Per-widget persistent typed state (scroll offsets, expand flags).
276    pub states: &'a mut StateRegistry,
277    /// The layer this hook's widgets register into (panel-local or the
278    /// overlay's own).
279    pub layer: LayerId,
280}
281
282/// One dock leaf's content hook context (design §6.3).
283pub struct PanelCx<'a, S: Spec> {
284    /// The window being composed.
285    pub window: WindowId,
286    /// The leaf being drawn.
287    pub leaf: LeafId,
288    /// The app's own panel value (the active tab of the leaf).
289    pub panel: &'a S::Panel,
290    /// The panel's tab index inside the leaf.
291    pub index: usize,
292    /// Content rect, window-local logical pixels (inside the leaf frame
293    /// and its tab strip).
294    pub rect: Rect,
295    /// Device pixel ratio of the window.
296    pub dpr: f64,
297    /// Active theme tokens.
298    pub tokens: &'a Tokens,
299    /// The paint target.
300    pub render: &'a mut dyn RenderContext,
301    /// Widget registration face.
302    pub widgets: Widgets<'a>,
303    /// This frame's input truth of the window.
304    pub view: &'a VisualView<S>,
305    /// Frame clock.
306    pub time: FrameTime,
307    /// Declared effects out.
308    pub out: &'a mut HookOps<S>,
309}
310
311/// One open overlay's body hook context (design §6.3); same reach as
312/// [`PanelCx`], plus the overlay identity and the body rect the kernel's
313/// frame leaves.
314pub struct OverlayCx<'a, S: Spec> {
315    /// The window being composed.
316    pub window: WindowId,
317    /// The overlay being drawn.
318    pub id: S::Overlay,
319    /// Body rect, window-local logical pixels (inside the kernel-drawn
320    /// frame).
321    pub body: Rect,
322    /// Content rect the body may register widgets into (equals `body`).
323    pub rect: Rect,
324    /// Device pixel ratio of the window.
325    pub dpr: f64,
326    /// Active theme tokens.
327    pub tokens: &'a Tokens,
328    /// The paint target.
329    pub render: &'a mut dyn RenderContext,
330    /// Widget registration face (the overlay's own layer).
331    pub widgets: Widgets<'a>,
332    /// This frame's input truth of the window.
333    pub view: &'a VisualView<S>,
334    /// Frame clock.
335    pub time: FrameTime,
336    /// Declared effects out.
337    pub out: &'a mut HookOps<S>,
338}