Skip to main content

bhoo/
lib.rs

1//! Bhoo: small, event-driven UI foundations for SpectreOS.
2//! Application values remain caller-owned. Coordinates are logical pixels.
3#[cfg(test)]
4extern crate self as bhoo;
5use unicode_segmentation::UnicodeSegmentation;
6use unicode_width::UnicodeWidthStr;
7
8pub mod icons;
9pub mod media;
10pub mod motion;
11pub mod platform;
12mod ripple;
13pub mod scroll;
14pub mod shapes;
15pub mod systems;
16pub mod timing;
17
18pub use icons::SystemIcon;
19pub use media::{Image, ImageFit};
20pub use scroll::EdgeStretch;
21pub use shapes::{beercss_shapes, shape_data};
22#[cfg(feature = "gles")]
23pub use glow;
24#[cfg(feature = "gles")]
25pub use platform::gles::{RenderStats as GlesRenderStats, Renderer as GlesRenderer};
26#[cfg(feature = "wayland")]
27pub use platform::window;
28
29// Backward-compatible top-level re-exports for Material widgets and Android compatibility.
30pub use systems::android::{
31    reference as android_reference,
32    state::{
33        calendar as android_calendar,
34        date_spinner as android_date_spinner,
35        dialer_filter as android_dialer_filter,
36        expandable_list as android_expandable_list,
37        number_picker as android_number_picker,
38        time_clock as android_time_clock,
39        time_spinner as android_time_spinner,
40    },
41    xml as android_xml,
42};
43pub use systems::material::{
44    ActionTileOptions, AlertOptions, AlertSeverity, AlertVariant, AppBarAction, AppBarIcon,
45    AutocompleteOptions, AvatarContent, AvatarGroupCounts, AvatarGroupOptions, AvatarShape,
46    BadgeContent, BadgeGravity, BadgeNumberFormat, BadgeNumberLimit, BadgeOptions, BannerOptions,
47    BottomAppBarOverflowState, BottomAppBarScrollBehavior, BottomAppBarState, ButtonGroupState,
48    ButtonVariant, CardIconGravity, CardOptions, CardVariant, CardVisualState, CarouselItem,
49    CarouselLayout, CarouselOptions, CarouselState, ChatMessage, CheckState, ChipKind,
50    ChipOptions, Choice, CommandItem, DatePickerOptions, DatePickerState, DatePickerView,
51    DockedToolbarEdge, DockedToolbarInsets, DockedToolbarScrollState, EmptyStateOptions,
52    ExpansionPanelOptions, FabColor, FabElevation, FabMenuAction, FabMenuOptions, FabMenuState,
53    FabOptions, FieldAffordance, FloatingPillSlot, FloatingToolbarExpansionScrollState,
54    GridListItem, GridListOptions, ListState, MaterialIcon, MenuTypeaheadState,
55    NavigationDestination, NavigationIcon, Options, OverlayDismissPolicy, OverlayKind,
56    OverlaySection, OverlayState, OverlayStyle, PageDirection, PageIndicatorOptions,
57    PaginationOptions, RouteTransitionKind, RouteTransitionState, ScaffoldAdaptiveOptions,
58    ScaffoldOptions, ScaffoldSlots, ScrollbarDragState, ScrollbarIndicatorState,
59    ScrollbarOrientation, SearchOverlayState, SelectState, ShapeRotationState, SkeletonAnimation,
60    SkeletonOptions, SlideDirection, SliderExpressiveOptions, SortDirection, SplitButtonOptions,
61    SplitButtonSize, SplitPaneOptions, SplitPaneOrientation, StepperState, SwipeDismissState,
62    SwitchIconMode, TabItem, TabOptions, TabStyle, TableColumn, TableSortState, TimePickerMode,
63    TimePickerOptions, TimePickerState, ToastOptions, ToastState, ToolbarAction,
64    ToolbarFabPosition, ToolbarFabSelection, ToolbarKind, ToolbarState, TopAppBarMaterialAction,
65    TopAppBarScrollBehavior, TopAppBarState, TopAppBarVariant, TreeItem, TreeState,
66    WindowFrameAction, WindowFrameOptions, WindowFrameState, hue_to_color, loading, month_days,
67    progress, pull_refresh, segmented_card_radii, snackbar, time_picker_label,
68    time_picker_label_24h, time_picker_label_step, weekday,
69};
70pub use loading::LoadingState;
71pub use progress::WavyProgressOptions;
72
73/// Direction of a decorative divider's long axis.
74#[derive(Clone, Copy, Debug, PartialEq, Eq)]
75pub enum DividerOrientation {
76    Horizontal,
77    Vertical,
78}
79/// Appearance and logical insets for a Material divider.
80#[derive(Clone, Copy, Debug)]
81pub struct DividerOptions {
82    pub orientation: DividerOrientation,
83    pub inset_start: f32,
84    pub inset_end: f32,
85    pub thickness: f32,
86    pub rtl: bool,
87    pub color: Option<Color>,
88}
89impl Default for DividerOptions {
90    fn default() -> Self {
91        Self { orientation: DividerOrientation::Horizontal, inset_start: 0.0, inset_end: 0.0, thickness: 1.0, rtl: false, color: None }
92    }
93}
94
95use motion::{Motion, Spring};
96pub use motion::{MotionPreference, MotionScheme};
97use std::{
98    collections::{HashMap, HashSet},
99    sync::Arc,
100};
101
102#[derive(Clone, Copy, Debug, Default, PartialEq)]
103pub struct Rect {
104    pub x: f32,
105    pub y: f32,
106    pub width: f32,
107    pub height: f32,
108}
109impl Rect {
110    pub fn contains(self, p: [f32; 2]) -> bool {
111        self.width > 0.0
112            && self.height > 0.0
113            && p[0] >= self.x
114            && p[0] < self.x + self.width
115            && p[1] >= self.y
116            && p[1] < self.y + self.height
117    }
118    pub fn intersect(self, other: Self) -> Self {
119        let x = self.x.max(other.x);
120        let y = self.y.max(other.y);
121        Self {
122            x,
123            y,
124            width: ((self.x + self.width).min(other.x + other.width) - x).max(0.0),
125            height: ((self.y + self.height).min(other.y + other.height) - y).max(0.0),
126        }
127    }
128    pub fn inset(self, padding: f32) -> Self {
129        Self {
130            x: self.x + padding,
131            y: self.y + padding,
132            width: (self.width - padding * 2.0).max(0.0),
133            height: (self.height - padding * 2.0).max(0.0),
134        }
135    }
136}
137
138#[derive(Clone, Copy, Debug, PartialEq, Eq)]
139pub struct Color(pub u8, pub u8, pub u8, pub u8);
140impl Color {
141    pub fn mix(self, other: Self, t: f32) -> Self {
142        let t = t.clamp(0.0, 1.0);
143        let lerp = |a: u8, b: u8| (a as f32 + (b as f32 - a as f32) * t).round() as u8;
144        Self(
145            lerp(self.0, other.0),
146            lerp(self.1, other.1),
147            lerp(self.2, other.2),
148            lerp(self.3, other.3),
149        )
150    }
151    pub fn opacity(self, opacity: f32) -> Self {
152        Self(
153            self.0,
154            self.1,
155            self.2,
156            (self.3 as f32 * opacity.clamp(0.0, 1.0)).round() as u8,
157        )
158    }
159}
160
161#[derive(Clone, Copy, Debug)]
162pub struct Theme {
163    pub background: Color,
164    pub text: Color,
165    pub control: Color,
166    pub hovered: Color,
167    pub pressed: Color,
168    pub radius: f32,
169    pub primary: Color,
170    pub on_primary: Color,
171    pub secondary: Color,
172    pub outline: Color,
173    pub error: Color,
174    pub on_error: Color,
175    pub on_secondary: Color,
176    pub secondary_container: Color,
177    pub on_secondary_container: Color,
178    pub surface_low: Color,
179    pub surface_high: Color,
180    pub surface_highest: Color,
181    pub outline_variant: Color,
182    pub primary_container: Color,
183    pub on_primary_container: Color,
184    pub tertiary_container: Color,
185    pub on_tertiary_container: Color,
186    pub inverse_surface: Color,
187    pub inverse_on_surface: Color,
188    pub inverse_primary: Color,
189    pub on_surface_variant: Color,
190    pub surface_variant: Color,
191}
192impl Default for Theme {
193    fn default() -> Self {
194        Self {
195            background: Color(18, 18, 22, 255),
196            text: Color(240, 240, 245, 255),
197            control: Color(42, 42, 50, 255),
198            hovered: Color(58, 58, 68, 255),
199            pressed: Color(76, 68, 100, 255),
200            radius: 8.0,
201            primary: Color(208, 188, 255, 255),
202            on_primary: Color(56, 30, 114, 255),
203            secondary: Color(74, 68, 88, 255),
204            outline: Color(147, 143, 153, 255),
205            error: Color(255, 180, 171, 255),
206            on_error: Color(105, 0, 5, 255),
207            on_secondary: Color(232, 222, 248, 255),
208            secondary_container: Color(74, 68, 88, 255),
209            on_secondary_container: Color(232, 222, 248, 255),
210            surface_low: Color(29, 27, 32, 255),
211            surface_high: Color(43, 41, 48, 255),
212            surface_highest: Color(54, 52, 59, 255),
213            outline_variant: Color(73, 69, 79, 255),
214            primary_container: Color(79, 55, 139, 255),
215            on_primary_container: Color(234, 221, 255, 255),
216            tertiary_container: Color(99, 59, 72, 255),
217            on_tertiary_container: Color(255, 216, 228, 255),
218            inverse_surface: Color(230, 225, 229, 255),
219            inverse_on_surface: Color(49, 48, 51, 255),
220            inverse_primary: Color(103, 80, 164, 255),
221            on_surface_variant: Color(202, 196, 208, 255),
222            surface_variant: Color(73, 69, 79, 255),
223        }
224    }
225}
226impl Theme {
227    /// Material Design 3 light theme preset (matching Bhoo's dark `Theme::default()`).
228    pub fn light() -> Self {
229        Self {
230            background: Color(250, 250, 248, 255),
231            text: Color(31, 35, 32, 255),
232            control: Color(238, 240, 235, 255),
233            hovered: Color(221, 231, 222, 255),
234            pressed: Color(200, 221, 206, 255),
235            radius: 8.0,
236            primary: Color(43, 106, 77, 255),
237            on_primary: Color(255, 255, 255, 255),
238            secondary: Color(220, 235, 224, 255),
239            outline: Color(121, 132, 123, 255),
240            error: Color(183, 57, 57, 255),
241            on_error: Color(255, 255, 255, 255),
242            on_secondary: Color(31, 53, 40, 255),
243            secondary_container: Color(220, 235, 224, 255),
244            on_secondary_container: Color(31, 53, 40, 255),
245            surface_low: Color(246, 246, 242, 255),
246            surface_high: Color(232, 235, 229, 255),
247            surface_highest: Color(226, 229, 221, 255),
248            outline_variant: Color(192, 201, 192, 255),
249            primary_container: Color(200, 235, 212, 255),
250            on_primary_container: Color(12, 55, 32, 255),
251            tertiary_container: Color(207, 231, 246, 255),
252            on_tertiary_container: Color(20, 53, 70, 255),
253            inverse_surface: Color(45, 49, 46, 255),
254            inverse_on_surface: Color(242, 243, 238, 255),
255            inverse_primary: Color(160, 210, 179, 255),
256            on_surface_variant: Color(70, 79, 72, 255),
257            surface_variant: Color(220, 229, 220, 255),
258        }
259    }
260
261    /// Linearly interpolate every color token and corner radius between `self` and `other`.
262    pub fn mix(self, other: Self, t: f32) -> Self {
263        let t = t.clamp(0.0, 1.0);
264        Self {
265            background: self.background.mix(other.background, t),
266            text: self.text.mix(other.text, t),
267            control: self.control.mix(other.control, t),
268            hovered: self.hovered.mix(other.hovered, t),
269            pressed: self.pressed.mix(other.pressed, t),
270            radius: self.radius + (other.radius - self.radius) * t,
271            primary: self.primary.mix(other.primary, t),
272            on_primary: self.on_primary.mix(other.on_primary, t),
273            secondary: self.secondary.mix(other.secondary, t),
274            outline: self.outline.mix(other.outline, t),
275            error: self.error.mix(other.error, t),
276            on_error: self.on_error.mix(other.on_error, t),
277            on_secondary: self.on_secondary.mix(other.on_secondary, t),
278            secondary_container: self.secondary_container.mix(other.secondary_container, t),
279            on_secondary_container: self.on_secondary_container.mix(other.on_secondary_container, t),
280            surface_low: self.surface_low.mix(other.surface_low, t),
281            surface_high: self.surface_high.mix(other.surface_high, t),
282            surface_highest: self.surface_highest.mix(other.surface_highest, t),
283            outline_variant: self.outline_variant.mix(other.outline_variant, t),
284            primary_container: self.primary_container.mix(other.primary_container, t),
285            on_primary_container: self.on_primary_container.mix(other.on_primary_container, t),
286            tertiary_container: self.tertiary_container.mix(other.tertiary_container, t),
287            on_tertiary_container: self.on_tertiary_container.mix(other.on_tertiary_container, t),
288            inverse_surface: self.inverse_surface.mix(other.inverse_surface, t),
289            inverse_on_surface: self.inverse_on_surface.mix(other.inverse_on_surface, t),
290            inverse_primary: self.inverse_primary.mix(other.inverse_primary, t),
291            on_surface_variant: self.on_surface_variant.mix(other.on_surface_variant, t),
292            surface_variant: self.surface_variant.mix(other.surface_variant, t),
293        }
294    }
295}
296
297#[derive(Clone, Copy, Debug, PartialEq, Eq)]
298pub enum Key {
299    Tab,
300    Enter,
301    Space,
302    Left,
303    Right,
304    Up,
305    Down,
306    Home,
307    End,
308    PageUp,
309    PageDown,
310    Character(char),
311    Escape,
312    Menu,
313}
314#[derive(Clone, Copy, Debug, PartialEq, Eq)]
315pub struct KeyInput {
316    pub key: Key,
317    pub pressed: bool,
318    pub repeat: bool,
319    pub shift: bool,
320}
321
322#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
323pub enum PointerKind {
324    #[default]
325    Mouse,
326    Touch,
327    Pen,
328}
329#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
330pub enum RippleStyle {
331    #[default]
332    MaterialWeb,
333    AngularMaterial,
334}
335
336/// One input snapshot. Press/release are edges, time is monotonic seconds.
337#[derive(Clone, Copy, Debug, Default)]
338pub struct Input {
339    pub pointer: Option<[f32; 2]>,
340    pub pointer_kind: PointerKind,
341    pub pressed: bool,
342    pub released: bool,
343    pub cancelled: bool,
344    pub blurred: bool,
345    pub key: Option<KeyInput>,
346    /// Logical pixel scroll delta, positive y scrolls down.
347    pub scroll: [f32; 2],
348    pub time: f64,
349}
350
351#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash)]
352pub enum FontFamily {
353    #[default]
354    Sans,
355    Serif,
356    Monospace,
357}
358
359#[derive(Clone, Copy, Debug, PartialEq)]
360pub struct TextStyle {
361    pub size: f32,
362    pub weight: u16,
363    /// 0 = start, 1 = center, 2 = end.
364    pub align: u8,
365    pub padding: f32,
366    pub letter_spacing: f32,
367    pub italic: bool,
368    pub family: FontFamily,
369}
370impl Default for TextStyle {
371    fn default() -> Self {
372        Self {
373            size: 16.0,
374            weight: 400,
375            align: 0,
376            padding: 0.0,
377            letter_spacing: 0.0,
378            italic: false,
379            family: FontFamily::Sans,
380        }
381    }
382}
383impl TextStyle {
384    pub const LABEL: Self = Self {
385        size: 14.0,
386        weight: 500,
387        align: 1,
388        padding: 16.0,
389        letter_spacing: 0.096,
390        italic: false,
391        family: FontFamily::Sans,
392    };
393}
394/// Backend-supplied normalized ASCII advances. Fixed storage; no per-frame font queries.
395#[derive(Clone, Copy, Debug)]
396pub struct TextMetrics {
397    pub normal: [f32; 95],
398    pub medium: [f32; 95],
399    /// Baseline displacement from the center of a text line, in em units.
400    pub normal_baseline_offset: f32,
401    pub medium_baseline_offset: f32,
402}
403impl Default for TextMetrics {
404    fn default() -> Self {
405        Self {
406            normal: [0.55; 95],
407            medium: [0.55; 95],
408            normal_baseline_offset: 0.3,
409            medium_baseline_offset: 0.3,
410        }
411    }
412}
413impl TextMetrics {
414    pub fn lines(
415        &self,
416        text: &str,
417        max_width: f32,
418        style: TextStyle,
419        mut line: impl FnMut(&str),
420    ) -> usize {
421        let mut start = 0;
422        let mut end = 0;
423        let mut width = 0.0;
424        let mut count = 0;
425        for word in text.split_whitespace() {
426            let offset = word.as_ptr() as usize - text.as_ptr() as usize;
427            let w = self.width(word, style);
428            let gap = if end > start {
429                self.width(&text[end..offset], style)
430            } else {
431                0.0
432            };
433            if end > start && (width + gap + w > max_width || text[end..offset].contains('\n')) {
434                line(&text[start..end]);
435                count += 1;
436                start = offset;
437                width = w;
438            } else {
439                if end == start {
440                    start = offset;
441                }
442                width += gap + w;
443            }
444            end = offset + word.len();
445        }
446        if end > start {
447            line(&text[start..end]);
448            count += 1;
449        } else if count == 0 {
450            line("");
451            count = 1;
452        }
453        count
454    }
455    pub fn width(&self, text: &str, style: TextStyle) -> f32 {
456        let advances = if style.weight >= 500 {
457            &self.medium
458        } else {
459            &self.normal
460        };
461        let mut count = 0;
462        let mut width = 0.0;
463        // ASCII is the common path. For other text use one fallback advance per
464        // grapheme, so combining marks and joined emoji are not counted twice.
465        let visible = |c:char| !c.is_control() && !matches!(c,'\u{00ad}'|'\u{200b}'|'\u{200c}'|'\u{200d}'|'\u{2060}'|'\u{feff}');
466        let mut add = |ch:char,wide:bool| {
467            let code = ch as usize;
468            width += if wide {
469                style.size
470            } else if (32..127).contains(&code) {
471                advances[code - 32] * style.size
472            } else {
473                style.size * 0.6
474            };
475            count += 1;
476        };
477        if text.is_ascii() {
478            for ch in text.chars().filter(|c|visible(*c)) {add(ch,false);}
479        } else {
480            for grapheme in text.graphemes(true) {
481                let columns=UnicodeWidthStr::width(grapheme);
482                if columns>0 && let Some(ch)=grapheme.chars().find(|c|visible(*c)) {add(ch,columns>=2);}
483            }
484        }
485        width + (count - 1).max(0) as f32 * style.letter_spacing
486    }
487}
488
489#[derive(Clone, Debug, PartialEq)]
490pub enum DrawCommand {
491    Clear(Color),
492    RoundedRect {
493        bounds: Rect,
494        radius: f32,
495        color: Color,
496    },
497    Ellipse { bounds: Rect, color: Color },
498    Outline { bounds: Rect, radius:f32, width:f32, color:Color },
499    Text {
500        bounds: Rect,
501        text: Arc<str>,
502        color: Color,
503        style: TextStyle,
504    },
505    Shadow {
506        bounds: Rect,
507        radius: f32,
508        offset: [f32; 2],
509        blur: f32,
510        spread: f32,
511        color: Color,
512    },
513    /// Soft radial ink, clipped to the control's rounded shape in every renderer.
514    Ripple {
515        bounds: Rect,
516        corner_radius: f32,
517        center: [f32; 2],
518        radius: f32,
519        color: Color,
520        soft: bool,
521    },
522    Loading {
523        bounds: Rect,
524        sample: loading::LoadingSample,
525        color: Color,
526    },
527    /// A caller-owned RGBA image with a normalized source crop.
528    Image {
529        bounds: Rect,
530        uv: [f32; 4],
531        radius: f32,
532        color: Color,
533        image: Image,
534    },
535    /// A static, tessellated Beer CSS shape.
536    Shape {
537        bounds: Rect,
538        index: u8,
539        color: Color,
540        rotation: f32,
541    },
542    Arc {
543        bounds: Rect,
544        start: f32,
545        sweep: f32,
546        stroke: f32,
547        color: Color,
548        rounded: bool,
549    },
550    Line {
551        from: [f32; 2],
552        to: [f32; 2],
553        width: f32,
554        color: Color,
555    },
556    /// A two- or three-point stroke with flat caps and a miter join.
557    Polyline {
558        points: [[f32; 2]; 3],
559        count: u8,
560        width: f32,
561        color: Color,
562    },
563    PushClip(Rect),
564    PopClip,
565    PushScaleY {
566        origin: f32,
567        scale: f32,
568    },
569    PopScaleY,
570    PushTransform {
571        origin: [f32; 2],
572        translate: [f32; 2],
573        scale: [f32; 2],
574        rotation_rad: f32,
575    },
576    PopTransform,
577    PushLayer {
578        bounds: Rect,
579        alpha: f32,
580    },
581    PopLayer,
582}
583
584/// Axis-aligned clip of the shape's square viewport after rotation.
585pub fn shape_clip_bounds(bounds: Rect, rotation: f32) -> Rect {
586    if rotation == 0.0 {
587        return bounds;
588    }
589    let size = bounds.width.min(bounds.height);
590    let (sin, cos) = rotation.sin_cos();
591    let extent = size * (sin.abs() + cos.abs());
592    Rect {
593        x: bounds.x + (bounds.width - extent) / 2.0,
594        y: bounds.y + (bounds.height - extent) / 2.0,
595        width: extent,
596        height: extent,
597    }
598}
599
600#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
601pub enum Role {
602    #[default]
603    Button,
604    Checkbox,
605    RadioGroup,
606    Radio,
607    Switch,
608    Slider,
609    TabList,
610    Tab,
611    ListBox,
612    ListItem,
613    Progress,
614    Tooltip,
615    Group,
616    TextField,
617    Menu,
618    MenuItem,
619    Link,
620    /// Momentary activation toggles a persistent on/off state.
621    ToggleButton,
622    /// Non-interactive polite status message for platform accessibility bridges.
623    Status,
624    /// Non-focusable modal dialog container and its descriptive text.
625    Dialog,
626    DialogDescription,
627    /// A carousel collection and an actionable item within it.
628    Carousel,
629    CarouselItem,
630}
631
632/// Backend-independent semantic snapshot. A native accessibility bridge is future work.
633#[derive(Clone, Debug)]
634pub struct SemanticNode {
635    pub id: u64,
636    pub part: u32,
637    pub role: Role,
638    pub label: Arc<str>,
639    pub bounds: Rect,
640    pub enabled: bool,
641    pub focused: bool,
642    pub selected: bool,
643    pub checked: Option<CheckState>,
644    pub invalid: bool,
645    pub filled: bool,
646    pub required: bool,
647    pub value: Option<f32>,
648    pub range: Option<[f32; 2]>,
649}
650
651#[derive(Clone, Copy, Debug, Default, PartialEq)]
652pub struct Response {
653    pub id: u64,
654    pub bounds: Rect,
655    pub hovered: bool,
656    pub pressed: bool,
657    pub clicked: bool,
658    pub focused: bool,
659    pub changed: bool,
660    pub enabled: bool,
661}
662
663#[derive(Clone, Copy, Debug, PartialEq, Eq)]
664enum Capture {
665    Pointer,
666    Keyboard,
667}
668
669struct CachedText {
670    text: Arc<str>,
671    seen: u64,
672}
673
674pub struct Ui {
675    pub theme: Theme,
676    pub text_metrics: TextMetrics,
677    /// Optional full render viewport, distinct from the padded content layout bounds.
678    pub viewport: Option<Rect>,
679    pub high_contrast: bool,
680    pub ripple_style: RippleStyle,
681    pub motion_preference: MotionPreference,
682    pub motion_scheme: MotionScheme,
683    active: Option<u64>,
684    capture: Capture,
685    focused: Option<u64>,
686    pending_focus: Option<u64>,
687    pending_focus_keyboard: bool,
688    keyboard_focus: bool,
689    focus_order: Vec<u64>,
690    next_focus_order: Vec<u64>,
691    part_focus: HashMap<u64, usize>,
692    scrolls: HashMap<u64, scroll::ScrollPhysics>,
693    checkbox_transitions: HashMap<u64, (CheckState, CheckState)>,
694    seen: HashSet<u64>,
695    motion: Motion,
696    ripples: ripple::Ripples,
697    pause_generation: u64,
698    overlay_active: bool,
699    tooltip_visible: bool,
700    tooltip_dismissed: Option<u64>,
701    tooltip_started: Option<(u64, f64)>,
702    tooltip_showing: Option<u64>,
703    semantics: Vec<SemanticNode>,
704    text_cache: HashMap<Arc<str>, CachedText>,
705    text_bytes: usize,
706    epoch: u64,
707    time: f64,
708    continuous: bool,
709    wakeup: Option<f64>,
710    hover: Option<u64>,
711    hover_start: f64,
712    overlays: Vec<DrawCommand>,
713}
714impl Default for Ui {
715    fn default() -> Self {
716        Self {
717            theme: Theme::default(),
718            text_metrics: TextMetrics::default(),
719            viewport: None,
720            high_contrast: false,
721            ripple_style: RippleStyle::default(),
722            motion_preference: MotionPreference::Full,
723            motion_scheme: MotionScheme::Standard,
724            active: None,
725            capture: Capture::Pointer,
726            focused: None,
727            pending_focus: None,
728            pending_focus_keyboard: false,
729            keyboard_focus: false,
730            focus_order: Vec::new(),
731            next_focus_order: Vec::new(),
732            part_focus: HashMap::new(),
733            scrolls: HashMap::new(),
734            checkbox_transitions: HashMap::new(),
735            seen: HashSet::new(),
736            motion: Motion::default(),
737            ripples: ripple::Ripples::default(),
738            pause_generation: 0,
739            overlay_active: false,
740            tooltip_visible: false,
741            tooltip_dismissed: None,
742            tooltip_started: None,
743            tooltip_showing: None,
744            semantics: Vec::new(),
745            text_cache: HashMap::new(),
746            text_bytes: 0,
747            epoch: 0,
748            time: 0.0,
749            continuous: false,
750            wakeup: None,
751            hover: None,
752            hover_start: 0.0,
753            overlays: Vec::new(),
754        }
755    }
756}
757impl Ui {
758    pub fn needs_redraw(&self) -> bool {
759        self.continuous || self.motion.is_animating()
760    }
761    pub fn next_wakeup(&self) -> Option<f64> {
762        self.wakeup
763    }
764    pub fn semantics(&self) -> &[SemanticNode] {
765        &self.semantics
766    }
767    pub fn pause_animations(&mut self) {
768        self.pause_generation = self.pause_generation.wrapping_add(1);
769        self.motion.pause_clocks();
770        self.ripples.pause();
771        self.tooltip_started = None;
772        self.tooltip_showing = None;
773        self.active = None;
774        self.pending_focus = None;
775        self.wakeup = None;
776        self.continuous = false;
777    }
778    pub fn has_escape_target(&self) -> bool {
779        self.overlay_active || self.tooltip_visible || self.active.is_some()
780    }
781    pub fn focused(&self) -> Option<u64> {
782        self.focused
783    }
784    /// Transfer focus from a host editing adapter to an enabled control from the last frame.
785    pub fn adapter_focus(&mut self, id: Option<u64>) {
786        self.focused = id.filter(|id| self.focus_order.contains(id));
787        self.keyboard_focus = false;
788    }
789    /// Transfer focus from a keyboard or assistive-technology control, retaining
790    /// the visible keyboard focus treatment. Unknown or disabled IDs clear focus.
791    pub fn accessibility_focus(&mut self, id: Option<u64>) {
792        self.focused = id.filter(|id| self.focus_order.contains(id));
793        self.keyboard_focus = self.focused.is_some();
794    }
795    pub fn cached_text_bytes(&self) -> usize {
796        self.text_bytes
797    }
798    pub fn retained_motion_properties(&self) -> usize {
799        self.motion.retained_properties()
800    }
801    pub fn frame(
802        &mut self,
803        input: Input,
804        bounds: Rect,
805        gap: f32,
806        build: impl FnOnce(&mut Frame<'_>),
807    ) -> Vec<DrawCommand> {
808        let mut commands = Vec::new();
809        self.frame_into(input, bounds, gap, &mut commands, build);
810        commands
811    }
812    pub fn frame_into(
813        &mut self,
814        input: Input,
815        bounds: Rect,
816        gap: f32,
817        commands: &mut Vec<DrawCommand>,
818        build: impl FnOnce(&mut Frame<'_>),
819    ) {
820        self.epoch = self.epoch.wrapping_add(1);
821        if input.time.is_finite() {
822            self.time = input.time.max(self.time);
823        }
824        self.motion.begin(self.time, self.motion_preference);
825        self.ripples.begin();
826        self.continuous = false;
827        self.wakeup = None;
828        self.semantics.clear();
829        self.seen.clear();
830        self.next_focus_order.clear();
831        self.overlays.clear();
832        self.overlay_active = false;
833        self.tooltip_visible = false;
834        commands.clear();
835        if input.cancelled || input.blurred {
836            self.active = None;
837        }
838        if input.blurred {
839            self.pending_focus = None;
840            self.focused = None;
841            self.keyboard_focus = false;
842        }
843        if let Some(key) = input.key
844            && key.key == Key::Tab
845            && key.pressed
846        {
847            self.active = None;
848            self.keyboard_focus = true;
849            let len = self.focus_order.len();
850            if len > 0 {
851                let previous = self
852                    .focused
853                    .and_then(|id| self.focus_order.iter().position(|x| *x == id));
854                let index = match (previous, key.shift) {
855                    (Some(i), false) => (i + 1) % len,
856                    (Some(i), true) => (i + len - 1) % len,
857                    (None, false) => 0,
858                    (None, true) => len - 1,
859                };
860                self.focused = Some(self.focus_order[index]);
861            }
862        }
863        let clip = self.viewport.unwrap_or(bounds);
864        let mut frame = Frame {
865            ui: self,
866            input,
867            bounds,
868            clip,
869            cursor: bounds.y,
870            gap: gap.max(0.0),
871            commands: std::mem::take(commands),
872            enabled: true,
873            key_consumed: false,
874            feedback_blocked: false,
875            overlay_phase: None,
876            overlay_nested_scroll: 0.0,
877            content_color: None,
878        };
879        frame
880            .commands
881            .push(DrawCommand::Clear(frame.ui.theme.background));
882        build(&mut frame);
883        if input.released
884            || input.cancelled
885            || input.blurred
886            || frame
887                .ui
888                .active
889                .is_some_and(|id| !frame.ui.seen.contains(&id))
890        {
891            frame.ui.active = None;
892        }
893        if let Some(id) = frame.ui.pending_focus {
894            if frame.ui.next_focus_order.contains(&id) {
895                frame.ui.focused = Some(id);
896                frame.ui.keyboard_focus = frame.ui.pending_focus_keyboard;
897                frame.ui.pending_focus = None;
898                for node in &mut frame.ui.semantics {
899                    node.focused = node.id == id && node.enabled;
900                }
901                frame.ui.continuous = true;
902            } else if !frame.ui.seen.contains(&id) {
903                frame.ui.pending_focus = None;
904            }
905        }
906        if frame
907            .ui
908            .focused
909            .is_some_and(|id| !frame.ui.next_focus_order.contains(&id))
910        {
911            frame.ui.focused = None;
912        }
913        if frame
914            .ui
915            .hover
916            .is_some_and(|id| !frame.ui.seen.contains(&id))
917        {
918            frame.ui.hover = None;
919        }
920        if frame
921            .ui
922            .tooltip_dismissed
923            .is_some_and(|id| !frame.ui.seen.contains(&id))
924        {
925            frame.ui.tooltip_dismissed = None;
926        }
927        if frame
928            .ui
929            .tooltip_started
930            .is_some_and(|(id, _)| !frame.ui.seen.contains(&id))
931        {
932            frame.ui.tooltip_started = None;
933            frame.ui.tooltip_showing = None;
934        }
935        frame.ui.motion.finish();
936        frame.ui.ripples.finish();
937        frame
938            .ui
939            .part_focus
940            .retain(|id, _| frame.ui.seen.contains(id));
941        frame
942            .ui
943            .checkbox_transitions
944            .retain(|id, _| frame.ui.seen.contains(id));
945        frame.commands.append(&mut frame.ui.overlays);
946        *commands = frame.commands;
947        std::mem::swap(&mut frame.ui.focus_order, &mut frame.ui.next_focus_order);
948        // Reclaim unused labels at a low frequency. Cache insertions are hard-bounded.
949        if frame.ui.epoch.is_multiple_of(60) {
950            let epoch = frame.ui.epoch;
951            frame.ui.text_cache.retain(|_, value| value.seen == epoch);
952            frame.ui.text_bytes = frame.ui.text_cache.keys().map(|s| s.len()).sum();
953        }
954    }
955    fn text(&mut self, text: &str) -> Arc<str> {
956        if let Some(cached) = self.text_cache.get_mut(text) {
957            cached.seen = self.epoch;
958            return Arc::clone(&cached.text);
959        }
960        let value: Arc<str> = Arc::from(text);
961        if self.text_cache.len() < 1024 && self.text_bytes.saturating_add(text.len()) <= 128 * 1024
962        {
963            self.text_bytes += text.len();
964            self.text_cache.insert(
965                Arc::clone(&value),
966                CachedText {
967                    text: Arc::clone(&value),
968                    seen: self.epoch,
969                },
970            );
971        }
972        value
973    }
974}
975
976pub struct Frame<'a> {
977    ui: &'a mut Ui,
978    input: Input,
979    bounds: Rect,
980    clip: Rect,
981    cursor: f32,
982    gap: f32,
983    commands: Vec<DrawCommand>,
984    enabled: bool,
985    key_consumed: bool,
986    feedback_blocked: bool,
987    overlay_phase: Option<systems::material::OverlayPhase>,
988    overlay_nested_scroll: f32,
989    content_color: Option<Color>,
990}
991impl Frame<'_> {
992    pub fn theme(&self) -> Theme {
993        self.ui.theme
994    }
995    pub fn input(&self) -> Input {
996        self.input
997    }
998    pub fn clear(&mut self, color: Color) {
999        self.commands.push(DrawCommand::Clear(color));
1000    }
1001    pub fn available(&self) -> Rect {
1002        Rect {
1003            y: self.cursor,
1004            height: (self.bounds.y + self.bounds.height - self.cursor).max(0.0),
1005            ..self.bounds
1006        }
1007    }
1008    pub fn with_enabled(&mut self, enabled: bool, build: impl FnOnce(&mut Self)) {
1009        let previous = self.enabled;
1010        self.enabled &= enabled;
1011        build(self);
1012        self.enabled = previous;
1013    }
1014    fn allocate(&mut self, height: f32) -> Rect {
1015        let bounds = Rect {
1016            x: self.bounds.x,
1017            y: self.cursor,
1018            width: self.bounds.width.max(0.0),
1019            height: height
1020                .min((self.bounds.y + self.bounds.height - self.cursor).max(0.0))
1021                .max(0.0),
1022        };
1023        self.cursor += height + self.gap;
1024        bounds
1025    }
1026    fn rect(&mut self, bounds: Rect, radius: f32, color: Color) {
1027        self.commands.push(DrawCommand::RoundedRect {
1028            bounds,
1029            radius,
1030            color,
1031        });
1032    }
1033    fn text_at(&mut self, bounds: Rect, text: &str, color: Color) {
1034        self.styled_text(bounds, text, color, TextStyle::default());
1035    }
1036    pub fn styled_text(&mut self, bounds: Rect, text: &str, color: Color, style: TextStyle) {
1037        let text = self.ui.text(text);
1038        self.commands.push(DrawCommand::Text {
1039            bounds,
1040            text,
1041            color,
1042            style,
1043        });
1044    }
1045    pub fn text_width(&self, text: &str, style: TextStyle) -> f32 {
1046        self.ui.text_metrics.width(text, style)
1047    }
1048    pub fn shadow(
1049        &mut self,
1050        bounds: Rect,
1051        radius: f32,
1052        offset: [f32; 2],
1053        blur: f32,
1054        spread: f32,
1055        color: Color,
1056    ) {
1057        self.commands.push(DrawCommand::Shadow {
1058            bounds,
1059            radius,
1060            offset,
1061            blur,
1062            spread,
1063            color,
1064        });
1065    }
1066    pub fn push_transform(
1067        &mut self,
1068        origin: [f32; 2],
1069        translate: [f32; 2],
1070        scale: [f32; 2],
1071        rotation_rad: f32,
1072    ) {
1073        self.commands.push(DrawCommand::PushTransform {
1074            origin,
1075            translate,
1076            scale,
1077            rotation_rad,
1078        });
1079    }
1080    pub fn pop_transform(&mut self) {
1081        self.commands.push(DrawCommand::PopTransform);
1082    }
1083    pub fn push_layer(&mut self, bounds: Rect, alpha: f32) {
1084        self.commands.push(DrawCommand::PushLayer {
1085            bounds,
1086            alpha: alpha.clamp(0.0, 1.0),
1087        });
1088    }
1089    pub fn pop_layer(&mut self) {
1090        self.commands.push(DrawCommand::PopLayer);
1091    }
1092    fn animate(&mut self, id: u64, property: u8, target: f32, initial: f32) -> f32 {
1093        self.ui
1094            .motion
1095            .effect(id, property, target, initial, Spring::EFFECTS)
1096    }
1097    fn animate_geometry(&mut self, id: u64, property: u8, target: f32, initial: f32) -> f32 {
1098        self.ui.motion.effect(
1099            id,
1100            property,
1101            target,
1102            initial,
1103            self.ui.motion_scheme.fast_spatial(),
1104        )
1105    }
1106    fn interact(&mut self, id: u64, bounds: Rect, enabled: bool) -> Response {
1107        assert!(
1108            self.ui.seen.insert(id),
1109            "Bhoo widget IDs must be unique within a frame: {id}"
1110        );
1111        let hit = bounds.intersect(self.clip);
1112        let enabled = enabled && self.enabled && hit.width > 0.0 && hit.height > 0.0;
1113        if enabled {
1114            self.ui.next_focus_order.push(id);
1115        } else {
1116            if self.ui.active == Some(id) {
1117                self.ui.active = None;
1118            }
1119            if self.ui.focused == Some(id) {
1120                self.ui.focused = None;
1121            }
1122        }
1123        let hovered = enabled && self.input.pointer.is_some_and(|p| hit.contains(p));
1124        if hovered && self.ui.hover != Some(id) {
1125            self.ui.hover = Some(id);
1126            self.ui.hover_start = self.ui.time;
1127        }
1128        if self.ui.hover == Some(id) && !hovered {
1129            self.ui.hover = None;
1130        }
1131        let mut clicked = false;
1132        if enabled && !self.input.cancelled && !self.input.blurred {
1133            if hovered && self.input.pressed && self.ui.active.is_none() {
1134                self.ui.active = Some(id);
1135                self.ui.capture = Capture::Pointer;
1136                self.ui.focused = Some(id);
1137                self.ui.keyboard_focus = false;
1138            }
1139            if self.ui.active == Some(id)
1140                && self.ui.capture == Capture::Pointer
1141                && self.input.released
1142            {
1143                clicked = hovered;
1144            }
1145            if self.ui.focused == Some(id)
1146                && !self.key_consumed
1147                && let Some(key) = self.input.key
1148            {
1149                match (key.key, key.pressed, key.repeat) {
1150                    (Key::Enter, true, false) => {
1151                        clicked = true;
1152                        self.key_consumed = true;
1153                    }
1154                    (Key::Space, true, false) => {
1155                        self.ui.active = Some(id);
1156                        self.ui.capture = Capture::Keyboard;
1157                        self.key_consumed = true;
1158                    }
1159                    (Key::Space, false, _)
1160                        if self.ui.active == Some(id) && self.ui.capture == Capture::Keyboard =>
1161                    {
1162                        clicked = true;
1163                        self.ui.active = None;
1164                        self.key_consumed = true;
1165                    }
1166                    (Key::Escape, true, _) => {
1167                        self.ui.active = None;
1168                        self.key_consumed = true;
1169                    }
1170                    _ => {}
1171                }
1172            }
1173        }
1174        if clicked {
1175            self.ui.continuous = true;
1176        }
1177        Response {
1178            id,
1179            bounds,
1180            hovered: hovered && self.input.pointer_kind != PointerKind::Touch,
1181            pressed: enabled
1182                && self.ui.active == Some(id)
1183                && !self.input.released
1184                && !self.input.cancelled,
1185            clicked,
1186            focused: enabled && !self.feedback_blocked && self.ui.focused == Some(id),
1187            changed: false,
1188            enabled,
1189        }
1190    }
1191    #[allow(clippy::too_many_arguments)]
1192    fn semantic(
1193        &mut self,
1194        response: Response,
1195        role: Role,
1196        label: &str,
1197        selected: bool,
1198        checked: Option<CheckState>,
1199        value: Option<f32>,
1200        range: Option<[f32; 2]>,
1201    ) {
1202        let label = self.ui.text(label);
1203        self.ui.semantics.push(SemanticNode {
1204            id: response.id,
1205            part: 0,
1206            role,
1207            label,
1208            bounds: response.bounds.intersect(self.clip),
1209            enabled: response.enabled,
1210            focused: response.focused,
1211            selected,
1212            checked,
1213            invalid: false,
1214            filled: false,
1215            required: false,
1216            value,
1217            range,
1218        });
1219    }
1220    /// Paint the shared keyboard focus indicator for a custom semantic target.
1221    pub fn focus_ring(&mut self, response: Response) {
1222        if !self.ui.high_contrast {
1223            return;
1224        }
1225        let visible = response.focused && self.ui.keyboard_focus;
1226        let alpha = self.animate(response.id, 2, f32::from(visible), f32::from(visible));
1227        if alpha > 0.001 {
1228            let b = response.bounds;
1229            let c = self.ui.theme.primary.opacity(alpha);
1230            for r in [
1231                Rect {
1232                    x: b.x,
1233                    y: b.y,
1234                    width: b.width,
1235                    height: 2.0,
1236                },
1237                Rect {
1238                    x: b.x,
1239                    y: b.y + b.height - 2.0,
1240                    width: b.width,
1241                    height: 2.0,
1242                },
1243                Rect {
1244                    x: b.x,
1245                    y: b.y,
1246                    width: 2.0,
1247                    height: b.height,
1248                },
1249                Rect {
1250                    x: b.x + b.width - 2.0,
1251                    y: b.y,
1252                    width: 2.0,
1253                    height: b.height,
1254                },
1255            ] {
1256                self.rect(r, 1.0, c);
1257            }
1258        }
1259    }
1260    /// Material ink is a draw operation, not a second input target.
1261    fn ink(&mut self, r: Response, corner_radius: f32, color: Color) {
1262        self.ink_part(r, 0, corner_radius, color, true);
1263    }
1264    fn ink_part(
1265        &mut self,
1266        r: Response,
1267        part: u32,
1268        corner_radius: f32,
1269        color: Color,
1270        allow_label: bool,
1271    ) {
1272        let visible = r.bounds.intersect(self.clip);
1273        if !r.enabled
1274            || self.ui.motion_preference == MotionPreference::Reduced
1275            || self.input.blurred
1276            || visible.width <= 0.0
1277            || visible.height <= 0.0
1278        {
1279            self.ui.ripples.clear((r.id, part));
1280            return;
1281        }
1282        let keyboard = r.focused
1283            && self.input.key.is_some_and(|k| {
1284                k.pressed && !k.repeat && matches!(k.key, Key::Space | Key::Enter)
1285            });
1286        let pointer = self.input.pressed
1287            && r.pressed
1288            && self.ui.capture == Capture::Pointer
1289            && (allow_label || self.input.pointer.is_some_and(|p| r.bounds.contains(p)));
1290        let origin = if pointer {
1291            self.input.pointer.map(|p| {
1292                if r.bounds.contains(p) {
1293                    [
1294                        (p[0] - r.bounds.x) / r.bounds.width.max(1.0),
1295                        (p[1] - r.bounds.y) / r.bounds.height.max(1.0),
1296                    ]
1297                } else {
1298                    [0.5; 2]
1299                }
1300            })
1301        } else if keyboard {
1302            Some([0.5; 2])
1303        } else {
1304            None
1305        };
1306        let held = r.pressed && !self.input.cancelled;
1307        if self.input.cancelled {
1308            self.ui.ripples.cancel_pending((r.id, part), self.ui.time);
1309        }
1310        if let Some(sample) = self.ui.ripples.sample_with_style(
1311            (r.id, part),
1312            self.ui.time,
1313            origin,
1314            held,
1315            pointer && self.input.pointer_kind == PointerKind::Touch,
1316            self.ui.ripple_style,
1317        ) {
1318            self.ui.continuous |= sample.moving;
1319            if let Some(wake) = sample.wake {
1320                self.ui.wakeup = Some(self.ui.wakeup.map_or(wake, |old| old.min(wake)));
1321            }
1322            let b = r.bounds;
1323            let max = b.width.max(b.height);
1324            let initial = (max * 0.2).floor().max(1.0);
1325            let diameter = b.width.hypot(b.height) + 10.0 + (max * 0.35).max(75.0);
1326            let mut radius = (initial + (diameter - initial) * sample.growth) * 0.5;
1327            let start = [
1328                b.x + sample.origin[0] * b.width,
1329                b.y + sample.origin[1] * b.height,
1330            ];
1331            let mut center = [
1332                start[0] + (b.x + b.width * 0.5 - start[0]) * sample.growth,
1333                start[1] + (b.y + b.height * 0.5 - start[1]) * sample.growth,
1334            ];
1335            let angular = sample.style == RippleStyle::AngularMaterial;
1336            if angular {
1337                center = start;
1338                radius = (b.width * sample.origin[0].max(1.0 - sample.origin[0]))
1339                    .hypot(b.height * sample.origin[1].max(1.0 - sample.origin[1]))
1340                    * sample.growth;
1341            }
1342            if sample.opacity > 0.0 {
1343                self.commands.push(DrawCommand::Ripple {
1344                    bounds: b,
1345                    corner_radius,
1346                    center,
1347                    radius,
1348                    color: color.opacity(0.12 * sample.opacity),
1349                    soft: !angular,
1350                });
1351            }
1352        }
1353    }
1354    fn key_for(&mut self, response: Response) -> Option<Key> {
1355        if response.enabled
1356            && response.focused
1357            && !self.key_consumed
1358            && let Some(key) = self.input.key
1359            && key.pressed
1360        {
1361            self.key_consumed = true;
1362            return Some(key.key);
1363        }
1364        None
1365    }
1366    pub fn label(&mut self, text: impl AsRef<str>) {
1367        let text = text.as_ref();
1368        let style = TextStyle::default();
1369        let metrics = self.ui.text_metrics;
1370        let width = self.bounds.width;
1371        let count = metrics.lines(text, width, style, |_| {}).max(1);
1372        let height = (count as f32 * 24.0).max(28.0);
1373        let b = self.allocate(height);
1374        let mut index = 0;
1375        metrics.lines(text, width, style, |line| {
1376            let y = b.y + (height - count as f32 * 24.0) * 0.5 + index as f32 * 24.0;
1377            self.styled_text(
1378                Rect {
1379                    y,
1380                    height: 24.0,
1381                    ..b
1382                },
1383                line,
1384                self.content_color.unwrap_or(self.ui.theme.text),
1385                style,
1386            );
1387            index += 1;
1388        });
1389    }
1390}
1391
1392#[cfg(test)]
1393#[path = "lib.spec.rs"]
1394mod tests;