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}
78
79impl<'a, S: Spec> InitCx<'a, S> {
80    /// Enqueue a command, applied from the first tick on.
81    pub fn command(&mut self, cmd: AppCommand<S>) {
82        self.out.push(cmd);
83    }
84}
85
86/// Intent hook door: the published snapshot (read-only) plus commands.
87pub struct IntentCx<'a, S: Spec> {
88    /// The snapshot published at the end of this tick (already includes
89    /// every change the intent reports).
90    pub view: &'a VisualSnapshot<S>,
91    pub(crate) out: &'a mut Vec<AppCommand<S>>,
92}
93
94impl<'a, S: Spec> IntentCx<'a, S> {
95    /// Enqueue a command, applied in the next settle pass of this tick.
96    pub fn command(&mut self, cmd: AppCommand<S>) {
97        self.out.push(cmd);
98    }
99}
100
101/// Effects a content hook may declare; nothing else crosses (design §6.3).
102pub enum HookOp<S: Spec> {
103    /// Repaint this window next frame (animation, live data).
104    RequestFrame,
105    /// Tell the OS where the text caret is (IME candidate window).
106    ImeArea(Rect),
107    /// A visual command, applied in the next settle pass.
108    Command(AppCommand<S>),
109}
110
111/// The sink a hook writes its declared effects into.
112pub struct HookOps<S: Spec> {
113    pub(crate) ops: Vec<HookOp<S>>,
114}
115
116impl<S: Spec> Default for HookOps<S> {
117    fn default() -> Self {
118        Self { ops: Vec::new() }
119    }
120}
121
122impl<S: Spec> HookOps<S> {
123    /// Repaint this window next frame.
124    pub fn request_frame(&mut self) {
125        self.ops.push(HookOp::RequestFrame);
126    }
127
128    /// Report the text caret rect (window-local logical pixels) to the OS.
129    pub fn ime_area(&mut self, rect: Rect) {
130        self.ops.push(HookOp::ImeArea(rect));
131    }
132
133    /// Enqueue a visual command for the next settle pass.
134    pub fn command(&mut self, cmd: AppCommand<S>) {
135        self.ops.push(HookOp::Command(cmd));
136    }
137}
138
139/// Wall-clock facts of this frame; both values come from the host clock
140/// the runtime was given, never read inside the crate.
141#[derive(Clone, Copy, Debug, Default, PartialEq)]
142pub struct FrameTime {
143    /// Host clock of the tick.
144    pub now: Seconds,
145    /// Seconds since the previous painted frame of this window.
146    pub dt: f64,
147}
148
149/// Read-only per-window truth of this frame, built at the start of the
150/// compose phase (design §5.2, read path a).
151///
152/// Owned, not borrowed: the compose phase mutates the input engine
153/// (registrations) while hooks hold the view, so the engine views cannot
154/// be lent out; the copied state is exactly what the engines reported at
155/// phase start, which is the same-tick truth the design asks the view to
156/// be. Clicks are the last evaluated frame's (a release is evaluated by
157/// the `EndFrame` of the compose that saw it and read back from the next
158/// compose on — one frame of latency, like every retained-registration
159/// immediate-mode UI).
160pub struct VisualView<S: Spec> {
161    pub(crate) hovered: Option<WidgetId>,
162    pub(crate) pressed: Option<WidgetId>,
163    pub(crate) focused: Option<WidgetId>,
164    pub(crate) clicked: Vec<(WidgetId, u8)>,
165    pub(crate) scroll: (f64, f64),
166    pub(crate) captured: bool,
167    pub(crate) open_overlays: Vec<S::Overlay>,
168}
169
170// Manual impl: a derive would demand `S: Default` of the marker type.
171impl<S: Spec> Default for VisualView<S> {
172    fn default() -> Self {
173        Self {
174            hovered: None,
175            pressed: None,
176            focused: None,
177            clicked: Vec::new(),
178            scroll: (0.0, 0.0),
179            captured: false,
180            open_overlays: Vec::new(),
181        }
182    }
183}
184
185impl<S: Spec> VisualView<S> {
186    /// The widget under the pointer, if any.
187    pub fn hovered(&self) -> Option<&WidgetId> {
188        self.hovered.as_ref()
189    }
190
191    /// `id` is under the pointer.
192    pub fn is_hovered(&self, id: &WidgetId) -> bool {
193        self.hovered.as_ref() == Some(id)
194    }
195
196    /// The widget being pressed, if any.
197    pub fn pressed(&self) -> Option<&WidgetId> {
198        self.pressed.as_ref()
199    }
200
201    /// `id` is being pressed.
202    pub fn is_pressed(&self, id: &WidgetId) -> bool {
203        self.pressed.as_ref() == Some(id)
204    }
205
206    /// The widget with keyboard focus, if any.
207    pub fn focused(&self) -> Option<&WidgetId> {
208        self.focused.as_ref()
209    }
210
211    /// `id` has keyboard focus.
212    pub fn is_focused(&self, id: &WidgetId) -> bool {
213        self.focused.as_ref() == Some(id)
214    }
215
216    /// `id` was clicked in the last evaluated frame (single, double or
217    /// triple — see [`VisualView::click_count`]).
218    pub fn clicked(&self, id: &WidgetId) -> bool {
219        self.click_count(id) > 0
220    }
221
222    /// The click count `id` was last clicked with (0 = not clicked,
223    /// 1 single, 2 double, 3 triple).
224    pub fn click_count(&self, id: &WidgetId) -> u8 {
225        self.clicked
226            .iter()
227            .find_map(|(w, n)| (w == id).then_some(*n))
228            .unwrap_or(0)
229    }
230
231    /// Every widget clicked in the last evaluated frame, with counts.
232    pub fn clicks(&self) -> &[(WidgetId, u8)] {
233        &self.clicked
234    }
235
236    /// Scroll delta accumulated for this frame, in lines.
237    pub fn scroll(&self) -> (f64, f64) {
238        self.scroll
239    }
240
241    /// The pointer is captured by a widget or an engine.
242    pub fn captured(&self) -> bool {
243        self.captured
244    }
245
246    /// This overlay is open in the window.
247    pub fn overlay_open(&self, id: S::Overlay) -> bool {
248        self.open_overlays.contains(&id)
249    }
250
251    /// Every open overlay of the window, bottom to top.
252    pub fn open_overlays(&self) -> &[S::Overlay] {
253        &self.open_overlays
254    }
255}
256
257/// Widget registration face a hook draws against: the window's coordinator
258/// (library L1 `register_*` fns take it), the per-widget typed state store
259/// and the layer the hook's widgets register into.
260///
261/// The coordinator's state-mutating driver methods are deliberately not
262/// reachable here (one writer of focus / hover / capture, design §6.3);
263/// lib brief L6 makes that mechanical.
264pub struct Widgets<'a> {
265    /// The window's input coordinator (widget registration only).
266    pub coord: &'a mut InputCoordinator,
267    /// Per-widget persistent typed state (scroll offsets, expand flags).
268    pub states: &'a mut StateRegistry,
269    /// The layer this hook's widgets register into (panel-local or the
270    /// overlay's own).
271    pub layer: LayerId,
272}
273
274/// One dock leaf's content hook context (design §6.3).
275pub struct PanelCx<'a, S: Spec> {
276    /// The window being composed.
277    pub window: WindowId,
278    /// The leaf being drawn.
279    pub leaf: LeafId,
280    /// The app's own panel value (the active tab of the leaf).
281    pub panel: &'a S::Panel,
282    /// The panel's tab index inside the leaf.
283    pub index: usize,
284    /// Content rect, window-local logical pixels (inside the leaf frame
285    /// and its tab strip).
286    pub rect: Rect,
287    /// Device pixel ratio of the window.
288    pub dpr: f64,
289    /// Active theme tokens.
290    pub tokens: &'a Tokens,
291    /// The paint target.
292    pub render: &'a mut dyn RenderContext,
293    /// Widget registration face.
294    pub widgets: Widgets<'a>,
295    /// This frame's input truth of the window.
296    pub view: &'a VisualView<S>,
297    /// Frame clock.
298    pub time: FrameTime,
299    /// Declared effects out.
300    pub out: &'a mut HookOps<S>,
301}
302
303/// One open overlay's body hook context (design §6.3); same reach as
304/// [`PanelCx`], plus the overlay identity and the body rect the kernel's
305/// frame leaves.
306pub struct OverlayCx<'a, S: Spec> {
307    /// The window being composed.
308    pub window: WindowId,
309    /// The overlay being drawn.
310    pub id: S::Overlay,
311    /// Body rect, window-local logical pixels (inside the kernel-drawn
312    /// frame).
313    pub body: Rect,
314    /// Content rect the body may register widgets into (equals `body`).
315    pub rect: Rect,
316    /// Device pixel ratio of the window.
317    pub dpr: f64,
318    /// Active theme tokens.
319    pub tokens: &'a Tokens,
320    /// The paint target.
321    pub render: &'a mut dyn RenderContext,
322    /// Widget registration face (the overlay's own layer).
323    pub widgets: Widgets<'a>,
324    /// This frame's input truth of the window.
325    pub view: &'a VisualView<S>,
326    /// Frame clock.
327    pub time: FrameTime,
328    /// Declared effects out.
329    pub out: &'a mut HookOps<S>,
330}