1#[cfg(test)]
4extern crate self as bhoo;
5use unicode_segmentation::UnicodeSegmentation;
6use unicode_width::UnicodeWidthStr;
7
8pub mod crop;
9pub mod icons;
10pub mod media;
11pub mod monet;
12pub mod motion;
13pub mod platform;
14pub mod projective;
15pub mod reorder;
16mod ripple;
17pub mod scroll;
18pub mod shapes;
19pub mod systems;
20pub mod timing;
21
22pub use crop::{CropUpdate, CropViewportState};
23#[cfg(feature = "gles")]
24pub use glow;
25pub use icons::SystemIcon;
26pub use media::{Image, ImageFit};
27pub use monet::{MonetScheme, MonetStyle, WallpaperColors};
28#[cfg(feature = "gles")]
29pub use platform::gles::{RenderStats as GlesRenderStats, Renderer as GlesRenderer};
30#[cfg(feature = "wayland")]
31pub use platform::window;
32pub use scroll::EdgeStretch;
33pub use shapes::{beercss_shapes, shape_data};
34
35pub use loading::LoadingState;
37pub use progress::WavyProgressOptions;
38pub use systems::android::{
39 reference as android_reference,
40 state::{
41 calendar as android_calendar, date_spinner as android_date_spinner,
42 dialer_filter as android_dialer_filter, expandable_list as android_expandable_list,
43 number_picker as android_number_picker, time_clock as android_time_clock,
44 time_spinner as android_time_spinner,
45 },
46 xml as android_xml,
47};
48pub use systems::material::{
49 ActionTileOptions, AlertOptions, AlertSeverity, AlertVariant, AppBarAction, AppBarIcon,
50 AutocompleteOptions, AvatarContent, AvatarGroupCounts, AvatarGroupOptions, AvatarShape,
51 BadgeContent, BadgeGravity, BadgeNumberFormat, BadgeNumberLimit, BadgeOptions, BannerOptions,
52 BottomAppBarOverflowState, BottomAppBarScrollBehavior, BottomAppBarState, ButtonGroupState,
53 ButtonVariant, CardIconGravity, CardOptions, CardVariant, CardVisualState, CarouselItem,
54 CarouselLayout, CarouselOptions, CarouselState, ChatMessage, CheckState, ChipKind, ChipOptions,
55 Choice, CommandItem, DatePickerOptions, DatePickerState, DatePickerView, DockedToolbarEdge,
56 DockedToolbarInsets, DockedToolbarScrollState, EmptyStateOptions, ExpansionPanelOptions,
57 FabColor, FabElevation, FabMenuAction, FabMenuOptions, FabMenuState, FabOptions,
58 FieldAffordance, FloatingPillSlot, FloatingToolbarExpansionScrollState, GridListItem,
59 GridListOptions, ListState, MaterialIcon, MenuTypeaheadState, NavigationDestination,
60 NavigationIcon, Options, OverlayDismissPolicy, OverlayKind, OverlaySection, OverlayState,
61 OverlayStyle, PageDirection, PageIndicatorOptions, PaginationOptions, RouteTransitionKind,
62 RouteTransitionState, ScaffoldAdaptiveOptions, ScaffoldOptions, ScaffoldSlots,
63 ScrollbarDragState, ScrollbarIndicatorState, ScrollbarOrientation, SearchOverlayState,
64 SelectState, SelectionDismiss, ShapeRotationState, SkeletonAnimation, SkeletonOptions,
65 SlideDirection, SliderExpressiveOptions, SortDirection, SplitButtonOptions, SplitButtonSize,
66 SplitPaneOptions, SplitPaneOrientation, StepperState, SwipeDismissState, SwitchIconMode,
67 TabItem, TabOptions, TabStyle, TableColumn, TableSortState, TimePickerMode, TimePickerOptions,
68 TimePickerState, ToastOptions, ToastState, ToolbarAction, ToolbarFabPosition,
69 ToolbarFabSelection, ToolbarKind, ToolbarState, TopAppBarMaterialAction,
70 TopAppBarScrollBehavior, TopAppBarState, TopAppBarVariant, TreeItem, TreeState,
71 WindowFrameAction, WindowFrameOptions, WindowFrameState, container_transform_rect,
72 hue_to_color, loading, month_days, progress, pull_refresh, segmented_card_radii, snackbar,
73 time_picker_label, time_picker_label_24h, time_picker_label_step, weekday,
74};
75
76#[derive(Clone, Copy, Debug, PartialEq, Eq)]
78pub enum DividerOrientation {
79 Horizontal,
80 Vertical,
81}
82#[derive(Clone, Copy, Debug)]
84pub struct DividerOptions {
85 pub orientation: DividerOrientation,
86 pub inset_start: f32,
87 pub inset_end: f32,
88 pub thickness: f32,
89 pub rtl: bool,
90 pub color: Option<Color>,
91}
92impl Default for DividerOptions {
93 fn default() -> Self {
94 Self {
95 orientation: DividerOrientation::Horizontal,
96 inset_start: 0.0,
97 inset_end: 0.0,
98 thickness: 1.0,
99 rtl: false,
100 color: None,
101 }
102 }
103}
104
105use motion::{Motion, Spring};
106pub use motion::{MotionPreference, MotionScheme};
107use std::{
108 collections::{HashMap, HashSet},
109 sync::Arc,
110};
111
112#[derive(Clone, Copy, Debug, Default, PartialEq)]
113pub struct Rect {
114 pub x: f32,
115 pub y: f32,
116 pub width: f32,
117 pub height: f32,
118}
119impl Rect {
120 pub fn contains(self, p: [f32; 2]) -> bool {
121 self.width > 0.0
122 && self.height > 0.0
123 && p[0] >= self.x
124 && p[0] < self.x + self.width
125 && p[1] >= self.y
126 && p[1] < self.y + self.height
127 }
128 pub fn intersect(self, other: Self) -> Self {
129 let x = self.x.max(other.x);
130 let y = self.y.max(other.y);
131 Self {
132 x,
133 y,
134 width: ((self.x + self.width).min(other.x + other.width) - x).max(0.0),
135 height: ((self.y + self.height).min(other.y + other.height) - y).max(0.0),
136 }
137 }
138 pub fn inset(self, padding: f32) -> Self {
139 Self {
140 x: self.x + padding,
141 y: self.y + padding,
142 width: (self.width - padding * 2.0).max(0.0),
143 height: (self.height - padding * 2.0).max(0.0),
144 }
145 }
146}
147
148#[derive(Clone, Copy, Debug, PartialEq, Eq)]
149pub struct Color(pub u8, pub u8, pub u8, pub u8);
150impl Color {
151 pub fn mix(self, other: Self, t: f32) -> Self {
152 let t = t.clamp(0.0, 1.0);
153 let lerp = |a: u8, b: u8| (a as f32 + (b as f32 - a as f32) * t).round() as u8;
154 Self(
155 lerp(self.0, other.0),
156 lerp(self.1, other.1),
157 lerp(self.2, other.2),
158 lerp(self.3, other.3),
159 )
160 }
161 pub fn opacity(self, opacity: f32) -> Self {
162 Self(
163 self.0,
164 self.1,
165 self.2,
166 (self.3 as f32 * opacity.clamp(0.0, 1.0)).round() as u8,
167 )
168 }
169}
170
171#[derive(Clone, Copy, Debug)]
172pub struct Theme {
173 pub background: Color,
174 pub text: Color,
175 pub control: Color,
176 pub hovered: Color,
177 pub pressed: Color,
178 pub radius: f32,
179 pub primary: Color,
180 pub on_primary: Color,
181 pub secondary: Color,
182 pub outline: Color,
183 pub error: Color,
184 pub on_error: Color,
185 pub on_secondary: Color,
186 pub secondary_container: Color,
187 pub on_secondary_container: Color,
188 pub surface_low: Color,
189 pub surface_high: Color,
190 pub surface_highest: Color,
191 pub outline_variant: Color,
192 pub primary_container: Color,
193 pub on_primary_container: Color,
194 pub tertiary_container: Color,
195 pub on_tertiary_container: Color,
196 pub inverse_surface: Color,
197 pub inverse_on_surface: Color,
198 pub inverse_primary: Color,
199 pub on_surface_variant: Color,
200 pub surface_variant: Color,
201}
202impl Default for Theme {
203 fn default() -> Self {
204 Self {
205 background: Color(18, 18, 22, 255),
206 text: Color(240, 240, 245, 255),
207 control: Color(42, 42, 50, 255),
208 hovered: Color(58, 58, 68, 255),
209 pressed: Color(76, 68, 100, 255),
210 radius: 8.0,
211 primary: Color(208, 188, 255, 255),
212 on_primary: Color(56, 30, 114, 255),
213 secondary: Color(74, 68, 88, 255),
214 outline: Color(147, 143, 153, 255),
215 error: Color(255, 180, 171, 255),
216 on_error: Color(105, 0, 5, 255),
217 on_secondary: Color(232, 222, 248, 255),
218 secondary_container: Color(74, 68, 88, 255),
219 on_secondary_container: Color(232, 222, 248, 255),
220 surface_low: Color(29, 27, 32, 255),
221 surface_high: Color(43, 41, 48, 255),
222 surface_highest: Color(54, 52, 59, 255),
223 outline_variant: Color(73, 69, 79, 255),
224 primary_container: Color(79, 55, 139, 255),
225 on_primary_container: Color(234, 221, 255, 255),
226 tertiary_container: Color(99, 59, 72, 255),
227 on_tertiary_container: Color(255, 216, 228, 255),
228 inverse_surface: Color(230, 225, 229, 255),
229 inverse_on_surface: Color(49, 48, 51, 255),
230 inverse_primary: Color(103, 80, 164, 255),
231 on_surface_variant: Color(202, 196, 208, 255),
232 surface_variant: Color(73, 69, 79, 255),
233 }
234 }
235}
236impl Theme {
237 pub fn light() -> Self {
239 Self {
240 background: Color(250, 250, 248, 255),
241 text: Color(31, 35, 32, 255),
242 control: Color(238, 240, 235, 255),
243 hovered: Color(221, 231, 222, 255),
244 pressed: Color(200, 221, 206, 255),
245 radius: 8.0,
246 primary: Color(43, 106, 77, 255),
247 on_primary: Color(255, 255, 255, 255),
248 secondary: Color(220, 235, 224, 255),
249 outline: Color(121, 132, 123, 255),
250 error: Color(183, 57, 57, 255),
251 on_error: Color(255, 255, 255, 255),
252 on_secondary: Color(31, 53, 40, 255),
253 secondary_container: Color(220, 235, 224, 255),
254 on_secondary_container: Color(31, 53, 40, 255),
255 surface_low: Color(246, 246, 242, 255),
256 surface_high: Color(232, 235, 229, 255),
257 surface_highest: Color(226, 229, 221, 255),
258 outline_variant: Color(192, 201, 192, 255),
259 primary_container: Color(200, 235, 212, 255),
260 on_primary_container: Color(12, 55, 32, 255),
261 tertiary_container: Color(207, 231, 246, 255),
262 on_tertiary_container: Color(20, 53, 70, 255),
263 inverse_surface: Color(45, 49, 46, 255),
264 inverse_on_surface: Color(242, 243, 238, 255),
265 inverse_primary: Color(160, 210, 179, 255),
266 on_surface_variant: Color(70, 79, 72, 255),
267 surface_variant: Color(220, 229, 220, 255),
268 }
269 }
270
271 pub fn mix(self, other: Self, t: f32) -> Self {
273 let t = t.clamp(0.0, 1.0);
274 Self {
275 background: self.background.mix(other.background, t),
276 text: self.text.mix(other.text, t),
277 control: self.control.mix(other.control, t),
278 hovered: self.hovered.mix(other.hovered, t),
279 pressed: self.pressed.mix(other.pressed, t),
280 radius: self.radius + (other.radius - self.radius) * t,
281 primary: self.primary.mix(other.primary, t),
282 on_primary: self.on_primary.mix(other.on_primary, t),
283 secondary: self.secondary.mix(other.secondary, t),
284 outline: self.outline.mix(other.outline, t),
285 error: self.error.mix(other.error, t),
286 on_error: self.on_error.mix(other.on_error, t),
287 on_secondary: self.on_secondary.mix(other.on_secondary, t),
288 secondary_container: self.secondary_container.mix(other.secondary_container, t),
289 on_secondary_container: self
290 .on_secondary_container
291 .mix(other.on_secondary_container, t),
292 surface_low: self.surface_low.mix(other.surface_low, t),
293 surface_high: self.surface_high.mix(other.surface_high, t),
294 surface_highest: self.surface_highest.mix(other.surface_highest, t),
295 outline_variant: self.outline_variant.mix(other.outline_variant, t),
296 primary_container: self.primary_container.mix(other.primary_container, t),
297 on_primary_container: self.on_primary_container.mix(other.on_primary_container, t),
298 tertiary_container: self.tertiary_container.mix(other.tertiary_container, t),
299 on_tertiary_container: self
300 .on_tertiary_container
301 .mix(other.on_tertiary_container, t),
302 inverse_surface: self.inverse_surface.mix(other.inverse_surface, t),
303 inverse_on_surface: self.inverse_on_surface.mix(other.inverse_on_surface, t),
304 inverse_primary: self.inverse_primary.mix(other.inverse_primary, t),
305 on_surface_variant: self.on_surface_variant.mix(other.on_surface_variant, t),
306 surface_variant: self.surface_variant.mix(other.surface_variant, t),
307 }
308 }
309}
310
311#[derive(Clone, Copy, Debug, PartialEq, Eq)]
312pub enum Key {
313 Tab,
314 Enter,
315 Space,
316 Left,
317 Right,
318 Up,
319 Down,
320 Home,
321 End,
322 PageUp,
323 PageDown,
324 Character(char),
325 Escape,
326 Menu,
327}
328#[derive(Clone, Copy, Debug, PartialEq, Eq)]
329pub struct KeyInput {
330 pub key: Key,
331 pub pressed: bool,
332 pub repeat: bool,
333 pub shift: bool,
334}
335
336#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
337pub enum PointerKind {
338 #[default]
339 Mouse,
340 Touch,
341 Pen,
342}
343#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
344pub enum RippleStyle {
345 #[default]
346 MaterialWeb,
347 AngularMaterial,
348}
349
350#[derive(Clone, Copy, Debug)]
352pub struct Input {
353 pub pointer: Option<[f32; 2]>,
354 pub pointer_kind: PointerKind,
355 pub pressed: bool,
356 pub released: bool,
357 pub cancelled: bool,
358 pub blurred: bool,
359 pub key: Option<KeyInput>,
360 pub scroll: [f32; 2],
362 pub time: f64,
363 pub pinch_scale: f32,
365 pub pinch_center: Option<[f32; 2]>,
367 pub touch_count: u8,
369}
370
371impl Default for Input {
372 fn default() -> Self {
373 Self {
374 pointer: None,
375 pointer_kind: PointerKind::Mouse,
376 pressed: false,
377 released: false,
378 cancelled: false,
379 blurred: false,
380 key: None,
381 scroll: [0.0; 2],
382 time: 0.0,
383 pinch_scale: 1.0,
384 pinch_center: None,
385 touch_count: 0,
386 }
387 }
388}
389
390#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash)]
391pub enum FontFamily {
392 #[default]
393 System,
394 Sans,
395 Serif,
396 Monospace,
397}
398
399#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
401pub enum SystemFont {
402 #[default]
403 Default,
404 Serif,
405 Monospace,
406 CompactSans,
407}
408
409impl SystemFont {
410 pub const fn from_index(index: usize) -> Self {
411 match index {
412 1 => Self::Serif,
413 2 => Self::Monospace,
414 3 => Self::CompactSans,
415 _ => Self::Default,
416 }
417 }
418
419 #[cfg(not(target_arch = "wasm32"))]
421 pub fn load_session() -> Self {
422 let config = std::env::var_os("XDG_CONFIG_HOME")
423 .map(std::path::PathBuf::from)
424 .filter(|path| path.is_absolute())
425 .or_else(|| {
426 std::env::var_os("HOME").map(|home| std::path::PathBuf::from(home).join(".config"))
427 });
428 config
429 .and_then(|path| std::fs::read_to_string(path.join("wisp/settings.conf")).ok())
430 .and_then(|settings| {
431 settings.lines().rev().find_map(|line| {
432 let (key, value) = line.split_once('=')?;
433 if key.trim() != "font_style" {
434 return None;
435 }
436 value.trim().parse::<usize>().ok()
437 })
438 })
439 .map_or(Self::Default, |index| Self::from_index(index.min(3)))
440 }
441
442 pub fn resolve_commands(self, commands: &mut [DrawCommand]) {
444 for command in commands {
445 if let DrawCommand::Text { style, .. } = command
446 && style.family == FontFamily::System
447 {
448 *style = self.apply(*style);
449 }
450 }
451 }
452
453 pub fn apply(self, mut style: TextStyle) -> TextStyle {
455 style.family = match self {
456 Self::Default | Self::CompactSans => FontFamily::Sans,
457 Self::Serif => FontFamily::Serif,
458 Self::Monospace => FontFamily::Monospace,
459 };
460 if self == Self::CompactSans {
461 style.letter_spacing -= 0.38;
462 }
463 style
464 }
465}
466
467#[derive(Clone, Copy, Debug, PartialEq)]
468pub struct TextStyle {
469 pub size: f32,
470 pub weight: u16,
471 pub align: u8,
473 pub padding: f32,
474 pub letter_spacing: f32,
475 pub italic: bool,
476 pub family: FontFamily,
477}
478impl Default for TextStyle {
479 fn default() -> Self {
480 Self {
481 size: 16.0,
482 weight: 400,
483 align: 0,
484 padding: 0.0,
485 letter_spacing: 0.0,
486 italic: false,
487 family: FontFamily::System,
488 }
489 }
490}
491impl TextStyle {
492 pub const LABEL: Self = Self {
493 size: 14.0,
494 weight: 500,
495 align: 1,
496 padding: 16.0,
497 letter_spacing: 0.096,
498 italic: false,
499 family: FontFamily::System,
500 };
501}
502#[derive(Clone, Copy, Debug, PartialEq)]
504pub struct TextMetrics {
505 pub normal: [f32; 95],
506 pub medium: [f32; 95],
507 pub serif: [[f32; 95]; 2],
508 pub monospace: [[f32; 95]; 2],
509 pub system_font: SystemFont,
510 pub normal_baseline_offset: f32,
512 pub medium_baseline_offset: f32,
513}
514impl Default for TextMetrics {
515 fn default() -> Self {
516 Self {
517 normal: [0.55; 95],
518 medium: [0.55; 95],
519 serif: [[0.55; 95]; 2],
520 monospace: [[0.60; 95]; 2],
521 system_font: SystemFont::Default,
522 normal_baseline_offset: 0.3,
523 medium_baseline_offset: 0.3,
524 }
525 }
526}
527impl TextMetrics {
528 pub fn set_family_advance(&mut self, family: u32, code: u32, normal: f32, medium: f32) {
530 if !(32..127).contains(&code)
531 || !(0.0..=2.0).contains(&normal)
532 || !(0.0..=2.0).contains(&medium)
533 {
534 return;
535 }
536 let index = code as usize - 32;
537 match family {
538 0 => {
539 self.normal[index] = normal;
540 self.medium[index] = medium;
541 }
542 1 => {
543 self.serif[0][index] = normal;
544 self.serif[1][index] = medium;
545 }
546 2 => {
547 self.monospace[0][index] = normal;
548 self.monospace[1][index] = medium;
549 }
550 _ => {}
551 }
552 }
553
554 fn resolve(&self, style: TextStyle) -> TextStyle {
555 if style.family == FontFamily::System {
556 self.system_font.apply(style)
557 } else {
558 style
559 }
560 }
561
562 pub(crate) fn ascii_advances(&self, style: TextStyle) -> (&[f32; 95], f32) {
563 let style = self.resolve(style);
564 let medium = style.weight >= 500;
565 let advances = match style.family {
566 FontFamily::Serif => &self.serif[usize::from(medium)],
567 FontFamily::Monospace => &self.monospace[usize::from(medium)],
568 _ if medium => &self.medium,
569 _ => &self.normal,
570 };
571 (advances, style.size)
572 }
573
574 pub fn lines(
575 &self,
576 text: &str,
577 max_width: f32,
578 style: TextStyle,
579 mut line: impl FnMut(&str),
580 ) -> usize {
581 let mut start = 0;
582 let mut end = 0;
583 let mut width = 0.0;
584 let mut count = 0;
585 for word in text.split_whitespace() {
586 let offset = word.as_ptr() as usize - text.as_ptr() as usize;
587 let w = self.width(word, style);
588 let gap = if end > start {
589 self.width(&text[end..offset], style)
590 } else {
591 0.0
592 };
593 if end > start && (width + gap + w > max_width || text[end..offset].contains('\n')) {
594 line(&text[start..end]);
595 count += 1;
596 start = offset;
597 width = w;
598 } else {
599 if end == start {
600 start = offset;
601 }
602 width += gap + w;
603 }
604 end = offset + word.len();
605 }
606 if end > start {
607 line(&text[start..end]);
608 count += 1;
609 } else if count == 0 {
610 line("");
611 count = 1;
612 }
613 count
614 }
615 pub fn width(&self, text: &str, style: TextStyle) -> f32 {
616 let style = self.resolve(style);
617 let medium = style.weight >= 500;
618 let advances = match style.family {
619 FontFamily::Serif => &self.serif[usize::from(medium)],
620 FontFamily::Monospace => &self.monospace[usize::from(medium)],
621 _ if medium => &self.medium,
622 _ => &self.normal,
623 };
624 let mut count = 0;
625 let mut width = 0.0;
626 let visible = |c: char| {
629 !c.is_control()
630 && !matches!(
631 c,
632 '\u{00ad}' | '\u{200b}' | '\u{200c}' | '\u{200d}' | '\u{2060}' | '\u{feff}'
633 )
634 };
635 let mut add = |ch: char, wide: bool| {
636 let code = ch as usize;
637 width += if wide {
638 style.size
639 } else if (32..127).contains(&code) {
640 advances[code - 32] * style.size
641 } else {
642 style.size * 0.6
643 };
644 count += 1;
645 };
646 if text.is_ascii() {
647 for ch in text.chars().filter(|c| visible(*c)) {
648 add(ch, false);
649 }
650 } else {
651 for grapheme in text.graphemes(true) {
652 let columns = UnicodeWidthStr::width(grapheme);
653 if columns > 0
654 && let Some(ch) = grapheme.chars().find(|c| visible(*c))
655 {
656 add(ch, columns >= 2);
657 }
658 }
659 }
660 width + (count - 1).max(0) as f32 * style.letter_spacing
661 }
662}
663
664#[derive(Clone, Debug, PartialEq)]
665pub enum DrawCommand {
666 Clear(Color),
667 RoundedRect {
668 bounds: Rect,
669 radius: f32,
670 color: Color,
671 },
672 Ellipse {
673 bounds: Rect,
674 color: Color,
675 },
676 Outline {
677 bounds: Rect,
678 radius: f32,
679 width: f32,
680 color: Color,
681 },
682 Text {
683 bounds: Rect,
684 text: Arc<str>,
685 color: Color,
686 style: TextStyle,
687 },
688 Shadow {
689 bounds: Rect,
690 radius: f32,
691 offset: [f32; 2],
692 blur: f32,
693 spread: f32,
694 color: Color,
695 },
696 Ripple {
698 bounds: Rect,
699 corner_radius: f32,
700 center: [f32; 2],
701 radius: f32,
702 color: Color,
703 soft: bool,
704 },
705 Loading {
706 bounds: Rect,
707 sample: loading::LoadingSample,
708 color: Color,
709 },
710 Image {
712 bounds: Rect,
713 uv: [f32; 4],
714 radius: f32,
715 color: Color,
716 image: Image,
717 },
718 Shape {
720 bounds: Rect,
721 index: u8,
722 color: Color,
723 rotation: f32,
724 },
725 Arc {
726 bounds: Rect,
727 start: f32,
728 sweep: f32,
729 stroke: f32,
730 color: Color,
731 rounded: bool,
732 },
733 Line {
734 from: [f32; 2],
735 to: [f32; 2],
736 width: f32,
737 color: Color,
738 },
739 Polyline {
741 points: [[f32; 2]; 3],
742 count: u8,
743 width: f32,
744 color: Color,
745 },
746 PushClip(Rect),
747 PopClip,
748 PushScaleY {
749 origin: f32,
750 scale: f32,
751 },
752 PopScaleY,
753 PushTransform {
754 origin: [f32; 2],
755 translate: [f32; 2],
756 scale: [f32; 2],
757 rotation_rad: f32,
758 },
759 PushProjective { matrix: [[f32; 3]; 3] },
761 PopTransform,
762 PushLayer {
763 bounds: Rect,
764 alpha: f32,
765 },
766 PushRoundedLayer {
767 bounds: Rect,
768 radius: f32,
769 },
770 PopLayer,
771}
772
773pub fn shape_clip_bounds(bounds: Rect, rotation: f32) -> Rect {
775 if rotation == 0.0 {
776 return bounds;
777 }
778 let size = bounds.width.min(bounds.height);
779 let (sin, cos) = rotation.sin_cos();
780 let extent = size * (sin.abs() + cos.abs());
781 Rect {
782 x: bounds.x + (bounds.width - extent) / 2.0,
783 y: bounds.y + (bounds.height - extent) / 2.0,
784 width: extent,
785 height: extent,
786 }
787}
788
789#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
790pub enum Role {
791 #[default]
792 Button,
793 Checkbox,
794 RadioGroup,
795 Radio,
796 Switch,
797 Slider,
798 TabList,
799 Tab,
800 ListBox,
801 ListItem,
802 Progress,
803 Tooltip,
804 Group,
805 TextField,
806 Menu,
807 MenuItem,
808 Link,
809 ToggleButton,
811 Status,
813 Dialog,
815 DialogDescription,
816 Carousel,
818 CarouselItem,
819}
820
821#[derive(Clone, Debug)]
823pub struct SemanticNode {
824 pub id: u64,
825 pub part: u32,
826 pub role: Role,
827 pub label: Arc<str>,
828 pub bounds: Rect,
829 pub enabled: bool,
830 pub focused: bool,
831 pub selected: bool,
832 pub checked: Option<CheckState>,
833 pub invalid: bool,
834 pub filled: bool,
835 pub required: bool,
836 pub value: Option<f32>,
837 pub range: Option<[f32; 2]>,
838}
839
840#[derive(Clone, Copy, Debug, Default, PartialEq)]
841pub struct Response {
842 pub id: u64,
843 pub bounds: Rect,
844 pub hovered: bool,
845 pub pressed: bool,
846 pub clicked: bool,
847 pub focused: bool,
848 pub changed: bool,
849 pub enabled: bool,
850}
851
852#[derive(Clone, Copy, Debug, PartialEq, Eq)]
853enum Capture {
854 Pointer,
855 Keyboard,
856}
857
858struct CachedText {
859 text: Arc<str>,
860 seen: u64,
861}
862
863pub struct Ui {
864 pub theme: Theme,
865 pub text_metrics: TextMetrics,
866 pub viewport: Option<Rect>,
868 pub high_contrast: bool,
869 pub ripple_style: RippleStyle,
870 pub motion_preference: MotionPreference,
871 pub motion_scheme: MotionScheme,
872 active: Option<u64>,
873 capture: Capture,
874 focused: Option<u64>,
875 pending_focus: Option<u64>,
876 pending_focus_keyboard: bool,
877 keyboard_focus: bool,
878 focus_order: Vec<u64>,
879 next_focus_order: Vec<u64>,
880 part_focus: HashMap<u64, usize>,
881 scrolls: HashMap<u64, scroll::ScrollPhysics>,
882 checkbox_transitions: HashMap<u64, (CheckState, CheckState)>,
883 seen: HashSet<u64>,
884 motion: Motion,
885 ripples: ripple::Ripples,
886 pause_generation: u64,
887 overlay_active: bool,
888 tooltip_visible: bool,
889 tooltip_dismissed: Option<u64>,
890 tooltip_started: Option<(u64, f64)>,
891 tooltip_showing: Option<u64>,
892 semantics: Vec<SemanticNode>,
893 scroll_limits: HashMap<u64, f32>,
894 text_cache: HashMap<Arc<str>, CachedText>,
895 text_bytes: usize,
896 epoch: u64,
897 time: f64,
898 continuous: bool,
899 wakeup: Option<f64>,
900 hover: Option<u64>,
901 hover_start: f64,
902 overlays: Vec<DrawCommand>,
903}
904impl Default for Ui {
905 fn default() -> Self {
906 Self {
907 theme: Theme::default(),
908 text_metrics: TextMetrics::default(),
909 viewport: None,
910 high_contrast: false,
911 ripple_style: RippleStyle::default(),
912 motion_preference: MotionPreference::Full,
913 motion_scheme: MotionScheme::Standard,
914 active: None,
915 capture: Capture::Pointer,
916 focused: None,
917 pending_focus: None,
918 pending_focus_keyboard: false,
919 keyboard_focus: false,
920 focus_order: Vec::new(),
921 next_focus_order: Vec::new(),
922 part_focus: HashMap::new(),
923 scrolls: HashMap::new(),
924 checkbox_transitions: HashMap::new(),
925 seen: HashSet::new(),
926 motion: Motion::default(),
927 ripples: ripple::Ripples::default(),
928 pause_generation: 0,
929 overlay_active: false,
930 tooltip_visible: false,
931 tooltip_dismissed: None,
932 tooltip_started: None,
933 tooltip_showing: None,
934 semantics: Vec::new(),
935 scroll_limits: HashMap::new(),
936 text_cache: HashMap::new(),
937 text_bytes: 0,
938 epoch: 0,
939 time: 0.0,
940 continuous: false,
941 wakeup: None,
942 hover: None,
943 hover_start: 0.0,
944 overlays: Vec::new(),
945 }
946 }
947}
948impl Ui {
949 pub fn needs_redraw(&self) -> bool {
950 self.continuous || self.motion.is_animating()
951 }
952 pub fn next_wakeup(&self) -> Option<f64> {
953 self.wakeup
954 }
955 pub fn semantics(&self) -> &[SemanticNode] {
956 &self.semantics
957 }
958 pub fn pause_animations(&mut self) {
959 self.pause_generation = self.pause_generation.wrapping_add(1);
960 self.motion.pause_clocks();
961 self.ripples.pause();
962 self.tooltip_started = None;
963 self.tooltip_showing = None;
964 self.active = None;
965 self.pending_focus = None;
966 self.wakeup = None;
967 self.continuous = false;
968 }
969 pub fn has_escape_target(&self) -> bool {
970 self.overlay_active || self.tooltip_visible || self.active.is_some()
971 }
972 pub fn focused(&self) -> Option<u64> {
973 self.focused
974 }
975 pub fn adapter_focus(&mut self, id: Option<u64>) {
977 self.focused = id.filter(|id| self.focus_order.contains(id));
978 self.keyboard_focus = false;
979 }
980 pub fn accessibility_focus(&mut self, id: Option<u64>) {
983 self.focused = id.filter(|id| self.focus_order.contains(id));
984 self.keyboard_focus = self.focused.is_some();
985 }
986 pub fn cached_text_bytes(&self) -> usize {
987 self.text_bytes
988 }
989 pub fn retained_motion_properties(&self) -> usize {
990 self.motion.retained_properties()
991 }
992 pub fn frame(
993 &mut self,
994 input: Input,
995 bounds: Rect,
996 gap: f32,
997 build: impl FnOnce(&mut Frame<'_>),
998 ) -> Vec<DrawCommand> {
999 let mut commands = Vec::new();
1000 self.frame_into(input, bounds, gap, &mut commands, build);
1001 commands
1002 }
1003 pub fn frame_into(
1004 &mut self,
1005 input: Input,
1006 bounds: Rect,
1007 gap: f32,
1008 commands: &mut Vec<DrawCommand>,
1009 build: impl FnOnce(&mut Frame<'_>),
1010 ) {
1011 self.epoch = self.epoch.wrapping_add(1);
1012 if input.time.is_finite() {
1013 self.time = input.time.max(self.time);
1014 }
1015 self.motion.begin(self.time, self.motion_preference);
1016 self.ripples.begin();
1017 self.continuous = false;
1018 self.wakeup = None;
1019 self.semantics.clear();
1020 self.scroll_limits.clear();
1021 self.seen.clear();
1022 self.next_focus_order.clear();
1023 self.overlays.clear();
1024 self.overlay_active = false;
1025 self.tooltip_visible = false;
1026 commands.clear();
1027 if input.cancelled || input.blurred {
1028 self.active = None;
1029 }
1030 if input.blurred {
1031 self.pending_focus = None;
1032 self.focused = None;
1033 self.keyboard_focus = false;
1034 }
1035 if let Some(key) = input.key
1036 && key.key == Key::Tab
1037 && key.pressed
1038 {
1039 self.active = None;
1040 self.keyboard_focus = true;
1041 let len = self.focus_order.len();
1042 if len > 0 {
1043 let previous = self
1044 .focused
1045 .and_then(|id| self.focus_order.iter().position(|x| *x == id));
1046 let index = match (previous, key.shift) {
1047 (Some(i), false) => (i + 1) % len,
1048 (Some(i), true) => (i + len - 1) % len,
1049 (None, false) => 0,
1050 (None, true) => len - 1,
1051 };
1052 self.focused = Some(self.focus_order[index]);
1053 }
1054 }
1055 let clip = self.viewport.unwrap_or(bounds);
1056 let mut frame = Frame {
1057 ui: self,
1058 input,
1059 bounds,
1060 clip,
1061 cursor: bounds.y,
1062 gap: gap.max(0.0),
1063 commands: std::mem::take(commands),
1064 enabled: true,
1065 key_consumed: false,
1066 pointer_activation: None,
1067 feedback_blocked: false,
1068 overlay_phase: None,
1069 overlay_nested_scroll: 0.0,
1070 content_color: None,
1071 };
1072 frame
1073 .commands
1074 .push(DrawCommand::Clear(frame.ui.theme.background));
1075 let system_font = frame.ui.text_metrics.system_font;
1076 build(&mut frame);
1077 if input.released
1078 || input.cancelled
1079 || input.blurred
1080 || frame
1081 .ui
1082 .active
1083 .is_some_and(|id| !frame.ui.seen.contains(&id))
1084 {
1085 frame.ui.active = None;
1086 }
1087 if let Some(id) = frame.ui.pending_focus {
1088 if frame.ui.next_focus_order.contains(&id) {
1089 frame.ui.focused = Some(id);
1090 frame.ui.keyboard_focus = frame.ui.pending_focus_keyboard;
1091 frame.ui.pending_focus = None;
1092 for node in &mut frame.ui.semantics {
1093 node.focused = node.id == id && node.enabled;
1094 }
1095 frame.ui.continuous = true;
1096 } else if !frame.ui.seen.contains(&id) {
1097 frame.ui.pending_focus = None;
1098 }
1099 }
1100 if frame
1101 .ui
1102 .focused
1103 .is_some_and(|id| !frame.ui.next_focus_order.contains(&id))
1104 {
1105 frame.ui.focused = None;
1106 }
1107 if frame
1108 .ui
1109 .hover
1110 .is_some_and(|id| !frame.ui.seen.contains(&id))
1111 {
1112 frame.ui.hover = None;
1113 }
1114 if frame
1115 .ui
1116 .tooltip_dismissed
1117 .is_some_and(|id| !frame.ui.seen.contains(&id))
1118 {
1119 frame.ui.tooltip_dismissed = None;
1120 }
1121 if frame
1122 .ui
1123 .tooltip_started
1124 .is_some_and(|(id, _)| !frame.ui.seen.contains(&id))
1125 {
1126 frame.ui.tooltip_started = None;
1127 frame.ui.tooltip_showing = None;
1128 }
1129 frame.ui.motion.finish();
1130 frame.ui.ripples.finish();
1131 frame
1132 .ui
1133 .part_focus
1134 .retain(|id, _| frame.ui.seen.contains(id));
1135 frame
1136 .ui
1137 .checkbox_transitions
1138 .retain(|id, _| frame.ui.seen.contains(id));
1139 frame.commands.append(&mut frame.ui.overlays);
1140 frame
1141 .ui
1142 .text_metrics
1143 .system_font
1144 .resolve_commands(&mut frame.commands);
1145 frame.ui.text_metrics.system_font = system_font;
1146 *commands = frame.commands;
1147 std::mem::swap(&mut frame.ui.focus_order, &mut frame.ui.next_focus_order);
1148 if frame.ui.epoch.is_multiple_of(60) {
1150 let epoch = frame.ui.epoch;
1151 frame.ui.text_cache.retain(|_, value| value.seen == epoch);
1152 frame.ui.text_bytes = frame.ui.text_cache.keys().map(|s| s.len()).sum();
1153 }
1154 }
1155 fn text(&mut self, text: &str) -> Arc<str> {
1156 if let Some(cached) = self.text_cache.get_mut(text) {
1157 cached.seen = self.epoch;
1158 return Arc::clone(&cached.text);
1159 }
1160 let value: Arc<str> = Arc::from(text);
1161 if self.text_cache.len() < 1024 && self.text_bytes.saturating_add(text.len()) <= 128 * 1024
1162 {
1163 self.text_bytes += text.len();
1164 self.text_cache.insert(
1165 Arc::clone(&value),
1166 CachedText {
1167 text: Arc::clone(&value),
1168 seen: self.epoch,
1169 },
1170 );
1171 }
1172 value
1173 }
1174}
1175
1176pub struct Frame<'a> {
1177 ui: &'a mut Ui,
1178 input: Input,
1179 bounds: Rect,
1180 clip: Rect,
1181 cursor: f32,
1182 gap: f32,
1183 commands: Vec<DrawCommand>,
1184 enabled: bool,
1185 key_consumed: bool,
1186 pointer_activation: Option<u64>,
1187 feedback_blocked: bool,
1188 overlay_phase: Option<systems::material::OverlayPhase>,
1189 overlay_nested_scroll: f32,
1190 content_color: Option<Color>,
1191}
1192impl Frame<'_> {
1193 pub fn theme(&self) -> Theme {
1194 self.ui.theme
1195 }
1196 pub fn input(&self) -> Input {
1197 self.input
1198 }
1199 pub fn take_text_input_request(&mut self) -> Option<(u64, Rect)> {
1202 let id = self.pointer_activation.take()?;
1203 self.text_input_bounds(id).map(|bounds| (id, bounds))
1204 }
1205
1206 pub fn text_input_bounds(&self, id: u64) -> Option<Rect> {
1208 self.ui
1209 .semantics
1210 .iter()
1211 .rev()
1212 .find(|node| node.id == id && node.role == Role::TextField && node.enabled)
1213 .map(|node| node.bounds)
1214 }
1215
1216 pub fn clear(&mut self, color: Color) {
1217 self.commands.push(DrawCommand::Clear(color));
1218 }
1219 pub fn available(&self) -> Rect {
1220 Rect {
1221 y: self.cursor,
1222 height: (self.bounds.y + self.bounds.height - self.cursor).max(0.0),
1223 ..self.bounds
1224 }
1225 }
1226 pub fn with_enabled(&mut self, enabled: bool, build: impl FnOnce(&mut Self)) {
1227 let previous = self.enabled;
1228 self.enabled &= enabled;
1229 build(self);
1230 self.enabled = previous;
1231 }
1232 fn allocate(&mut self, height: f32) -> Rect {
1233 let bounds = Rect {
1234 x: self.bounds.x,
1235 y: self.cursor,
1236 width: self.bounds.width.max(0.0),
1237 height: height
1238 .min((self.bounds.y + self.bounds.height - self.cursor).max(0.0))
1239 .max(0.0),
1240 };
1241 self.cursor += height + self.gap;
1242 bounds
1243 }
1244 fn rect(&mut self, bounds: Rect, radius: f32, color: Color) {
1245 self.commands.push(DrawCommand::RoundedRect {
1246 bounds,
1247 radius,
1248 color,
1249 });
1250 }
1251 fn text_at(&mut self, bounds: Rect, text: &str, color: Color) {
1252 self.styled_text(bounds, text, color, TextStyle::default());
1253 }
1254 pub fn record_paint(&mut self, build: impl FnOnce(&mut Self)) -> Vec<DrawCommand> {
1256 let start = self.commands.len();
1257 build(self);
1258 self.commands[start..].to_vec()
1259 }
1260
1261 pub fn replay_paint(&mut self, commands: &[DrawCommand]) {
1263 self.commands.extend_from_slice(commands);
1264 }
1265
1266 pub fn styled_text(&mut self, bounds: Rect, text: &str, color: Color, style: TextStyle) {
1267 let text = self.ui.text(text);
1268 self.commands.push(DrawCommand::Text {
1269 bounds,
1270 text,
1271 color,
1272 style,
1273 });
1274 }
1275 pub fn set_system_font(&mut self, font: SystemFont) {
1278 self.ui.text_metrics.system_font = font;
1279 }
1280
1281 pub fn text_width(&self, text: &str, style: TextStyle) -> f32 {
1282 self.ui.text_metrics.width(text, style)
1283 }
1284 pub fn shadow(
1285 &mut self,
1286 bounds: Rect,
1287 radius: f32,
1288 offset: [f32; 2],
1289 blur: f32,
1290 spread: f32,
1291 color: Color,
1292 ) {
1293 self.commands.push(DrawCommand::Shadow {
1294 bounds,
1295 radius,
1296 offset,
1297 blur,
1298 spread,
1299 color,
1300 });
1301 }
1302 pub fn push_transform(
1303 &mut self,
1304 origin: [f32; 2],
1305 translate: [f32; 2],
1306 scale: [f32; 2],
1307 rotation_rad: f32,
1308 ) {
1309 self.commands.push(DrawCommand::PushTransform {
1310 origin,
1311 translate,
1312 scale,
1313 rotation_rad,
1314 });
1315 }
1316 pub fn pop_transform(&mut self) {
1317 self.commands.push(DrawCommand::PopTransform);
1318 }
1319 pub fn push_projective(&mut self, matrix: [[f32; 3]; 3]) -> bool {
1321 if !matrix.iter().flatten().all(|value| value.is_finite()) { return false; }
1322 self.commands.push(DrawCommand::PushProjective { matrix });
1323 true
1324 }
1325 pub fn push_layer(&mut self, bounds: Rect, alpha: f32) {
1326 self.commands.push(DrawCommand::PushLayer {
1327 bounds,
1328 alpha: alpha.clamp(0.0, 1.0),
1329 });
1330 }
1331 pub fn within_rounded_layer(
1334 &mut self,
1335 bounds: Rect,
1336 radius: f32,
1337 build: impl FnOnce(&mut Self),
1338 ) {
1339 if radius <= 0.0 {
1340 self.within(bounds, build);
1341 return;
1342 }
1343 self.commands
1344 .push(DrawCommand::PushRoundedLayer { bounds, radius });
1345 build(self);
1346 self.pop_layer();
1347 }
1348
1349 pub fn pop_layer(&mut self) {
1350 self.commands.push(DrawCommand::PopLayer);
1351 }
1352 fn animate(&mut self, id: u64, property: u8, target: f32, initial: f32) -> f32 {
1353 self.ui
1354 .motion
1355 .effect(id, property, target, initial, Spring::EFFECTS)
1356 }
1357 fn animate_geometry(&mut self, id: u64, property: u8, target: f32, initial: f32) -> f32 {
1358 self.ui.motion.effect(
1359 id,
1360 property,
1361 target,
1362 initial,
1363 self.ui.motion_scheme.fast_spatial(),
1364 )
1365 }
1366 fn interact(&mut self, id: u64, bounds: Rect, enabled: bool) -> Response {
1367 assert!(
1368 self.ui.seen.insert(id),
1369 "Bhoo widget IDs must be unique within a frame: {id}"
1370 );
1371 let hit = bounds.intersect(self.clip);
1372 let enabled = enabled && self.enabled && hit.width > 0.0 && hit.height > 0.0;
1373 if enabled {
1374 self.ui.next_focus_order.push(id);
1375 } else {
1376 if self.ui.active == Some(id) {
1377 self.ui.active = None;
1378 }
1379 if self.ui.focused == Some(id) {
1380 self.ui.focused = None;
1381 }
1382 }
1383 let hovered = enabled && self.input.pointer.is_some_and(|p| hit.contains(p));
1384 if hovered && self.ui.hover != Some(id) {
1385 self.ui.hover = Some(id);
1386 self.ui.hover_start = self.ui.time;
1387 }
1388 if self.ui.hover == Some(id) && !hovered {
1389 self.ui.hover = None;
1390 }
1391 let mut clicked = false;
1392 if enabled && !self.input.cancelled && !self.input.blurred {
1393 if hovered && self.input.pressed && self.ui.active.is_none() {
1394 self.ui.active = Some(id);
1395 self.ui.capture = Capture::Pointer;
1396 self.ui.focused = Some(id);
1397 self.ui.keyboard_focus = false;
1398 }
1399 if self.ui.active == Some(id)
1400 && self.ui.capture == Capture::Pointer
1401 && self.input.released
1402 {
1403 clicked = hovered;
1404 if clicked {
1405 self.pointer_activation = Some(id);
1406 }
1407 }
1408 if self.ui.focused == Some(id)
1409 && !self.key_consumed
1410 && let Some(key) = self.input.key
1411 {
1412 match (key.key, key.pressed, key.repeat) {
1413 (Key::Enter, true, false) => {
1414 clicked = true;
1415 self.key_consumed = true;
1416 }
1417 (Key::Space, true, false) => {
1418 self.ui.active = Some(id);
1419 self.ui.capture = Capture::Keyboard;
1420 self.key_consumed = true;
1421 }
1422 (Key::Space, false, _)
1423 if self.ui.active == Some(id) && self.ui.capture == Capture::Keyboard =>
1424 {
1425 clicked = true;
1426 self.ui.active = None;
1427 self.key_consumed = true;
1428 }
1429 (Key::Escape, true, _) => {
1430 self.ui.active = None;
1431 self.key_consumed = true;
1432 }
1433 _ => {}
1434 }
1435 }
1436 }
1437 if clicked {
1438 self.ui.continuous = true;
1439 }
1440 Response {
1441 id,
1442 bounds,
1443 hovered: hovered && self.input.pointer_kind != PointerKind::Touch,
1444 pressed: enabled
1445 && self.ui.active == Some(id)
1446 && !self.input.released
1447 && !self.input.cancelled,
1448 clicked,
1449 focused: enabled && !self.feedback_blocked && self.ui.focused == Some(id),
1450 changed: false,
1451 enabled,
1452 }
1453 }
1454 #[allow(clippy::too_many_arguments)]
1455 fn semantic(
1456 &mut self,
1457 response: Response,
1458 role: Role,
1459 label: &str,
1460 selected: bool,
1461 checked: Option<CheckState>,
1462 value: Option<f32>,
1463 range: Option<[f32; 2]>,
1464 ) {
1465 let label = self.ui.text(label);
1466 self.ui.semantics.push(SemanticNode {
1467 id: response.id,
1468 part: 0,
1469 role,
1470 label,
1471 bounds: response.bounds.intersect(self.clip),
1472 enabled: response.enabled,
1473 focused: response.focused,
1474 selected,
1475 checked,
1476 invalid: false,
1477 filled: false,
1478 required: false,
1479 value,
1480 range,
1481 });
1482 }
1483 pub fn focus_ring(&mut self, response: Response) {
1485 if !self.ui.high_contrast {
1486 return;
1487 }
1488 let visible = response.focused && self.ui.keyboard_focus;
1489 let alpha = self.animate(response.id, 2, f32::from(visible), f32::from(visible));
1490 if alpha > 0.001 {
1491 let b = response.bounds;
1492 let c = self.ui.theme.primary.opacity(alpha);
1493 for r in [
1494 Rect {
1495 x: b.x,
1496 y: b.y,
1497 width: b.width,
1498 height: 2.0,
1499 },
1500 Rect {
1501 x: b.x,
1502 y: b.y + b.height - 2.0,
1503 width: b.width,
1504 height: 2.0,
1505 },
1506 Rect {
1507 x: b.x,
1508 y: b.y,
1509 width: 2.0,
1510 height: b.height,
1511 },
1512 Rect {
1513 x: b.x + b.width - 2.0,
1514 y: b.y,
1515 width: 2.0,
1516 height: b.height,
1517 },
1518 ] {
1519 self.rect(r, 1.0, c);
1520 }
1521 }
1522 }
1523 fn ink(&mut self, r: Response, corner_radius: f32, color: Color) {
1525 self.ink_part(r, 0, corner_radius, color, true);
1526 }
1527 fn ink_part(
1528 &mut self,
1529 r: Response,
1530 part: u32,
1531 corner_radius: f32,
1532 color: Color,
1533 allow_label: bool,
1534 ) {
1535 let visible = r.bounds.intersect(self.clip);
1536 if !r.enabled
1537 || self.ui.motion_preference == MotionPreference::Reduced
1538 || self.input.blurred
1539 || visible.width <= 0.0
1540 || visible.height <= 0.0
1541 {
1542 self.ui.ripples.clear((r.id, part));
1543 return;
1544 }
1545 let keyboard = r.focused
1546 && self.input.key.is_some_and(|k| {
1547 k.pressed && !k.repeat && matches!(k.key, Key::Space | Key::Enter)
1548 });
1549 let pointer = self.input.pressed
1550 && r.pressed
1551 && self.ui.capture == Capture::Pointer
1552 && (allow_label || self.input.pointer.is_some_and(|p| r.bounds.contains(p)));
1553 let origin = if pointer {
1554 self.input.pointer.map(|p| {
1555 if r.bounds.contains(p) {
1556 [
1557 (p[0] - r.bounds.x) / r.bounds.width.max(1.0),
1558 (p[1] - r.bounds.y) / r.bounds.height.max(1.0),
1559 ]
1560 } else {
1561 [0.5; 2]
1562 }
1563 })
1564 } else if keyboard {
1565 Some([0.5; 2])
1566 } else {
1567 None
1568 };
1569 let held = r.pressed && !self.input.cancelled;
1570 if self.input.cancelled {
1571 self.ui.ripples.cancel_pending((r.id, part), self.ui.time);
1572 }
1573 if let Some(sample) = self.ui.ripples.sample_with_style(
1574 (r.id, part),
1575 self.ui.time,
1576 origin,
1577 held,
1578 pointer && self.input.pointer_kind == PointerKind::Touch,
1579 self.ui.ripple_style,
1580 ) {
1581 self.ui.continuous |= sample.moving;
1582 if let Some(wake) = sample.wake {
1583 self.ui.wakeup = Some(self.ui.wakeup.map_or(wake, |old| old.min(wake)));
1584 }
1585 let b = r.bounds;
1586 let max = b.width.max(b.height);
1587 let initial = (max * 0.2).floor().max(1.0);
1588 let diameter = b.width.hypot(b.height) + 10.0 + (max * 0.35).max(75.0);
1589 let mut radius = (initial + (diameter - initial) * sample.growth) * 0.5;
1590 let start = [
1591 b.x + sample.origin[0] * b.width,
1592 b.y + sample.origin[1] * b.height,
1593 ];
1594 let mut center = [
1595 start[0] + (b.x + b.width * 0.5 - start[0]) * sample.growth,
1596 start[1] + (b.y + b.height * 0.5 - start[1]) * sample.growth,
1597 ];
1598 let angular = sample.style == RippleStyle::AngularMaterial;
1599 if angular {
1600 center = start;
1601 radius = (b.width * sample.origin[0].max(1.0 - sample.origin[0]))
1602 .hypot(b.height * sample.origin[1].max(1.0 - sample.origin[1]))
1603 * sample.growth;
1604 }
1605 if sample.opacity > 0.0 {
1606 self.commands.push(DrawCommand::Ripple {
1607 bounds: b,
1608 corner_radius,
1609 center,
1610 radius,
1611 color: color.opacity(0.12 * sample.opacity),
1612 soft: !angular,
1613 });
1614 }
1615 }
1616 }
1617 fn key_for(&mut self, response: Response) -> Option<Key> {
1618 if response.enabled
1619 && response.focused
1620 && !self.key_consumed
1621 && let Some(key) = self.input.key
1622 && key.pressed
1623 {
1624 self.key_consumed = true;
1625 return Some(key.key);
1626 }
1627 None
1628 }
1629 pub fn label(&mut self, text: impl AsRef<str>) {
1630 let text = text.as_ref();
1631 let style = TextStyle::default();
1632 let metrics = self.ui.text_metrics;
1633 let width = self.bounds.width;
1634 let count = metrics.lines(text, width, style, |_| {}).max(1);
1635 let height = (count as f32 * 24.0).max(28.0);
1636 let b = self.allocate(height);
1637 let mut index = 0;
1638 metrics.lines(text, width, style, |line| {
1639 let y = b.y + (height - count as f32 * 24.0) * 0.5 + index as f32 * 24.0;
1640 self.styled_text(
1641 Rect {
1642 y,
1643 height: 24.0,
1644 ..b
1645 },
1646 line,
1647 self.content_color.unwrap_or(self.ui.theme.text),
1648 style,
1649 );
1650 index += 1;
1651 });
1652 }
1653}
1654
1655#[cfg(test)]
1656#[path = "lib.spec.rs"]
1657mod tests;