Skip to main content

kova_native_widgets/
context.rs

1//! Contexts passed to event handlers, painters and measurers.
2
3use crate::tree::NodeId;
4use kova_native_assets::{ImageData, SvgData};
5use kova_native_core::{
6    Bounds, Color, Corners, Edges, ElementId, Fill, Instant, Point, Size, Transform2D,
7};
8use kova_native_input::{Action, DispatchPhase};
9use kova_native_render::{
10    Atlas, AtlasImage, AtlasKey, AtlasKind, ContentMask, DrawState, LayerMask, Quad, Scene,
11    ShaderId, Shadow,
12};
13use kova_native_text::{TextLayout, TextStyle, TextSystem};
14use std::borrow::Cow;
15
16/// Access to the system clipboard from event handlers.
17pub trait Clipboard {
18    fn read_text(&mut self) -> Option<String>;
19    fn write_text(&mut self, text: &str);
20}
21
22/// An in-memory clipboard (tests, headless use).
23#[derive(Default)]
24pub struct MemoryClipboard(pub Option<String>);
25
26impl Clipboard for MemoryClipboard {
27    fn read_text(&mut self) -> Option<String> {
28        self.0.clone()
29    }
30
31    fn write_text(&mut self, text: &str) {
32        self.0 = Some(text.to_string());
33    }
34}
35
36/// Requests from UI code to the window / application.
37#[derive(Clone, Debug, PartialEq)]
38pub enum WindowCommand {
39    SetTitle(String),
40    Minimize,
41    ToggleMaximize,
42    Close,
43    /// Exit the application.
44    Quit,
45}
46
47pub(crate) enum Command {
48    Focus(NodeId),
49    /// Focus `NodeId` only if nothing is focused when the command applies.
50    RestoreFocus(NodeId),
51    FocusId(ElementId),
52    Blur,
53    FocusNext,
54    FocusPrev,
55    Repaint(NodeId),
56    Relayout(NodeId),
57    ScrollIntoView(ElementId),
58    DispatchAction(Box<dyn Action>),
59    Window(WindowCommand),
60}
61
62/// Context for event handlers.
63pub struct EventCx<'a> {
64    pub(crate) node: NodeId,
65    pub(crate) bounds: Bounds,
66    pub(crate) transform: Transform2D,
67    pub(crate) phase: DispatchPhase,
68    pub(crate) focused: bool,
69    pub(crate) propagation_stopped: bool,
70    pub(crate) default_prevented: bool,
71    pub(crate) commands: &'a mut Vec<Command>,
72    pub(crate) clipboard: &'a mut dyn Clipboard,
73    pub(crate) text: &'a mut TextSystem,
74    pub(crate) now: Instant,
75}
76
77impl EventCx<'_> {
78    /// Stops the event from reaching further nodes.
79    pub fn stop_propagation(&mut self) {
80        self.propagation_stopped = true;
81    }
82
83    /// Suppresses Kova Native's default behavior for this event (focus on click,
84    /// Tab navigation, text input...).
85    pub fn prevent_default(&mut self) {
86        self.default_prevented = true;
87    }
88
89    /// The current element's layout bounds in logical window coordinates,
90    /// before visual transforms. Use `to_local` to map pointer positions.
91    pub fn bounds(&self) -> Bounds {
92        self.bounds
93    }
94
95    /// Converts a window position to element-local coordinates, undoing the
96    /// visual transforms of this element and its ancestors.
97    pub fn to_local(&self, position: Point) -> Point {
98        self.transform
99            .inverse()
100            .map_or(position, |inv| inv.apply(position))
101            - self.bounds.origin
102    }
103
104    pub fn phase(&self) -> DispatchPhase {
105        self.phase
106    }
107
108    /// Whether the current element has keyboard focus.
109    pub fn is_focused(&self) -> bool {
110        self.focused
111    }
112
113    /// Focuses the current element.
114    pub fn focus_self(&mut self) {
115        self.commands.push(Command::Focus(self.node));
116    }
117
118    /// Focuses the element with the given id.
119    pub fn focus_id(&mut self, id: impl Into<ElementId>) {
120        self.commands.push(Command::FocusId(id.into()));
121    }
122
123    pub fn blur(&mut self) {
124        self.commands.push(Command::Blur);
125    }
126
127    pub fn focus_next(&mut self) {
128        self.commands.push(Command::FocusNext);
129    }
130
131    pub fn focus_prev(&mut self) {
132        self.commands.push(Command::FocusPrev);
133    }
134
135    /// Scrolls the nearest scrolling ancestors of the element with `id` so
136    /// that it becomes fully visible (keyboard navigation in long lists).
137    pub fn scroll_into_view(&mut self, id: impl Into<ElementId>) {
138        self.commands.push(Command::ScrollIntoView(id.into()));
139    }
140
141    /// Dispatches an action along the focus path after this event.
142    pub fn dispatch_action(&mut self, action: impl Action) {
143        self.commands
144            .push(Command::DispatchAction(Box::new(action)));
145    }
146
147    /// Requests a repaint of the current element (for state kept outside
148    /// signals, e.g. inside custom elements).
149    pub fn repaint(&mut self) {
150        self.commands.push(Command::Repaint(self.node));
151    }
152
153    /// Requests re-measuring/re-layout of the current element.
154    pub fn relayout(&mut self) {
155        self.commands.push(Command::Relayout(self.node));
156    }
157
158    pub fn read_clipboard(&mut self) -> Option<String> {
159        self.clipboard.read_text()
160    }
161
162    pub fn write_clipboard(&mut self, text: &str) {
163        self.clipboard.write_text(text);
164    }
165
166    pub fn text_system(&mut self) -> &mut TextSystem {
167        self.text
168    }
169
170    pub fn now(&self) -> Instant {
171        self.now
172    }
173
174    pub fn set_window_title(&mut self, title: impl Into<String>) {
175        self.commands
176            .push(Command::Window(WindowCommand::SetTitle(title.into())));
177    }
178
179    pub fn minimize_window(&mut self) {
180        self.commands.push(Command::Window(WindowCommand::Minimize));
181    }
182
183    pub fn toggle_maximize_window(&mut self) {
184        self.commands
185            .push(Command::Window(WindowCommand::ToggleMaximize));
186    }
187
188    pub fn close_window(&mut self) {
189        self.commands.push(Command::Window(WindowCommand::Close));
190    }
191
192    /// Exits the application.
193    pub fn quit(&mut self) {
194        self.commands.push(Command::Window(WindowCommand::Quit));
195    }
196}
197
198/// Context for measuring leaf content.
199pub struct MeasureCx<'a> {
200    pub text: &'a mut TextSystem,
201    pub scale: f32,
202}
203
204/// Context for painting. All public methods take *logical* coordinates in
205/// window space; conversion to device pixels, pixel snapping, transforms,
206/// clipping and group opacity are applied automatically.
207pub struct PaintCx<'a> {
208    pub(crate) scene: &'a mut Scene,
209    pub(crate) text: &'a mut TextSystem,
210    pub(crate) atlas: &'a mut Atlas,
211    pub(crate) scale: f32,
212    /// Accumulated transform in logical coordinates.
213    pub(crate) transform: Transform2D,
214    /// Clip in device pixels.
215    pub(crate) clip: ContentMask,
216    pub(crate) opacity: f32,
217    pub(crate) bounds: Bounds,
218    pub(crate) content_bounds: Bounds,
219    /// Resolved (possibly animating) corner radii of the element.
220    pub(crate) radii: Corners<f32>,
221    pub(crate) text_style: TextStyle,
222    pub(crate) text_color: Color,
223    pub(crate) now: Instant,
224    pub(crate) animating: &'a mut bool,
225    /// Earliest time this element asked to be repainted at.
226    pub(crate) wake_at: Option<Instant>,
227    pub(crate) focused: bool,
228    pub(crate) hovered: bool,
229}
230
231impl PaintCx<'_> {
232    /// The element's border box in window coordinates.
233    pub fn bounds(&self) -> Bounds {
234        self.bounds
235    }
236
237    /// The element's content box (inside border and padding).
238    pub fn content_bounds(&self) -> Bounds {
239        self.content_bounds
240    }
241
242    /// The element's resolved corner radii (logical px).
243    pub fn corner_radii(&self) -> Corners<f32> {
244        self.radii
245    }
246
247    pub fn scale_factor(&self) -> f32 {
248        self.scale
249    }
250
251    pub fn now(&self) -> Instant {
252        self.now
253    }
254
255    /// The inherited text style.
256    pub fn text_style(&self) -> &TextStyle {
257        &self.text_style
258    }
259
260    /// The inherited (possibly animating) text color.
261    pub fn text_color(&self) -> Color {
262        self.text_color
263    }
264
265    pub fn is_focused(&self) -> bool {
266        self.focused
267    }
268
269    pub fn is_hovered(&self) -> bool {
270        self.hovered
271    }
272
273    pub fn text_system(&mut self) -> &mut TextSystem {
274        self.text
275    }
276
277    /// Keeps frames coming (call every frame while animating).
278    pub fn request_animation_frame(&mut self) {
279        *self.animating = true;
280    }
281
282    /// Schedules a repaint at `at` without rendering every frame in between
283    /// (caret blinking, countdowns, delayed reveals).
284    pub fn request_frame_at(&mut self, at: Instant) {
285        self.wake_at = Some(self.wake_at.map_or(at, |w| w.min(at)));
286    }
287
288    pub(crate) fn draw_state(&self) -> DrawState {
289        let t = self.transform;
290        DrawState {
291            transform: Transform2D {
292                tx: t.tx * self.scale,
293                ty: t.ty * self.scale,
294                ..t
295            },
296            clip: self.clip,
297            opacity: self.opacity,
298        }
299    }
300
301    /// Converts logical bounds to device pixels, snapping edges to the pixel grid.
302    pub fn snap(&self, b: Bounds) -> Bounds {
303        let s = self.scale;
304        let x0 = (b.left() * s).round();
305        let y0 = (b.top() * s).round();
306        let x1 = (b.right() * s).round();
307        let y1 = (b.bottom() * s).round();
308        Bounds::new(Point::new(x0, y0), Size::new(x1 - x0, y1 - y0))
309    }
310
311    fn snap_width(&self, w: f32) -> f32 {
312        if w <= 0.0 {
313            0.0
314        } else {
315            (w * self.scale).round().max(1.0)
316        }
317    }
318
319    /// Paints a rounded rectangle with optional border.
320    pub fn paint_quad(
321        &mut self,
322        bounds: Bounds,
323        radii: Corners<f32>,
324        fill: impl Into<Fill>,
325        border_widths: Edges<f32>,
326        border_color: Color,
327    ) {
328        let quad = Quad {
329            bounds: self.snap(bounds),
330            radii: radii.scale(self.scale),
331            fill: fill.into(),
332            border_widths: border_widths.map(|w| self.snap_width(w)),
333            border_color,
334        };
335        let state = self.draw_state();
336        self.scene.push_quad(&quad, &state);
337    }
338
339    /// Fills a rectangle.
340    pub fn fill_rect(&mut self, bounds: Bounds, fill: impl Into<Fill>) {
341        self.paint_quad(bounds, Corners::ZERO, fill, Edges::ZERO, Color::TRANSPARENT);
342    }
343
344    /// Fills a rounded rectangle.
345    pub fn fill_rounded(&mut self, bounds: Bounds, radius: f32, fill: impl Into<Fill>) {
346        self.paint_quad(
347            bounds,
348            Corners::all(radius),
349            fill,
350            Edges::ZERO,
351            Color::TRANSPARENT,
352        );
353    }
354
355    pub fn paint_shadow(
356        &mut self,
357        bounds: Bounds,
358        radii: Corners<f32>,
359        shadow: &crate::style::BoxShadow,
360    ) {
361        let s = self.scale;
362        let shadow = Shadow {
363            bounds: self.snap(bounds),
364            radii: radii.scale(s),
365            color: shadow.color,
366            offset: shadow.offset.scale(s),
367            blur: shadow.blur * s,
368            spread: shadow.spread * s,
369            inset: shadow.inset,
370        };
371        let state = self.draw_state();
372        self.scene.push_shadow(&shadow, &state);
373    }
374
375    /// Paints laid out text with its top-left corner at `origin`.
376    pub fn paint_text(&mut self, layout: &TextLayout, origin: Point, color: Color) {
377        let state = self.draw_state();
378        let scene = &mut *self.scene;
379        let atlas = &mut *self.atlas;
380        let text = &mut *self.text;
381        let scale = self.scale;
382        // Snap the text origin to whole device pixels for crisp baselines.
383        let origin = Point::new(
384            (origin.x * scale).round() / scale,
385            (origin.y * scale).round() / scale,
386        );
387        layout.for_each_glyph(origin, scale, |glyph| {
388            let tile = atlas.get_or_insert_with(AtlasKey::Glyph(glyph.key), || {
389                text.rasterize(glyph.key).map(|r| AtlasImage {
390                    kind: if r.is_color {
391                        AtlasKind::Color
392                    } else {
393                        AtlasKind::Mono
394                    },
395                    width: r.width,
396                    height: r.height,
397                    data: Cow::Owned(r.data),
398                    origin: (r.left, -r.top),
399                })
400            });
401            let Some(tile) = tile else { return };
402            let b = Bounds::new(
403                Point::new(
404                    (glyph.x + tile.origin.0) as f32,
405                    (glyph.y + tile.origin.1) as f32,
406                ),
407                Size::new(tile.width as f32, tile.height as f32),
408            );
409            match tile.kind {
410                AtlasKind::Mono => {
411                    scene.push_mono_sprite(b, &tile, glyph.color.unwrap_or(color), &state)
412                }
413                AtlasKind::Color => scene.push_poly_sprite(b, &tile, Corners::ZERO, false, &state),
414            }
415        });
416    }
417
418    /// Paints a raster image stretched to `bounds`.
419    pub fn paint_image(
420        &mut self,
421        image: &ImageData,
422        bounds: Bounds,
423        radii: Corners<f32>,
424        grayscale: bool,
425    ) {
426        let tile = self
427            .atlas
428            .get_or_insert_with(AtlasKey::Image(image.id()), || {
429                Some(AtlasImage {
430                    kind: AtlasKind::Color,
431                    width: image.width(),
432                    height: image.height(),
433                    data: Cow::Borrowed(image.pixels()),
434                    origin: (0, 0),
435                })
436            });
437        if let Some(tile) = tile {
438            let b = self.snap(bounds);
439            let state = self.draw_state();
440            self.scene
441                .push_poly_sprite(b, &tile, radii.scale(self.scale), grayscale, &state);
442        }
443    }
444
445    /// Paints an SVG rasterized at the exact device size of `bounds`. With
446    /// `tint`, the SVG is used as a coverage mask filled with that color.
447    pub fn paint_svg(&mut self, svg: &SvgData, bounds: Bounds, tint: Option<Color>) {
448        let b = self.snap(bounds);
449        let (w, h) = (b.size.width.max(1.0) as u32, b.size.height.max(1.0) as u32);
450        let mono = tint.is_some();
451        let tile = self.atlas.get_or_insert_with(
452            AtlasKey::Vector {
453                id: svg.id(),
454                width: w,
455                height: h,
456                mono,
457            },
458            || {
459                let data = if mono {
460                    svg.rasterize_mask(w, h)?
461                } else {
462                    svg.rasterize(w, h)?
463                };
464                Some(AtlasImage {
465                    kind: if mono {
466                        AtlasKind::Mono
467                    } else {
468                        AtlasKind::Color
469                    },
470                    width: w,
471                    height: h,
472                    data: Cow::Owned(data),
473                    origin: (0, 0),
474                })
475            },
476        );
477        if let Some(tile) = tile {
478            let state = self.draw_state();
479            match tint {
480                Some(color) => self.scene.push_mono_sprite(b, &tile, color, &state),
481                None => self
482                    .scene
483                    .push_poly_sprite(b, &tile, Corners::ZERO, false, &state),
484            }
485        }
486    }
487
488    /// Frosted glass behind `bounds`.
489    pub fn paint_backdrop_blur(
490        &mut self,
491        bounds: Bounds,
492        radii: Corners<f32>,
493        blur: f32,
494        tint: Color,
495    ) {
496        let b = self.snap(bounds);
497        let state = self.draw_state();
498        self.scene
499            .push_backdrop_blur(b, radii.scale(self.scale), blur * self.scale, tint, &state);
500    }
501
502    /// Paints `bounds` (logical px) with a custom shader registered through
503    /// [`kova_native_render::register_shader`]. `params` arrive as
504    /// `input.params0`/`params1`, `time` as `input.time`, and the inherited
505    /// text color as `input.color`.
506    pub fn paint_shader(
507        &mut self,
508        shader: ShaderId,
509        bounds: Bounds,
510        radii: Corners<f32>,
511        params: [f32; 8],
512        time: f32,
513    ) {
514        let b = self.snap(bounds);
515        let state = self.draw_state();
516        self.scene.push_custom(
517            shader,
518            b,
519            radii.scale(self.scale),
520            params,
521            time,
522            self.text_color,
523            self.scale,
524            &state,
525        );
526    }
527
528    /// Starts an offscreen layer; pair with [`PaintCx::pop_layer`].
529    pub fn push_layer(&mut self) {
530        self.scene.push_layer();
531    }
532
533    /// Composites the innermost layer inside `bounds` (logical px) through
534    /// `mask`, following the current transform and clip.
535    pub fn pop_layer(&mut self, bounds: Bounds, mask: &crate::style::Mask) {
536        let b = self.snap(bounds);
537        let layer_mask = match mask {
538            crate::style::Mask::LinearGradient {
539                angle,
540                from,
541                to,
542                start,
543                end,
544            } => LayerMask::LinearGradient {
545                angle: *angle,
546                from: *from,
547                to: *to,
548                start: *start,
549                end: *end,
550            },
551            crate::style::Mask::Svg(svg) => {
552                let (w, h) = (b.size.width.max(1.0) as u32, b.size.height.max(1.0) as u32);
553                let tile = self.atlas.get_or_insert_with(
554                    AtlasKey::Vector {
555                        id: svg.id(),
556                        width: w,
557                        height: h,
558                        mono: true,
559                    },
560                    || {
561                        Some(AtlasImage {
562                            kind: AtlasKind::Mono,
563                            width: w,
564                            height: h,
565                            data: Cow::Owned(svg.rasterize_mask(w, h)?),
566                            origin: (0, 0),
567                        })
568                    },
569                );
570                match tile {
571                    Some(tile) => LayerMask::Tile(tile),
572                    None => LayerMask::None,
573                }
574            }
575            crate::style::Mask::Image(image) => {
576                let tile = self
577                    .atlas
578                    .get_or_insert_with(AtlasKey::Image(image.id()), || {
579                        Some(AtlasImage {
580                            kind: AtlasKind::Color,
581                            width: image.width(),
582                            height: image.height(),
583                            data: Cow::Borrowed(image.pixels()),
584                            origin: (0, 0),
585                        })
586                    });
587                match tile {
588                    Some(tile) => LayerMask::Tile(tile),
589                    None => LayerMask::None,
590                }
591            }
592        };
593        // Content inside the layer already carries the group opacity.
594        let state = DrawState {
595            opacity: 1.0,
596            ..self.draw_state()
597        };
598        self.scene.pop_layer(b, layer_mask, &state);
599    }
600
601    /// Runs `f` with an additional (rounded) clip in logical coordinates.
602    /// Only axis aligned clips are exact under rotation.
603    pub fn with_clip<R>(
604        &mut self,
605        bounds: Bounds,
606        radii: Corners<f32>,
607        f: impl FnOnce(&mut Self) -> R,
608    ) -> R {
609        let device = self.transform_bounds_to_device(bounds);
610        let mask = ContentMask::rounded(
611            device,
612            radii.scale(self.scale * self.transform.approx_scale()),
613        );
614        let previous = self.clip;
615        self.clip = previous.intersect(&mask);
616        let r = f(self);
617        self.clip = previous;
618        r
619    }
620
621    pub(crate) fn transform_bounds_to_device(&self, bounds: Bounds) -> Bounds {
622        let world = self.transform.apply_bounds(&bounds);
623        let s = self.scale;
624        let x0 = (world.left() * s).round();
625        let y0 = (world.top() * s).round();
626        let x1 = (world.right() * s).round();
627        let y1 = (world.bottom() * s).round();
628        Bounds::new(Point::new(x0, y0), Size::new(x1 - x0, y1 - y0))
629    }
630}