1mod canvas_render;
2mod classes;
3mod components;
4mod cull;
5mod focus_ring;
6mod follow;
7mod layout_scope;
8mod layout_tree;
9mod list;
10mod list_motion;
11mod measure;
12mod overlay;
13mod pace;
14mod parent_viewport;
15mod relations;
16mod renders;
17mod resize_anchor;
18mod scrollbars;
19mod selection_ends;
20mod services;
21mod slots;
22mod sticky;
23mod terminal_layout;
24#[cfg(test)]
25mod tests;
26mod touch;
27mod views;
28mod watch;
29mod web_evaluation;
30
31const CANVAS_IMAGES: usize = 1024;
34
35pub(crate) const SOURCE_NOT_GRANTED: &str = "the source is not granted by capabilities.";
38
39use std::{rc::Rc, sync::Arc};
40
41use slab::Slab;
42use taffy::{AvailableSpace, NodeId as LayoutId, Overflow, Position};
43
44#[doc(hidden)]
45pub use self::components::set_part_requester;
46pub use self::measure::{ListScrollPosition, Measurement};
47use self::{
48 layout_tree::LayoutTree,
49 list::{ExtraKind, Follow, ListState, PendingScroll, PinTarget},
50};
51use crate::{
52 animation::AnimationProp,
53 geometry::{Bounds, Percentage, Point, Points, Size, rect, size_pt},
54 mount::{
55 InputConfig, ModalConfig, MountBatch, MountItem, NativeProps, ScreenConfig, ScrollBehavior,
56 StickyCell, VideoProps, ViewKind,
57 },
58 ops::{
59 CellSlot, Command, EventKind, EventMask, EventPayload, HeaderSlot, ImageProp, ImageSource,
60 KeyboardDismissMode, ModalAnimation, ModalProp, NativeProp, NodeId, Op, PayloadValue, Prop,
61 ROOT_ID, ResizeMode, ScreenAnimation, ScreenProp, ScrollProp, Tag,
62 },
63 props::{AccessibilityProp, EdgeInsets, GestureValues, LayoutAnimation, ViewProps},
64 style::{Color, PaintStyle, Style, StylePatch, TextAlign, TextStyle, ViewStyle},
65 tailwind::{ClassEnvironment, ClassList, ClassProps, Tailwind},
66 text::{AttributedText, MeasureCache, ResolvedTextStyle, TextEngine, TextLayout},
67};
68
69type Key = u32;
72
73struct Run {
75 text: String,
76 block: Key,
78}
79
80type Bar = (NodeId, Option<crate::ScrollbarSetting>);
85
86const NO_KEY: Key = Key::MAX;
87
88const MAX_VIRTUAL_ROUNDS: u32 = 8;
90const MEASURED_RUN: usize = 1024;
94mod dirty {
96 pub(super) const VIEW: u32 = 1 << 0;
98 pub(super) const EVENTS: u32 = 1 << 1;
100 pub(super) const TEXT_BUILD: u32 = 1 << 2;
102 pub(super) const TEXT_MOUNT: u32 = 1 << 3;
104 pub(super) const IMAGE: u32 = 1 << 4;
106 pub(super) const SCROLL: u32 = 1 << 5;
108 pub(super) const REFRESHING: u32 = 1 << 6;
110 pub(super) const ANIMATION: u32 = 1 << 7;
112 pub(super) const PAN: u32 = 1 << 8;
114 pub(super) const INPUT: u32 = 1 << 9;
116 pub(super) const INPUT_VALUE: u32 = 1 << 10;
118 pub(super) const VIEW_PROPS: u32 = 1 << 11;
120 pub(super) const SCREEN: u32 = 1 << 12;
122 pub(super) const MODAL: u32 = 1 << 13;
124 pub(super) const NATIVE: u32 = 1 << 14;
126 pub(super) const SCROLL_BEHAVIOR: u32 = 1 << 15;
128 pub(super) const CANVAS: u32 = 1 << 16;
130 pub(super) const COMPONENT: u32 = 1 << 17;
132 pub(super) const LABEL: u32 = 1 << 18;
135 pub(super) const SHADER: u32 = 1 << 19;
137 pub(super) const NAV_SHADER: u32 = 1 << 20;
139}
140
141#[derive(Debug, Default)]
144struct RootState {
145 reported: Option<Size<Points>>,
147 insets: EdgeInsets,
149 header: Option<f32>,
153 laid_out: Option<(Size<Points>, f32)>,
155 screen: ScreenConfig,
157 modal: ModalConfig,
159 nav_shader: Option<crate::NavShader>,
161 slot: HeaderSlot,
163 empty: bool,
166 native_id: Option<Box<str>>,
168 status_bar: Option<crate::StatusBarSetting>,
170 status_bar_entry: Option<crate::element::status_bar::StatusBarEntry>,
173 overlay: Option<Box<overlay::OverlayState>>,
175}
176
177#[derive(Debug, Clone, Copy, PartialEq)]
179struct Paragraph {
180 allow_font_scaling: bool,
182 max_font_multiplier: f32,
184 selection_color: Option<crate::Color>,
186 fit: bool,
188 min_font_scale: f32,
190}
191
192impl Default for Paragraph {
193 fn default() -> Self {
194 Self {
195 allow_font_scaling: true,
196 max_font_multiplier: 0.0,
197 selection_color: None,
198 fit: false,
199 min_font_scale: 0.0,
200 }
201 }
202}
203
204impl Paragraph {
205 fn font_multiplier(&self, font_scale: f32) -> f32 {
207 if !self.allow_font_scaling {
208 return 1.0;
209 }
210 if self.max_font_multiplier >= 1.0 {
211 font_scale.min(self.max_font_multiplier)
212 } else {
213 font_scale
214 }
215 }
216}
217
218#[derive(Debug, Clone, Copy, PartialEq, Eq)]
219enum Kind {
220 View,
221 Text,
222 RawText,
223 Image,
224 Scroll,
225 List,
226 Cell,
227 Input,
228 Stack,
229 Screen,
230 Modal,
231 HeaderItem,
232 InputAccessory,
233 Canvas,
234 WebView,
235 Video,
236 Native,
237 Overlay,
238 Shader,
239 GpuView,
242}
243
244impl Kind {
245 fn is_container(self) -> bool {
247 matches!(
248 self,
249 Kind::View
250 | Kind::Scroll
251 | Kind::List
252 | Kind::Cell
253 | Kind::Stack
254 | Kind::Screen
255 | Kind::Modal
256 | Kind::HeaderItem
257 | Kind::InputAccessory
258 | Kind::Overlay
259 | Kind::Shader
260 | Kind::GpuView
261 )
262 }
263
264 fn is_root(self) -> bool {
266 matches!(
267 self,
268 Kind::Screen | Kind::Modal | Kind::HeaderItem | Kind::InputAccessory | Kind::Overlay
269 )
270 }
271
272 fn view_kind(self) -> ViewKind {
273 match self {
274 Kind::Text => ViewKind::Text,
275 Kind::Image => ViewKind::Image,
276 Kind::Scroll | Kind::List => ViewKind::Scroll,
277 Kind::Input => ViewKind::Input,
278 Kind::Stack => ViewKind::Stack,
279 Kind::Screen => ViewKind::Screen,
280 Kind::Modal => ViewKind::Modal,
281 Kind::HeaderItem => ViewKind::HeaderItem,
282 Kind::InputAccessory => ViewKind::InputAccessory,
283 Kind::Canvas => ViewKind::Canvas,
284 Kind::WebView => ViewKind::WebView,
285 Kind::Video => ViewKind::Video,
286 Kind::Native => ViewKind::Native,
287 Kind::View
292 | Kind::Cell
293 | Kind::RawText
294 | Kind::Overlay
295 | Kind::Shader
296 | Kind::GpuView => ViewKind::View,
297 }
298 }
299
300 fn of(tag: Tag) -> Self {
303 match tag {
304 Tag::View => Kind::View,
305 Tag::Text => Kind::Text,
306 Tag::Image => Kind::Image,
307 Tag::Scroll => Kind::Scroll,
308 Tag::List => Kind::List,
309 Tag::Cell => Kind::Cell,
310 Tag::Input => Kind::Input,
311 Tag::Stack => Kind::Stack,
312 Tag::Screen => Kind::Screen,
313 Tag::Modal => Kind::Modal,
314 Tag::HeaderItem => Kind::HeaderItem,
315 Tag::InputAccessory => Kind::InputAccessory,
316 Tag::Canvas => Kind::Canvas,
317 Tag::WebView => Kind::WebView,
318 Tag::Video => Kind::Video,
319 Tag::Native => Kind::Native,
320 Tag::Overlay => Kind::Overlay,
321 Tag::Shader
322 | Tag::ShaderEffect
323 | Tag::ShaderTransition
324 | Tag::ScreenEffect
325 | Tag::ScreenTransition => Kind::Shader,
326 Tag::GpuView => Kind::GpuView,
327 }
328 }
329
330 fn derives_layout(self) -> bool {
333 matches!(
334 self,
335 Kind::Scroll | Kind::List | Kind::Cell | Kind::Screen | Kind::Modal | Kind::Overlay
336 )
337 }
338}
339
340const ACCENT_PROP: &str = "accentColor";
343
344#[derive(Debug, Default)]
346struct ComponentState {
347 name: Option<Arc<str>>,
348 props: Vec<(Arc<str>, crate::JsonValue)>,
349 changed: Vec<Arc<str>>,
351 slots: Vec<Arc<str>>,
354 bound: Vec<(u16, crate::animation::NodeId)>,
357 slots_changed: std::cell::Cell<bool>,
360 source: Option<crate::gpu::GpuSource>,
363}
364
365impl ComponentState {
366 fn is_bound(&self, name: &str) -> bool {
367 self.bound
368 .iter()
369 .any(|(s, _)| &*self.slots[*s as usize] == name)
370 }
371}
372
373#[derive(Debug)]
374struct ScrollState {
375 horizontal: bool,
376 scrollbar: crate::ScrollbarSetting,
377 bar: Option<Bar>,
379 refreshing: bool,
380 scroll_value: Option<crate::animation::NodeId>,
381 pull_value: Option<crate::animation::NodeId>,
382 keyboard_dismiss: KeyboardDismissMode,
383 content: Option<Size<Points>>,
385 content_item: Option<(u64, usize)>,
391 culled_content: Option<Size<Points>>,
394 behavior: ScrollBehavior,
395 event_throttle_ms: f32,
397 zoom: f32,
399 offset: (f32, f32),
401 step: (f32, f32),
405 issued: u32,
409 target: Option<(u32, (f32, f32))>,
413 dependents: Vec<Key>,
416 pending: Vec<(u32, PendingScroll)>,
419 asked: Option<parent_viewport::Asked>,
421 page_sticky: Vec<list::StickyRange>,
424 view_sticky: Vec<list::StickyRange>,
426 culls: bool,
429}
430
431impl Default for ScrollState {
432 fn default() -> Self {
433 Self {
434 horizontal: false,
435 scrollbar: crate::ScrollbarSetting::Shown,
437 bar: None,
438 refreshing: false,
439 scroll_value: None,
440 pull_value: None,
441 keyboard_dismiss: KeyboardDismissMode::None,
442 content: None,
443 content_item: None,
444 culled_content: None,
445 behavior: ScrollBehavior::default(),
446 event_throttle_ms: 0.0,
447 zoom: 1.0,
448 offset: (0.0, 0.0),
449 step: (0.0, 0.0),
450 issued: 0,
451 target: None,
452 dependents: Vec::new(),
453 pending: Vec::new(),
454 asked: None,
455 page_sticky: Vec::new(),
456 view_sticky: Vec::new(),
457 culls: false,
458 }
459 }
460}
461
462#[derive(Debug, Default)]
463struct InputState {
464 value: String,
465 value_set: bool,
467 count: u32,
469 composing: Option<String>,
475 config: InputConfig,
477 content: Option<Bounds<Points>>,
479 content_size: Option<Size<Points>>,
481 placeholder_measured: bool,
483 empty_line: Option<(u64, Size<Points>)>,
487 scrollbar: crate::ScrollbarSetting,
489 bar: Option<Bar>,
491 watched: bool,
495 scroll: Option<InputScroll>,
498}
499
500#[derive(Debug, Clone, Copy, PartialEq)]
502struct InputScroll {
503 offset: Point<Points>,
504 content: Size<Points>,
505 viewport: Size<Points>,
506}
507
508#[derive(Debug, Default)]
510struct ShaderNode {
511 source: Option<Arc<str>>,
513 shader: Option<crate::shader::Shader>,
515 uniforms: crate::shader::ShaderUniforms,
516 paused: bool,
517 role: crate::shader::ShaderRole,
519 progress: crate::shader::ShaderProgress,
521 overflow: Points,
523 value: Option<crate::shader::TransitionKey>,
526 shown: Option<crate::shader::TransitionKey>,
527 duration: Option<f32>,
529 fallback: crate::TransitionFallback,
531 layer: Option<Arc<crate::shader::ShaderLayer>>,
533}
534
535const DEFAULT_TRANSITION_MS: f32 = 300.0;
537
538const DEFAULT_NAV_SHADER_MS: f32 = 350.0;
540
541fn shader_role(tag: Tag) -> Option<crate::shader::ShaderRole> {
543 use crate::shader::ShaderRole as R;
544 Some(match tag {
545 Tag::Shader => R::Fill,
546 Tag::ShaderEffect => R::Effect,
547 Tag::ShaderTransition => R::Transition,
548 Tag::ScreenEffect => R::Screen,
549 Tag::ScreenTransition => R::ScreenTransition,
550 _ => return None,
551 })
552}
553
554#[derive(Debug, Default)]
555struct ImageState {
556 source: Option<ImageSource>,
557 options: crate::mount::ImageOptions,
558 svg_current_color: bool,
561}
562
563#[derive(Default)]
566struct Sparse<T: 'static>(Option<Rc<T>>);
567
568trait SharedDefault: Sized + PartialEq + 'static {
569 fn shared_default() -> &'static Self;
570}
571
572impl SharedDefault for ViewStyle {
573 fn shared_default() -> &'static Self {
574 &ViewStyle::DEFAULT
575 }
576}
577
578impl SharedDefault for TextStyle {
579 fn shared_default() -> &'static Self {
580 &TextStyle::DEFAULT
581 }
582}
583
584impl<T: SharedDefault + Clone> Sparse<T> {
585 fn set(&mut self, value: T) {
586 if let Some(rc) = &mut self.0 {
589 if let Some(inner) = Rc::get_mut(rc) {
590 *inner = value;
591 return;
592 }
593 if value == *T::shared_default() {
594 self.0 = None;
595 return;
596 }
597 if **rc == value {
598 return;
599 }
600 *rc = Rc::new(value);
601 } else if value != *T::shared_default() {
602 self.0 = Some(Rc::new(value));
603 }
604 }
605
606 fn is_default(&self) -> bool {
607 self.0.as_ref().is_none_or(|v| **v == *T::shared_default())
608 }
609}
610
611impl<T: SharedDefault> std::ops::Deref for Sparse<T> {
612 type Target = T;
613 fn deref(&self) -> &T {
614 match &self.0 {
615 Some(rc) => rc,
616 None => T::shared_default(),
617 }
618 }
619}
620
621impl<T: SharedDefault + std::fmt::Debug> std::fmt::Debug for Sparse<T> {
622 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
623 (**self).fmt(f)
624 }
625}
626
627impl<T: SharedDefault> PartialEq<T> for Sparse<T> {
628 fn eq(&self, other: &T) -> bool {
629 **self == *other
630 }
631}
632
633#[derive(Debug, Clone, Copy, PartialEq, Eq)]
636struct Positional(u8);
637
638impl Positional {
639 const NONE: Self = Self(0);
640 const CHILDREN: Self = Self(1);
642 const QUEUED: Self = Self(2);
645 const PASS: Self = Self(4);
648
649 fn has(self, flag: Self) -> bool {
650 self.0 & flag.0 != 0
651 }
652
653 fn remove(&mut self, flag: Self) {
654 self.0 &= !flag.0;
655 }
656}
657
658impl std::ops::BitOrAssign for Positional {
659 fn bitor_assign(&mut self, flag: Self) {
660 self.0 |= flag.0;
661 }
662}
663
664struct Node {
665 id: NodeId,
666 kind: Kind,
667 inline: bool,
669 parent: Key,
670 children: Vec<Key>,
671 height: u32,
676 layout: Option<LayoutId>,
679 base_layout: Option<Box<taffy::Style>>,
683 view_style: Sparse<ViewStyle>,
684 text_style: Sparse<TextStyle>,
685 paint: Option<Rc<PaintStyle>>,
688 animated: Vec<(AnimationProp, crate::animation::NodeId)>,
689 drawing: Option<Arc<crate::canvas::Drawing>>,
691 shader: Option<Box<ShaderNode>>,
693 inline_style: StylePatch,
695 class_names: Option<Box<classes::ClassNames>>,
697 classes: Option<std::rc::Rc<ClassList>>,
699 class_props: Option<Rc<ClassProps>>,
701 states: u16,
703 tracked: u16,
705 projected: u16,
708 passed_hover: bool,
712 resting_fill: Option<Color>,
716 data: Box<[&'static str]>,
720 parts: Option<Box<classes::NodeParts>>,
723 positional: Positional,
726 spaced: bool,
728 inherited_color: Option<Color>,
731 child_perspective: Option<Points>,
733 ch: f32,
735 reads_ch: bool,
737 color_used: Option<Color>,
740 color_queued: bool,
741 position_used: u8,
744 wants_fixed: bool,
746 fixed_view: bool,
748 decoration: bool,
752 cell_border: Option<u8>,
757 ring_inside: bool,
760 cell_label: terminal_layout::Labelled,
766 beside: Key,
769 class_pointer: crate::props::PointerEvents,
772 pointer_auto_inside: bool,
775 sticky: Option<Box<taffy::Rect<taffy::LengthPercentageAuto>>>,
778 follow: Option<Box<follow::Following>>,
780 object_fit: Option<ResizeMode>,
783 insets: Option<Box<[EdgeInsets; 2]>>,
785 env: Option<Box<(crate::style::EnvEdges, [EdgeInsets; 2])>>,
788 events: EventMask,
789 key_parent: Option<NodeId>,
792 z_index: i32,
794 vertical_align: crate::style::VerticalAlign,
796 copy_text: Option<Arc<str>>,
799 clears_keyboard: bool,
802 rtl: bool,
804 direction: Option<bool>,
806 has_logical: bool,
808 props: Option<Box<ViewProps>>,
810 text: String,
812 paragraph: Paragraph,
814 image: Option<Box<ImageState>>,
815 scroll: Option<Box<ScrollState>>,
816 list: Option<Box<ListState>>,
817 input: Option<Box<InputState>>,
818 root: Option<Box<RootState>>,
820 control: Option<Box<NativeProps>>,
822 component: Option<Box<ComponentState>>,
824 slot: Option<CellSlot>,
826 gestures: GestureValues,
828 pan_enabled: bool,
830 created: bool,
832 culled: bool,
835 placeholder: bool,
838 row_asked: bool,
839 frame: Bounds<Points>,
841 overflow: Option<Bounds<Points>>,
844 dirty: u32,
845 queued: bool,
846 text_queued: bool,
848 relaid: bool,
850 emitted: Option<(Origin, taffy::Size<f32>)>,
858 escapes: bool,
862 spare: bool,
866 hidden_in_text: bool,
870 left_behind: bool,
876 elevation: Points,
878 backdrop_material: crate::BackdropMaterial,
880 macos_backdrop: Option<crate::MacOsBackdrop>,
882 windows_backdrop: Option<crate::WindowsBackdrop>,
884 attached: Vec<NodeId>,
887 overlay_watched: u8,
890 ranked_children: bool,
893}
894
895impl Node {
896 fn is_overlay(&self) -> bool {
897 self.kind == Kind::Overlay || self.fixed_view
898 }
899
900 fn is_layout_root(&self) -> bool {
901 self.kind.is_root() || self.fixed_view || self.decoration
902 }
903
904 fn scrollbar_setting(&self) -> Option<&crate::ScrollbarSetting> {
906 match (&self.scroll, &self.input) {
907 (Some(scroll), _) => Some(&scroll.scrollbar),
908 (None, Some(input)) => Some(&input.scrollbar),
909 _ => None,
910 }
911 }
912
913 fn bar(&self) -> Option<&Bar> {
915 match (&self.scroll, &self.input) {
916 (Some(scroll), _) => scroll.bar.as_ref(),
917 (None, Some(input)) => input.bar.as_ref(),
918 _ => None,
919 }
920 }
921
922 fn bar_slot(&mut self) -> Option<&mut Option<Bar>> {
924 match (&mut self.scroll, &mut self.input) {
925 (Some(scroll), _) => Some(&mut scroll.bar),
926 (None, Some(input)) => Some(&mut input.bar),
927 _ => None,
928 }
929 }
930
931 fn mounted_events(&self) -> EventMask {
936 let mut events = self.events;
937 if !self.pan_enabled {
938 events.set(EventKind::PanStart, false);
939 events.set(EventKind::PanEnd, false);
940 }
941 if self.overlay_watched != 0 {
942 events.set(EventKind::Touch, true);
943 }
944 if self.states & crate::tailwind::state::DISABLED != 0 {
945 for e in DISABLED_OFF {
946 events.set(e, false);
947 }
948 }
949 if self.overlay_watched & overlay::watch::HINT != 0 {
951 events.set(EventKind::MouseEnter, true);
952 events.set(EventKind::MouseLeave, true);
953 }
954 events
955 }
956
957 fn stack_rank(&self) -> (i32, bool) {
962 if self.decoration && self.beside == NO_KEY {
963 return (i32::MAX, true);
964 }
965 (self.z_index, self.sticky.is_some())
966 }
967
968 fn mounted_view_style(&self) -> Box<ViewStyle> {
971 let mut style = Box::new(self.view_style.clone());
972 style.elevation = self.elevation;
973 style.backdrop_material = self.backdrop_material;
974 style.macos_backdrop = self.macos_backdrop;
975 style.windows_backdrop = self.windows_backdrop;
976 if self.list.as_ref().is_some_and(|l| l.parent) {
979 style.overflow_hidden = true;
980 }
981 if self.spare || self.hidden_in_text {
982 style.hidden = true;
983 }
984 style.shows_label = self.cell_label != terminal_layout::Labelled::No;
985 style.label_arrow_only = self.cell_label == terminal_layout::Labelled::Arrow;
986 if let Some(sides) = self.cell_border {
987 let w = &mut style.borders.widths;
988 for (bit, side) in [&mut w.top, &mut w.right, &mut w.bottom, &mut w.left]
989 .into_iter()
990 .enumerate()
991 {
992 if sides & (1 << bit) == 0 {
993 *side = Points::ZERO;
994 }
995 }
996 }
997 if self.kind == Kind::Canvas && self.drawing.as_ref().is_some_and(|d| d.paints_background())
1000 {
1001 style.background_color = crate::style::Color::TRANSPARENT;
1002 style.clear_background_images();
1003 }
1004 if style.transform.has_fractions() {
1005 let size = if self.frame.size.width.is_nan() {
1006 Size::default()
1007 } else {
1008 self.frame.size
1009 };
1010 style.transform = style.transform.resolve_fractions(size);
1011 }
1012 style
1013 }
1014
1015 fn mounted_props(&self) -> Box<ViewProps> {
1021 let mut props = self.props.clone().unwrap_or_default();
1022 props.overlay_anchor = self
1023 .root
1024 .as_ref()
1025 .and_then(|root| root.overlay.as_ref())
1026 .and_then(|overlay| overlay.native_anchor);
1027 props.tab_after = self
1028 .root
1029 .as_ref()
1030 .and_then(|root| root.overlay.as_ref())
1031 .and_then(|overlay| overlay.tab_after);
1032 props.key_parent = self.key_parent;
1033 if props.pointer_events == crate::props::PointerEvents::Auto {
1034 props.pointer_events = self.class_pointer;
1035 }
1036 if self.states & crate::tailwind::state::DISABLED != 0 {
1037 props.accessibility.state.disabled = true;
1038 }
1039 if self.spare || self.hidden_in_text || self.left_behind {
1040 props.accessibility.hidden = true;
1041 }
1042 if let Some(list) = self.list.as_ref().filter(|l| l.parent) {
1043 props.screen_order = Some(if list.horizontal {
1044 crate::geometry::Axis::Horizontal
1045 } else {
1046 crate::geometry::Axis::Vertical
1047 });
1048 }
1049 props
1050 }
1051
1052 fn new(id: NodeId, kind: Kind) -> Self {
1053 Self {
1054 id,
1055 kind,
1056 inline: false,
1057 parent: NO_KEY,
1058 children: Vec::new(),
1059 height: 0,
1060 layout: None,
1061 base_layout: None,
1062 view_style: Sparse::default(),
1063 text_style: Sparse::default(),
1064 paint: None,
1065 animated: Vec::new(),
1066 drawing: None,
1067 shader: matches!(kind, Kind::Shader).then(Box::default),
1068 inline_style: StylePatch::default(),
1069 class_names: None,
1070 classes: None,
1071 class_props: None,
1072 states: 0,
1073 tracked: if matches!(kind, Kind::Input) {
1075 crate::tailwind::state::FOCUSED
1076 } else {
1077 0
1078 },
1079 projected: 0,
1080 passed_hover: false,
1081 resting_fill: None,
1082 data: Box::default(),
1083 parts: None,
1084 positional: Positional::NONE,
1085 spaced: false,
1086 inherited_color: None,
1087 child_perspective: None,
1088 ch: 0.0,
1089 reads_ch: false,
1090 color_used: None,
1091 color_queued: false,
1092 position_used: 0,
1093 wants_fixed: false,
1094 fixed_view: false,
1095 decoration: false,
1096 cell_border: None,
1097 ring_inside: false,
1098 cell_label: terminal_layout::Labelled::No,
1099 beside: NO_KEY,
1100 class_pointer: crate::props::PointerEvents::Auto,
1101 pointer_auto_inside: false,
1102 sticky: None,
1103 follow: None,
1104 object_fit: None,
1105 insets: None,
1106 env: None,
1107 events: EventMask::default(),
1108 key_parent: None,
1109 z_index: 0,
1110 vertical_align: crate::style::VerticalAlign::Baseline,
1111 copy_text: None,
1112 clears_keyboard: false,
1113 rtl: false,
1114 direction: None,
1115 has_logical: false,
1116 props: None,
1117 text: String::new(),
1118 paragraph: Paragraph::default(),
1119 image: matches!(kind, Kind::Image).then(Box::default),
1120 scroll: matches!(kind, Kind::Scroll | Kind::List).then(Box::default),
1121 list: matches!(kind, Kind::List).then(|| Box::new(ListState::new())),
1122 input: matches!(kind, Kind::Input).then(Box::default),
1123 root: kind.is_root().then(Box::default),
1124 control: match kind {
1125 Kind::WebView => Some(NativeProps::WebView(Box::default())),
1126 Kind::Video => Some(NativeProps::Video(Box::<VideoProps>::default())),
1127 _ => None,
1128 }
1129 .map(Box::new),
1130 component: matches!(kind, Kind::Native | Kind::GpuView).then(Box::default),
1131 slot: None,
1132 gestures: GestureValues::default(),
1133 pan_enabled: true,
1134 created: false,
1135 culled: false,
1136 placeholder: false,
1137 row_asked: false,
1138 frame: Bounds::UNSET,
1139 overflow: None,
1140 attached: Vec::new(),
1141 overlay_watched: 0,
1142 ranked_children: false,
1143 elevation: Points::ZERO,
1144 backdrop_material: crate::BackdropMaterial::default(),
1145 macos_backdrop: None,
1146 windows_backdrop: None,
1147 dirty: 0,
1148 queued: false,
1149 text_queued: false,
1150 relaid: false,
1151 emitted: None,
1152 escapes: false,
1153 spare: false,
1154 hidden_in_text: false,
1155 left_behind: false,
1156 }
1157 }
1158}
1159
1160struct TextContext<P> {
1162 text: Arc<AttributedText>,
1163 alignments: crate::AttachmentAlignments,
1164 options: crate::TextOptions,
1167 spacers: Vec<u32>,
1170 layout_hash: u64,
1172 prepared: Option<P>,
1174 min_content: Option<Points>,
1176 field: Option<Box<TextContext<P>>>,
1179 cache: Option<(Option<f32>, Size<Points>)>,
1181 baseline: Option<(f32, Option<Points>)>,
1184 same_lines: Option<SameLines>,
1187 no_ahead: bool,
1190 near_screen: u32,
1193 held: bool,
1195 deferred: bool,
1198 estimated: bool,
1201 laid_out: Option<LaidText>,
1204 metadata_changed: bool,
1206 pretty: Option<Box<(f32, Points)>>,
1210}
1211
1212#[derive(Clone, Copy)]
1216struct SameLines {
1217 narrowest: f32,
1218 widest: f32,
1219 size: Size<Points>,
1220}
1221
1222const SAME_LINES_AHEAD: f32 = 8.0;
1225
1226struct LaidText {
1228 content: Bounds<Points>,
1229 layout: TextLayout,
1230 text: Arc<AttributedText>,
1231}
1232
1233impl<P> TextContext<P> {
1234 fn new(text: Arc<AttributedText>) -> Self {
1235 Self {
1236 layout_hash: text.layout_hash(),
1237 alignments: Default::default(),
1238 options: Default::default(),
1239 spacers: Vec::new(),
1240 text,
1241 prepared: None,
1242 same_lines: None,
1243 no_ahead: false,
1244 near_screen: 0,
1245 held: false,
1246 deferred: false,
1247 estimated: false,
1248 min_content: None,
1249 field: None,
1250 cache: None,
1251 baseline: None,
1252 laid_out: None,
1253 metadata_changed: false,
1254 pretty: None,
1255 }
1256 }
1257 fn remount_metadata(
1259 &mut self,
1260 content: Bounds<Points>,
1261 ) -> Option<(Arc<AttributedText>, TextLayout)> {
1262 if !self.metadata_changed {
1263 return None;
1264 }
1265 let laid = self.laid_out.as_mut().filter(|l| l.content == content)?;
1266 let text =
1267 if laid.text.spans == self.text.spans && laid.text.max_lines == self.text.max_lines {
1268 self.text.clone()
1269 } else {
1270 let mut text = (*laid.text).clone();
1273 text.set_metadata(&self.text);
1274 Arc::new(text)
1275 };
1276 laid.text = text.clone();
1277 self.metadata_changed = false;
1278 Some((text, laid.layout.clone()))
1279 }
1280}
1281
1282const FIELD_SAMPLE: &str = "00000000000000000000";
1285
1286enum LeafContext<P> {
1288 Text(Box<TextContext<P>>),
1291 Image(Option<Size<Points>>),
1292 Native(Option<Size<Points>>),
1294}
1295
1296#[derive(Debug, Clone, PartialEq, Eq)]
1298pub struct ListBind {
1299 pub list: NodeId,
1301 pub binds: Vec<(u32, u32)>,
1303}
1304
1305fn take_queued_binds(binds: &mut Vec<ListBind>, list: NodeId) -> Vec<u32> {
1312 let mut slots = Vec::new();
1313 binds.retain(|b| {
1314 if b.list != list {
1315 return true;
1316 }
1317 slots.extend(b.binds.iter().map(|&(slot, _)| slot));
1318 false
1319 });
1320 slots
1321}
1322
1323pub const MAX_TREE_DEPTH: usize = 1024;
1331
1332#[derive(Debug, Clone, Copy, PartialEq, Eq)]
1335pub enum ApplyError {
1336 UnknownNode(NodeId),
1338 DuplicateNode(NodeId),
1340 NotAChild(NodeId),
1342 BadAnchor(NodeId),
1344 Cycle(NodeId),
1346 TooManyNodes(usize),
1348 TooDeep(usize),
1351 IdOutOfRange(NodeId),
1354}
1355
1356impl ApplyError {
1357 pub fn is_fatal(&self) -> bool {
1360 matches!(
1361 self,
1362 ApplyError::TooManyNodes(_) | ApplyError::TooDeep(_) | ApplyError::IdOutOfRange(_)
1363 )
1364 }
1365}
1366
1367#[derive(Default)]
1370struct Retags {
1371 made: rustc_hash::FxHashSet<NodeId>,
1373 seen: usize,
1375 retagged: rustc_hash::FxHashMap<NodeId, usize>,
1378}
1379
1380pub struct Core<M: TextEngine> {
1387 nodes: Slab<Node>,
1388 slots: crate::id_table::IdTable<Key>,
1390 admitted_id_extent: usize,
1392 runs: rustc_hash::FxHashMap<NodeId, Run>,
1396 folded: rustc_hash::FxHashMap<Key, NodeId>,
1398 layout: LayoutTree<LeafContext<M::Prepared>>,
1399 text_engine: Rc<M>,
1400 geometry_engine: Option<Rc<dyn crate::text::GeometryEngine>>,
1403 geometries: rustc_hash::FxHashMap<NodeId, crate::text::TextGeometry>,
1406 measure_cache: MeasureCache,
1407 resizing_commit: u32,
1409 resize_settling: bool,
1413 pending_text: Vec<Key>,
1415 attachment_blocks: Vec<Key>,
1418 lists: Vec<Key>,
1420 parent_lists: Vec<Key>,
1423 outer_moved: bool,
1425 extent_changed: bool,
1427 culls_content: bool,
1429 culling: Vec<Key>,
1431 cull_dirty: bool,
1433 cull_made: bool,
1436 cells_framed: bool,
1439 cull_scratch: Vec<(Key, f32, f32, f32, f32)>,
1443 reach: crate::animation::Reach,
1447 pace: pace::Pace,
1449 list_motion: list_motion::ListMotion,
1451 placeholders: Vec<(Key, NodeId)>,
1454 asked_rows: Vec<NodeId>,
1457 placeholders_resized: bool,
1460 outer_asked: Vec<Key>,
1462 sticky_views: Vec<Key>,
1464 sticky_nodes: Vec<Key>,
1466 sticky_scrollers: Vec<Key>,
1468 builtin_scrollbars: Option<(crate::element::ScrollbarSource, crate::element::AnyValue)>,
1471 scrollbars_pending: Vec<Key>,
1474 watched_inputs: Vec<NodeId>,
1477 fitted_pending: Vec<Key>,
1481 decorated: Vec<Key>,
1483 sticky_changed: bool,
1486 followers: Vec<Key>,
1488 relators: Vec<relations::Relator>,
1491 follow_changed: bool,
1494 sticky_warned: bool,
1496 inset_warned: bool,
1499 shaders: rustc_hash::FxHashMap<u64, Result<crate::shader::Shader, crate::shader::ShaderError>>,
1502 web_unchecked: rustc_hash::FxHashSet<(Key, NodeId)>,
1507 transition_starts: Vec<MountItem>,
1510 pictured: rustc_hash::FxHashSet<NodeId>,
1512 unlinked_from: Vec<NodeId>,
1516 roots: Vec<Key>,
1518 accessories: rustc_hash::FxHashMap<Box<str>, NodeId>,
1520 header_heights: (Points, Points),
1522 safe_area: EdgeInsets,
1526 overlay_bounds: Option<crate::geometry::Bounds<Points>>,
1530 snap_to_window_margin: Points,
1533 list_binds: Vec<ListBind>,
1534 kept_lists: Vec<Key>,
1536 selection_kept: Vec<NodeId>,
1538 kept_scratch: Vec<Key>,
1540 paced_lists: Vec<NodeId>,
1543 paced_scratch: Vec<(u32, u32)>,
1545 events: Vec<crate::element::JsEvent>,
1548 cells_scratch: Vec<(u32, Key)>,
1550 awaiting_renders: Vec<Key>,
1553 root: Key,
1554 viewport: Size<Points>,
1555 mount: Vec<MountItem>,
1556 track_tree_order: bool,
1557 tree_order_changed: bool,
1558 tab_places_stale: bool,
1561 key_ancestry_dirty: bool,
1565 mount_projected: bool,
1568 batches: u64,
1571 retags: Option<Box<Retags>>,
1574 commands: Vec<(NodeId, Command)>,
1576 focus_back: Option<(NodeId, Option<NodeId>, Option<bool>)>,
1582 focus_origins: Vec<(NodeId, Option<(Key, NodeId)>)>,
1587 pointer_focus_back: Option<NodeId>,
1591 layout_animation: Option<LayoutAnimation>,
1593 scoped_layout: Vec<(NodeId, crate::LayoutTransition, bool)>,
1596 resized: Vec<Key>,
1598 restructured: Vec<Key>,
1600 env_styled: rustc_hash::FxHashSet<NodeId>,
1602 env_scratch: Vec<NodeId>,
1604 keyboard_moved: bool,
1608 status_bar_nodes: Vec<Key>,
1611 status_bars_moved: bool,
1614 orientation_pages: Vec<(Key, u8)>,
1617 orientations_shown: u8,
1619 pointer_none_classes: u32,
1622 pointer_pending: Vec<Key>,
1629 slop_moved: Vec<Key>,
1633 focus: Option<(Key, NodeId)>,
1636 focus_chain: Vec<(Key, NodeId)>,
1639 focus_scratch: Vec<(Key, NodeId)>,
1641 focus_moved: bool,
1645 blur_held: bool,
1651 focus_within_changed: bool,
1654 modality: Option<crate::platform::InputModality>,
1657 focus_visible: bool,
1660 focus_by_keyboard: bool,
1666 focus_by_pointer: bool,
1670 pointer_keymap: Option<(Arc<crate::keymap::Keymap>, bool)>,
1675 restoring_modal_focus: bool,
1678 modals_opened: Vec<(Key, NodeId)>,
1681 modal_focus_given: Option<NodeId>,
1686 focus_visible_on: Option<(Key, NodeId)>,
1689 focus_visible_moved: bool,
1692 projected_focus: Vec<(Key, NodeId)>,
1697 pressed_impulses: Vec<(Key, NodeId, crate::time::Instant)>,
1700 passed_hovers: rustc_hash::FxHashMap<NodeId, Vec<NodeId>>,
1703 fixed_changed: Vec<(Key, NodeId)>,
1706 zero_advances: rustc_hash::FxHashMap<(Option<crate::style::FontFamily>, u32, u16, bool), f32>,
1709 ch_styled: Vec<(Key, NodeId)>,
1713 ch_readers: usize,
1715 color_changed: Vec<(Key, NodeId)>,
1718 font_scale: f32,
1720 default_font: Option<crate::style::FontFamily>,
1724 queue: Vec<Key>,
1725 position_parents: Vec<Key>,
1729 needs_layout: bool,
1730 tailwind: Tailwind,
1732 resolved_styles:
1736 rustc_hash::FxHashMap<classes::ResolvedKey, std::rc::Rc<classes::ResolvedClassStyle>>,
1737 #[cfg(test)]
1739 resolve_uncached: bool,
1740 class_env: ClassEnvironment,
1743 appearance: crate::platform::Appearance,
1745 system_dark: bool,
1747 max_nodes: usize,
1749 fold_runs: bool,
1751 access: Arc<crate::access::Access>,
1753 base_url: Option<Arc<str>>,
1756 media_files: Arc<crate::access::MediaFiles>,
1759 canvas_images: rustc_hash::FxHashMap<Arc<str>, Option<Arc<str>>>,
1764 denied: rustc_hash::FxHashSet<String>,
1766 windows: rustc_hash::FxHashMap<NodeId, crate::desktop::window::WindowRecord>,
1769 window_ids: rustc_hash::FxHashMap<String, (NodeId, bool)>,
1772 quit_mode: Option<crate::desktop::QuitMode>,
1776 default_quit_mode: crate::desktop::QuitMode,
1780 main_window_options: Option<crate::desktop::MainWindowOptions>,
1784 launch_defaults_applied: bool,
1787 keep_main_placement: bool,
1790 main_shown: bool,
1793 clipboard: Option<Arc<dyn crate::clipboard::ClipboardBackend>>,
1796 picker: Option<Arc<dyn crate::picker::PickerBackend>>,
1799 window_backend: Option<Arc<dyn crate::desktop::WindowBackend>>,
1802 audio: Option<Arc<dyn crate::audio::AudioBackend>>,
1804 login_item: Option<crate::desktop::LoginItems>,
1807 components: components::Components,
1809 overlays: Vec<Key>,
1812 overlay_state: overlay::Overlays,
1814}
1815
1816impl<M: TextEngine + 'static> Core<M> {
1817 pub fn new(text_engine: M, viewport: Size<Points>) -> Self {
1819 let mut core = Self::with_engine(text_engine, viewport);
1820 core.geometry_engine = Some(core.text_engine.clone());
1821 let engine = core.text_engine.clone();
1823 core.components
1824 .runtime
1825 .set_measure(Rc::new(move |font, text| {
1826 crate::canvas::line_metrics(&*engine, font, text)
1827 }));
1828 core
1829 }
1830}
1831
1832impl<M: TextEngine> Core<M> {
1833 fn with_engine(text_engine: M, viewport: Size<Points>) -> Self {
1834 let mut layout = LayoutTree::with_capacity(256);
1835 let root_layout = layout.new_leaf(root_style(viewport));
1836 let mut nodes = Slab::with_capacity(256);
1837 let mut root = Node::new(ROOT_ID, Kind::View);
1838 root.layout = Some(root_layout);
1839 root.created = true;
1841 let root = nodes.insert(root) as Key;
1842 layout.set_tag(root_layout, root);
1843 layout.set_role(
1845 root_layout,
1846 terminal_layout::Role {
1847 root: true,
1848 ..terminal_layout::Role::default()
1849 },
1850 );
1851 let mut slots = crate::id_table::IdTable::new();
1852 slots.insert(ROOT_ID as usize, root);
1853 Self {
1854 nodes,
1855 admitted_id_extent: slots.extent(),
1856 slots,
1857 layout,
1858 text_engine: Rc::new(text_engine),
1859 geometry_engine: None,
1860 geometries: Default::default(),
1861 measure_cache: MeasureCache::default(),
1862 resizing_commit: 0,
1863 resize_settling: false,
1864 pending_text: Vec::new(),
1865 attachment_blocks: Vec::new(),
1866 max_nodes: usize::MAX,
1867 fold_runs: true,
1868 access: Arc::default(),
1869 base_url: None,
1870 media_files: Arc::default(),
1871 canvas_images: Default::default(),
1872 denied: Default::default(),
1873 windows: Default::default(),
1874 window_ids: Default::default(),
1875 runs: Default::default(),
1876 folded: Default::default(),
1877 quit_mode: None,
1881 default_quit_mode: crate::desktop::QuitMode::Explicit,
1882 main_window_options: None,
1883 launch_defaults_applied: false,
1884 keep_main_placement: false,
1885 main_shown: false,
1886 clipboard: None,
1887 picker: None,
1888 window_backend: None,
1889 audio: None,
1890 login_item: None,
1891 components: components::Components::for_viewport(viewport),
1892 lists: Vec::new(),
1893 parent_lists: Vec::new(),
1894 outer_moved: false,
1895 extent_changed: false,
1896 culls_content: true,
1897 culling: Vec::new(),
1898 cull_dirty: false,
1899 reach: crate::animation::Reach::default(),
1900 cull_made: false,
1901 cells_framed: false,
1902 cull_scratch: Vec::new(),
1903 pace: pace::Pace::default(),
1904 list_motion: list_motion::ListMotion::default(),
1905 placeholders: Vec::new(),
1906 asked_rows: Vec::new(),
1907 placeholders_resized: false,
1908 outer_asked: Vec::new(),
1909 sticky_views: Vec::new(),
1910 sticky_nodes: Vec::new(),
1911 sticky_scrollers: Vec::new(),
1912 builtin_scrollbars: None,
1913 scrollbars_pending: Vec::new(),
1914 watched_inputs: Vec::new(),
1915 fitted_pending: Vec::new(),
1916 decorated: Vec::new(),
1917 sticky_changed: false,
1918 followers: Vec::new(),
1919 relators: Vec::new(),
1920 follow_changed: false,
1921 sticky_warned: false,
1922 inset_warned: false,
1923 shaders: Default::default(),
1924 web_unchecked: Default::default(),
1925 transition_starts: Vec::new(),
1926 pictured: Default::default(),
1927 unlinked_from: Vec::new(),
1928 roots: Vec::new(),
1929 accessories: Default::default(),
1930 header_heights: (Points(44.0), Points(96.0)),
1931 safe_area: EdgeInsets::default(),
1932 overlay_bounds: None,
1933 snap_to_window_margin: crate::overlay::DEFAULT_SNAP_TO_WINDOW_MARGIN,
1934 list_binds: Vec::new(),
1935 kept_lists: Vec::new(),
1936 selection_kept: Vec::new(),
1937 kept_scratch: Vec::new(),
1938 paced_lists: Vec::new(),
1939 paced_scratch: Vec::new(),
1940 events: Vec::new(),
1941 cells_scratch: Vec::new(),
1942 awaiting_renders: Vec::new(),
1943 root,
1944 viewport,
1945 mount: Vec::new(),
1946 track_tree_order: false,
1947 tree_order_changed: false,
1948 tab_places_stale: false,
1949 key_ancestry_dirty: false,
1950 mount_projected: false,
1951 batches: 0,
1952 retags: None,
1953 commands: Vec::new(),
1954 focus_back: None,
1955 focus_origins: Vec::new(),
1956 pointer_focus_back: None,
1957 layout_animation: None,
1958 scoped_layout: Vec::new(),
1959 resized: Vec::new(),
1960 restructured: Vec::new(),
1961 env_styled: Default::default(),
1962 env_scratch: Vec::new(),
1963 keyboard_moved: false,
1964 status_bar_nodes: Vec::new(),
1965 status_bars_moved: false,
1966 orientation_pages: Vec::new(),
1967 orientations_shown: 0,
1968 pointer_none_classes: 0,
1969 pointer_pending: Vec::new(),
1970 slop_moved: Vec::new(),
1971 focus: None,
1972 focus_chain: Vec::new(),
1973 focus_scratch: Vec::new(),
1974 focus_moved: false,
1975 blur_held: false,
1976 focus_within_changed: false,
1977 modality: None,
1978 focus_visible: false,
1979 focus_by_keyboard: false,
1980 focus_by_pointer: false,
1981 pointer_keymap: None,
1982 restoring_modal_focus: false,
1983 modals_opened: Vec::new(),
1984 modal_focus_given: None,
1985 focus_visible_on: None,
1986 focus_visible_moved: false,
1987 projected_focus: Vec::new(),
1988 pressed_impulses: Vec::new(),
1989 passed_hovers: Default::default(),
1990 fixed_changed: Vec::new(),
1991 zero_advances: Default::default(),
1992 ch_styled: Vec::new(),
1993 ch_readers: 0,
1994 color_changed: Vec::new(),
1995 font_scale: 1.0,
1996 default_font: None,
1997 queue: Vec::new(),
1998 position_parents: Vec::new(),
1999 needs_layout: true,
2000 tailwind: Tailwind::new(),
2001 resolved_styles: rustc_hash::FxHashMap::default(),
2002 #[cfg(test)]
2003 resolve_uncached: false,
2004 class_env: ClassEnvironment::default(),
2005 appearance: crate::platform::Appearance::System,
2006 system_dark: false,
2007 overlays: Vec::new(),
2008 overlay_state: overlay::Overlays::default(),
2009 }
2010 }
2011
2012 pub fn set_header_heights(&mut self, normal: Points, large: Points) {
2015 if self.header_heights != (normal, large) {
2016 self.header_heights = (normal, large);
2017 self.needs_layout = true;
2018 }
2019 }
2020
2021 pub fn set_safe_area(&mut self, insets: EdgeInsets) {
2023 if self.safe_area != insets {
2024 self.safe_area = insets;
2025 self.needs_layout = true;
2026 }
2027 }
2028
2029 pub fn set_overlay_area(&mut self, area: Option<crate::geometry::Bounds<Points>>) {
2038 if self.overlay_bounds == area {
2039 return;
2040 }
2041 self.overlay_bounds = area;
2042 if self.root_overlay_shown() {
2045 self.needs_layout = true;
2046 }
2047 }
2048
2049 pub fn set_snap_to_window_margin(&mut self, margin: Points) {
2054 let margin = Points(margin.0.max(0.0));
2055 if self.snap_to_window_margin == margin {
2056 return;
2057 }
2058 self.snap_to_window_margin = margin;
2059 for (_, node) in &mut self.nodes {
2060 if let Some(root) = node.root.as_mut()
2061 && let Some(overlay) = root.overlay.as_mut()
2062 && !overlay.margin_set
2063 {
2064 overlay.placed = None;
2065 root.laid_out = None;
2066 }
2067 }
2068 self.needs_layout = true;
2069 }
2070
2071 pub fn set_root_size(&mut self, id: NodeId, size: Size<Points>, insets: EdgeInsets) {
2074 let Ok(key) = self.key(id) else { return };
2075 if let Some(root) = self.nodes[key as usize].root.as_mut()
2076 && (root.reported != Some(size) || root.insets != insets)
2077 {
2078 root.reported = Some(size);
2079 root.insets = insets;
2080 self.needs_layout = true;
2081 }
2082 }
2083
2084 pub fn set_screen_header(&mut self, id: NodeId, height: Option<Points>) {
2089 let Ok(key) = self.key(id) else { return };
2090 let height = height.map(|h| h.0).filter(|h| h.is_finite() && *h >= 0.0);
2091 if let Some(root) = self.nodes[key as usize].root.as_mut()
2092 && root.header != height
2093 {
2094 root.header = height;
2095 self.needs_layout = true;
2096 }
2097 }
2098
2099 pub fn set_font_scale(&mut self, scale: f32) {
2102 let scale = if scale.is_finite() && scale > 0.0 {
2103 scale
2104 } else {
2105 1.0
2106 };
2107 if scale == self.font_scale {
2108 return;
2109 }
2110 self.font_scale = scale;
2111 self.ch_changed(self.root);
2112 self.relayout_text();
2113 }
2114
2115 pub(crate) fn set_default_font(&mut self, family: Option<crate::style::FontFamily>) {
2118 if family == self.default_font {
2119 return;
2120 }
2121 self.default_font = family;
2122 self.ch_changed(self.root);
2123 self.relayout_text();
2124 }
2125
2126 fn relayout_text(&mut self) {
2128 let blocks: Vec<(Key, Kind)> = self
2129 .nodes
2130 .iter()
2131 .filter(|(_, n)| matches!(n.kind, Kind::Text | Kind::Input) && !n.inline)
2132 .map(|(k, n)| (k as Key, n.kind))
2133 .collect();
2134 for (key, kind) in blocks {
2135 if kind == Kind::Text {
2136 self.mark(key, dirty::TEXT_BUILD);
2137 } else {
2138 self.measure_input(key);
2139 self.mark(key, dirty::INPUT);
2140 }
2141 }
2142 }
2143
2144 fn repick_images(&mut self, old: f32, new: f32) {
2147 let changes = |s: &Option<ImageSource>| {
2148 s.as_ref()
2149 .is_some_and(|s| !s.scales.is_empty() && s.variant(old) != s.variant(new))
2150 };
2151 let images: Vec<Key> = self
2152 .nodes
2153 .iter()
2154 .filter(|(_, n)| {
2155 n.image
2156 .as_ref()
2157 .is_some_and(|i| changes(&i.source) || changes(&i.options.placeholder))
2158 })
2159 .map(|(k, _)| k as Key)
2160 .collect();
2161 for key in images {
2162 self.mark(key, dirty::IMAGE);
2163 }
2164 }
2165
2166 pub fn node_count(&self) -> usize {
2168 self.nodes.len()
2169 }
2170
2171 pub fn node_id_room(&self) -> usize {
2175 self.slots.len()
2176 }
2177
2178 pub fn set_access(&mut self, access: Arc<crate::access::Access>) {
2181 {
2183 let _entered = self.components.runtime.enter();
2184 crate::element::global::<crate::element::desktop::WindowAccess>()
2185 .set(crate::element::desktop::WindowAccess(Some(access.clone())));
2186 }
2187 self.components.runtime.set_access(access.clone());
2188 self.access = access;
2189 self.canvas_images.clear();
2190 }
2191
2192 pub fn set_base_url(&mut self, url: Option<Arc<str>>) {
2199 self.base_url = url;
2200 self.canvas_images.clear();
2201 }
2202
2203 pub fn set_media_files(&mut self, files: Arc<crate::access::MediaFiles>) {
2208 self.media_files = files;
2209 self.canvas_images.clear();
2210 }
2211
2212 #[cfg(not(target_arch = "wasm32"))]
2217 pub fn set_image_context(&mut self, context: crate::image::loader::Context) {
2218 crate::image::loader::set_context(context);
2219 }
2220
2221 pub fn set_clipboard(&mut self, backend: Option<Arc<dyn crate::clipboard::ClipboardBackend>>) {
2224 self.clipboard = backend;
2225 }
2226
2227 pub fn set_picker(&mut self, backend: Option<Arc<dyn crate::picker::PickerBackend>>) {
2231 self.picker = backend;
2232 }
2233
2234 pub fn set_quit_mode(&mut self, mode: crate::desktop::QuitMode) {
2238 self.quit_mode = Some(mode);
2239 }
2240
2241 #[doc(hidden)]
2246 pub fn __set_default_quit_mode(&mut self, mode: crate::desktop::QuitMode) {
2247 self.default_quit_mode = mode;
2248 }
2249
2250 pub fn set_main_window(&mut self, options: &crate::desktop::MainWindowOptions) {
2259 self.main_window_options = Some(options.clone());
2260 self.keep_main_placement = options.restore_bounds;
2261 self.main_shown |= options.visible_at_launch();
2262 if let Some(state) = self.components.environment.window_state {
2263 self.keep_window_placement(crate::ROOT_ID, &state);
2264 }
2265 if options.attributes.is_empty() {
2266 return;
2267 }
2268 if self.key(crate::ROOT_ID).is_ok() {
2271 self.window_command(
2272 crate::ROOT_ID,
2273 crate::desktop::DesktopCommand::SetAttributes(Box::new(options.attributes.clone())),
2274 true,
2275 );
2276 }
2277 }
2278
2279 pub fn set_window_backend(&mut self, backend: Option<Arc<dyn crate::desktop::WindowBackend>>) {
2284 self.window_backend = backend;
2285 }
2286
2287 pub fn set_audio(&mut self, backend: Option<Arc<dyn crate::audio::AudioBackend>>) {
2291 self.audio = backend;
2292 }
2293
2294 pub fn set_login_item(&mut self, backend: Option<Arc<dyn crate::desktop::LoginItemBackend>>) {
2299 self.login_item = backend.map(crate::desktop::LoginItems::new);
2300 }
2301
2302 pub fn set_storage(&mut self, backend: Option<Arc<dyn crate::storage::StorageBackend>>) {
2305 self.components
2306 .runtime
2307 .set_storage(crate::storage::Store::new(backend));
2308 }
2309
2310 pub fn set_data_dir(&mut self, dir: Option<std::path::PathBuf>) {
2313 self.components.runtime.set_data_dir(dir);
2314 }
2315
2316 pub fn set_app_info(&mut self, info: Option<crate::platform::AppInfo>) {
2320 self.components.runtime.set_app_info(info);
2321 }
2322
2323 pub fn set_updater(
2327 &mut self,
2328 updater: Option<std::sync::Arc<dyn crate::runtime::UpdaterHost>>,
2329 ) {
2330 self.components.runtime.set_updater(updater);
2331 }
2332
2333 fn deny(&mut self, what: String) {
2335 if self.denied.len() < 256 && self.denied.insert(what.clone()) {
2336 log::warn!(target: "js", "{what}");
2337 }
2338 }
2339
2340 pub fn set_max_nodes(&mut self, max: usize) {
2343 self.max_nodes = max.max(1);
2344 }
2345
2346 pub fn set_resizing(&mut self, resizing: bool) {
2352 if resizing == self.measure_cache.resizing.is_some() {
2353 return;
2354 }
2355 if resizing {
2356 self.resizing_commit = self.resizing_commit.wrapping_add(1).max(1);
2357 self.measure_cache.resizing = Some(self.resizing_commit);
2358 return;
2359 }
2360 self.measure_cache.resizing = None;
2361 let keys: Vec<(Key, LayoutId)> = self
2362 .nodes
2363 .iter()
2364 .filter_map(|(key, node)| Some((key as Key, node.layout?)))
2365 .collect();
2366 for (key, layout) in keys {
2367 let Some(LeafContext::Text(cx)) = self.layout.get_node_context_mut(layout) else {
2368 continue;
2369 };
2370 if std::mem::take(&mut cx.held) {
2371 self.layout.mark_dirty(layout);
2372 self.needs_layout = true;
2373 self.resize_settling = true;
2374 self.queue_text(key);
2375 }
2376 }
2377 }
2378
2379 fn mark_near_screen(&mut self) {
2383 self.resizing_commit = self.resizing_commit.wrapping_add(1).max(1);
2384 self.measure_cache.resizing = Some(self.resizing_commit);
2385 let (width, height) = (self.viewport.width.0, self.viewport.height.0);
2386 let mut stack = vec![(self.root, 0.0f32, 0.0f32)];
2387 while let Some((key, x, y)) = stack.pop() {
2388 let node = &self.nodes[key as usize];
2389 let frame = node.frame;
2390 let (mut x, mut y) = (x, y);
2391 if !frame.origin.x.0.is_nan() {
2395 x += frame.origin.x.0;
2396 y += frame.origin.y.0;
2397 let (w, h) = (frame.size.width.0, frame.size.height.0);
2398 let sized = w > 0.0 && h > 0.0;
2399 if sized
2400 && (x + w < -width || x > 2.0 * width || y + h < -height || y > 2.0 * height)
2401 {
2402 continue;
2403 }
2404 }
2405 if let Some(scroll) = node.scroll.as_deref() {
2406 x -= scroll.offset.0;
2407 y -= scroll.offset.1;
2408 }
2409 stack.extend(node.children.iter().map(|&child| (child, x, y)));
2410 if let Some(layout) = node.layout
2411 && let Some(LeafContext::Text(cx)) = self.layout.get_node_context_mut(layout)
2412 {
2413 cx.near_screen = self.resizing_commit;
2414 if std::mem::take(&mut cx.held) {
2415 self.layout.mark_dirty(layout);
2416 self.queue_text(key);
2417 }
2418 }
2419 }
2420 }
2421
2422 pub fn set_viewport(&mut self, viewport: Size<Points>) {
2424 if viewport != self.viewport {
2425 self.viewport = viewport;
2426 self.resize_settling = true;
2427 let root = self.nodes[self.root as usize].layout.expect("root layout");
2428 self.layout.set_style(root, root_style(viewport));
2429 self.needs_layout = true;
2430 self.components_viewport(viewport);
2432 }
2433 }
2434
2435 pub fn set_scroll_offset(&mut self, id: NodeId, offset: Point<Points>, applied: u32) {
2439 let (x, y) = (offset.x.0, offset.y.0);
2440 let Ok(key) = self.key(id) else { return };
2441 let node = &mut self.nodes[key as usize];
2442 let horizontal = node.scroll.as_ref().is_some_and(|s| s.horizontal);
2443 let mut dependents = false;
2444 let mut moved = false;
2445 if let Some(scroll) = node.scroll.as_mut() {
2446 moved = scroll.offset != (x, y);
2447 let issued = scroll.target.is_some_and(|(n, _)| n <= applied);
2449 scroll.step = match issued {
2450 true => (0.0, 0.0),
2451 false => (x - scroll.offset.0, y - scroll.offset.1),
2452 };
2453 scroll.offset = (x, y);
2454 if issued {
2455 scroll.target = None;
2456 }
2457 if !scroll.dependents.is_empty() {
2458 scroll.pending.retain(|&(n, _)| n > applied);
2459 dependents = true;
2460 }
2461 }
2462 if let Some(list) = node.list.as_mut() {
2463 list.reported(if horizontal { x } else { y }, applied);
2464 }
2465 self.cull_moved(key);
2466 if dependents {
2467 self.dependents_dirty(key);
2468 }
2469 self.follow_changed |= moved && !self.followers.is_empty();
2472 if moved && !self.overlays.is_empty() {
2475 self.overlay_scrolled(key);
2476 }
2477 }
2478
2479 pub fn key_scrolled(&mut self, id: NodeId, key_move: crate::scroll::KeyMove) {
2489 let Ok(key) = self.key(id) else { return };
2490 let queued = self.commands.iter().filter(|(to, _)| *to == id).count() as u32;
2491 let Some(list) = self.nodes[key as usize].list.as_mut() else {
2492 return;
2493 };
2494 if !list.follows_end_key() {
2495 return;
2496 }
2497 if key_move == crate::scroll::KeyMove::End {
2498 let repeat = match list.key_ends.last() {
2500 Some(&n) => n + 1 == queued,
2501 None => queued == 0 && list.follows_end(),
2502 };
2503 if !repeat {
2504 list.key_ends.push(queued);
2505 self.commands
2506 .push((id, Command::ScrollToEnd { animated: true }));
2507 }
2508 return;
2509 }
2510 list.unpin();
2511 let ends = std::mem::take(&mut list.key_ends);
2512 for &n in ends.iter().rev() {
2514 let at = self
2515 .commands
2516 .iter()
2517 .enumerate()
2518 .filter(|(_, (to, _))| *to == id)
2519 .nth(n as usize)
2520 .map(|(at, _)| at);
2521 if let Some(at) = at {
2522 self.commands.remove(at);
2523 }
2524 }
2525 }
2526
2527 pub fn set_kept(&mut self, nodes: &[NodeId]) {
2534 self.selection_kept.clear();
2535 self.selection_kept.extend_from_slice(nodes);
2536 self.sync_kept();
2537 }
2538
2539 fn sync_kept(&mut self) {
2551 let mut holders = std::mem::take(&mut self.kept_scratch);
2552 holders.clear();
2553 holders.extend(
2554 self.selection_kept
2555 .iter()
2556 .filter_map(|&id| self.key(id).ok()),
2557 );
2558 let focus = self
2559 .focus
2560 .filter(|&(key, id)| self.nodes.get(key as usize).is_some_and(|n| n.id == id))
2561 .map(|(key, _)| key);
2562 holders.extend(focus);
2563 holders.extend(self.overlays.iter().copied().filter(|&key| {
2564 self.overlay(key)
2565 .is_some_and(|o| o.host.is_some() && o.config.hint.is_none())
2566 }));
2567 let mut kept: Vec<(Key, u32)> = Vec::new();
2568 for &holder in &holders {
2569 let mut key = holder;
2570 loop {
2573 let parent = self.nodes[key as usize].parent;
2574 if parent == NO_KEY {
2575 break;
2576 }
2577 if let Some(list) = self.nodes[parent as usize].list.as_ref()
2578 && let Some(index) = list
2579 .slots
2580 .iter()
2581 .find(|s| s.cell == key)
2582 .and_then(|s| s.index)
2583 {
2584 kept.push((parent, index));
2585 if focus == Some(holder) {
2586 if index > 0 {
2587 kept.push((parent, index - 1));
2588 }
2589 if index + 1 < list.count {
2590 kept.push((parent, index + 1));
2591 }
2592 }
2593 }
2594 key = parent;
2595 }
2596 }
2597 self.kept_scratch = holders;
2598 if kept.is_empty() && self.kept_lists.is_empty() {
2599 return;
2600 }
2601 let mut lists: Vec<Key> = kept.iter().map(|&(list, _)| list).collect();
2602 lists.sort_unstable();
2603 lists.dedup();
2604 for &list in self.kept_lists.iter().filter(|l| !lists.contains(l)) {
2605 if let Some(state) = self
2606 .nodes
2607 .get_mut(list as usize)
2608 .and_then(|n| n.list.as_mut())
2609 {
2610 state.set_kept(Vec::new());
2611 }
2612 }
2613 for &list in &lists {
2614 let items = kept
2615 .iter()
2616 .filter(|&&(l, _)| l == list)
2617 .map(|&(_, i)| i)
2618 .collect();
2619 if let Some(state) = self.nodes[list as usize].list.as_mut() {
2620 state.set_kept(items);
2621 }
2622 }
2623 self.kept_lists = lists;
2624 }
2625
2626 pub fn set_input_scroll(
2630 &mut self,
2631 id: NodeId,
2632 offset: Point<Points>,
2633 content: Size<Points>,
2634 viewport: Size<Points>,
2635 ) {
2636 let Ok(key) = self.key(id) else { return };
2637 if let Some(input) = self.nodes[key as usize].input.as_mut() {
2638 input.scroll = Some(InputScroll {
2639 offset,
2640 content,
2641 viewport,
2642 });
2643 }
2644 }
2645
2646 pub fn set_zoom(&mut self, id: NodeId, scale: f32) {
2648 let Ok(key) = self.key(id) else { return };
2649 if let Some(scroll) = self.nodes[key as usize].scroll.as_mut() {
2650 scroll.zoom = scale;
2651 }
2652 }
2653
2654 pub fn set_component_size(&mut self, id: NodeId, size: Size<Points>) {
2657 let Ok(key) = self.key(id) else { return };
2658 let Some(layout) = self.nodes[key as usize].layout else {
2659 return;
2660 };
2661 if let Some(LeafContext::Native(own)) = self.layout.get_node_context_mut(layout)
2662 && *own != Some(size)
2663 {
2664 *own = Some(size);
2665 self.layout.mark_dirty(layout);
2666 self.needs_layout = true;
2667 }
2668 }
2669
2670 pub fn scroll_listener(&self, id: NodeId) -> Option<(f32, Size<Points>, Size<Points>, f32)> {
2674 let node = &self.nodes[self.key(id).ok()? as usize];
2675 if !node.events.contains(EventKind::Scroll) {
2676 return None;
2677 }
2678 let scroll = node.scroll.as_ref()?;
2679 let frame = node.frame.size;
2680 let content = scroll.content.unwrap_or(frame);
2681 let z = scroll.zoom;
2682 Some((scroll.event_throttle_ms, content * z, frame, z))
2683 }
2684
2685 pub fn take_list_binds(&mut self, out: &mut Vec<ListBind>) {
2690 out.append(&mut self.list_binds);
2691 }
2692
2693 pub fn has_paced_list_binds(&self) -> bool {
2695 !self.paced_lists.is_empty()
2696 }
2697
2698 pub fn take_paced_list_binds(&mut self, cells: usize, out: &mut Vec<ListBind>) {
2703 let mut left = cells;
2704 let mut lists = std::mem::take(&mut self.paced_lists);
2705 let mut one = std::mem::take(&mut self.paced_scratch);
2706 let start = out.len();
2707 while left > 0 && !lists.is_empty() {
2708 lists.retain(|&id| {
2709 if left == 0 {
2710 return true;
2711 }
2712 let Some(list) = self
2713 .key(id)
2714 .ok()
2715 .and_then(|key| self.nodes[key as usize].list.as_mut())
2716 else {
2717 return false;
2718 };
2719 one.clear();
2720 left -= list.take_paced(1, &mut one);
2721 if let Some((slot, index)) = one.pop() {
2722 match out[start..].iter_mut().find(|b| b.list == id) {
2723 Some(bind) => bind.binds.push((slot, index)),
2724 None => out.push(ListBind {
2725 list: id,
2726 binds: vec![(slot, index)],
2727 }),
2728 }
2729 }
2730 list.has_paced()
2731 });
2732 }
2733 self.paced_lists = lists;
2734 self.paced_scratch = one;
2735 }
2736
2737 pub fn has_events(&self) -> bool {
2739 !self.events.is_empty()
2740 }
2741
2742 pub fn take_events(&mut self, out: &mut Vec<crate::element::JsEvent>) {
2746 if !self.asked_rows.is_empty() {
2747 let rows = std::mem::take(&mut self.asked_rows);
2748 self.events.push(crate::element::JsEvent::Rows(rows));
2749 }
2750 out.append(&mut self.events);
2751 self.components.executor.hand_answers();
2754 }
2755
2756 pub fn has_due_answers(&self) -> bool {
2760 self.components.executor.has_due_answers()
2761 }
2762
2763 pub fn register_font(&mut self, data: &[u8]) -> Result<(), String> {
2766 self.text_engine
2767 .register_font(&crate::text::font_data(data)?)?;
2768 self.fonts_changed();
2769 Ok(())
2770 }
2771
2772 pub fn fonts_changed(&mut self) {
2776 self.zero_advances.clear();
2777 self.ch_changed(self.root);
2778 self.measure_cache.clear();
2779 let blocks: Vec<Key> = self
2780 .nodes
2781 .iter()
2782 .filter(|(_, n)| {
2783 matches!(n.kind, Kind::Text | Kind::Input) && !n.inline && n.layout.is_some()
2784 })
2785 .map(|(k, _)| k as Key)
2786 .collect();
2787 for key in blocks {
2788 let layout = self.nodes[key as usize].layout.expect("text layout");
2789 let cx = self.text_cx(layout);
2790 cx.prepared = None;
2791 cx.min_content = None;
2792 cx.cache = None;
2793 cx.baseline = None;
2794 cx.same_lines = None;
2795 cx.no_ahead = false;
2796 cx.laid_out = None;
2797 if let Some(field) = &mut cx.field {
2798 field.prepared = None;
2799 field.cache = None;
2800 }
2801 self.layout.mark_dirty(layout);
2802 self.needs_layout = true;
2803 if self.nodes[key as usize].kind == Kind::Text {
2804 self.queue_text(key);
2805 } else {
2806 self.mark(key, dirty::INPUT);
2808 }
2809 }
2810 }
2811
2812 pub fn remount(&mut self) {
2817 self.fonts_changed();
2818 let keys: Vec<Key> = self
2819 .nodes
2820 .iter()
2821 .filter(|(_, n)| n.created)
2822 .map(|(k, _)| k as Key)
2823 .collect();
2824 for key in keys {
2825 let flags = self.mount_state(key);
2826 self.mark(key, flags);
2827 let node = &mut self.nodes[key as usize];
2828 if let Some(root) = node.root.as_mut() {
2829 root.laid_out = None;
2830 }
2831 let id = node.id;
2836 if let Some(scroll) = node.scroll.as_mut()
2837 && let Some(size) = scroll.content
2838 {
2839 scroll.content_item = Some((self.batches, self.mount.len()));
2840 self.mount.push(MountItem::ScrollContent { id, size });
2841 }
2842 if let Some(layout) = node.layout {
2843 self.layout.mark_dirty(layout);
2845 }
2846 let ranges = self.sticky_ranges(key);
2850 if !ranges.is_empty() {
2851 self.mount.push(MountItem::StickyCells {
2852 id,
2853 cells: ranges
2854 .into_iter()
2855 .map(|r| StickyCell {
2856 cell: r.cell,
2857 start: Points(r.start),
2858 end: Points(r.end),
2859 offset: r.offset,
2860 })
2861 .collect(),
2862 });
2863 }
2864 }
2865 self.needs_layout = true;
2866 }
2867
2868 pub fn limit_paste(&self, id: NodeId, payload: &mut EventPayload) {
2873 let EventPayload::Paste(paste) = payload else {
2874 return;
2875 };
2876 let max = self
2877 .key(id)
2878 .ok()
2879 .and_then(|key| self.nodes[key as usize].input.as_ref())
2880 .and_then(|input| input.config.paste_max_size);
2881 if let Some(max) = max {
2882 paste.limit_files(max);
2883 }
2884 }
2885
2886 pub fn input_changed(&mut self, id: NodeId, text: &str, count: u32) {
2889 let Ok(key) = self.key(id) else { return };
2890 let Some(input) = self.nodes[key as usize].input.as_mut() else {
2891 return;
2892 };
2893 input.count = count;
2894 if input.value != text {
2895 input.value.clear();
2896 input.value.push_str(text);
2897 self.measure_input(key);
2898 }
2899 }
2900
2901 pub fn input_composing(&mut self, id: NodeId, shown: Option<&str>) {
2907 let Ok(key) = self.key(id) else { return };
2908 let Some(input) = self.nodes[key as usize].input.as_mut() else {
2909 return;
2910 };
2911 if input.composing.as_deref() == shown {
2912 return;
2913 }
2914 input.composing = shown.map(str::to_owned);
2915 self.measure_input(key);
2916 }
2917
2918 pub fn apply(&mut self, op: Op) -> Result<(), ApplyError> {
2920 let _entered = self.components.runtime.enter();
2921 if self.components.instances.is_empty()
2926 && !matches!(
2927 op,
2928 Op::Command {
2929 command: Command::Native { .. },
2930 ..
2931 } | Op::Listen {
2932 id: ROOT_ID,
2933 event: EventKind::BackPress | EventKind::BackProgress | EventKind::KeyCommand,
2934 ..
2935 } | Op::SetProp {
2936 id: ROOT_ID,
2937 prop: Prop::Keymap(_),
2938 }
2939 )
2940 {
2941 return self.apply_op(op);
2942 }
2943 match self.intercept(op)? {
2944 Some(op) => self.apply_op(op),
2945 None => Ok(()),
2946 }
2947 }
2948
2949 fn apply_op(&mut self, op: Op) -> Result<(), ApplyError> {
2951 if !self.runs.is_empty()
2952 && let Op::Evaluate { id, .. }
2953 | Op::Draw { id, .. }
2954 | Op::SetStyle { id, .. }
2955 | Op::SetProp { id, .. }
2956 | Op::Listen { id, .. }
2957 | Op::Placeholder { id }
2958 | Op::Command { id, .. } = op
2959 {
2960 self.materialize_run(id)?;
2961 }
2962 match op {
2963 Op::Evaluate {
2964 id,
2965 call,
2966 script,
2967 timeout,
2968 } => {
2969 self.start_js_web_evaluation(id, call, script, timeout);
2970 Ok(())
2971 }
2972 Op::RenderCanvas { call, request } => {
2973 self.start_js_canvas_render(call, *request);
2974 Ok(())
2975 }
2976 Op::Rust(op) => {
2977 self.run_rust(op);
2978 Ok(())
2979 }
2980 Op::Create { id, tag } => self.create(id, tag),
2981 Op::CreateText { id, text } => {
2982 let idx = id as usize;
2983 if self.slots.contains(idx) || self.runs.contains_key(&id) {
2984 return Err(ApplyError::DuplicateNode(id));
2985 }
2986 self.check_id_range(id)?;
2987 if self.fold_runs {
2988 if self.nodes.len().saturating_add(self.runs.len()) >= self.max_nodes {
2989 return Err(ApplyError::TooManyNodes(self.max_nodes));
2990 }
2991 self.runs.insert(
2992 id,
2993 Run {
2994 text,
2995 block: NO_KEY,
2996 },
2997 );
2998 self.admitted_id_extent = self.admitted_id_extent.max(idx.saturating_add(1));
2999 return Ok(());
3000 }
3001 let key = self.alloc(id, Kind::RawText)?;
3002 self.nodes[key as usize].text = text;
3003 Ok(())
3004 }
3005 Op::SetText { id, text } => {
3006 if let Some(run) = self.runs.get_mut(&id) {
3007 if run.text != text {
3008 run.text = text;
3009 let block = run.block;
3010 if block != NO_KEY {
3011 self.mark_text_block(block);
3012 }
3013 }
3014 return Ok(());
3015 }
3016 let key = self.key(id)?;
3017 let node = &mut self.nodes[key as usize];
3018 if node.text != text {
3019 node.text = text;
3020 if node.inline {
3021 self.mark_text_block(key);
3022 }
3023 }
3024 Ok(())
3025 }
3026 Op::SetStyle { id, style, patch } => self.set_inline_style(id, style, patch),
3027 Op::SetProp { id, prop } => {
3028 let role = matches!(
3029 prop,
3030 Prop::Accessibility(
3031 AccessibilityProp::Role(_)
3032 | AccessibilityProp::Label(_)
3033 | AccessibilityProp::State(_)
3034 ) | Prop::Scrollbar(_)
3035 | Prop::Horizontal(_)
3036 );
3037 let result = self.set_prop(id, prop);
3038 if role && let Ok(key) = self.key(id) {
3039 self.sync_grid_role(key);
3040 }
3041 result
3042 }
3043 Op::Listen { id, event, enabled } => {
3044 let key = self.key(id)?;
3045 let node = &mut self.nodes[key as usize];
3046 let before = node.events;
3047 node.events.set(event, enabled);
3048 if PRESSES.contains(&event) || HANDLED.contains(&event) {
3049 self.sync_grid_role(key);
3050 }
3051 if event == EventKind::Layout && enabled && !before.contains(event) {
3052 self.report_frame(key);
3053 }
3054 let node = &self.nodes[key as usize];
3055 let key_events = matches!(event, EventKind::KeyDown | EventKind::KeyUp);
3056 if node.events != before {
3057 let relink = node.inline && (pressable(before) || pressable(node.events));
3058 let overlay_listeners = node.is_overlay()
3059 && matches!(event, EventKind::PressOutside | EventKind::Cancel);
3060 self.mark(key, dirty::EVENTS);
3061 if overlay_listeners {
3062 self.dirty_overlay_listeners();
3063 }
3064 if key_events {
3065 self.key_ancestry_dirty = true;
3066 }
3067 if relink {
3069 self.mark_text_block(key);
3070 }
3071 }
3072 if enabled
3075 && matches!(
3076 event,
3077 EventKind::Scroll
3078 | EventKind::Refresh
3079 | EventKind::ScrollEnd
3080 | EventKind::ScrollDragStart
3081 | EventKind::ScrollDragEnd
3082 | EventKind::MomentumStart
3083 | EventKind::MomentumEnd
3084 )
3085 && self.nodes[key as usize]
3086 .list
3087 .as_ref()
3088 .is_some_and(|l| l.parent)
3089 {
3090 self.warn_ignored(key);
3091 }
3092 Ok(())
3093 }
3094 Op::Insert {
3095 parent,
3096 child,
3097 before,
3098 } => self.insert(parent, child, before),
3099 Op::Remove { parent, child } => {
3100 let parent = self.key(parent)?;
3101 if let Some(run) = self.runs.get(&child) {
3102 if run.block != parent {
3103 return Err(ApplyError::NotAChild(child));
3104 }
3105 self.unfold_run(child);
3106 return Ok(());
3107 }
3108 let child = self.key(child)?;
3109 if self.nodes[child as usize].parent != parent {
3110 return Err(ApplyError::NotAChild(self.nodes[child as usize].id));
3111 }
3112 self.detach(child);
3113 Ok(())
3114 }
3115 Op::Release { id } => self.release(id),
3116 Op::Placeholder { id } => {
3117 let key = self.key(id)?;
3118 self.placeholder(key);
3119 Ok(())
3120 }
3121 Op::Animation(op) => {
3122 if self.reach.apply(&op) && !self.culling.is_empty() {
3125 self.cull_dirty = true;
3126 }
3127 self.mount.push(MountItem::Animation(op));
3128 Ok(())
3129 }
3130 Op::Draw { id, mut drawing } => {
3131 let key = self.key(id)?;
3132 if self.nodes[key as usize].kind != Kind::Canvas {
3133 return Ok(());
3134 }
3135 self.check_canvas_images(&mut drawing);
3136 let node = &mut self.nodes[key as usize];
3137 let slots_changed = node
3138 .drawing
3139 .as_ref()
3140 .map_or(!drawing.slots.is_empty(), |d| d.slots != drawing.slots);
3141 if node.drawing.as_deref() == Some(&*drawing) {
3142 return Ok(());
3143 }
3144 if node.drawing.is_none() && drawing.ops.is_empty() && drawing.nodes.is_empty() {
3147 return Ok(());
3148 }
3149 let background_moved = node.drawing.as_ref().is_some_and(|d| d.paints_background())
3152 != drawing.paints_background();
3153 let natural = drawing.fit().map(|fit| fit.size);
3156 if node
3157 .drawing
3158 .as_ref()
3159 .and_then(|d| d.fit())
3160 .map(|fit| fit.size)
3161 != natural
3162 && let Some(layout) = node.layout
3163 {
3164 self.layout
3165 .set_node_context(layout, natural.map(|n| LeafContext::Image(Some(n))));
3166 self.layout.mark_dirty(layout);
3167 self.needs_layout = true;
3168 }
3169 let node = &mut self.nodes[key as usize];
3170 node.drawing = Some(Arc::from(drawing));
3171 let flags = dirty::CANVAS
3172 | if slots_changed { dirty::ANIMATION } else { 0 }
3173 | if background_moved { dirty::VIEW } else { 0 };
3174 self.mark(key, flags);
3175 Ok(())
3176 }
3177 Op::Command {
3178 id: crate::ROOT_ID,
3179 command: Command::LayoutAnimation(animation),
3180 } => {
3181 self.layout_animation = Some(animation);
3182 Ok(())
3183 }
3184 Op::Command {
3186 id,
3187 command: Command::LayoutAnimation(animation),
3188 } => {
3189 self.key(id)?;
3190 if let Some(transition) = animation.update {
3191 self.scope_layout_animation(id, transition);
3192 }
3193 Ok(())
3194 }
3195 Op::Command {
3196 id: crate::ROOT_ID,
3197 command: Command::SetStatusBar(patch),
3198 } => {
3199 self.components.status_bars.set_base(patch);
3200 Ok(())
3201 }
3202 Op::Command {
3205 id,
3206 command: Command::SetJsResponder { block },
3207 } => {
3208 self.key(id)?;
3209 self.block_native(touch::Side::Js, block.then_some(id));
3210 Ok(())
3211 }
3212 Op::Command {
3213 id,
3214 command: Command::CancelPress,
3215 } => {
3216 self.key(id)?;
3217 self.cancel_press(id);
3218 Ok(())
3219 }
3220 Op::Command {
3221 command: Command::ClearJsResponder,
3222 ..
3223 } => {
3224 self.block_native(touch::Side::Js, None);
3225 Ok(())
3226 }
3227 Op::Command {
3229 id,
3230 command: Command::Measure { call },
3231 } if self.key(id).is_err() => {
3232 self.answer_measure(id, call);
3233 Ok(())
3234 }
3235 Op::Command {
3236 id,
3237 command: Command::MeasureScrollPosition { call },
3238 } if self.key(id).is_err() => {
3239 self.answer_scroll_position(id, call);
3240 Ok(())
3241 }
3242 Op::Command {
3245 id,
3246 command: Command::Desktop(desktop),
3247 } if desktop.is_core_handled() => {
3248 self.key(id)?;
3249 self.window_command(id, *desktop, false);
3250 Ok(())
3251 }
3252 Op::Command { id, command } => {
3253 self.key(id)?;
3254 self.commands.push((id, command));
3255 Ok(())
3256 }
3257 }
3258 }
3259
3260 fn window_command(
3265 &mut self,
3266 id: NodeId,
3267 command: crate::desktop::DesktopCommand,
3268 launch: bool,
3269 ) {
3270 use crate::desktop::{
3271 DesktopCommand, WindowPlacement, WindowRequest,
3272 window::{WindowRecord, placement_key},
3273 };
3274 match command {
3275 DesktopCommand::SetQuitMode(_) if !self.access.allows_application() => {
3278 self.deny(
3279 "the application (its main window, menu, tray, global shortcuts, quitting and restarting) is not granted: add `\"application\": true` to capabilities in nsh.json".into(),
3280 );
3281 }
3282 DesktopCommand::SetAttributes(_)
3285 if id == crate::ROOT_ID && !launch && !self.access.allows_application() =>
3286 {
3287 self.deny(
3288 "the application (its main window, menu, tray, global shortcuts, quitting and restarting) is not granted: add `\"application\": true` to capabilities in nsh.json".into(),
3289 );
3290 }
3291 DesktopCommand::Request(WindowRequest::SetPlacement(_))
3292 if id == crate::ROOT_ID && !self.access.allows_application() =>
3293 {
3294 self.deny(
3295 "the application (its main window, menu, tray, global shortcuts, quitting and restarting) is not granted: add `\"application\": true` to capabilities in nsh.json".into(),
3296 );
3297 }
3298 DesktopCommand::SetAttributes(_) if !self.has_window() => {
3299 log::debug!("window attributes of view {id}: the surface has no window");
3300 }
3301 DesktopCommand::SetAttributes(mut attributes) => {
3302 attributes.sanitize();
3303 let denied = self.access.deny_window_attributes(&mut attributes);
3304 if !denied.is_empty() {
3305 self.deny(format!(
3306 "nsh/desktop: the window attributes {} are not granted by capabilities.windows: left as they are",
3307 denied.join(", ")
3308 ));
3309 }
3310 if attributes.size_to_content.is_some()
3313 && let Ok(key) = self.key(id)
3314 && let Some(layout) = self.nodes[key as usize].layout
3315 {
3316 self.layout.mark_dirty(layout);
3317 self.needs_layout = true;
3318 }
3319 self.windows
3320 .entry(id)
3321 .or_default()
3322 .pending
3323 .merge(&attributes);
3324 }
3325 DesktopCommand::SetQuitMode(mode) => {
3326 self.quit_mode = Some(mode);
3327 }
3328 DesktopCommand::OpenWindow(mut open) => {
3329 let options = &mut open.options;
3330 let open_now = self
3333 .window_ids
3334 .values()
3335 .filter(|(node, _)| *node != id && self.key(*node).is_ok())
3336 .count();
3337 if !self.launch_defaults_applied {
3343 if let Some(defaults) = self.main_window_options.clone() {
3344 if options.default_size.is_none() {
3345 options.default_size = defaults.default_size;
3346 }
3347 if options.default_position.is_none() {
3348 options.default_position = defaults.default_position;
3349 }
3350 if options.display.is_none() {
3351 options.display = defaults.display;
3352 }
3353 if options.default_mode.is_none() {
3354 options.default_mode = defaults.default_mode;
3355 }
3356 if !options.restore_bounds {
3357 options.restore_bounds = defaults.restore_bounds;
3358 }
3359 let mut attributes = defaults.attributes;
3360 attributes.merge(&options.attributes);
3361 options.attributes = attributes;
3362 }
3363 if let Some(state) = self.components.environment.window_state {
3364 if options.default_size.is_none() {
3365 options.default_size = Some(state.content_bounds.size);
3366 }
3367 if options.default_position.is_none() {
3368 options.default_position =
3369 Some(crate::desktop::WindowPosition::At(state.bounds.origin));
3370 }
3371 }
3372 }
3373 if !open.implicit
3376 && let Err(message) =
3377 self.access
3378 .check_window(options.kind, &options.attributes, open_now)
3379 {
3380 self.deny(format!("nsh/desktop: {message}: the window does not open"));
3381 return;
3382 }
3383 self.launch_defaults_applied = true;
3386 options.attributes.sanitize();
3387 options.attributes =
3388 crate::desktop::WindowAttributes::resolve(options.kind, &options.attributes);
3389 open.parent = options
3392 .parent
3393 .as_deref()
3394 .and_then(|parent| self.window_ids.get(parent).map(|(node, _)| *node));
3395 if options.restore_bounds {
3396 let _entered = self.components.runtime.enter();
3397 open.placement = crate::storage::Storage::get_item(&placement_key(&options.id))
3398 .and_then(|json| serde_json::from_str::<WindowPlacement>(&json).ok())
3399 .map(|p| self.components.runtime.fit_window_placement(p));
3400 }
3401 let size = open
3402 .placement
3403 .map(|p| p.bounds.size)
3404 .or(options.default_size);
3405 self.windows.insert(
3406 id,
3407 WindowRecord::opened(options.attributes.clone(), size, open.implicit),
3408 );
3409 self.window_ids
3410 .insert(options.id.clone(), (id, options.restore_bounds));
3411 self.key_ancestry_dirty = true;
3412 self.commands.push((
3413 id,
3414 Command::Desktop(Box::new(DesktopCommand::OpenWindow(open))),
3415 ));
3416 }
3417 DesktopCommand::Request(WindowRequest::SetPlacement(placement)) => {
3420 let placement = self.components.runtime.fit_window_placement(placement);
3421 self.commands.push((
3422 id,
3423 Command::Desktop(Box::new(DesktopCommand::Request(
3424 WindowRequest::SetPlacement(placement),
3425 ))),
3426 ));
3427 }
3428 other => self.commands.push((id, Command::Desktop(Box::new(other)))),
3429 }
3430 }
3431
3432 fn flush_windows(&mut self) {
3435 if self.windows.is_empty() {
3436 return;
3437 }
3438 let had_windows = !self.window_ids.is_empty();
3439 let gone: Vec<NodeId> = self
3440 .windows
3441 .keys()
3442 .copied()
3443 .filter(|&id| {
3447 !self
3448 .key(id)
3449 .is_ok_and(|k| id == crate::ROOT_ID || self.nodes[k as usize].parent != NO_KEY)
3450 })
3451 .collect();
3452 let mut closed_implicit = false;
3453 for id in gone {
3454 if let Some(record) = self.windows.remove(&id) {
3455 closed_implicit |= record.implicit;
3456 }
3457 self.window_ids.retain(|_, (node, _)| *node != id);
3458 }
3459 if had_windows && self.window_ids.is_empty() {
3474 self.last_window_closed();
3475 let mode = self.quit_mode.unwrap_or(if closed_implicit {
3476 crate::desktop::QuitMode::LastWindowClosed
3477 } else {
3478 self.default_quit_mode
3479 });
3480 if mode.quits(self.components.environment.os) {
3481 self.commands.push((
3482 ROOT_ID,
3483 Command::Desktop(Box::new(crate::desktop::DesktopCommand::Quit)),
3484 ));
3485 }
3486 }
3487 let mut ids: Vec<NodeId> = self.windows.keys().copied().collect();
3488 ids.sort_unstable();
3489 for id in ids {
3490 let Some(diff) = self.windows.get_mut(&id).and_then(|r| r.take_diff()) else {
3491 continue;
3492 };
3493 let at = self
3496 .commands
3497 .iter()
3498 .position(|(to, c)| {
3499 *to == id
3500 && matches!(c, Command::Desktop(d)
3501 if matches!(**d, crate::desktop::DesktopCommand::Request(_)))
3502 })
3503 .unwrap_or(self.commands.len());
3504 self.commands.insert(
3505 at,
3506 (
3507 id,
3508 Command::Desktop(Box::new(crate::desktop::DesktopCommand::SetAttributes(
3509 Box::new(diff),
3510 ))),
3511 ),
3512 );
3513 }
3514 }
3515
3516 fn fit_window(&mut self, key: Key, layout: LayoutId) {
3521 let id = self.nodes[key as usize].id;
3522 let Some(record) = self.windows.get_mut(&id) else {
3523 return;
3524 };
3525 let (width, height) = record.fits();
3526 if !width && !height {
3527 record.fitted = None;
3528 return;
3529 }
3530 let laid_out = self.layout.unrounded_layout(layout).size;
3531 let size = crate::geometry::size(
3532 Points(laid_out.width.ceil()),
3533 Points(laid_out.height.ceil()),
3534 );
3535 if record.fitted == Some(size) {
3536 return;
3537 }
3538 record.fitted = Some(size);
3539 self.commands.push((
3540 id,
3541 Command::Desktop(Box::new(crate::desktop::DesktopCommand::Request(
3542 crate::desktop::WindowRequest::SetContentSize {
3543 width: width.then_some(size.width),
3544 height: height.then_some(size.height),
3545 },
3546 ))),
3547 ));
3548 }
3549
3550 pub(crate) fn root_view_size(&self, key: Key) -> Option<Size<Points>> {
3558 let node = &self.nodes[key as usize];
3559 if let Some(size) = node.root.as_ref().and_then(|r| r.reported) {
3560 return Some(size);
3561 }
3562 if self.window_ids.values().any(|(id, _)| *id == node.id) {
3563 return self.windows.get(&node.id).and_then(|r| r.fitted.or(r.size));
3564 }
3565 Some(self.viewport)
3566 }
3567
3568 pub(crate) fn window_of(&self, key: Key) -> NodeId {
3571 if self.window_ids.is_empty() {
3572 return crate::ROOT_ID;
3573 }
3574 let mut k = self.nodes[key as usize].parent;
3575 while k != NO_KEY {
3576 let n = &self.nodes[k as usize];
3577 if n.kind == Kind::Modal && self.window_ids.values().any(|(node, _)| *node == n.id) {
3578 return n.id;
3579 }
3580 k = n.parent;
3581 }
3582 crate::ROOT_ID
3583 }
3584
3585 fn has_window(&self) -> bool {
3591 let os = self.components.environment.os;
3592 os.is_desktop() || os == crate::platform::Os::Web
3593 }
3594
3595 pub(crate) fn keep_window_placement(
3605 &mut self,
3606 id: NodeId,
3607 state: &crate::desktop::WindowState,
3608 ) {
3609 if id == crate::ROOT_ID {
3610 self.main_shown |= state.visible;
3611 if !self.main_shown {
3612 return;
3613 }
3614 }
3615 let key = if id == crate::ROOT_ID {
3616 self.keep_main_placement
3617 .then(|| crate::desktop::window::placement_key("main"))
3618 } else {
3619 self.window_ids
3620 .iter()
3621 .find(|(_, (node, keep))| *node == id && *keep)
3622 .map(|(key, _)| crate::desktop::window::placement_key(key))
3623 };
3624 let Some(key) = key else {
3625 return;
3626 };
3627 if let Ok(json) = serde_json::to_string(&state.placement) {
3628 let _entered = self.components.runtime.enter();
3629 if crate::storage::Storage::get_item(&key).as_deref() != Some(json.as_str()) {
3630 let _ = crate::storage::Storage::set_item(key, json);
3631 }
3632 }
3633 }
3634
3635 pub fn content_height(&self) -> Option<Points> {
3643 self.nodes[self.root as usize]
3644 .children
3645 .iter()
3646 .filter_map(|&key| {
3647 let node = &self.nodes[key as usize];
3648 let layout = node.layout?;
3649 if node.is_layout_root()
3650 || self.layout.displays_none(layout)
3651 || matches!(
3652 self.layout.style(layout).position,
3653 Position::Absolute | Position::Fixed
3654 )
3655 || node.frame.origin.y.0.is_nan()
3656 {
3657 return None;
3658 }
3659 Some(node.frame.origin.y.0 + node.frame.size.height.0)
3660 })
3661 .reduce(f32::max)
3662 .map(Points)
3663 }
3664
3665 pub fn commit(&mut self) -> Option<MountBatch> {
3668 self.geometries.clear();
3671 self.poll_downloads();
3674 if self.components.executor.has_due_answers() {
3678 self.run_answers();
3679 }
3680 self.pace_commit();
3681 self.sync_quit_requests();
3682 self.commit_round();
3683 for _ in 0..MAX_VIRTUAL_ROUNDS {
3690 let watched = self.sync_watches();
3691 if !self.bind_virtual_lists()
3694 && !std::mem::take(&mut self.extent_changed)
3695 && !watched
3696 && !std::mem::take(&mut self.cull_made)
3697 && !std::mem::take(&mut self.placeholders_resized)
3698 && self.scrollbars_pending.is_empty()
3699 {
3700 break;
3701 }
3702 self.commit_round();
3703 }
3704 if !self.outer_asked.is_empty() {
3705 self.send_outer_scrolls();
3706 }
3707 if self.sync_quit_requests() {
3709 self.commit_round();
3710 }
3711 self.split_scoped_frames();
3712 self.mark_shader_inputs();
3713 if !self.transition_starts.is_empty() {
3714 let starts = std::mem::take(&mut self.transition_starts);
3717 self.mount.splice(0..0, starts);
3718 }
3719 if std::mem::take(&mut self.tab_places_stale) && !self.overlays.is_empty() {
3720 self.order_overlays_for_tab();
3721 }
3722 if std::mem::take(&mut self.tree_order_changed) {
3723 let mut order = Vec::new();
3724 let mut pending = vec![self.root];
3725 let mut cells = Vec::new();
3726 while let Some(key) = pending.pop() {
3727 let node = &self.nodes[key as usize];
3728 if node.created {
3729 order.push(node.id);
3730 }
3731 match &node.list {
3732 Some(list) if node.children.len() > 1 => {
3736 cells.clear();
3737 cells.extend_from_slice(&node.children);
3738 let start = |k: &Key| {
3739 let at = self.nodes[*k as usize].frame.origin;
3740 if list.horizontal {
3741 (at.x.0, at.y.0)
3742 } else {
3743 (at.y.0, at.x.0)
3744 }
3745 };
3746 cells.sort_by(|a, b| {
3747 let (a, b) = (start(a), start(b));
3748 a.0.total_cmp(&b.0).then(a.1.total_cmp(&b.1))
3749 });
3750 pending.extend(cells.iter().rev().copied());
3751 }
3752 _ => pending.extend(node.children.iter().rev().copied()),
3753 }
3754 }
3755 self.mount.push(MountItem::TreeOrder(order));
3756 }
3757 if self.mount.is_empty() || matches!(self.mount[..], [MountItem::LayoutAnimation(_)]) {
3758 self.mount.clear();
3759 None
3760 } else {
3761 self.batches += 1;
3762 Some(MountBatch {
3763 items: std::mem::take(&mut self.mount),
3764 })
3765 }
3766 }
3767
3768 pub fn set_tree_order_tracking(&mut self, enabled: bool) {
3771 self.track_tree_order = enabled;
3772 self.tree_order_changed = enabled;
3773 }
3774
3775 pub fn set_projected_state_mounting(&mut self, enabled: bool) {
3781 self.mount_projected = enabled;
3782 }
3783
3784 fn commit_round(&mut self) {
3787 if !self.components.hovers.is_empty() {
3789 self.pass_hovers();
3790 }
3791 if !self.scrollbars_pending.is_empty() {
3793 self.sync_scrollbars();
3794 }
3795 self.render_components();
3797 self.flush_positions();
3801 self.prepare_reveals();
3802 let visible_moved = std::mem::take(&mut self.focus_visible_moved);
3806 let held = self.blur_held && self.focus.is_none() && !self.focus_chain.is_empty();
3808 if self.focus_moved && !held {
3809 self.update_focus_within();
3810 self.update_focus_visible();
3811 if !self.overlays.is_empty() {
3813 self.focus_hints();
3814 }
3815 } else if visible_moved {
3816 self.update_focus_visible();
3819 }
3820 self.sync_pointer_keymap();
3821 self.sync_colors();
3822 self.sync_ch();
3823 self.sync_fixed();
3824 self.sync_overlays();
3825 if std::mem::take(&mut self.key_ancestry_dirty) {
3826 self.sync_key_parents();
3827 self.sync_key_contents();
3828 }
3829 if self.focus.is_some() || !self.overlays.is_empty() || !self.kept_lists.is_empty() {
3832 self.sync_kept();
3833 }
3834 self.sync_back();
3835 self.sync_back_progress();
3836 self.sync_keys();
3837 self.sync_env();
3840 if let Some(animation) = self.layout_animation.take() {
3841 self.note_list_motion(animation);
3842 self.mount.insert(0, MountItem::LayoutAnimation(animation));
3843 }
3844 self.flush_pointer_events();
3845 if !self.relators.is_empty() {
3846 self.sync_relations();
3847 }
3848 self.flush_dirty();
3849 let relayout = self.needs_layout;
3850 if relayout {
3851 self.needs_layout = false;
3852 let settling = std::mem::take(&mut self.resize_settling);
3853 let anchors = if settling || self.measure_cache.resizing.is_some() {
3854 self.resize_anchors()
3855 } else {
3856 Vec::new()
3857 };
3858 if self.measure_cache.resizing.is_some() {
3859 self.mark_near_screen();
3860 }
3861 let relaid = self.relayout_boundaries();
3864 if self.layout_main() {
3867 let root = self.root;
3868 let children = std::mem::take(&mut self.nodes[root as usize].children);
3869 for &child in &children {
3870 if !self.nodes[child as usize].is_layout_root() {
3871 self.emit_frames(child);
3872 }
3873 }
3874 self.nodes[root as usize].children = children;
3875 }
3876 self.layout_roots();
3878 self.layout_cells();
3879 for key in relaid {
3880 self.emit_frames(key);
3881 }
3882 self.keep_resize_anchors(anchors);
3883 }
3884 let sized = relayout && !self.placeholders.is_empty() && self.size_placeholders();
3887 if sized {
3888 self.cull_dirty = true;
3889 } else if self.cull_dirty || (relayout && !self.culling.is_empty()) {
3890 self.sync_culled();
3892 }
3893 self.update_lists(relayout);
3894 if std::mem::take(&mut self.cells_framed) && !sized && !self.culling.is_empty() {
3901 self.sync_culled();
3902 }
3903 if !self.slop_moved.is_empty() {
3904 self.update_slop_overflow();
3905 }
3906 if !self.pace.waiting.is_empty() {
3909 self.sync_paced();
3910 }
3911 self.place_followers(relayout);
3913 if !self.decorated.is_empty() {
3914 self.layout_scrollbars();
3915 }
3916 if !self.overlays.is_empty() {
3917 self.place_overlays();
3918 }
3919 if !self.fitted_pending.is_empty() {
3920 self.send_fitted();
3921 }
3922 self.flush_text();
3923 self.sync_status_bars();
3925 if let Some(config) = self.components.status_bars.take_changed() {
3926 self.commands
3927 .push((crate::ROOT_ID, Command::StatusBar(config)));
3928 }
3929 self.sync_orientations();
3930 self.flush_windows();
3932 for (id, answer) in std::mem::take(&mut self.components.measures) {
3934 answer.borrow_mut().deliver(self.measure(id));
3935 }
3936 for (id, answer) in std::mem::take(&mut self.components.scroll_positions) {
3937 answer.borrow_mut().deliver(self.list_scroll_position(id));
3938 }
3939 for (id, answer) in std::mem::take(&mut self.components.transition_times) {
3941 answer.borrow_mut().deliver(self.transition_time(id));
3942 }
3943 for (id, answer) in std::mem::take(&mut self.components.text_contents) {
3945 answer.borrow_mut().deliver(self.text_content(id));
3946 }
3947 if self
3950 .commands
3951 .iter()
3952 .any(|(_, c)| matches!(c, Command::Reveal(_)))
3953 {
3954 let mut projected = Vec::new();
3955 for (id, command) in std::mem::take(&mut self.commands) {
3956 let commands = match command {
3957 Command::Reveal(options) => self.reveal_scrolls(id, options, &projected),
3958 command => vec![(id, command)],
3959 };
3960 for (id, command) in commands {
3961 if let Some(to) = self.scrolled_to(id, &command) {
3962 projected.push((id, to));
3963 }
3964 self.commands.push((id, command));
3965 }
3966 }
3967 }
3968 for (id, press, answer) in std::mem::take(&mut self.components.presses) {
3970 let target = self.press_target(id, press.page_position);
3971 if let Some((node, position)) = target {
3972 self.events.push(crate::element::JsEvent::Event(
3973 node,
3974 EventKind::Press,
3975 EventPayload::Press(crate::PressEvent { position, ..press }),
3976 ));
3977 }
3978 answer.borrow_mut().deliver(target.is_some());
3979 }
3980 self.sync_download_listeners();
3984 self.focus_opened_modals();
3985 if let Some((id, from, past)) = self.focus_back.take() {
3991 let origin = self
3992 .focus_origins
3993 .iter()
3994 .position(|&(to, _)| to == id)
3995 .map(|i| self.focus_origins.swap_remove(i).1);
3996 let from = from.and_then(|from| self.key(from).ok());
3997 let moved_out = |to: NodeId| {
3998 self.key(to)
3999 .is_ok_and(|key| from.is_none_or(|from| !self.is_ancestor(from, key)))
4000 };
4001 let moved = self
4002 .commands
4003 .iter()
4004 .any(|(to, c)| matches!(c, Command::Focus) && moved_out(*to))
4005 || self.mount.iter().any(|m| {
4006 matches!(
4007 m,
4008 MountItem::Command {
4009 id: to,
4010 command: Command::Focus,
4011 } if moved_out(*to)
4012 )
4013 });
4014 let past = past.filter(|_| !moved).and_then(|forward| {
4017 let key = self.key(id).ok()?;
4018 Some(self.tab_neighbor(key, forward, from).unwrap_or(id))
4019 });
4020 if let Some(to) = past {
4021 self.commands.push((to, Command::Focus));
4022 } else if !moved {
4023 match origin {
4024 None => self.commands.push((id, Command::Focus)),
4027 Some(before) if self.press_leaves_focus() => {
4028 self.focus_back_to_origin(before, from);
4029 }
4030 Some(_) => {
4034 self.commands.push((id, Command::Focus));
4035 self.pointer_focus_back = Some(id);
4036 }
4037 }
4038 }
4039 }
4040 let mut kept = Vec::new();
4042 for (id, mut command) in std::mem::take(&mut self.commands) {
4043 if let Command::Measure { call } = command {
4046 self.answer_measure(id, call);
4047 continue;
4048 }
4049 if let Command::MeasureScrollPosition { call } = command {
4050 self.answer_scroll_position(id, call);
4051 continue;
4052 }
4053 let Ok(key) = self.key(id) else {
4054 continue;
4058 };
4059 if !self.nodes[key as usize].created && !self.uncull(key) {
4061 continue;
4062 }
4063 let node = &self.nodes[key as usize];
4064 if id != crate::ROOT_ID
4065 && let Some(backend) = &self.window_backend
4066 && let Command::Desktop(desktop) = &command
4067 && desktop.is_window_command()
4068 {
4069 backend.command(id, desktop);
4070 continue;
4071 }
4072 if node.list.as_ref().is_some_and(|l| l.parent)
4075 && matches!(
4076 command,
4077 Command::ScrollTo { .. }
4078 | Command::ScrollToIndex { .. }
4079 | Command::ScrollToEnd { .. }
4080 )
4081 {
4082 kept.push((id, command));
4083 continue;
4084 }
4085 if let Command::ImageInfo { id: request, uri } = &mut command {
4088 match self.media_source(uri) {
4089 Some(granted) => {
4090 if let Some(url) = granted {
4091 *uri = url.to_string();
4092 }
4093 }
4094 None => {
4095 let message = media_not_granted(
4096 "Image.getSize / prefetch of",
4097 uri,
4098 self.base_url.as_deref(),
4099 );
4100 self.answer_image_info(*request, Err(message.clone()));
4101 self.deny(message);
4102 continue;
4103 }
4104 }
4105 }
4106 if let Command::Desktop(desktop) = &mut command {
4109 self.check_menu_icons(desktop);
4110 if id == crate::ROOT_ID {
4111 self.remember_app_menu(desktop);
4112 }
4113 }
4114 match &command {
4117 Command::SetClipboard(_)
4118 | Command::SetClipboardItem(_)
4119 | Command::ReadClipboard { .. }
4120 | Command::SetClipboardImage(_)
4121 | Command::ReadClipboardImage { .. }
4122 | Command::ReadClipboardFiles { .. }
4123 if !self.access.allows_clipboard() =>
4124 {
4125 if let Command::ReadClipboard { id: request, .. }
4126 | Command::ReadClipboardImage { id: request, .. }
4127 | Command::ReadClipboardFiles { id: request } = &command
4128 {
4129 self.answer_clipboard(*request, components::ClipboardAnswer::default());
4130 }
4131 if matches!(
4132 command,
4133 Command::SetClipboard(_) | Command::SetClipboardItem(_)
4134 ) {
4135 self.answer_clipboard_write(crate::element::ClipboardWrite::Failed);
4136 }
4137 self.deny("the clipboard is not granted: add `\"clipboard\": true` to capabilities in nsh.json".into());
4138 continue;
4139 }
4140 Command::SetClipboard(_)
4143 | Command::SetClipboardItem(_)
4144 | Command::ReadClipboard { .. }
4145 | Command::SetClipboardImage(_)
4146 | Command::ReadClipboardImage { .. }
4147 | Command::ReadClipboardFiles { .. }
4148 if self.clipboard.is_some() =>
4149 {
4150 let clipboard = self.clipboard.clone().expect("a clipboard");
4151 match &command {
4152 Command::SetClipboard(text) => {
4153 clipboard.set_text(Some(text.clone()));
4154 self.answer_clipboard_write(crate::element::ClipboardWrite::Written);
4155 }
4156 Command::SetClipboardItem(item) => {
4157 clipboard.set_item(Some(item.clone()));
4158 self.answer_clipboard_write(crate::element::ClipboardWrite::Written);
4159 }
4160 Command::SetClipboardImage(_) => clipboard.set_item(None),
4161 Command::ReadClipboard {
4162 id: request,
4163 has_only,
4164 } => {
4165 let text = clipboard.text();
4166 let answer = components::ClipboardAnswer {
4167 has: text.is_some(),
4168 text: text.filter(|_| !has_only),
4169 ..Default::default()
4170 };
4171 self.answer_clipboard(*request, answer);
4172 }
4173 Command::ReadClipboardImage { id: request, .. }
4174 | Command::ReadClipboardFiles { id: request } => {
4175 self.answer_clipboard(*request, components::ClipboardAnswer::default());
4176 }
4177 _ => {}
4178 }
4179 continue;
4180 }
4181 Command::SetClipboard(_) | Command::SetClipboardItem(_)
4184 if !self.components.environment.clipboard_write_result =>
4185 {
4186 self.answer_clipboard_write(crate::element::ClipboardWrite::Requested);
4187 }
4188 Command::HostCall { name, .. } | Command::HostPost { name, .. } => {
4191 if let Some(error) = crate::host_channel::refusal(&self.access, name) {
4192 self.deny(error.to_string());
4193 if let Command::HostCall { id: call, .. } = command {
4194 self.answer_host(call, Err(error));
4195 }
4196 continue;
4197 }
4198 }
4199 Command::SendInput(_) if !self.access.allows_web_input() => {
4200 self.deny("trusted web view input is not granted: add `\"input\": true` to capabilities.webview in nsh.json".into());
4201 continue;
4202 }
4203 Command::Load(load)
4206 if !self
4207 .access
4208 .allows_webview_with(&load.src, self.web_origin(key)) =>
4209 {
4210 self.deny(not_granted("the web page", &load.src, "webview.hosts"));
4211 continue;
4212 }
4213 Command::StatusBar(_) if !self.access.allows_status_bar() => {
4214 self.deny("the status bar is not granted: add `\"statusBar\": true` to capabilities in nsh.json".into());
4215 continue;
4216 }
4217 Command::Desktop(desktop)
4228 if !self.access.allows_application()
4229 && !desktop.is_core_handled()
4230 && !matches!(
4231 **desktop,
4232 crate::desktop::DesktopCommand::PopupMenu { .. }
4233 | crate::desktop::DesktopCommand::Request(
4234 crate::desktop::WindowRequest::SetContentSize { .. }
4235 )
4236 )
4237 && (id == crate::ROOT_ID || !desktop.is_window_command()) =>
4238 {
4239 self.deny("the application (its main window, menu, tray, global shortcuts, quitting and restarting) is not granted: add `\"application\": true` to capabilities in nsh.json".into());
4240 continue;
4241 }
4242 _ => {}
4243 }
4244 let node = &self.nodes[key as usize];
4245 let id = node.id;
4246 match command {
4247 Command::ScrollToEnd { animated } => {
4248 let Some(content) = node.scroll.as_ref().and_then(|s| s.content) else {
4249 continue;
4250 };
4251 let horizontal = node.scroll.as_ref().is_some_and(|s| s.horizontal);
4252 let frame = node.frame;
4253 let (x, y) = if horizontal {
4254 (
4255 (content.width - frame.size.width).max(Points::ZERO),
4256 Points::ZERO,
4257 )
4258 } else {
4259 (
4260 Points::ZERO,
4261 (content.height - frame.size.height).max(Points::ZERO),
4262 )
4263 };
4264 command = Command::ScrollTo { x, y, animated };
4265 }
4266 Command::ScrollToIndex { .. } => continue,
4267 _ => {}
4268 }
4269 if let Command::ScrollTo { x, y, animated } = command
4271 && self.nodes[key as usize].kind == Kind::Scroll
4272 {
4273 let horizontal = self.nodes[key as usize]
4274 .scroll
4275 .as_ref()
4276 .is_some_and(|s| s.horizontal);
4277 let to = if horizontal { x.0 } else { y.0 };
4278 self.scroll_issued(
4279 key,
4280 PendingScroll::To {
4281 offset: to,
4282 animated,
4283 },
4284 );
4285 if let Some(scroll) = self.nodes[key as usize].scroll.as_mut() {
4286 scroll.target = Some((scroll.issued, (x.0, y.0)));
4287 }
4288 }
4289 self.mount.push(MountItem::Command { id, command });
4290 }
4291 self.commands.append(&mut kept);
4292 }
4293
4294 #[inline]
4295 fn key(&self, id: NodeId) -> Result<Key, ApplyError> {
4296 match self.slots.get(id as usize) {
4297 Some(&k) => Ok(k),
4298 None => Err(ApplyError::UnknownNode(id)),
4299 }
4300 }
4301
4302 fn check_id_range(&self, id: NodeId) -> Result<(), ApplyError> {
4303 if id as usize > self.admitted_id_extent.saturating_add(self.max_nodes) {
4304 return Err(ApplyError::IdOutOfRange(id));
4305 }
4306 Ok(())
4307 }
4308
4309 fn insert_key(&mut self, idx: usize, key: Key) {
4310 self.slots.insert(idx, key);
4311 self.admitted_id_extent = self.admitted_id_extent.max(self.slots.extent());
4312 }
4313
4314 fn alloc(&mut self, id: NodeId, kind: Kind) -> Result<Key, ApplyError> {
4315 let idx = id as usize;
4316 if self.nodes.len().saturating_add(self.runs.len()) >= self.max_nodes {
4317 return Err(ApplyError::TooManyNodes(self.max_nodes));
4318 }
4319 self.check_id_range(id)?;
4320 if self.slots.contains(idx) || self.runs.contains_key(&id) {
4321 return Err(ApplyError::DuplicateNode(id));
4322 }
4323 let key = self.nodes.insert(Node::new(id, kind)) as Key;
4324 self.insert_key(idx, key);
4325 self.dirty_overlay_listeners();
4327 Ok(key)
4328 }
4329
4330 pub(super) fn alias(&mut self, alias: NodeId, id: NodeId) -> Result<(), ApplyError> {
4335 let key = self.key(id)?;
4336 let idx = alias as usize;
4337 self.check_id_range(alias)?;
4338 if self.slots.contains(idx) {
4339 return Err(ApplyError::DuplicateNode(alias));
4340 }
4341 self.insert_key(idx, key);
4342 self.dirty_overlay_listeners();
4344 Ok(())
4345 }
4346
4347 pub(super) fn is_alias(&self, id: NodeId) -> bool {
4349 self.key(id).is_ok_and(|k| self.nodes[k as usize].id != id)
4350 }
4351
4352 pub(super) fn unalias(&mut self, id: NodeId) {
4354 if self.is_alias(id) {
4355 self.slots.remove(id as usize);
4356 self.dirty_overlay_listeners();
4357 }
4358 }
4359
4360 pub(super) fn native_id(&self, id: NodeId) -> NodeId {
4362 self.key(id).map_or(id, |k| self.nodes[k as usize].id)
4363 }
4364
4365 fn create(&mut self, id: NodeId, tag: Tag) -> Result<(), ApplyError> {
4366 let kind = Kind::of(tag);
4367 let key = self.alloc(id, kind)?;
4368 let mut custom_layout = None;
4369 if let Some(role) = shader_role(tag) {
4370 self.nodes[key as usize]
4371 .shader
4372 .as_mut()
4373 .expect("a shader node")
4374 .role = role;
4375 if matches!(
4376 role,
4377 crate::shader::ShaderRole::Screen | crate::shader::ShaderRole::ScreenTransition
4378 ) {
4379 let mut style = crate::style::unstyled_layout();
4381 style.position = taffy::Position::Absolute;
4382 style.size = taffy::Size {
4383 width: taffy::Dimension::length(0.0),
4384 height: taffy::Dimension::length(0.0),
4385 };
4386 custom_layout = Some(style);
4387 }
4388 }
4389 let context = leaf_context(kind);
4390 let layout = match custom_layout {
4391 Some(style) => match context {
4392 Some(context) => self.layout.new_leaf_with_context(style, context),
4393 None => self.layout.new_leaf(style),
4394 },
4395 None => self.layout.new_default_leaf(context),
4396 };
4397 self.layout.set_tag(layout, key);
4398 self.nodes[key as usize].layout = Some(layout);
4399 self.sync_grid_role(key);
4400 self.became(key);
4401 if kind == Kind::WebView && !self.components.environment.web_views {
4402 self.web_view_unavailable(id);
4403 }
4404 Ok(())
4405 }
4406
4407 fn web_view_unavailable(&mut self, id: NodeId) {
4411 self.events.push(crate::element::JsEvent::Event(
4412 id,
4413 EventKind::Error,
4414 EventPayload::Map(vec![
4415 (
4416 "message",
4417 PayloadValue::Str("web views are not available on this platform".into()),
4418 ),
4419 (
4420 "code",
4421 PayloadValue::Str(crate::element::codes::UNAVAILABLE.into()),
4422 ),
4423 ]),
4424 ));
4425 }
4426
4427 fn is_control(&self, key: Key) -> bool {
4432 use crate::AccessibilityRole as R;
4433 let node = &self.nodes[key as usize];
4434 node.kind == Kind::Input
4435 || (!node.inline && pressable(node.events))
4436 || node.props.as_ref().is_some_and(|p| {
4437 matches!(
4438 p.accessibility.role,
4439 R::Button
4440 | R::ImageButton
4441 | R::Link
4442 | R::Search
4443 | R::Textbox
4444 | R::Checkbox
4445 | R::Radio
4446 | R::Switch
4447 | R::Tab
4448 | R::Menuitem
4449 | R::MenuItemCheckbox
4450 | R::MenuItemRadio
4451 | R::Option
4452 | R::Combobox
4453 | R::Adjustable
4454 | R::Spinbutton
4455 )
4456 })
4457 }
4458
4459 fn grid_role(&self, key: Key) -> terminal_layout::Role {
4466 let kind = self.nodes[key as usize].kind;
4467 let left_out = match kind {
4468 Kind::Image => terminal_layout::LeftOut::Picture,
4471 Kind::Video | Kind::WebView | Kind::Shader | Kind::GpuView | Kind::Canvas => {
4472 terminal_layout::LeftOut::IfIcon
4473 }
4474 _ => terminal_layout::LeftOut::No,
4475 };
4476 let control = self.is_control(key);
4477 let popup = control
4480 && self.nodes[key as usize].props.as_ref().is_some_and(|p| {
4481 p.accessibility.state.expanded.is_some() && p.accessibility.state.has_popup
4482 });
4483 let (label, word) = control
4484 .then(|| self.nodes[key as usize].props.as_ref())
4485 .flatten()
4486 .map_or((0, 0), |p| {
4487 let cols = |t: &str| terminal_layout::columns(t).min(u16::MAX as usize) as u16;
4488 let name = p
4489 .accessibility
4490 .label
4491 .as_deref()
4492 .map(str::trim)
4493 .filter(|l| !l.is_empty());
4494 match (p.accessibility.state.expanded, name) {
4495 (Some(_), _) if !popup => (1, 1),
4499 (Some(_), None) => (1, 1),
4500 (Some(_), Some(l)) => {
4505 let first = l.split_whitespace().next().unwrap_or("");
4506 (cols(l).saturating_add(2), cols(first).saturating_add(2))
4507 }
4508 (None, l) => l.map_or((0, 0), |l| {
4509 (cols(l), cols(l.split_whitespace().next().unwrap_or("")))
4510 }),
4511 }
4512 });
4513 let node = &self.nodes[key as usize];
4514 let view = &node.view_style;
4515 let c = view.corner_radius;
4516 let radius = [c.top_left, c.top_right, c.bottom_right, c.bottom_left]
4517 .into_iter()
4518 .map(|r| r.unwrap_or(view.border_radius).0)
4519 .fold(0.0, f32::max);
4520 let w = view.borders.widths;
4521 let border_color = [w.top, w.right, w.bottom, w.left]
4522 .iter()
4523 .position(|&v| v > Points::ZERO)
4524 .map_or(crate::Color::TRANSPARENT, |i| view.borders.colors[i]);
4525 let glyphs = kind == Kind::Text
4528 && node
4529 .layout
4530 .and_then(|l| self.layout.get_node_context(l))
4531 .is_some_and(|cx| match cx {
4532 LeafContext::Text(cx) => cx.text.text.chars().any(|ch| !ch.is_whitespace()),
4533 _ => false,
4534 });
4535 let worded = kind == Kind::Text
4537 && node
4538 .layout
4539 .and_then(|l| self.layout.get_node_context(l))
4540 .is_some_and(|cx| match cx {
4541 LeafContext::Text(cx) => cx.text.text.chars().any(char::is_alphanumeric),
4542 _ => false,
4543 });
4544 let clamped = kind == Kind::Text
4546 && node
4547 .layout
4548 .and_then(|l| self.layout.get_node_context(l))
4549 .is_some_and(|cx| match cx {
4550 LeafContext::Text(cx) => cx.text.max_lines > 0,
4551 _ => false,
4552 });
4553 let disclosure = control
4554 && self.nodes[key as usize].props.as_ref().is_some_and(|p| {
4555 p.accessibility.state.expanded.is_some() && !p.accessibility.state.has_popup
4556 });
4557 let marked = kind == Kind::Text
4559 && node
4560 .layout
4561 .and_then(|l| self.layout.get_node_context(l))
4562 .is_some_and(|cx| match cx {
4563 LeafContext::Text(cx) => {
4564 cx.text.text.trim_start().starts_with(['â–¸', 'â–¾', 'â–¹', 'â–¿'])
4565 }
4566 _ => false,
4567 });
4568 terminal_layout::Role {
4569 control,
4570 label,
4571 word,
4572 popup,
4573 disclosure,
4574 marked,
4575 text: matches!(kind, Kind::Text | Kind::Input),
4576 scroll: matches!(kind, Kind::Scroll | Kind::List),
4577 root: key == self.root,
4578 fills: matches!(kind, Kind::Screen | Kind::Modal),
4579 sized: matches!(
4580 kind,
4581 Kind::Native
4582 | Kind::List
4583 | Kind::Image
4584 | Kind::Video
4585 | Kind::WebView
4586 | Kind::Shader
4587 | Kind::GpuView
4588 ),
4589 input: kind == Kind::Input,
4590 glyphs,
4591 worded,
4592 clamped,
4593 radius,
4594 fill: node.resting_fill.unwrap_or(view.background_color),
4595 interactive: {
4596 let events = self.nodes[key as usize].events;
4597 pressable(events) || HANDLED.iter().any(|&e| events.contains(e))
4598 },
4599 animated_fill: self.nodes[key as usize]
4600 .animated
4601 .iter()
4602 .any(|(p, _)| matches!(p, AnimationProp::BackgroundColor)),
4603 border_color,
4604 splitter: match view.cursor {
4605 crate::Cursor::ColResize => terminal_layout::Splitter::Columns,
4606 crate::Cursor::RowResize => terminal_layout::Splitter::Rows,
4607 _ => terminal_layout::Splitter::No,
4608 },
4609 left_out,
4610 overlay: kind == Kind::Overlay,
4611 meter: node.props.as_ref().is_some_and(|p| {
4612 p.accessibility.role == crate::element::AccessibilityRole::Progressbar
4613 }),
4614 indicator: match node.scroll.as_deref() {
4617 Some(scroll)
4618 if scroll.scrollbar != crate::ScrollbarSetting::Hidden
4619 && scroll.bar.is_none() =>
4620 {
4621 if scroll.horizontal {
4622 terminal_layout::Indicator::Horizontal
4623 } else {
4624 terminal_layout::Indicator::Vertical
4625 }
4626 }
4627 _ => terminal_layout::Indicator::No,
4628 },
4629 }
4630 }
4631
4632 fn sync_grid_role(&mut self, key: Key) {
4635 if let Some(layout) = self.nodes[key as usize].layout {
4636 let role = self.grid_role(key);
4637 if self.layout.set_role(layout, role) {
4638 self.needs_layout = true;
4639 }
4640 }
4641 }
4642
4643 fn became(&mut self, key: Key) {
4645 let kind = self.nodes[key as usize].kind;
4646 if kind.derives_layout() {
4647 let style = self.nodes[key as usize]
4648 .layout
4649 .map(|l| self.layout.style(l).clone())
4650 .unwrap_or_else(crate::style::unstyled_layout);
4651 self.nodes[key as usize].base_layout = Some(Box::new(style));
4652 }
4653 let node = &mut self.nodes[key as usize];
4654 if kind == Kind::Text {
4655 node.dirty |= dirty::TEXT_BUILD;
4656 }
4657 if kind == Kind::List {
4658 self.lists.push(key);
4659 }
4660 if matches!(kind, Kind::Scroll | Kind::List | Kind::Input)
4661 && self.builtin_scrollbars.is_some()
4662 {
4663 self.scrollbars_pending.push(key);
4664 }
4665 if kind.is_root() {
4666 self.roots.push(key);
4667 }
4668 if kind == Kind::Input {
4669 self.measure_input(key);
4670 }
4671 if kind == Kind::Overlay
4672 && let Some(layout) = self.nodes[key as usize].layout
4673 {
4674 self.overlay_made(key, layout);
4675 }
4676 self.sync_layout_style(key);
4677 }
4678
4679 pub(super) fn retag(&mut self, id: NodeId, tag: Tag) -> bool {
4684 let Ok(key) = self.key(id) else {
4685 return false;
4686 };
4687 let kind = Kind::of(tag);
4688 let node = &self.nodes[key as usize];
4689 if node.kind == kind {
4690 return true;
4691 }
4692 let id = node.id;
4693 if node.kind != Kind::View || !node.children.is_empty() {
4694 return false;
4695 }
4696 if node.created && !self.made_in_this_batch(id) {
4697 return false;
4698 }
4699 let node = &self.nodes[key as usize];
4700 let parent = node.parent;
4702 let at = (parent != NO_KEY).then(|| {
4703 let siblings = &self.nodes[parent as usize].children;
4704 let i = siblings.iter().position(|&c| c == key).expect("child");
4705 let next = siblings.get(i + 1).map(|&c| self.nodes[c as usize].id);
4706 (self.nodes[parent as usize].id, next)
4707 });
4708 if parent != NO_KEY {
4709 self.unlink(key, false);
4710 }
4711 let retags = self.retags.get_or_insert_default();
4714 retags.made.remove(&id);
4715 retags.retagged.insert(id, self.mount.len());
4716 let fresh = Node::new(id, kind);
4718 let node = &mut self.nodes[key as usize];
4719 node.created = false;
4720 node.kind = kind;
4721 node.image = fresh.image;
4722 node.scroll = fresh.scroll;
4723 node.list = fresh.list;
4724 node.input = fresh.input;
4725 node.root = fresh.root;
4726 node.control = fresh.control;
4727 node.component = fresh.component;
4728 let layout = node.layout.expect("a view has a layout");
4729 self.dirty_overlays();
4730 self.layout.set_node_context(layout, leaf_context(kind));
4731 self.became(key);
4732 self.sync_accent(key);
4734 self.sync_grid_role(key);
4737 if let Some((parent, before)) = at {
4738 let _ = self.insert(parent, id, before);
4739 }
4740 true
4741 }
4742
4743 fn made_in_this_batch(&mut self, id: NodeId) -> bool {
4747 let retags = self.retags.get_or_insert_default();
4748 let from = retags.seen;
4749 retags
4750 .made
4751 .extend(self.mount[from..].iter().filter_map(|m| match m {
4752 MountItem::Create { id, .. } => Some(*id),
4753 _ => None,
4754 }));
4755 retags.seen = self.mount.len();
4756 let made = retags.made.contains(&id);
4757 self.retagging(self.mount.len() - from);
4758 made
4759 }
4760
4761 pub(super) fn drop_retagged(&mut self) {
4764 let Some(retags) = self.retags.as_deref_mut() else {
4765 return;
4766 };
4767 if retags.retagged.is_empty() {
4768 return;
4769 }
4770 let retagged = std::mem::take(&mut retags.retagged);
4771 let (seen, made) = (retags.seen, &mut retags.made);
4772 let mut at = 0;
4773 self.mount.retain(|m| {
4774 let i = at;
4775 at += 1;
4776 let (MountItem::Create { id, .. } | MountItem::Insert { child: id, .. }) = m else {
4777 return true;
4778 };
4779 if retagged.get(id).is_some_and(|&then| i < then) {
4780 return false;
4781 }
4782 if i >= seen && matches!(m, MountItem::Create { .. }) {
4783 made.insert(*id);
4784 }
4785 true
4786 });
4787 retags.seen = self.mount.len();
4788 self.retagging(at);
4789 }
4790
4791 pub(super) fn end_retags(&mut self) {
4795 self.drop_retagged();
4796 #[cfg(test)]
4797 if self.retags.is_some() {
4798 let rounds = &self.components.retag_rounds;
4799 rounds.set(rounds.get() + 1);
4800 }
4801 self.retags = None;
4802 }
4803
4804 fn measure_input(&mut self, key: Key) {
4808 let node = &self.nodes[key as usize];
4809 let (Some(input), Some(layout)) = (&node.input, node.layout) else {
4810 return;
4811 };
4812 let shown = input.composing.as_deref().unwrap_or(&input.value);
4813 let placeholder = shown.is_empty() && !input.config.placeholder.is_empty();
4814 let text = self.input_text(
4815 key,
4816 if placeholder {
4817 &input.config.placeholder
4818 } else {
4819 shown
4820 },
4821 );
4822 let field = self.input_text(key, FIELD_SAMPLE);
4823 let cx = self.text_cx(layout);
4824 let same = cx.text.layout_eq(&text);
4825 let same_field = cx.field.as_ref().is_some_and(|f| f.text.layout_eq(&field));
4826 let input = self.nodes[key as usize]
4827 .input
4828 .as_mut()
4829 .expect("input state");
4830 if same && same_field && input.placeholder_measured == placeholder {
4833 return;
4834 }
4835 input.placeholder_measured = placeholder;
4836 let cx = self.text_cx(layout);
4837 if !same {
4838 let kept = cx.field.take();
4839 *cx = TextContext::new(Arc::new(text));
4840 cx.field = kept;
4841 }
4842 if !same_field {
4843 cx.field = Some(Box::new(TextContext::new(Arc::new(field))));
4844 }
4845 self.layout.mark_dirty(layout);
4846 self.needs_layout = true;
4847 }
4848
4849 fn input_text(&self, key: Key, content: &str) -> AttributedText {
4851 let node = &self.nodes[key as usize];
4852 let multiline = node.input.as_ref().is_some_and(|i| i.config.multiline);
4853 let mut text = AttributedText {
4854 max_lines: if multiline { 0 } else { 1 },
4855 ..AttributedText::default()
4856 };
4857 let style = scaled(
4858 self.inherited_text_style(key).inherit(&node.text_style),
4859 node.paragraph.font_multiplier(self.font_scale),
4860 );
4861 text.paragraph_strut = Some(style);
4862 if multiline {
4863 text.push(&broken_runs(content), style);
4864 } else {
4865 text.push(content, style);
4866 }
4867 if content.is_empty() || (multiline && content.ends_with('\n')) {
4870 text.push("\u{200b}", style);
4871 }
4872 text
4873 }
4874
4875 pub(super) fn lay_out_through(&mut self, key: Key) {
4882 let node = &self.nodes[key as usize];
4883 if node.kind == Kind::View
4884 && let Some(layout) = node.layout
4885 {
4886 self.layout.set_holder(layout);
4887 self.needs_layout = true;
4888 }
4889 }
4890
4891 fn sync_layout_style(&mut self, key: Key) {
4894 let node = &self.nodes[key as usize];
4895 let (Some(layout), Some(base)) = (node.layout, node.base_layout.as_deref()) else {
4896 return;
4897 };
4898 let mut style = base.clone();
4899 let kind = node.kind;
4900 if let Some(root) = self.nodes[key as usize].root.as_mut() {
4901 root.laid_out = None;
4903 }
4904 let node = &self.nodes[key as usize];
4905 match kind {
4906 Kind::Scroll => {
4907 let horizontal = node.scroll.as_ref().is_some_and(|s| s.horizontal);
4910 if horizontal {
4911 style.flex_direction = taffy::FlexDirection::Row;
4912 style.overflow.x = Overflow::Scroll;
4913 if node.rtl {
4914 std::mem::swap(&mut style.padding.left, &mut style.padding.right);
4918 std::mem::swap(&mut style.border.left, &mut style.border.right);
4919 style.direction = taffy::Direction::Ltr;
4920 }
4921 } else {
4922 style.overflow.y = Overflow::Scroll;
4923 }
4924 }
4925 Kind::List => {
4926 style.overflow = taffy::Point {
4927 x: Overflow::Hidden,
4928 y: Overflow::Hidden,
4929 }
4930 }
4931 Kind::Cell => {
4932 let horizontal = self
4937 .nodes
4938 .get(node.parent as usize)
4939 .and_then(|p| p.scroll.as_ref())
4940 .is_some_and(|s| s.horizontal);
4941 style.position = Position::Relative;
4942 if horizontal {
4943 style.size.height = taffy::Dimension::percent(1.0);
4944 } else {
4945 style.size.width = taffy::Dimension::percent(1.0);
4946 }
4947 }
4948 Kind::Overlay => style.position = Position::Absolute,
4950 _ => {}
4951 }
4952 if node.fixed_view {
4953 style.position = Position::Fixed;
4954 }
4955 if self.layout.set_style(layout, style) {
4956 self.needs_layout = true;
4957 }
4958 }
4959
4960 fn set_inline_style(
4961 &mut self,
4962 id: NodeId,
4963 style: Box<Style>,
4964 patch: StylePatch,
4965 ) -> Result<(), ApplyError> {
4966 let key = self.key(id)?;
4967 let node = &mut self.nodes[key as usize];
4968 node.inline_style = patch;
4969 if node.classes.is_some() || node.spaced || node.inline_style.reads_current_color() {
4970 self.restyle(key);
4971 return Ok(());
4972 }
4973 let mut props = node.class_props.as_deref().cloned().unwrap_or_default();
4974 style.node_props(&mut props);
4975 self.set_class_props(key, props);
4976 self.set_style(id, *style)
4977 }
4978
4979 fn set_style(&mut self, id: NodeId, style: Style) -> Result<(), ApplyError> {
4980 let key = self.key(id)?;
4981 let Style {
4982 mut layout,
4983 mut view,
4984 text,
4985 paint,
4986 animated,
4987 z_index,
4988 vertical_align,
4989 direction,
4990 logical,
4991 pending,
4992 perspective,
4993 } = style;
4994 if animated
4995 .iter()
4996 .any(|(p, _)| matches!(p, AnimationProp::BackgroundColor))
4997 {
4998 view.clear_background_images();
5001 }
5002 if key != self.root {
5003 self.nodes[key as usize].direction = direction;
5004 }
5005 let rtl = self.resolved_rtl(key);
5006 let sticky = prepare_layout(
5007 &mut layout,
5008 &mut view,
5009 &logical,
5010 rtl,
5011 pending.sticky_position,
5012 );
5013 let input = self.nodes[key as usize].kind == Kind::Input;
5017 clip_overflow(&mut layout, view.overflow_hidden || input);
5018 self.install_style(
5019 key,
5020 StyleRecord {
5021 layout,
5022 view,
5023 text,
5024 paint: (paint != PaintStyle::default()).then(|| Rc::new(paint)),
5025 animated,
5026 sticky,
5027 perspective,
5028 object_fit: pending.object_fit,
5029 wants_fixed: pending.fixed_position,
5030 env: pending.env,
5031 z_index,
5032 vertical_align,
5033 has_logical: !logical.is_empty(),
5034 rtl,
5035 },
5036 );
5037 Ok(())
5038 }
5039
5040 fn apply_resolved_style(&mut self, key: Key, resolved: &classes::ResolvedClassStyle) {
5043 self.set_class_props_shared(key, resolved.props.as_ref());
5044 self.install_style(
5045 key,
5046 StyleRecord {
5047 layout: resolved.layout.clone(),
5048 view: resolved.view.clone(),
5049 text: resolved.text.clone(),
5050 paint: resolved.paint.clone(),
5051 animated: Vec::new(),
5052 sticky: resolved.sticky,
5053 perspective: resolved.perspective,
5054 object_fit: resolved.object_fit,
5055 wants_fixed: resolved.wants_fixed,
5056 env: crate::style::EnvEdges::default(),
5057 z_index: resolved.z_index,
5058 vertical_align: resolved.vertical_align,
5059 has_logical: resolved.has_logical,
5060 rtl: resolved.rtl,
5061 },
5062 );
5063 }
5064
5065 fn install_style(
5069 &mut self,
5070 key: Key,
5071 record: StyleRecord<impl LayoutSlot, impl StyleSlot<ViewStyle>, impl StyleSlot<TextStyle>>,
5072 ) {
5073 let StyleRecord {
5074 mut layout,
5075 view,
5076 text,
5077 paint,
5078 animated,
5079 sticky,
5080 perspective,
5081 object_fit,
5082 wants_fixed,
5083 env,
5084 z_index,
5085 vertical_align,
5086 has_logical,
5087 rtl,
5088 } = record;
5089 let hid_before = self.nodes[key as usize]
5090 .layout
5091 .is_some_and(|l| self.layout.displays_none(l));
5092 let node = &mut self.nodes[key as usize];
5093 node.has_logical = has_logical;
5094 if node.sticky.as_deref() != sticky.as_ref() {
5095 self.set_sticky(key, sticky.map(Box::new));
5096 }
5097 let node = &mut self.nodes[key as usize];
5098 if node.child_perspective != perspective {
5099 node.child_perspective = perspective;
5100 let children = node.children.clone();
5103 for c in children {
5104 self.mark(c, dirty::VIEW | dirty::ANIMATION);
5105 }
5106 }
5107 let node = &mut self.nodes[key as usize];
5108 if node.object_fit != object_fit {
5109 node.object_fit = object_fit;
5110 if node.image.is_some() {
5111 self.mark(key, dirty::IMAGE);
5112 } else if let Some(control) = node.control.as_mut() {
5113 let fit = object_fit.unwrap_or(ResizeMode::Contain);
5115 apply_native(control, NativeProp::VideoResizeMode(fit));
5116 self.mark(key, dirty::NATIVE);
5117 }
5118 }
5119 let node = &mut self.nodes[key as usize];
5120 if node.wants_fixed != wants_fixed {
5121 node.wants_fixed = wants_fixed;
5125 let id = node.id;
5126 if node.parent == NO_KEY {
5127 self.fix_or_unfix(key);
5128 } else {
5129 self.fixed_changed.push((key, id));
5130 }
5131 }
5132 let env = (!env.is_empty()).then(|| (env, self.env_insets(key, &env)));
5135 let node = &mut self.nodes[key as usize];
5136 let id = node.id;
5137 match env {
5138 Some(env) => {
5139 node.env = Some(Box::new(env));
5140 self.env_styled.insert(id);
5141 }
5142 None => {
5143 if node.env.take().is_some() {
5144 self.env_styled.remove(&id);
5145 }
5146 }
5147 }
5148 let node = &mut self.nodes[key as usize];
5149 let mut extra = node.insets.as_deref().copied();
5150 if let Some((_, applied)) = node.env.as_deref() {
5151 let sum = |a: EdgeInsets, b: EdgeInsets| EdgeInsets {
5152 top: a.top + b.top,
5153 right: a.right + b.right,
5154 bottom: a.bottom + b.bottom,
5155 left: a.left + b.left,
5156 };
5157 let [p, m] = extra.unwrap_or_default();
5158 extra = Some([sum(p, applied[0]), sum(m, applied[1])]);
5159 }
5160 if let Some([padding, margin]) = extra.as_ref() {
5161 let layout = layout.to_mut();
5162 let add = |p: &mut taffy::LengthPercentage, d: f32| {
5164 if let taffy::style::ExpandedLengthPercentage::Length(v) = p.expand() {
5165 *p = taffy::LengthPercentage::length(v + d);
5166 }
5167 };
5168 add(&mut layout.padding.top, padding.top.0);
5169 add(&mut layout.padding.right, padding.right.0);
5170 add(&mut layout.padding.bottom, padding.bottom.0);
5171 add(&mut layout.padding.left, padding.left.0);
5172 let add = |m: &mut taffy::LengthPercentageAuto, d: f32| {
5174 if let taffy::style::ExpandedLengthPercentageAuto::Length(v) = m.expand() {
5175 *m = taffy::LengthPercentageAuto::length(v + d);
5176 }
5177 };
5178 add(&mut layout.margin.top, margin.top.0);
5179 add(&mut layout.margin.right, margin.right.0);
5180 add(&mut layout.margin.bottom, margin.bottom.0);
5181 add(&mut layout.margin.left, margin.left.0);
5182 }
5183 let node = &mut self.nodes[key as usize];
5184 let flipped = node.rtl != rtl;
5185 node.rtl = rtl;
5186 let view_same = view.same(&node.view_style);
5189 let new_view = view.get();
5190 let position_changed =
5192 !view_same && node.view_style.object_position != new_view.object_position;
5193 let view_changed = !view_same
5194 && (!position_changed
5195 || node.view_style
5196 != ViewStyle {
5197 object_position: node.view_style.object_position,
5198 ..new_view.clone()
5199 });
5200 let span_drawing_changed = !view_same
5202 && node.inline
5203 && node.kind == Kind::Text
5204 && (span_background(&node.view_style, node.id) != span_background(new_view, node.id)
5205 || node.view_style.hidden != new_view.hidden);
5206 let clip_changed = !view_same
5208 && !node.inline
5209 && node.kind == Kind::Text
5210 && node.view_style.overflow_hidden != new_view.overflow_hidden;
5211 let text_same = text.same(&node.text_style);
5212 let text_changed = !text_same || span_drawing_changed;
5213 let passed_color = |node: &Node, text: &TextStyle| text.color.or(node.inherited_color);
5215 let color_passed =
5216 !text_same && passed_color(node, &node.text_style) != passed_color(node, text.get());
5217 let animation_changed = node.animated != animated;
5218 let paint_changed = !opt_rc_eq(node.paint.as_ref(), paint.as_ref());
5219 let z_changed = node.z_index != z_index;
5220 let align_changed =
5222 node.vertical_align != vertical_align && node.inline && node.kind != Kind::Text;
5223 let content_align_changed = node.vertical_align != vertical_align && !node.inline;
5225 let accent_changed = !view_same && node.view_style.accent_color != new_view.accent_color;
5226 view.install(&mut node.view_style);
5227 text.install(&mut node.text_style);
5228 if paint_changed {
5229 node.paint = paint;
5230 }
5231 node.animated = animated;
5232 node.z_index = z_index;
5233 node.vertical_align = vertical_align;
5234 self.sync_grid_role(key);
5236 if clip_changed {
5237 self.mark(key, dirty::TEXT_BUILD);
5238 }
5239 if align_changed {
5240 self.mark_text_block(key);
5241 } else if content_align_changed && let Some(place) = self.placed_in_text(key) {
5242 self.mark_text_block(place);
5243 }
5244 if z_changed {
5245 self.restack(key);
5246 }
5247 let node = &mut self.nodes[key as usize];
5248 fn keep_base(slot: &mut Option<Box<taffy::Style>>, layout: impl LayoutSlot) {
5249 match slot {
5250 Some(base) => **base = layout.into_owned(),
5251 None => *slot = Some(Box::new(layout.into_owned())),
5252 }
5253 }
5254 if node.kind.derives_layout() || node.fixed_view {
5255 keep_base(&mut node.base_layout, layout);
5256 self.sync_layout_style(key);
5257 } else if let Some(l) = node.layout {
5258 if layout.set_on(&mut self.layout, l) {
5260 self.needs_layout = true;
5261 }
5262 } else if node.kind == Kind::Text {
5263 let padding = |l: &taffy::Style| l.padding;
5267 let padded = node.base_layout.as_deref().map(padding) != Some(padding(layout.get()));
5268 keep_base(&mut node.base_layout, layout);
5269 if padded && node.inline {
5270 self.mark_text_block(key);
5271 }
5272 }
5273 let hid_after = self.nodes[key as usize]
5274 .layout
5275 .is_some_and(|l| self.layout.displays_none(l));
5276 if hid_before != hid_after {
5277 self.dirty_overlays();
5278 }
5279 let mut flags = 0;
5280 if view_changed {
5281 flags |= dirty::VIEW;
5282 if self.nodes[key as usize]
5285 .drawing
5286 .as_ref()
5287 .is_some_and(|d| d.paints_background())
5288 {
5289 flags |= dirty::CANVAS;
5290 }
5291 }
5292 if position_changed && self.nodes[key as usize].image.is_some() {
5293 flags |= dirty::IMAGE;
5294 }
5295 if accent_changed {
5296 self.sync_accent(key);
5297 }
5298 self.sticky_changed |= animation_changed && self.nodes[key as usize].sticky.is_some();
5300 let parent = self.nodes[key as usize].parent;
5301 let in_perspective =
5302 parent != NO_KEY && self.nodes[parent as usize].child_perspective.is_some();
5303 if animation_changed
5304 || view_changed && in_perspective && !self.nodes[key as usize].animated.is_empty()
5305 {
5306 flags |= dirty::ANIMATION;
5308 }
5309 if flags != 0 {
5310 self.mark(key, flags);
5311 }
5312 if text_changed || flipped {
5313 match self.nodes[key as usize].kind {
5314 Kind::Text => {
5315 self.mark_text_block(key);
5316 if color_passed {
5318 self.mark_inheriting_text(key);
5319 }
5320 }
5321 Kind::Input => {
5322 self.measure_input(key);
5323 self.mark(key, dirty::INPUT);
5324 }
5325 _ if text_changed => self.mark_inheriting_text(key),
5327 _ => {}
5328 }
5329 }
5330 if color_passed {
5331 let node = &self.nodes[key as usize];
5332 let color = node.text_style.color.or(node.inherited_color);
5333 self.inherit_color(key, color);
5334 }
5335 if paint_changed || text_changed {
5338 self.mark_view_painted(key);
5339 }
5340 if flipped {
5341 self.update_children_direction(key);
5342 if self.reads_direction(key) {
5345 self.restyle(key);
5346 }
5347 }
5348 }
5349
5350 fn mark_view_painted(&mut self, key: Key) {
5353 let mut stack = vec![key];
5354 while let Some(k) = stack.pop() {
5355 let node = &self.nodes[k as usize];
5356 match node.kind {
5357 Kind::Canvas => {
5358 if node
5359 .drawing
5360 .as_ref()
5361 .is_some_and(|d| !d.view_paints.is_empty())
5362 {
5363 self.mark(k, dirty::CANVAS);
5364 }
5365 }
5366 Kind::Text | Kind::RawText | Kind::Input => {}
5367 _ if node.image.as_ref().is_some_and(|i| i.svg_current_color) => {
5369 self.mark(k, dirty::IMAGE);
5370 }
5371 _ => stack.extend_from_slice(&self.nodes[k as usize].children),
5372 }
5373 }
5374 }
5375
5376 fn mounted_drawing(
5380 &self,
5381 key: Key,
5382 drawing: &Arc<crate::canvas::Drawing>,
5383 ) -> Arc<crate::canvas::Drawing> {
5384 if drawing.view_paints.is_empty() {
5385 return drawing.clone();
5386 }
5387 let node = &self.nodes[key as usize];
5388 let (paint, current) = self.resolved_paint(key);
5389 let style = &node.view_style;
5390 let images = style
5391 .effects
5392 .as_deref()
5393 .map_or(&[][..], |e| &e.background_images[..]);
5394 let size = if node.frame == Bounds::UNSET {
5395 Size::default()
5396 } else {
5397 node.frame.size
5398 };
5399 Arc::new(drawing.painted(&paint, current, style.background_color, images, size))
5400 }
5401
5402 fn send_fitted(&mut self) {
5405 let mut pending = std::mem::take(&mut self.fitted_pending);
5406 pending.sort_unstable();
5407 pending.dedup();
5408 for &key in &pending {
5409 let Some(node) = self.nodes.get(key as usize) else {
5410 continue;
5411 };
5412 if !node.created {
5413 continue;
5414 }
5415 let Some(drawing) = &node.drawing else {
5416 continue;
5417 };
5418 let (id, drawing) = (node.id, self.mounted_drawing(key, drawing));
5419 self.mount.push(MountItem::Canvas { id, drawing });
5420 }
5421 pending.clear();
5422 self.fitted_pending = pending;
5423 }
5424
5425 fn resolved_paint(&self, key: Key) -> (PaintStyle, crate::style::Color) {
5429 let node = &self.nodes[key as usize];
5430 let mut paint = node.paint.as_deref().cloned().unwrap_or_default();
5431 let mut k = node.parent;
5432 while k != NO_KEY {
5433 if let Some(p) = self.nodes[k as usize].paint.as_deref() {
5434 paint = paint.inherit(p);
5435 }
5436 k = self.nodes[k as usize].parent;
5437 }
5438 let color = node
5439 .text_style
5440 .color
5441 .unwrap_or_else(|| self.inherited_text_style(key).color);
5442 (paint, color)
5443 }
5444
5445 pub(super) fn resolved_rtl(&self, key: Key) -> bool {
5448 let node = &self.nodes[key as usize];
5449 if let Some(rtl) = node.direction {
5450 return rtl;
5451 }
5452 match node.parent {
5453 NO_KEY => key != self.root && self.nodes[self.root as usize].rtl,
5454 parent => self.nodes[parent as usize].rtl,
5455 }
5456 }
5457
5458 fn update_direction(&mut self, key: Key) {
5461 let rtl = self.resolved_rtl(key);
5462 if self.nodes[key as usize].rtl == rtl {
5463 return;
5464 }
5465 self.flip_direction(key, rtl);
5466 self.update_children_direction(key);
5467 }
5468
5469 fn update_children_direction(&mut self, key: Key) {
5470 let children = self.nodes[key as usize].children.clone();
5471 for child in children {
5472 self.update_direction(child);
5473 }
5474 }
5475
5476 fn flip_direction(&mut self, key: Key, rtl: bool) {
5480 let direction = if rtl {
5481 taffy::Direction::Rtl
5482 } else {
5483 taffy::Direction::Ltr
5484 };
5485 let node = &mut self.nodes[key as usize];
5486 node.rtl = rtl;
5487 if let Some(list) = node.list.as_mut() {
5488 let mirrored = rtl && list.horizontal;
5489 list.set_mirrored(mirrored);
5490 }
5491 let logical = node.has_logical || node.spaced;
5493 let kind = node.kind;
5494 if let Some(base) = node.base_layout.as_deref_mut() {
5495 base.direction = direction;
5496 self.sync_layout_style(key);
5497 } else if let Some(l) = node.layout {
5498 let mut layout = self.layout.style(l).clone();
5499 layout.direction = direction;
5500 self.layout.set_style(l, layout);
5501 self.needs_layout = true;
5502 }
5503 self.mark(key, dirty::VIEW);
5504 if logical || self.reads_direction(key) {
5505 self.restyle(key);
5506 }
5507 let node = &mut self.nodes[key as usize];
5508 let id = node.id;
5509 if let Some(scroll) = node.scroll.as_mut()
5510 && scroll.horizontal
5511 && node.list.as_ref().is_none_or(|l| !l.parent)
5512 {
5513 scroll.content = None;
5516 if !rtl {
5517 self.commands.push((
5518 id,
5519 Command::ScrollTo {
5520 x: Points::ZERO,
5521 y: Points::ZERO,
5522 animated: false,
5523 },
5524 ));
5525 }
5526 self.mark(key, dirty::SCROLL);
5527 }
5528 match kind {
5529 Kind::Text => self.mark_text_block(key),
5530 Kind::Input => {
5531 self.measure_input(key);
5532 self.mark(key, dirty::INPUT);
5533 }
5534 _ => {}
5535 }
5536 }
5537
5538 fn media_source(&self, uri: &str) -> Option<Option<Arc<str>>> {
5542 match self
5543 .access
5544 .media_url(uri, self.base_url.as_deref(), Some(&self.media_files))?
5545 {
5546 std::borrow::Cow::Borrowed(_) => Some(None),
5547 std::borrow::Cow::Owned(url) => Some(Some(url.into())),
5548 }
5549 }
5550
5551 fn check_canvas_images(&mut self, drawing: &mut crate::canvas::Drawing) {
5561 if self.access.is_unrestricted() {
5562 return;
5563 }
5564 let access = self.access.clone();
5565 let base = self.base_url.clone();
5566 let files = self.media_files.clone();
5567 let mut refused = Vec::new();
5568 let checked = &mut self.canvas_images;
5569 let mut files_here: rustc_hash::FxHashMap<Arc<str>, Option<Arc<str>>> =
5573 rustc_hash::FxHashMap::default();
5574 drawing.ops.retain_mut(|op| match op {
5575 crate::canvas::CanvasOp::DrawImage { image, .. } => {
5576 let granted = match checked
5577 .get(&image.uri)
5578 .or_else(|| files_here.get(&image.uri))
5579 {
5580 Some(granted) => granted.clone(),
5581 None => {
5582 let granted = access
5583 .media_url(&image.uri, base.as_deref(), Some(&files))
5584 .map(|url| match url {
5585 std::borrow::Cow::Owned(url) => Arc::from(url),
5586 std::borrow::Cow::Borrowed(_) => image.uri.clone(),
5587 });
5588 if crate::access::media_capability(&image.uri, base.as_deref()) == "network"
5589 {
5590 if checked.len() >= CANVAS_IMAGES {
5591 checked.clear();
5592 }
5593 checked.insert(image.uri.clone(), granted.clone());
5594 } else {
5595 files_here.insert(image.uri.clone(), granted.clone());
5596 }
5597 granted
5598 }
5599 };
5600 match granted {
5601 Some(url) => {
5602 image.uri = url;
5603 true
5604 }
5605 None => {
5606 refused.push(image.uri.clone());
5607 false
5608 }
5609 }
5610 }
5611 _ => true,
5612 });
5613 refused.sort_unstable();
5615 refused.dedup();
5616 for uri in refused {
5617 self.deny(media_not_granted(
5618 "a canvas image",
5619 &uri,
5620 self.base_url.as_deref(),
5621 ));
5622 }
5623 }
5624
5625 fn remember_app_menu(&mut self, desktop: &crate::desktop::DesktopCommand) {
5631 use crate::desktop::DesktopCommand;
5632 let change: Box<dyn FnOnce(&mut crate::element::menus::AppMenu)> = match desktop {
5633 DesktopCommand::SetMenu(items) => {
5634 let items = items.clone();
5635 Box::new(move |m| m.items = items)
5636 }
5637 DesktopCommand::SetMenuLabels(labels) => {
5638 let labels = (**labels).clone();
5639 Box::new(move |m| m.labels = labels)
5640 }
5641 _ => return,
5642 };
5643 let _entered = self.components.runtime.enter();
5644 let signal = crate::element::menus::app_menu(&self.components.executor.menus);
5645 signal.update(change);
5646 }
5647
5648 fn check_menu_icons(&mut self, desktop: &mut crate::desktop::DesktopCommand) {
5649 use crate::{
5650 ImageSource,
5651 desktop::{DesktopCommand, MenuItem},
5652 };
5653 if self.access.is_unrestricted() {
5654 return;
5655 }
5656 let mut check = |icon: &mut Option<ImageSource>| {
5657 let Some(source) = icon else { return };
5658 match self.media_source(&source.uri) {
5659 Some(Some(url)) => source.uri = url,
5660 Some(None) => {}
5661 None => {
5662 let message =
5663 media_not_granted("the menu icon", &source.uri, self.base_url.as_deref());
5664 *icon = None;
5665 self.deny(message);
5666 }
5667 }
5668 };
5669 fn each(items: &mut [MenuItem], check: &mut impl FnMut(&mut Option<ImageSource>)) {
5670 for item in items {
5671 match item {
5672 MenuItem::Action(action) => check(&mut action.icon),
5673 MenuItem::Submenu { items, icon, .. } => {
5674 check(icon);
5675 each(items, check);
5676 }
5677 MenuItem::Separator => {}
5678 }
5679 }
5680 }
5681 let checked = |items: &Arc<[MenuItem]>, check: &mut dyn FnMut(&mut Option<ImageSource>)| {
5682 let mut items = items.to_vec();
5683 each(&mut items, &mut |icon| check(icon));
5684 Arc::<[MenuItem]>::from(items)
5685 };
5686 match desktop {
5687 DesktopCommand::SetMenu(Some(items)) | DesktopCommand::PopupMenu { items, .. } => {
5688 *items = checked(items, &mut check);
5689 }
5690 DesktopCommand::SetTray(Some(tray)) => {
5691 check(&mut tray.icon);
5692 tray.menu = checked(&tray.menu, &mut check);
5693 }
5694 _ => {}
5695 }
5696 }
5697
5698 fn check_prop(&mut self, key: Key, prop: Prop) -> Prop {
5702 let prop = match prop {
5703 Prop::Native(NativeProp::AllowOrigin(Some(origin))) => {
5704 Prop::Native(NativeProp::AllowOrigin(self.check_allow_origin(&origin)))
5705 }
5706 Prop::Native(NativeProp::AllowNavigation(Some(hosts))) => {
5707 match crate::access::WebHosts::parse(&hosts) {
5708 Ok(_) => Prop::Native(NativeProp::AllowNavigation(Some(hosts))),
5709 Err(e) => {
5710 self.deny(format!("`allowNavigation`: {e}"));
5711 Prop::Native(NativeProp::AllowNavigation(None))
5712 }
5713 }
5714 }
5715 prop => prop,
5716 };
5717 if self.access.is_unrestricted() {
5718 return prop;
5719 }
5720 let node = &self.nodes[key as usize];
5721 let (id, kind) = (node.id, node.kind);
5722 if kind == Kind::WebView
5726 && self.access.allows_runtime_origin()
5727 && let Some(url) = web_url(&prop)
5728 && !url.is_empty()
5729 && !self.access.allows_webview_with(url, self.web_origin(key))
5730 {
5731 self.web_unchecked.insert((key, id));
5732 return prop;
5733 }
5734 let report = |core: &mut Self, message: String| core.report_access_denied(id, message);
5737 let refuse = |core: &mut Self, what: &str, uri: &str, capability: &str| {
5738 report(core, not_granted(what, uri, capability));
5739 };
5740 let refuse_media = |core: &mut Self, what: &str, uri: &str| {
5741 let message = media_not_granted(what, uri, core.base_url.as_deref());
5742 report(core, message);
5743 };
5744 let no_webviews = |core: &mut Self| {
5745 report(
5746 core,
5747 "web views are not granted: add `webview` to capabilities in nsh.json".into(),
5748 );
5749 };
5750 match prop {
5751 Prop::Source(Some(mut source)) => match self.media_source(&source.uri) {
5753 Some(granted) => {
5754 source.uri = granted.unwrap_or(source.uri);
5755 Prop::Source(Some(source))
5756 }
5757 None => {
5758 refuse_media(self, "the image", &source.uri);
5759 Prop::Source(None)
5760 }
5761 },
5762 Prop::Image(ImageProp::Placeholder(Some(mut source))) => {
5763 match self.media_source(&source.uri) {
5764 Some(granted) => {
5765 source.uri = granted.unwrap_or(source.uri);
5766 Prop::Image(ImageProp::Placeholder(Some(source)))
5767 }
5768 None => {
5769 refuse_media(self, "the placeholder", &source.uri);
5770 Prop::Image(ImageProp::Placeholder(None))
5771 }
5772 }
5773 }
5774 Prop::Native(NativeProp::Src(Some(url))) if kind == Kind::Video => {
5775 match self.media_source(&url) {
5776 Some(granted) => Prop::Native(NativeProp::Src(Some(granted.unwrap_or(url)))),
5777 None => {
5778 refuse_media(self, "the video", &url);
5779 Prop::Native(NativeProp::Src(None))
5780 }
5781 }
5782 }
5783 Prop::Native(NativeProp::Poster(Some(url))) if kind == Kind::Video => {
5784 match self.media_source(&url) {
5785 Some(granted) => Prop::Native(NativeProp::Poster(Some(granted.unwrap_or(url)))),
5786 None => {
5787 refuse_media(self, "the poster", &url);
5788 Prop::Native(NativeProp::Poster(None))
5789 }
5790 }
5791 }
5792 Prop::Native(NativeProp::Src(Some(url)))
5793 if kind == Kind::WebView
5794 && !self.access.allows_webview_with(&url, self.web_origin(key)) =>
5795 {
5796 refuse(self, "the web page", &url, "webview.hosts");
5797 Prop::Native(NativeProp::Src(None))
5798 }
5799 Prop::Native(NativeProp::Html(Some(_)))
5800 if kind == Kind::WebView && !self.access.allows_webviews() =>
5801 {
5802 no_webviews(self);
5803 Prop::Native(NativeProp::Html(None))
5804 }
5805 Prop::Native(NativeProp::Source(crate::WebSource::Uri(uri))) if kind == Kind::Video => {
5806 match self.media_source(&uri) {
5807 Some(granted) => Prop::Native(NativeProp::Source(crate::WebSource::Uri(
5808 granted.unwrap_or(uri),
5809 ))),
5810 None => {
5811 refuse_media(self, "the video", &uri);
5812 Prop::Native(NativeProp::Source(crate::WebSource::None))
5813 }
5814 }
5815 }
5816 Prop::Native(NativeProp::Source(crate::WebSource::Uri(uri)))
5817 if kind == Kind::WebView
5818 && !self.access.allows_webview_with(&uri, self.web_origin(key)) =>
5819 {
5820 refuse(self, "the web page", &uri, "webview.hosts");
5821 Prop::Native(NativeProp::Source(crate::WebSource::None))
5822 }
5823 Prop::Native(NativeProp::Source(crate::WebSource::Html { .. }))
5824 if kind == Kind::WebView && !self.access.allows_webviews() =>
5825 {
5826 no_webviews(self);
5827 Prop::Native(NativeProp::Source(crate::WebSource::None))
5828 }
5829 Prop::Native(NativeProp::BaseUrl(Some(url)))
5836 if kind == Kind::WebView
5837 && !url.is_empty()
5838 && self.access.allows_webviews()
5839 && !self.access.allows_webview_with(&url, self.web_origin(key)) =>
5840 {
5841 refuse(self, "the base URL", &url, "webview.hosts");
5842 Prop::Native(NativeProp::BaseUrl(None))
5843 }
5844 Prop::Native(NativeProp::Source(crate::WebSource::Html {
5845 html,
5846 base_url: Some(url),
5847 })) if kind == Kind::WebView
5848 && !url.is_empty()
5849 && !self.access.allows_webview_with(&url, self.web_origin(key)) =>
5850 {
5851 refuse(self, "the base URL", &url, "webview.hosts");
5852 Prop::Native(NativeProp::Source(crate::WebSource::Html {
5853 html,
5854 base_url: None,
5855 }))
5856 }
5857 prop => prop,
5858 }
5859 }
5860
5861 fn check_allow_origin(&mut self, origin: &str) -> Option<Arc<str>> {
5865 match crate::access::WebOrigin::parse(origin) {
5866 Err(e) => {
5867 self.deny(format!("`allowOrigin`: {e}"));
5868 None
5869 }
5870 Ok(_) if !self.access.is_unrestricted() && !self.access.allows_runtime_origin() => {
5871 self.deny(
5872 "`allowOrigin` is not granted: add `\"runtimeOrigin\": true` to capabilities.webview in nsh.json"
5873 .into(),
5874 );
5875 None
5876 }
5877 Ok(o) => Some(o.to_string().into()),
5878 }
5879 }
5880
5881 fn web_origin(&self, key: Key) -> Option<&crate::access::WebOrigin> {
5883 match self.nodes[key as usize].control.as_deref() {
5884 Some(NativeProps::WebView(p)) => p.allow_origin.as_ref(),
5885 _ => None,
5886 }
5887 }
5888
5889 fn settle_web_urls(&mut self, key: Key) {
5894 let id = self.nodes[key as usize].id;
5895 if !self.web_unchecked.remove(&(key, id)) {
5896 return;
5897 }
5898 let access = &self.access;
5899 let Some(NativeProps::WebView(p)) = self.nodes[key as usize].control.as_deref_mut() else {
5900 return;
5901 };
5902 let origin = p.allow_origin.clone();
5903 let refuses =
5904 |url: &str| !url.is_empty() && !access.allows_webview_with(url, origin.as_ref());
5905 let mut messages = Vec::new();
5906 let src = p.src.take_if(|url| refuses(url));
5908 if let Some(url) = &src {
5909 messages.push(not_granted("the web page", url, "webview.hosts"));
5910 }
5911 if let crate::WebSource::Uri(url) = &p.source
5913 && refuses(url)
5914 {
5915 if src.as_ref() != Some(url) {
5916 messages.push(not_granted("the web page", url, "webview.hosts"));
5917 }
5918 p.source = crate::WebSource::None;
5919 }
5920 let base = p.base_url.take_if(|url| refuses(url));
5921 if let Some(url) = &base {
5922 messages.push(not_granted("the base URL", url, "webview.hosts"));
5923 }
5924 if let crate::WebSource::Html { base_url, .. } = &mut p.source
5925 && let Some(url) = base_url.take_if(|url| refuses(url))
5926 && base.as_ref() != Some(&url)
5927 {
5928 messages.push(not_granted("the base URL", &url, "webview.hosts"));
5929 }
5930 for message in messages {
5931 self.report_access_denied(id, message);
5932 }
5933 }
5934
5935 fn report_access_denied(&mut self, id: NodeId, message: String) {
5938 self.events.push(crate::element::JsEvent::Event(
5939 id,
5940 EventKind::Error,
5941 EventPayload::Map(vec![
5942 ("message", PayloadValue::Str(message.clone())),
5943 (
5944 "code",
5945 PayloadValue::Str(crate::element::codes::ACCESS_DENIED.into()),
5946 ),
5947 ]),
5948 ));
5949 self.deny(message);
5950 }
5951
5952 fn compile(
5956 &mut self,
5957 source: &str,
5958 ) -> Result<crate::shader::Shader, crate::shader::ShaderError> {
5959 let hash = crate::shader::source_hash(source);
5960 let cached = self.shaders.get(&hash).filter(|c| match c {
5961 Ok(shader) => shader.source() == source,
5962 Err(_) => true,
5963 });
5964 if let Some(compiled) = cached {
5965 return compiled.clone();
5966 }
5967 let compiled = crate::shader::compile_source(source);
5968 if self.shaders.len() >= 64 {
5970 self.shaders.clear();
5971 }
5972 self.shaders.insert(hash, compiled.clone());
5973 compiled
5974 }
5975
5976 fn set_nav_shader(&mut self, key: Key, spec: Option<crate::shader::NavShaderSpec>) {
5979 let id = self.nodes[key as usize].id;
5980 if self.nodes[key as usize].root.is_none() {
5981 log::warn!(target: "js", "`transitionShader` is a page's or a dialog's; node {id} is neither");
5982 return;
5983 }
5984 let shader = spec.and_then(|spec| {
5985 let shader = self
5986 .compile(&spec.source)
5987 .map_err(|e| log::warn!(target: "js", "the transitionShader of node {id}: {e}"))
5988 .ok()?;
5989 let mut warnings = Vec::new();
5990 let layer = crate::shader::ShaderLayer::new(shader, &spec.uniforms.0, &mut warnings)
5991 .with_role(crate::shader::ShaderRole::Transition);
5992 for warning in warnings {
5993 log::warn!(target: "js", "the transitionShader of node {id}: {warning}");
5994 }
5995 let ms = spec.duration.unwrap_or(DEFAULT_NAV_SHADER_MS).max(0.0);
5996 Some(crate::NavShader {
5997 layer: Arc::new(layer),
5998 duration: std::time::Duration::from_micros((f64::from(ms) * 1000.0).round() as u64),
5999 })
6000 });
6001 let root = self.nodes[key as usize]
6002 .root
6003 .as_mut()
6004 .expect("checked above");
6005 if root.nav_shader != shader {
6006 root.nav_shader = shader;
6007 self.mark(key, dirty::NAV_SHADER);
6008 }
6009 }
6010
6011 fn mark_shader_inputs(&mut self) {
6020 let unlinked_from = std::mem::take(&mut self.unlinked_from);
6021 if self.pictured.is_empty()
6024 || self
6025 .mount
6026 .iter()
6027 .all(|item| matches!(item, MountItem::LayoutAnimation(_)))
6028 {
6029 return;
6030 }
6031 use crate::shader::{ShaderInput as I, ShaderRole as R};
6032 let ids: Vec<NodeId> = self.pictured.iter().copied().collect();
6033 let mut marked: Vec<NodeId> = Vec::new();
6034 let mut subtrees: Vec<(NodeId, Key)> = Vec::new();
6035 let mut backdrops: Vec<(NodeId, Key)> = Vec::new();
6036 for id in ids {
6037 let Ok(key) = self.key(id) else {
6038 self.pictured.remove(&id);
6039 continue;
6040 };
6041 let Some(layer) = self.nodes[key as usize]
6042 .shader
6043 .as_ref()
6044 .and_then(|s| s.layer.as_ref())
6045 else {
6046 continue;
6047 };
6048 let inputs = layer.shader.inputs();
6049 if matches!(layer.role, R::Screen | R::ScreenTransition) {
6050 marked.push(id);
6051 continue;
6052 }
6053 if inputs.contains(I::Backdrop) {
6054 backdrops.push((id, key));
6055 }
6056 if matches!(layer.role, R::Effect | R::Transition) {
6057 subtrees.push((id, key));
6058 }
6059 }
6060 if !backdrops.is_empty() {
6061 let mut everywhere = false;
6064 let mut changed: Vec<Key> = Vec::new();
6065 let mut seen = rustc_hash::FxHashSet::default();
6066 for item in &self.mount {
6067 match shown_by(item) {
6068 Shown::Nothing => {}
6069 Shown::Everywhere => {
6070 everywhere = true;
6071 break;
6072 }
6073 Shown::View(id) => {
6074 if seen.insert(id)
6075 && let Ok(key) = self.key(id)
6076 {
6077 changed.push(key);
6078 }
6079 }
6080 }
6081 }
6082 for &id in &unlinked_from {
6083 if seen.insert(id)
6084 && let Ok(key) = self.key(id)
6085 {
6086 changed.push(key);
6087 }
6088 }
6089 for &(id, key) in &backdrops {
6090 if everywhere || self.draws_before(&changed, key) {
6091 marked.push(id);
6092 }
6093 }
6094 }
6095 if !subtrees.is_empty() {
6096 let mut seen = rustc_hash::FxHashSet::default();
6097 let views = self.mount.iter().filter_map(MountItem::view);
6100 for view in views.chain(unlinked_from) {
6101 if !seen.insert(view) {
6102 continue;
6103 }
6104 let Ok(mut key) = self.key(view) else {
6105 continue;
6106 };
6107 loop {
6108 if let Some(&(id, _)) = subtrees.iter().find(|(_, k)| *k == key)
6109 && !marked.contains(&id)
6110 {
6111 marked.push(id);
6112 }
6113 let parent = self.nodes[key as usize].parent;
6114 if parent == NO_KEY {
6115 break;
6116 }
6117 key = parent;
6118 }
6119 }
6120 }
6121 for id in marked {
6122 self.mount.push(MountItem::ShaderInput { id });
6123 }
6124 }
6125
6126 fn draws_before(&self, views: &[Key], reader: Key) -> bool {
6133 if views.is_empty() {
6134 return false;
6135 }
6136 let mut up: Vec<Key> = Vec::new();
6138 let mut key = reader;
6139 while key != NO_KEY {
6140 up.push(key);
6141 key = self.nodes[key as usize].parent;
6142 }
6143 let at: rustc_hash::FxHashMap<Key, usize> =
6144 up.iter().enumerate().map(|(i, &k)| (k, i)).collect();
6145 views.iter().any(|&view| {
6146 let mut below = NO_KEY;
6147 let mut key = view;
6148 while key != NO_KEY {
6149 if let Some(&i) = at.get(&key) {
6150 if i == 0 {
6151 return false;
6153 }
6154 if below == NO_KEY {
6155 return true;
6157 }
6158 return self.stacks_before(key, below, up[i - 1]);
6161 }
6162 below = key;
6163 key = self.nodes[key as usize].parent;
6164 }
6165 true
6166 })
6167 }
6168
6169 fn stacks_before(&self, parent: Key, a: Key, b: Key) -> bool {
6171 let children = &self.nodes[parent as usize].children;
6172 let rank = |k: Key| {
6173 let index = children.iter().position(|&c| c == k).unwrap_or(usize::MAX);
6174 (self.nodes[k as usize].stack_rank(), index)
6175 };
6176 rank(a) < rank(b)
6177 }
6178
6179 fn set_shader_prop(&mut self, key: Key, prop: Prop) {
6183 let id = self.nodes[key as usize].id;
6184 let Some(state) = self.nodes[key as usize].shader.as_mut() else {
6185 log::warn!(target: "js", "shader props are a `<Shader>`'s; node {id} is not one");
6186 return;
6187 };
6188 match prop {
6189 Prop::ShaderSource(source) => {
6190 if state.source == source {
6191 return;
6192 }
6193 state.source = source.clone();
6194 state.shader = None;
6195 if let Some(source) = source {
6196 let compiled = self.compile(&source);
6197 let state = self.nodes[key as usize]
6198 .shader
6199 .as_mut()
6200 .expect("shader node");
6201 match compiled {
6202 Ok(shader) => state.shader = Some(shader),
6203 Err(error) => log::warn!(target: "js", "the shader of node {id}: {error}"),
6204 }
6205 }
6206 }
6207 Prop::Shader(shader) => {
6208 state.source = None;
6209 state.shader = shader;
6210 }
6211 Prop::Uniforms(uniforms) => state.uniforms = uniforms,
6212 Prop::ShaderPaused(paused) => state.paused = paused,
6213 Prop::ShaderProgress(progress) => state.progress = progress,
6214 Prop::MaxSampleOffset(overflow) => state.overflow = overflow.max(Points::ZERO),
6215 Prop::TransitionValue(value) => state.value = value,
6216 Prop::TransitionDuration(duration) => state.duration = duration,
6217 Prop::TransitionFallback(fallback) => state.fallback = fallback,
6218 _ => return,
6219 }
6220 let state = self.nodes[key as usize]
6221 .shader
6222 .as_mut()
6223 .expect("shader node");
6224 use crate::shader::ShaderRole as R;
6225 let transition = matches!(state.role, R::Transition | R::ScreenTransition);
6226 let program = state.shader.clone().or_else(|| {
6228 (transition && state.fallback == crate::TransitionFallback::Fade)
6229 .then(crate::shader::crossfade)
6230 .flatten()
6231 });
6232 let layer = program.map(|shader| {
6233 let mut warnings = Vec::new();
6234 let (progress, animated) = match state.progress {
6235 crate::shader::ShaderProgress::Number(n) => (n, None),
6236 crate::shader::ShaderProgress::Animated(node) => (Percentage(0.0), Some(node)),
6237 };
6238 let layer = crate::shader::ShaderLayer::new(shader, &state.uniforms.0, &mut warnings)
6239 .with_paused(state.paused)
6240 .with_role(state.role)
6241 .with_overflow(state.overflow)
6242 .with_progress(progress, animated);
6243 for warning in warnings {
6244 log::warn!(target: "js", "the shader of node {id}: {warning}");
6245 }
6246 Arc::new(layer)
6247 });
6248 if transition && state.value != state.shown {
6249 let before = std::mem::replace(&mut state.shown, state.value.clone());
6250 let ms = state.duration.unwrap_or(DEFAULT_TRANSITION_MS).max(0.0);
6251 if before.is_some() && layer.is_some() && ms > 0.0 {
6252 self.transition_starts.push(MountItem::ShaderTransition {
6253 id,
6254 duration: std::time::Duration::from_micros(
6255 (f64::from(ms) * 1000.0).round() as u64
6256 ),
6257 });
6258 }
6259 }
6260 let state = self.nodes[key as usize]
6261 .shader
6262 .as_mut()
6263 .expect("shader node");
6264 if layer.as_ref().is_some_and(|l| {
6265 !l.shader.inputs().is_empty() || matches!(l.role, R::Screen | R::ScreenTransition)
6266 }) {
6267 self.pictured.insert(id);
6268 } else {
6269 self.pictured.remove(&id);
6270 }
6271 if layer == state.layer {
6272 return;
6273 }
6274 let nodes_of = |l: &Option<Arc<crate::shader::ShaderLayer>>| {
6275 l.as_ref().map_or(&[][..], |l| &l.nodes[..]).to_vec()
6276 };
6277 let slots_changed = nodes_of(&layer) != nodes_of(&state.layer);
6278 state.layer = layer;
6279 self.mark(
6280 key,
6281 dirty::SHADER | if slots_changed { dirty::ANIMATION } else { 0 },
6282 );
6283 }
6284
6285 fn set_prop(&mut self, id: NodeId, prop: Prop) -> Result<(), ApplyError> {
6286 let key = self.key(id)?;
6287 let prop = match prop {
6290 Prop::Component(name) if self.nodes[key as usize].kind == Kind::View => {
6291 self.create_instance(id, name);
6292 return Ok(());
6293 }
6294 Prop::Component(name) if self.nodes[key as usize].kind == Kind::GpuView => {
6296 let source = self.components.gpu_renderer(&name);
6297 if source.is_none() {
6298 log::warn!(target: "js", "no GPU renderer is registered as `{name}`; the view draws nothing");
6299 }
6300 self.set_gpu_source(key, id, source);
6301 return Ok(());
6302 }
6303 Prop::GpuRenderer(source) => {
6304 if self.nodes[key as usize].kind == Kind::GpuView {
6305 self.set_gpu_source(key, id, source);
6306 } else {
6307 log::warn!("a GPU renderer on node {id}, which is no GPU view");
6308 }
6309 return Ok(());
6310 }
6311 Prop::ComponentSlot(name) => {
6312 self.set_slot_name(id, name);
6313 self.lay_out_through(key);
6314 return Ok(());
6315 }
6316 Prop::ComponentRender(slot) => {
6317 self.set_render_holder(id, slot);
6318 self.lay_out_through(key);
6319 return Ok(());
6320 }
6321 Prop::RustProp(name, value) => {
6322 if !self.set_component_prop(id, name, value) {
6323 log::warn!(target: "js", "a Rust component's prop on node {id}, which hosts none");
6324 }
6325 return Ok(());
6326 }
6327 Prop::Follow(target) => {
6328 self.set_follow_target(key, target);
6329 return Ok(());
6330 }
6331 Prop::PassPosition(pass) => {
6332 self.set_pass_position(key, pass);
6333 return Ok(());
6334 }
6335 Prop::FollowTransition(transition) => {
6336 self.set_follow_transition(key, transition);
6337 return Ok(());
6338 }
6339 Prop::Accessibility(AccessibilityProp::ActiveDescendant(target)) => {
6340 self.set_relation(key, relations::Relation::ActiveDescendant, target);
6341 return Ok(());
6342 }
6343 Prop::Accessibility(AccessibilityProp::Controls(target)) => {
6344 self.set_relation(key, relations::Relation::Controls, target);
6345 return Ok(());
6346 }
6347 Prop::Accessibility(AccessibilityProp::DescribedBy(target)) => {
6348 self.set_relation(key, relations::Relation::DescribedBy, target);
6349 return Ok(());
6350 }
6351 Prop::ScrollEdgeElement(target) => {
6352 self.set_scroll_edge(key, target);
6353 return Ok(());
6354 }
6355 Prop::Accessibility(AccessibilityProp::Description(description))
6358 if !self.relators.is_empty() && self.set_own_description(key, &description) =>
6359 {
6360 return Ok(());
6361 }
6362 prop => prop,
6363 };
6364 let prop = self.check_prop(key, prop);
6365 if let Prop::ShaderSource(_)
6366 | Prop::Shader(_)
6367 | Prop::Uniforms(_)
6368 | Prop::ShaderPaused(_)
6369 | Prop::ShaderProgress(_)
6370 | Prop::MaxSampleOffset(_)
6371 | Prop::TransitionValue(_)
6372 | Prop::TransitionDuration(_)
6373 | Prop::TransitionFallback(_) = prop
6374 {
6375 self.set_shader_prop(key, prop);
6376 return Ok(());
6377 }
6378 if let Prop::TransitionShader(spec) = prop {
6379 self.set_nav_shader(key, spec);
6380 return Ok(());
6381 }
6382 if let Prop::Screen(ScreenProp::StatusBar(setting)) = prop {
6383 self.set_status_bar(key, setting);
6384 return Ok(());
6385 }
6386 if let Prop::Screen(ScreenProp::Orientations(bits)) = prop {
6387 self.set_page_orientations(key, bits);
6388 return Ok(());
6389 }
6390 if let Prop::ListViewport(mode) = prop {
6391 self.set_list_viewport(key, mode);
6392 return Ok(());
6393 }
6394 if matches!(
6397 prop,
6398 Prop::Scroll(_)
6399 | Prop::KeyboardDismissMode(_)
6400 | Prop::Scrollbar(_)
6401 | Prop::Refreshing(_)
6402 | Prop::ScrollValue(_)
6403 | Prop::PullValue(_)
6404 | Prop::Native(NativeProp::Scrollable(_))
6405 ) && let Some(list) = self.nodes[key as usize].list.as_mut().filter(|l| l.parent)
6406 {
6407 list.ignored |= match prop {
6408 Prop::Scroll(ScrollProp::RefreshIndicator(None)) => 0,
6409 Prop::Scroll(ScrollProp::RefreshIndicator(Some(_))) | Prop::PullValue(Some(_)) => {
6410 list::ignored::REFRESH
6411 }
6412 Prop::Scroll(_)
6413 | Prop::KeyboardDismissMode(
6414 KeyboardDismissMode::OnDrag | KeyboardDismissMode::Interactive,
6415 )
6416 | Prop::Native(NativeProp::Scrollable(false)) => list::ignored::BEHAVIOR,
6417 Prop::Scrollbar(
6418 crate::ScrollbarSetting::Hidden
6419 | crate::ScrollbarSetting::Themed(_)
6420 | crate::ScrollbarSetting::ThemeValue(_),
6421 ) => list::ignored::SCROLLBAR,
6422 Prop::Refreshing(true) => list::ignored::REFRESH,
6423 Prop::ScrollValue(Some(_)) => list::ignored::SCROLL_VALUE,
6424 _ => 0,
6425 };
6426 self.warn_ignored(key);
6427 return Ok(());
6428 }
6429 let node = &mut self.nodes[key as usize];
6430 let mut flags = 0;
6431 let mut key_ancestry = false;
6432 let mut rebuild_span = false;
6433 let mut copy_text_changed = false;
6434 let mut slop_moved = false;
6435 match prop {
6436 Prop::Source(source) => {
6437 if let Some(image) = node.image.as_mut() {
6438 let source = source.map(ImageSource::inline);
6441 let size = source.as_ref().and_then(ImageSource::natural_size);
6442 image.source = source;
6443 flags |= dirty::IMAGE;
6444 let layout = node.layout.expect("image layout");
6445 if let Some(LeafContext::Image(natural)) =
6446 self.layout.get_node_context_mut(layout)
6447 && *natural != size
6448 {
6449 *natural = size;
6450 self.layout.mark_dirty(layout);
6451 self.needs_layout = true;
6452 }
6453 }
6454 }
6455 Prop::Image(option) => {
6456 if let Some(image) = node.image.as_mut() {
6457 match option {
6458 ImageProp::Placeholder(source) => {
6459 image.options.placeholder = source.map(ImageSource::inline)
6460 }
6461 ImageProp::BlurRadius(r) => image.options.blur_radius = r.max(Points::ZERO),
6462 ImageProp::FadeDuration(ms) => image.options.fade_ms = ms,
6463 ImageProp::SvgCurrentColor(on) => image.svg_current_color = on,
6464 }
6465 flags |= dirty::IMAGE;
6466 }
6467 }
6468 Prop::Horizontal(horizontal) => {
6469 if let Some(scroll) = node.scroll.as_mut()
6470 && scroll.horizontal != horizontal
6471 {
6472 scroll.horizontal = horizontal;
6473 flags |= dirty::SCROLL;
6474 let rtl = node.rtl;
6475 if let Some(list) = node.list.as_mut() {
6476 list.set_mirrored(horizontal && rtl);
6477 list.set_horizontal(horizontal);
6478 }
6479 let children = node.children.clone();
6480 self.sync_layout_style(key);
6481 for child in children {
6482 self.sync_layout_style(child);
6483 }
6484 if self.nodes[key as usize]
6485 .list
6486 .as_ref()
6487 .is_some_and(|l| l.parent)
6488 {
6489 self.sync_spacer(key, true);
6490 self.outer_moved = true;
6491 flags |= dirty::VIEW_PROPS;
6493 }
6494 }
6495 }
6496 Prop::Scrollbar(setting) => {
6497 if let Some(scroll) = node.scroll.as_mut() {
6498 scroll.scrollbar = setting;
6499 flags |= dirty::SCROLL;
6500 self.scrollbars_pending.push(key);
6501 } else if let Some(input) = node.input.as_mut() {
6502 input.scrollbar = setting;
6503 flags |= dirty::INPUT;
6504 self.scrollbars_pending.push(key);
6505 }
6506 }
6507 Prop::Scroll(prop) => {
6508 if let Some(scroll) = node.scroll.as_mut() {
6509 let b = &mut scroll.behavior;
6510 match prop {
6511 ScrollProp::Paging(on) => b.paging = on,
6512 ScrollProp::SnapInterval(v) => b.snap_interval = v.max(Points::ZERO),
6513 ScrollProp::SnapOffsets(v) => b.snap_offsets = v,
6514 ScrollProp::SnapAlignment(a) => b.snap_alignment = a,
6515 ScrollProp::Deceleration(r) => b.deceleration = r,
6516 ScrollProp::Bounces(on) => b.bounces = on,
6517 ScrollProp::ScrollsToTop(on) => b.scrolls_to_top = on,
6518 ScrollProp::SmoothWheel(on) => b.smooth_wheel = on,
6519 ScrollProp::WheelLineHeight(h) => b.wheel_line_height = h.max(Points::ZERO),
6520 ScrollProp::ContentInset(i) => b.content_inset = i,
6521 ScrollProp::ScrollbarInset(i) => {
6522 b.scrollbar_inset = i.map(|v| Points(v.0.max(0.0)));
6524 if scroll.bar.is_some() {
6526 self.needs_layout = true;
6527 }
6528 }
6529 ScrollProp::KeyboardTaps(t) => b.keyboard_taps = t,
6530 ScrollProp::DisableIntervalMomentum(on) => b.one_step = on,
6531 ScrollProp::MinZoom(v) => b.min_zoom = v.max(0.01),
6532 ScrollProp::MaxZoom(v) => b.max_zoom = v.max(0.01),
6533 ScrollProp::BouncesZoom(on) => b.bounces_zoom = on,
6534 ScrollProp::Pinch(on) => b.pinch = on,
6535 ScrollProp::CenterContent(on) => b.center_content = on,
6536 ScrollProp::RefreshIndicator(h) => {
6537 b.refresh_indicator = h.filter(|h| h.0 > 0.0);
6539 }
6540 ScrollProp::Zoom(scale) => {
6541 let id = node.id;
6544 self.commands.push((
6545 id,
6546 Command::ZoomTo {
6547 scale,
6548 center: None,
6549 animated: false,
6550 },
6551 ));
6552 }
6553 ScrollProp::EventThrottle(ms) => scroll.event_throttle_ms = ms.max(0.0),
6554 ScrollProp::ContentOffset(offset) => {
6555 let id = node.id;
6557 self.commands.push((
6558 id,
6559 Command::ScrollTo {
6560 x: offset.x,
6561 y: offset.y,
6562 animated: false,
6563 },
6564 ));
6565 }
6566 }
6567 flags |= dirty::SCROLL_BEHAVIOR;
6568 }
6569 }
6570 Prop::Refreshing(refreshing) => {
6571 if let Some(scroll) = node.scroll.as_mut() {
6572 scroll.refreshing = refreshing;
6573 flags |= dirty::REFRESHING;
6574 }
6575 }
6576 Prop::ScrollValue(value) => {
6577 if let Some(value) = value {
6578 self.reach.drive(value);
6579 }
6580 if let Some(scroll) = node.scroll.as_mut() {
6581 scroll.scroll_value = value;
6582 flags |= dirty::SCROLL;
6583 }
6584 }
6585 Prop::PullValue(value) => {
6586 if let Some(value) = value {
6587 self.reach.drive(value);
6588 }
6589 if let Some(scroll) = node.scroll.as_mut() {
6590 scroll.pull_value = value;
6591 flags |= dirty::SCROLL;
6592 }
6593 }
6594 Prop::Count(count) => {
6595 if let Some(list) = node.list.as_mut()
6596 && list.count != count
6597 {
6598 list.unrequest(&take_queued_binds(&mut self.list_binds, node.id));
6599 list.set_count(count);
6600 }
6601 }
6602 Prop::EstimatedItemSize(size) => {
6603 if let Some(list) = node.list.as_mut() {
6604 list.set_estimated(size.0);
6605 }
6606 }
6607 Prop::Slot(slot) => {
6608 node.slot = Some(slot);
6609 let parent = node.parent;
6610 if let Some(list) = self
6611 .nodes
6612 .get_mut(parent as usize)
6613 .and_then(|p| p.list.as_mut())
6614 {
6615 list.add_slot_cell(slot, key);
6616 }
6617 }
6618 Prop::Splice(at, removed, inserted) => {
6619 let loads_at_start = node.events.contains(EventKind::LoadMoreAtStart);
6620 if let Some(list) = node.list.as_mut() {
6621 list.loads_at_start = loads_at_start;
6622 list.unrequest(&take_queued_binds(&mut self.list_binds, node.id));
6623 list.splice(at, removed, inserted);
6624 }
6625 }
6626 Prop::ListDiff(diff) => {
6627 let loads_at_start = node.events.contains(EventKind::LoadMoreAtStart);
6628 if let Some(list) = node.list.as_mut() {
6629 list.loads_at_start = loads_at_start;
6630 list.unrequest(&take_queued_binds(&mut self.list_binds, node.id));
6631 list.reorder(&diff);
6632 }
6633 }
6634 Prop::Columns(columns) => {
6635 if let Some(list) = node.list.as_mut()
6636 && list.set_columns(columns)
6637 {
6638 self.needs_layout = true;
6641 }
6642 }
6643 Prop::Inverted(inverted) => {
6644 if let Some(list) = node.list.as_mut() {
6645 list.set_inverted(inverted);
6646 if list.parent {
6647 self.warn_ignored(key);
6648 }
6649 }
6650 }
6651 Prop::FollowEnd(threshold, animated) => {
6652 if let Some(list) = node.list.as_mut() {
6653 list.set_follow_end(threshold.map(|t| t.0), animated);
6654 if list.parent {
6655 self.warn_ignored(key);
6656 }
6657 }
6658 }
6659 Prop::ListAlignment(alignment) => {
6660 if let Some(list) = node.list.as_mut() {
6661 list.set_alignment(alignment);
6662 if list.parent {
6663 self.warn_ignored(key);
6664 }
6665 }
6666 }
6667 Prop::StickyIndices(indices) => {
6668 if let Some(list) = node.list.as_mut() {
6669 list.set_sticky(indices);
6670 if list.parent {
6671 self.warn_ignored(key);
6672 }
6673 }
6674 }
6675 Prop::StickyOffset(offset) => {
6676 if let Some(list) = node.list.as_mut() {
6677 list.set_sticky_node(None);
6678 list.set_sticky_offset(offset.0);
6679 if list.parent {
6680 self.warn_ignored(key);
6681 }
6682 }
6683 }
6684 Prop::StickyOffsetNode(node_id) => {
6685 if let Some(list) = node.list.as_mut() {
6686 list.set_sticky_offset(0.0);
6687 list.set_sticky_node(node_id);
6688 }
6689 }
6690 Prop::ListContent(content) => {
6691 if let Some(list) = node.list.as_mut()
6692 && list.set_content(content)
6693 {
6694 self.needs_layout = true;
6695 }
6696 }
6697 Prop::Viewability(config) => {
6698 if let Some(list) = node.list.as_mut()
6699 && list.viewability != config
6700 {
6701 list.viewability = config;
6702 list.dirty = true;
6703 }
6704 }
6705 Prop::LoadMoreThreshold(threshold) => {
6706 if let Some(list) = node.list.as_mut() {
6707 list.end_threshold = threshold.max(0.0);
6708 }
6709 }
6710 Prop::LoadMoreAtStartThreshold(threshold) => {
6711 if let Some(list) = node.list.as_mut() {
6712 list.start_threshold = threshold.max(0.0);
6713 }
6714 }
6715 Prop::CellIndex(index) => {
6716 let parent = node.parent;
6717 if let Some(list) = self
6718 .nodes
6719 .get_mut(parent as usize)
6720 .and_then(|p| p.list.as_mut())
6721 {
6722 list.rendered(key, index);
6723 }
6724 }
6725 Prop::PanValues(x, y) => {
6726 for value in [x, y].into_iter().flatten() {
6728 self.reach.drive(value);
6729 }
6730 (node.gestures.pan_x, node.gestures.pan_y) = (x, y);
6731 flags |= dirty::PAN;
6732 }
6733 Prop::PanEnabled(enabled) => {
6734 if node.pan_enabled != enabled {
6735 node.pan_enabled = enabled;
6736 flags |= dirty::PAN | dirty::EVENTS;
6737 }
6738 }
6739 Prop::PanScrollHandoff(value) => {
6740 let props = node.props.get_or_insert_default();
6741 if props.pan_scroll_handoff != value {
6742 props.pan_scroll_handoff = value;
6743 flags |= dirty::VIEW_PROPS;
6744 }
6745 }
6746 Prop::PinchValue(value) => {
6747 if let Some(value) = value {
6748 self.reach.drive(value);
6749 }
6750 node.gestures.pinch = value;
6751 flags |= dirty::PAN;
6752 }
6753 Prop::RotationValue(value) => {
6754 if let Some(value) = value {
6755 self.reach.drive(value);
6756 }
6757 node.gestures.rotation = value;
6758 flags |= dirty::PAN;
6759 }
6760 Prop::AllowFontScaling(allow) => {
6761 if node.paragraph.allow_font_scaling != allow {
6762 node.paragraph.allow_font_scaling = allow;
6763 self.font_settings_changed(key);
6764 }
6765 }
6766 Prop::SelectionColor(color) if node.input.is_none() => {
6767 if node.paragraph.selection_color != color {
6768 node.paragraph.selection_color = color;
6769 if node.kind == Kind::Text {
6770 self.mark_text_block(key);
6771 } else {
6772 self.mark_inheriting_text(key);
6775 }
6776 }
6777 }
6778 Prop::AdjustsFontSizeToFit(_) | Prop::MinimumFontScale(_) => {
6779 let before = (node.paragraph.fit, node.paragraph.min_font_scale);
6780 match prop {
6781 Prop::AdjustsFontSizeToFit(on) => node.paragraph.fit = on,
6782 Prop::MinimumFontScale(min) => node.paragraph.min_font_scale = min,
6783 _ => {}
6784 }
6785 if (node.paragraph.fit, node.paragraph.min_font_scale) != before {
6786 self.queue_text(key);
6787 if let Some(layout) = self.nodes[key as usize].layout
6788 && let Some(LeafContext::Text(cx)) =
6789 self.layout.get_node_context_mut(layout)
6790 {
6791 cx.laid_out = None;
6792 }
6793 }
6794 }
6795 Prop::MaxFontSizeMultiplier(max) => {
6796 if node.paragraph.max_font_multiplier != max {
6797 node.paragraph.max_font_multiplier = max;
6798 self.font_settings_changed(key);
6799 }
6800 }
6801 Prop::PointerEvents(value) => {
6802 let props = node.props.get_or_insert_default();
6803 if props.pointer_events != value {
6804 props.pointer_events = value;
6805 flags |= dirty::VIEW_PROPS;
6806 }
6807 }
6808 Prop::HitSlop(value) => {
6809 let props = node.props.get_or_insert_default();
6810 if props.hit_slop != value {
6811 props.hit_slop = value;
6812 flags |= dirty::VIEW_PROPS;
6813 slop_moved = true;
6814 }
6815 }
6816 Prop::Href(value) => {
6817 let value = value.filter(|href| !href.is_empty());
6818 let props = node.props.get_or_insert_default();
6819 if props.href != value {
6820 props.href = value;
6821 flags |= dirty::VIEW_PROPS;
6822 if node.kind == Kind::Text && node.inline {
6824 rebuild_span = true;
6825 }
6826 }
6827 }
6828 Prop::PanActivation(value) => {
6829 let props = node.props.get_or_insert_default();
6830 if props.pan_activation != value {
6831 props.pan_activation = value;
6832 flags |= dirty::VIEW_PROPS;
6833 }
6834 }
6835 Prop::InsetPadding(insets) | Prop::InsetMargin(insets) => {
6836 let slot = usize::from(matches!(prop, Prop::InsetMargin(_)));
6837 let mut all = node.insets.as_deref().copied().unwrap_or_default();
6838 if all[slot] != insets {
6839 all[slot] = insets;
6840 node.insets = (all != <[EdgeInsets; 2]>::default()).then(|| Box::new(all));
6841 self.restyle(key);
6842 }
6843 return Ok(());
6844 }
6845 Prop::Class(names) => {
6846 self.set_classes(key, Some(names), None);
6847 return Ok(());
6848 }
6849 Prop::ClassList(list) => {
6850 self.set_classes(key, None, Some(list));
6851 return Ok(());
6852 }
6853 Prop::TailwindTheme(json) => {
6854 self.set_tailwind_theme(&json);
6855 return Ok(());
6856 }
6857 Prop::UiTheme(json) => {
6858 self.set_ui_theme(&json);
6859 return Ok(());
6860 }
6861 Prop::SnapToWindowMargin(margin) => {
6862 self.set_snap_to_window_margin(margin);
6863 return Ok(());
6864 }
6865 Prop::LayoutDirection(rtl) => {
6866 if key == self.root && node.direction != Some(rtl) {
6869 node.direction = Some(rtl);
6870 self.mount.push(MountItem::LayoutDirection { rtl });
6871 self.update_direction(key);
6872 self.root_direction_changed(rtl);
6873 }
6874 return Ok(());
6875 }
6876 Prop::Appearance(appearance) => {
6877 if key == self.root {
6880 self.set_appearance(appearance);
6881 }
6882 return Ok(());
6883 }
6884 Prop::Keymap(keymap) => {
6885 if key == self.root {
6887 let keymap = self.keymap_with_focus(keymap);
6888 self.mount.push(MountItem::Keymap(keymap));
6889 }
6890 return Ok(());
6891 }
6892 Prop::LongPressDelay(value) => {
6893 let props = node.props.get_or_insert_default();
6894 if props.long_press_delay != value {
6895 props.long_press_delay = value;
6896 flags |= dirty::VIEW_PROPS;
6897 }
6898 }
6899 Prop::Ripple(value) => {
6900 let props = node.props.get_or_insert_default();
6901 if props.ripple != value {
6902 props.ripple = value;
6903 flags |= dirty::VIEW_PROPS;
6904 }
6905 }
6906 Prop::Elevation(value) => {
6907 let value = value.max(Points::ZERO);
6908 if node.elevation != value {
6909 node.elevation = value;
6910 flags |= dirty::VIEW;
6911 }
6912 }
6913 Prop::BackdropMaterial(value) => {
6914 if node.backdrop_material != value {
6915 node.backdrop_material = value;
6916 flags |= dirty::VIEW;
6917 }
6918 }
6919 Prop::MacOsBackdrop(value) => {
6920 if node.macos_backdrop != value {
6921 node.macos_backdrop = value;
6922 flags |= dirty::VIEW;
6923 }
6924 }
6925 Prop::WindowsBackdrop(value) => {
6926 if node.windows_backdrop != value {
6927 node.windows_backdrop = value;
6928 flags |= dirty::VIEW;
6929 }
6930 }
6931 Prop::ActiveStyle(patch) => {
6932 self.set_part_style(key, classes::Part::Active, patch);
6933 return Ok(());
6934 }
6935 Prop::HoverStyle(patch) => {
6936 self.set_part_style(key, classes::Part::Hover, patch);
6937 return Ok(());
6938 }
6939 Prop::FocusStyle(patch) => {
6940 self.set_part_style(key, classes::Part::Focus, patch);
6941 return Ok(());
6942 }
6943 Prop::DisabledStyle(patch) => {
6944 self.set_part_style(key, classes::Part::Disabled, patch);
6945 return Ok(());
6946 }
6947 Prop::SelectedStyle(patch) => {
6948 self.set_part_style(key, classes::Part::Selected, patch);
6949 return Ok(());
6950 }
6951 Prop::CheckedStyle(patch) => {
6952 self.set_part_style(key, classes::Part::Checked, patch);
6953 return Ok(());
6954 }
6955 Prop::IndeterminateStyle(patch) => {
6956 self.set_part_style(key, classes::Part::Indeterminate, patch);
6957 return Ok(());
6958 }
6959 Prop::PressedStyle(patch) => {
6960 self.set_part_style(key, classes::Part::Pressed, patch);
6961 return Ok(());
6962 }
6963 Prop::ExpandedStyle(patch) => {
6964 self.set_part_style(key, classes::Part::Expanded, patch);
6965 return Ok(());
6966 }
6967 Prop::FocusWithinStyle(patch) => {
6968 self.set_part_style(key, classes::Part::FocusWithin, patch);
6969 return Ok(());
6970 }
6971 Prop::FocusVisibleStyle(patch) => {
6972 self.set_part_style(key, classes::Part::FocusVisible, patch);
6973 return Ok(());
6974 }
6975 Prop::ProjectedStates(states) => {
6976 self.set_projected_states(key, states);
6977 return Ok(());
6978 }
6979 Prop::ProjectedData(data) => {
6980 self.set_projected_data(key, data);
6981 return Ok(());
6982 }
6983 Prop::ProjectedActive(group) => {
6984 self.set_projected_active(key, group);
6985 return Ok(());
6986 }
6987 Prop::HeaderStyle(patch) => {
6988 self.set_part_style(key, classes::Part::Header, patch);
6989 return Ok(());
6990 }
6991 Prop::HeaderClass(names) => {
6992 self.set_part_class(key, classes::Part::Header, &names);
6993 return Ok(());
6994 }
6995 Prop::HeaderClassList(list) => {
6996 self.set_part_class_list(key, classes::Part::Header, list);
6997 return Ok(());
6998 }
6999 Prop::ListContentClass(names) => {
7000 self.set_part_class(key, classes::Part::Content, &names);
7001 return Ok(());
7002 }
7003 Prop::TestId(value) => {
7004 let props = node.props.get_or_insert_default();
7005 if props.test_id != value {
7006 props.test_id = value;
7007 flags |= dirty::VIEW_PROPS;
7008 if node.kind == Kind::Text && node.inline {
7010 rebuild_span = true;
7011 }
7012 }
7013 }
7014 Prop::ClearsKeyboard(value) => {
7015 if node.clears_keyboard != value {
7016 node.clears_keyboard = value;
7020 }
7021 }
7022 Prop::CopyText(value) => {
7023 if node.copy_text != value {
7024 node.copy_text = value;
7025 copy_text_changed = true;
7028 }
7029 }
7030 Prop::WebElement(value) => {
7031 let props = node.props.get_or_insert_default();
7032 if props.web_element != value {
7033 props.web_element = value;
7034 flags |= dirty::VIEW_PROPS;
7035 }
7036 }
7037 Prop::WindowDrag(value) => {
7038 let props = node.props.get_or_insert_default();
7039 if props.window_drag != value {
7040 props.window_drag = value;
7041 flags |= dirty::VIEW_PROPS;
7042 }
7043 }
7044 Prop::WindowControl(value) => {
7045 let props = node.props.get_or_insert_default();
7046 if props.window_control != value {
7047 props.window_control = value;
7048 flags |= dirty::VIEW_PROPS;
7049 }
7050 }
7051 Prop::WindowResize(value) => {
7052 let props = node.props.get_or_insert_default();
7053 if props.window_resize != value {
7054 props.window_resize = value;
7055 flags |= dirty::VIEW_PROPS;
7056 }
7057 }
7058 Prop::Focusable(value) => {
7059 let props = node.props.get_or_insert_default();
7060 if props.focusable != value {
7061 props.focusable = value;
7062 flags |= dirty::VIEW_PROPS;
7063 }
7064 }
7065 Prop::KeyCapture(value) => {
7066 let props = node.props.get_or_insert_default();
7067 if props.key_capture != value {
7068 props.key_capture = value;
7069 flags |= dirty::VIEW_PROPS;
7070 key_ancestry = true;
7071 }
7072 }
7073 Prop::SelectableView(value) => {
7074 let props = node.props.get_or_insert_default();
7075 if props.selectable_view != value {
7076 props.selectable_view = value;
7077 flags |= dirty::VIEW_PROPS;
7078 }
7079 }
7080 Prop::SelectionMenu(items) => {
7081 let items: std::sync::Arc<[crate::desktop::MenuItem]> =
7082 crate::desktop::MenuItem::selection_menu(&items).into();
7083 let props = node.props.get_or_insert_default();
7084 if props.selection_menu != items {
7085 props.selection_menu = items;
7086 flags |= dirty::VIEW_PROPS;
7087 }
7088 }
7089 Prop::ContinuesText(value) => {
7090 let props = node.props.get_or_insert_default();
7091 if props.continues_text != value {
7092 props.continues_text = value;
7093 flags |= dirty::VIEW_PROPS;
7094 }
7095 }
7096 Prop::Accessibility(prop) => {
7097 let label_only =
7100 node.props.is_some() && matches!(prop, AccessibilityProp::Label(_));
7101 let props = node.props.get_or_insert_default();
7102 let a = &mut props.accessibility;
7103 let before = a.clone();
7104 match prop {
7105 AccessibilityProp::Accessible(v) => a.accessible = v,
7106 AccessibilityProp::Label(v) => a.label = v,
7107 AccessibilityProp::Hint(v) => a.hint = v,
7108 AccessibilityProp::Description(v) => a.description = v,
7109 AccessibilityProp::Role(v) => a.role = v,
7110 AccessibilityProp::State(v) => a.state = v,
7111 AccessibilityProp::Value(v) => a.value = v,
7112 AccessibilityProp::Hidden(v) => a.hidden = v,
7113 AccessibilityProp::Important(accessible, hidden) => {
7114 a.accessible = accessible;
7115 a.hidden = hidden;
7116 }
7117 AccessibilityProp::LiveRegion(v) => a.live_region = v,
7118 AccessibilityProp::Actions(v) => a.actions = v,
7119 AccessibilityProp::Level(v) => a.level = v,
7120 AccessibilityProp::Orientation(v) => a.orientation = v,
7121 AccessibilityProp::ActiveDescendant(_)
7123 | AccessibilityProp::Controls(_)
7124 | AccessibilityProp::DescribedBy(_) => {}
7125 }
7126 let states = classes::accessibility_states(&a.state);
7127 let states_changed = states != classes::accessibility_states(&before.state);
7128 if *a != before {
7129 flags |= if label_only {
7130 dirty::LABEL
7131 } else {
7132 dirty::VIEW_PROPS
7133 };
7134 }
7135 if states_changed {
7136 if flags != 0 {
7137 self.mark(key, flags);
7138 }
7139 self.set_accessibility_states(key, states);
7140 return Ok(());
7141 }
7142 }
7143 Prop::KeyboardDismissMode(mode) => {
7144 if let Some(scroll) = node.scroll.as_mut() {
7145 scroll.keyboard_dismiss = mode;
7146 flags |= dirty::SCROLL;
7147 }
7148 }
7149 Prop::Screen(ScreenProp::Animation(a)) if node.kind == Kind::Modal => {
7151 if let Some(root) = node.root.as_mut() {
7152 root.modal.animation = match a {
7153 ScreenAnimation::Default => ModalAnimation::Slide,
7154 ScreenAnimation::Fade => ModalAnimation::Fade,
7155 ScreenAnimation::None => ModalAnimation::None,
7156 };
7157 flags |= dirty::MODAL;
7158 }
7159 }
7160 Prop::Screen(prop) => {
7161 if let Some(root) = node.root.as_mut() {
7162 let c = &mut root.screen;
7163 match prop {
7164 ScreenProp::Title(v) => c.title = v,
7165 ScreenProp::HeaderVisible(v) => c.header_visible = v,
7166 ScreenProp::HeaderLargeTitle(v) => c.large_title = v,
7167 ScreenProp::HeaderTransparent(v) => c.header_transparent = v,
7168 ScreenProp::HeaderShadowVisible(v) => c.header_shadow_visible = v,
7169 ScreenProp::HeaderTitleAlign(v) => c.title_align = v,
7170 ScreenProp::HeaderBackgroundOnScroll(v) => {
7171 c.header_background_on_scroll = v
7172 }
7173 ScreenProp::HidesBottomBarWhenPushed(v) => {
7174 c.hides_bottom_bar_when_pushed = v
7175 }
7176 ScreenProp::HeaderBackTitle(v) => c.back_title = v,
7177 ScreenProp::HeaderBackVisible(v) => c.back_visible = v,
7178 ScreenProp::HeaderRightSystemItem(v) => c.right_system_item = v,
7179 ScreenProp::HeaderRightSymbol(v) => c.right_symbol = v,
7180 ScreenProp::HeaderLeftSystemItem(v) => c.left_system_item = v,
7181 ScreenProp::HeaderLeftSymbol(v) => c.left_symbol = v,
7182 ScreenProp::HeaderRightItems(v) => c.right_items = v,
7183 ScreenProp::HeaderLeftItems(v) => c.left_items = v,
7184 ScreenProp::PopOnSwipe(v) => c.gesture_enabled = v,
7185 ScreenProp::PopOnBack(v) => c.prevent_back = !v,
7186 ScreenProp::Animation(v) => c.animation = v,
7187 ScreenProp::StatusBar(_) | ScreenProp::Orientations(_) => {}
7189 }
7190 root.laid_out = None;
7192 self.needs_layout = true;
7193 flags |= dirty::SCREEN;
7194 }
7195 }
7196 Prop::NativeId(name) => {
7197 if node.kind == Kind::InputAccessory {
7198 let attached = node.parent != NO_KEY;
7199 if attached {
7200 self.accessory_attached(key, false);
7201 }
7202 if let Some(root) = self.nodes[key as usize].root.as_mut() {
7203 root.native_id = name;
7204 }
7205 if attached {
7206 self.accessory_attached(key, true);
7207 }
7208 return Ok(());
7209 }
7210 let value: Option<Arc<str>> = name.as_deref().map(Into::into);
7213 let props = node.props.get_or_insert_default();
7214 if props.native_id != value {
7215 props.native_id = value;
7216 flags |= dirty::VIEW_PROPS;
7217 }
7218 }
7219 Prop::Modal(prop) => {
7220 if let Some(root) = node.root.as_mut() {
7221 let c = &mut root.modal;
7222 match prop {
7223 ModalProp::Animation(v) => c.animation = v,
7224 ModalProp::Presentation(v) => c.presentation = v,
7225 ModalProp::StatusBarTranslucent(v) => c.status_bar_translucent = v,
7226 ModalProp::Orientations(v) => c.orientations = v,
7227 ModalProp::CloseOnEscape(v) => c.close_on_escape = v,
7228 ModalProp::CloseOnBackdropPress(v) => c.close_on_backdrop_press = v,
7229 ModalProp::CloseOnSwipe(v) => c.close_on_swipe = v,
7230 ModalProp::Detents(v) => c.detents = v,
7231 ModalProp::Detent(v) => c.detent = v,
7232 ModalProp::DefaultDetent(v) => c.default_detent = v,
7233 ModalProp::Grabber(v) => c.grabber = v,
7234 ModalProp::LargestUndimmedDetent(v) => c.largest_undimmed_detent = v,
7235 }
7236 flags |= dirty::MODAL;
7237 }
7238 }
7239 Prop::Overlay(prop) => {
7240 use crate::OverlayProp;
7241 let parent = node.parent;
7244 if matches!(prop, OverlayProp::Hint(_))
7245 && parent != NO_KEY
7246 && self.nodes[parent as usize]
7247 .positional
7248 .has(Positional::CHILDREN)
7249 {
7250 self.queue_positions(parent);
7251 }
7252 self.set_overlay_config(key, |c| match prop {
7253 OverlayProp::Anchor(v) => c.anchor = v,
7254 OverlayProp::Placement(v) => c.placement = v,
7255 OverlayProp::Align(v) => c.align = v,
7256 OverlayProp::Offset(v) => c.offset = v,
7257 OverlayProp::Margin(v) => c.margin = v,
7258 OverlayProp::Hint(v) => c.hint = v,
7259 OverlayProp::Open(v) => c.open = v,
7260 OverlayProp::Cover(v) => c.cover = v,
7261 });
7262 if matches!(prop, OverlayProp::Margin(_))
7263 && let Some(state) = self.overlay_mut(key)
7264 && !state.margin_set
7265 {
7266 state.margin_set = true;
7267 state.placed = None;
7268 self.needs_layout = true;
7269 }
7270 return Ok(());
7271 }
7272 Prop::Tooltip(content) => {
7273 self.set_tooltip(key, content);
7274 return Ok(());
7275 }
7276 Prop::HeaderSlot(slot) => {
7277 if let Some(root) = node.root.as_mut()
7278 && root.slot != slot
7279 {
7280 root.slot = slot;
7281 let parent = node.parent;
7282 if parent != NO_KEY {
7283 self.mark(parent, dirty::SCREEN);
7284 }
7285 }
7286 }
7287 Prop::Native(NativeProp::Scrollable(on)) if node.scroll.is_some() => {
7289 if let Some(scroll) = node.scroll.as_mut() {
7290 scroll.behavior.enabled = on;
7291 flags |= dirty::SCROLL_BEHAVIOR;
7292 }
7293 }
7294 Prop::Component(name) => {
7295 let created = node.created;
7296 if let Some(component) = node.component.as_mut() {
7297 match &component.name {
7298 None if created => {
7303 component.name = Some(name.clone());
7304 component.changed =
7305 component.props.iter().map(|(k, _)| k.clone()).collect();
7306 self.mount.push(MountItem::Component { id, name });
7307 flags |= dirty::COMPONENT;
7308 if !component.slots.is_empty() {
7309 component.slots_changed.set(true);
7310 flags |= dirty::ANIMATION;
7311 }
7312 }
7313 None => component.name = Some(name),
7314 Some(old) if *old != name => log::warn!(
7315 target: "js",
7316 "a native component cannot change from `{old}` to `{name}`; render a new element"
7317 ),
7318 Some(_) => {}
7319 }
7320 }
7321 }
7322 Prop::ComponentPropBinding(name, value) => {
7323 if let Some(component) = node.component.as_mut() {
7324 let slot = match component.slots.iter().position(|k| *k == name) {
7325 Some(s) => Some(s as u16),
7326 None if value.is_none() => None,
7327 None => {
7328 component.slots.push(name.clone());
7329 component.slots_changed.set(true);
7330 Some((component.slots.len() - 1) as u16)
7331 }
7332 };
7333 if let Some(slot) = slot {
7334 let at = component.bound.iter().position(|(s, _)| *s == slot);
7335 match (at, value) {
7336 (Some(i), Some(n)) => component.bound[i].1 = n,
7337 (None, Some(n)) => component.bound.push((slot, n)),
7338 (Some(i), None) => {
7339 component.bound.remove(i);
7340 if !component.changed.contains(&name) {
7342 component.changed.push(name);
7343 }
7344 flags |= dirty::COMPONENT;
7345 }
7346 (None, None) => {}
7347 }
7348 flags |= dirty::ANIMATION;
7349 }
7350 }
7351 }
7352 Prop::ComponentProp(name, value) => {
7353 if let Some(component) = node.component.as_mut() {
7354 let at = component.props.iter().position(|(k, _)| *k == name);
7355 match (at, value) {
7356 (Some(i), Some(v)) => component.props[i].1 = v,
7357 (None, Some(v)) => component.props.push((name.clone(), v)),
7358 (Some(i), None) => {
7359 component.props.swap_remove(i);
7360 }
7361 (None, None) => {}
7362 }
7363 if !component.changed.contains(&name) {
7364 component.changed.push(name);
7365 }
7366 flags |= dirty::COMPONENT;
7367 }
7368 }
7369 Prop::Native(prop) => {
7370 if let NativeProp::Disabled(d) = prop {
7371 self.set_disabled(key, d);
7373 }
7374 let node = &mut self.nodes[key as usize];
7375 if node.created
7378 && let Some(NativeProps::WebView(p)) = node.control.as_deref()
7379 {
7380 let changed = match &prop {
7381 NativeProp::Incognito(on) => Some(("`incognito` is", *on != p.incognito)),
7382 NativeProp::Zoomable(on) => Some(("`zoomable` is", *on != p.zoomable)),
7383 NativeProp::UrlSchemes(schemes) => Some((
7386 "URL schemes are",
7387 !schemes
7388 .iter()
7389 .map(|s| s.scheme())
7390 .eq(p.url_schemes.iter().map(|s| s.scheme())),
7391 )),
7392 _ => None,
7393 };
7394 if let Some((what, changed)) = changed {
7395 if changed {
7396 log::warn!(
7397 target: "js",
7398 "a web view's {what} read when it is made; render a new element to change it"
7399 );
7400 }
7401 return Ok(());
7402 }
7403 }
7404 if let Some(control) = node.control.as_mut() {
7405 apply_native(control, prop);
7406 flags |= dirty::NATIVE;
7407 }
7408 }
7409 Prop::Value(value) => {
7410 if let Some(input) = node.input.as_mut() {
7411 input.value_set = true;
7412 if input.value != value {
7413 input.value = value;
7414 flags |= dirty::INPUT_VALUE;
7415 self.measure_input(key);
7416 }
7417 }
7418 }
7419 Prop::DefaultValue(value) => {
7420 if let Some(input) = node.input.as_mut()
7421 && !input.value_set
7422 {
7423 input.value_set = true;
7424 input.value = value;
7425 flags |= dirty::INPUT_VALUE;
7426 self.measure_input(key);
7427 }
7428 }
7429 prop => {
7430 let Some(input) = node.input.as_mut() else {
7431 return Ok(());
7432 };
7433 let c = &mut input.config;
7434 let remeasure = match prop {
7435 Prop::Placeholder(text) => {
7436 c.placeholder = text;
7437 true
7438 }
7439 Prop::Multiline(multiline) => {
7440 c.multiline = multiline;
7441 self.scrollbars_pending.push(key);
7443 true
7444 }
7445 Prop::PlaceholderColor(color) => {
7446 c.placeholder_color = color;
7447 false
7448 }
7449 Prop::Secure(secure) => {
7450 c.secure = secure;
7451 false
7452 }
7453 Prop::KeyboardType(keyboard) => {
7454 c.keyboard = keyboard;
7455 false
7456 }
7457 Prop::KeyboardAppearance(appearance) => {
7458 c.keyboard_appearance = appearance;
7459 false
7460 }
7461 Prop::ReturnKeyType(key) => {
7462 c.return_key = key;
7463 false
7464 }
7465 Prop::AutoCapitalize(mode) => {
7466 c.auto_capitalize = mode;
7467 false
7468 }
7469 Prop::AutoCorrect(on) => {
7470 c.auto_correct = on;
7471 false
7472 }
7473 Prop::MaxLength(len) => {
7474 c.max_length = len;
7475 false
7476 }
7477 Prop::Readonly(on) => {
7478 c.editable = !on;
7479 false
7480 }
7481 Prop::SubmitBehavior(behavior) => {
7482 c.submit_behavior = behavior;
7483 false
7484 }
7485 Prop::PasteBehavior(behavior) => {
7486 c.paste_behavior = behavior;
7487 false
7488 }
7489 Prop::PasteMaxSize(max) => {
7490 c.paste_max_size = max;
7491 false
7492 }
7493 Prop::AutoFocus(on) => {
7494 c.auto_focus = on;
7495 false
7496 }
7497 Prop::SelectTextOnFocus(on) => {
7498 c.select_text_on_focus = on;
7499 false
7500 }
7501 Prop::Caret(on) => {
7502 c.caret_hidden = !on;
7503 false
7504 }
7505 Prop::InputAccessoryViewId(name) => {
7506 c.accessory_id = name;
7507 false
7508 }
7509 Prop::SelectionColor(color) => {
7510 c.selection_color = color;
7511 false
7512 }
7513 Prop::CaretColor(color) => {
7514 c.caret_color = color;
7515 false
7516 }
7517 Prop::AutoFill(fill) => {
7518 c.auto_fill = fill;
7519 false
7520 }
7521 Prop::Selection(start, end) => {
7522 let id = node.id;
7524 self.commands
7525 .push((id, Command::SetSelection { start, end }));
7526 return Ok(());
7527 }
7528 _ => return Ok(()),
7529 };
7530 flags |= dirty::INPUT;
7531 if remeasure {
7532 self.measure_input(key);
7533 }
7534 }
7535 }
7536 if flags != 0 {
7537 self.mark(key, flags);
7538 }
7539 if slop_moved {
7540 self.slop_moved.push(key);
7541 }
7542 if rebuild_span {
7543 self.mark_text_block(key);
7544 }
7545 if copy_text_changed {
7546 if self.nodes[key as usize].inline {
7547 self.mark_text_block(key);
7548 } else if let Some(place) = self.placed_in_text(key) {
7549 self.mark_text_block(place);
7550 }
7551 }
7552 if key_ancestry {
7553 self.key_ancestry_dirty = true;
7554 }
7555 Ok(())
7556 }
7557
7558 fn fold_run(
7561 &mut self,
7562 parent: Key,
7563 parent_id: NodeId,
7564 child_id: NodeId,
7565 before: Option<NodeId>,
7566 ) -> bool {
7567 let node = &self.nodes[parent as usize];
7568 if before.is_some()
7569 || node.kind != Kind::Text
7570 || !node.children.is_empty()
7571 || self.folded.contains_key(&parent)
7572 || self.components.slot_hosts.contains_key(&parent_id)
7573 {
7574 return false;
7575 }
7576 let Some(run) = self.runs.get_mut(&child_id) else {
7577 return false;
7578 };
7579 let from = std::mem::replace(&mut run.block, parent);
7581 if from != NO_KEY {
7582 self.folded.remove(&from);
7583 self.mark_text_block(from);
7584 }
7585 self.folded.insert(parent, child_id);
7586 self.mark_text_block(parent);
7587 true
7588 }
7589
7590 fn unfold_run(&mut self, id: NodeId) {
7592 let Some(run) = self.runs.get_mut(&id) else {
7593 return;
7594 };
7595 let block = std::mem::replace(&mut run.block, NO_KEY);
7596 if block != NO_KEY {
7597 self.folded.remove(&block);
7598 self.mark_text_block(block);
7599 }
7600 }
7601
7602 pub(super) fn materialize_run(&mut self, id: NodeId) -> Result<(), ApplyError> {
7607 let Some(run) = self.runs.remove(&id) else {
7608 return Ok(());
7609 };
7610 let key = match self.alloc(id, Kind::RawText) {
7611 Ok(key) => key,
7612 Err(e) => {
7613 self.runs.insert(id, run);
7614 return Err(e);
7615 }
7616 };
7617 self.nodes[key as usize].text = run.text;
7618 if run.block != NO_KEY {
7619 self.folded.remove(&run.block);
7620 let parent = self.nodes[run.block as usize].id;
7621 let _ = self.insert(parent, id, None);
7622 }
7623 Ok(())
7624 }
7625
7626 fn folded_text(&self, key: Key) -> Option<&str> {
7628 if self.folded.is_empty() {
7629 return None;
7630 }
7631 let id = self.folded.get(&key)?;
7632 self.runs.get(id).map(|r| r.text.as_str())
7633 }
7634
7635 fn insert(
7636 &mut self,
7637 parent_id: NodeId,
7638 child_id: NodeId,
7639 before: Option<NodeId>,
7640 ) -> Result<(), ApplyError> {
7641 let parent = self.key(parent_id)?;
7642 if !self.runs.is_empty() || !self.folded.is_empty() {
7643 if self.fold_run(parent, parent_id, child_id, before) {
7644 return Ok(());
7645 }
7646 self.materialize_run(child_id)?;
7647 if let Some(b) = before {
7648 self.materialize_run(b)?;
7649 }
7650 if let Some(&run) = self.folded.get(&parent) {
7651 self.materialize_run(run)?;
7652 }
7653 }
7654 let child = self.key(child_id)?;
7655 let from = self.nodes[child as usize].parent;
7656 if from != NO_KEY {
7657 self.input_bar_moves(child);
7658 self.note_move(from, parent);
7659 }
7660 let mut before = before.map(|b| self.key(b)).transpose()?;
7661 if before.is_none()
7663 && let Some((bar, _)) = self.nodes[parent as usize]
7664 .scroll
7665 .as_ref()
7666 .and_then(|s| s.bar.as_ref())
7667 && let Ok(bar) = self.key(*bar)
7668 && bar != child
7669 {
7670 before = Some(bar);
7671 }
7672 let Some(depth) = self
7673 .depth_outside(child, parent)
7674 .filter(|_| child != self.root)
7675 else {
7676 return Err(ApplyError::Cycle(child_id));
7677 };
7678 let max = MAX_TREE_DEPTH as u32;
7679 if depth + self.nodes[child as usize].height > max {
7680 if depth + self.count_heights(child) > max {
7682 return Err(ApplyError::TooDeep(MAX_TREE_DEPTH));
7683 }
7684 }
7685 if self.nodes[parent as usize]
7686 .shader
7687 .as_ref()
7688 .is_some_and(|s| {
7689 matches!(
7690 s.role,
7691 crate::shader::ShaderRole::Screen | crate::shader::ShaderRole::ScreenTransition
7692 )
7693 })
7694 {
7695 log::warn!(
7698 target: "js",
7699 "node {child_id} in screen effect {parent_id}: a screen effect or transition has no children"
7700 );
7701 }
7702 if let Some(b) = before
7703 && (b == child || self.nodes[b as usize].parent != parent)
7704 {
7705 return Err(ApplyError::BadAnchor(self.nodes[b as usize].id));
7706 }
7707
7708 let parent_created = self.nodes[parent as usize].created;
7712 if self.nodes[child as usize].parent != NO_KEY {
7713 self.unlink(child, !parent_created);
7714 }
7715
7716 let p = &self.nodes[parent as usize];
7717 let inline = p.kind == Kind::Text && !self.nodes[child as usize].fixed_view;
7720 let pos = match before {
7721 Some(b) => {
7722 let (pos, looked) = position_from_ends(&p.children, &b).expect("anchor is a child");
7723 self.placing(looked);
7724 pos
7725 }
7726 None => p.children.len(),
7727 };
7728 self.set_inline(child, inline);
7729 if !inline {
7730 self.set_hidden_in_text(child, false);
7733 }
7734 self.nodes[child as usize].parent = parent;
7735 if self.nodes[child as usize].kind == Kind::Overlay {
7736 self.key_ancestry_dirty = true;
7738 }
7739 self.nodes[parent as usize].children.insert(pos, child);
7740 self.dirty_overlays();
7741 self.raise_heights(child);
7742 self.key_content_changed(parent);
7743 self.rank_noted(child);
7744 self.tree_order_changed |= self.track_tree_order;
7745 self.tab_places_stale = true;
7746 if self.nodes[child as usize].states & crate::tailwind::state::FOCUS_WITHIN != 0 {
7747 self.focus_moved = true;
7749 }
7750 self.ch_changed(child);
7751 self.status_bars_moved |= !self.status_bar_nodes.is_empty();
7752 self.outer_moved |= !self.parent_lists.is_empty() && self.may_hold_page_list(child);
7753 self.sticky_changed |= !self.sticky_nodes.is_empty();
7754 self.update_direction(child);
7755 if self.nodes[parent as usize].child_perspective.is_some() {
7756 self.mark(child, dirty::VIEW | dirty::ANIMATION);
7757 }
7758 let node = &self.nodes[parent as usize];
7759 let color = node.text_style.color.or(node.inherited_color);
7760 if self.nodes[child as usize].inherited_color != color {
7761 self.inherit_color_from(child, color);
7762 }
7763 self.groups_changed(child, parent);
7764 let child_node = &self.nodes[child as usize];
7765 if child_node
7766 .classes
7767 .as_ref()
7768 .is_some_and(|c| c.deps() & crate::tailwind::deps::POSITION != 0)
7769 || (child_node.positional.has(Positional::PASS)
7771 && child_node.positional.has(Positional::CHILDREN))
7772 {
7773 self.reads_positions(parent);
7774 }
7775 if self.nodes[parent as usize]
7776 .positional
7777 .has(Positional::CHILDREN)
7778 {
7779 self.queue_positions(parent);
7780 }
7781 self.spacing_changed(parent, child);
7782 if self.pointer_none_classes > 0 {
7783 self.pointer_events_moved(parent);
7784 }
7785
7786 if inline {
7787 if self.nodes[child as usize].placeholder {
7788 self.ask_row(child);
7789 }
7790 self.mark_text_block(parent);
7791 return Ok(());
7792 }
7793 if self.nodes[parent as usize].list.is_some() {
7796 if let Some(slot) = self.nodes[child as usize].slot {
7797 self.nodes[parent as usize]
7798 .list
7799 .as_mut()
7800 .expect("list")
7801 .add_slot_cell(slot, child);
7802 }
7803 self.sync_layout_style(child);
7804 }
7805 let child_kind = self.nodes[child as usize].kind;
7806 if child_kind == Kind::InputAccessory {
7807 self.accessory_attached(child, true);
7808 }
7809 if child_kind == Kind::HeaderItem {
7810 self.mark(parent, dirty::SCREEN);
7811 }
7812 if let Some(child_layout) = self.nodes[child as usize].layout {
7813 if self.nodes[parent as usize].list.is_none()
7816 && !self.nodes[child as usize].is_layout_root()
7817 {
7818 let index = self.layout_index_at(parent, pos);
7819 let parent_layout = self.nodes[parent as usize]
7820 .layout
7821 .expect("block parent has layout");
7822 self.layout
7823 .insert_child_at_index(parent_layout, index as usize, child_layout);
7824 }
7825 self.needs_layout = true;
7826 let parent_created = parent_created
7829 || (child_kind == Kind::Modal
7830 && self.nodes[parent as usize].culled
7831 && self.uncull(parent));
7832 if parent_created
7835 && !self.nodes[child as usize].is_overlay()
7836 && !{
7837 let scope = self.cull_scope(parent);
7838 self.hold_back(scope, child)
7839 }
7840 {
7841 self.ensure_created(child);
7842 let before = match self.nodes[parent as usize].list.as_ref() {
7843 Some(list) if list.parent && !list.sent_sticky.is_empty() => {
7846 self.below_sticky(parent, child)
7847 }
7848 _ => self.native_before_at(parent, child, pos),
7849 };
7850 self.mount.push(MountItem::Insert {
7852 parent: self.nodes[parent as usize].id,
7853 child: self.nodes[child as usize].id,
7854 before,
7855 });
7856 }
7857 }
7858 Ok(())
7859 }
7860
7861 fn detach(&mut self, key: Key) {
7863 self.input_bar_moves(key);
7864 self.unlink(key, true);
7865 }
7866
7867 fn input_bar_moves(&mut self, key: Key) {
7870 let node = &self.nodes[key as usize];
7871 if node.input.as_ref().is_some_and(|i| i.bar.is_some()) {
7872 self.release_scrollbar(key);
7873 self.scrollbars_pending.push(key);
7874 }
7875 }
7876
7877 fn unlink(&mut self, key: Key, emit_remove: bool) {
7880 if self.nodes[key as usize].kind == Kind::Modal && self.nodes[key as usize].created {
7881 self.restoring_modal_focus = true;
7882 }
7883 let parent = self.nodes[key as usize].parent;
7884 let siblings = &mut self.nodes[parent as usize].children;
7885 let pos = siblings
7886 .iter()
7887 .position(|&c| c == key)
7888 .expect("child of parent");
7889 siblings.remove(pos);
7890 self.key_content_changed(parent);
7891 self.tree_order_changed |= self.track_tree_order;
7892 self.tab_places_stale = true;
7893 if let Some(list) = self.nodes[parent as usize].list.as_mut() {
7894 list.remove_cell(key);
7895 }
7896 if self.nodes[parent as usize]
7897 .positional
7898 .has(Positional::CHILDREN)
7899 {
7900 self.queue_positions(parent);
7901 }
7902 self.nodes[key as usize].parent = NO_KEY;
7903 self.dirty_overlays();
7904 if self.nodes[key as usize].states & crate::tailwind::state::FOCUS_WITHIN != 0 {
7905 self.focus_moved = true;
7907 }
7908 if self.nodes[parent as usize].child_perspective.is_some() {
7909 self.mark(key, dirty::VIEW | dirty::ANIMATION);
7911 }
7912 self.spacing_changed(parent, NO_KEY);
7913 if self.pointer_none_classes > 0 && self.pointer_region(parent).is_some() {
7914 self.pointer_pending.push(key);
7916 self.pointer_events_moved(parent);
7917 }
7918 self.groups_changed(key, parent);
7919 self.status_bars_moved |= !self.status_bar_nodes.is_empty();
7920 self.outer_moved |= !self.parent_lists.is_empty() && self.may_hold_page_list(key);
7921 self.sticky_changed |= !self.sticky_nodes.is_empty();
7922 if !self.pictured.is_empty() {
7923 self.unlinked_from.push(self.nodes[parent as usize].id);
7924 }
7925 let node = &self.nodes[key as usize];
7926 let (inline, layout, created, id) = (node.inline, node.layout, node.created, node.id);
7927 self.resize_settling |= node.row_asked;
7930 if inline {
7931 self.mark_text_block(parent);
7932 return;
7933 }
7934 let kind = self.nodes[key as usize].kind;
7935 if kind == Kind::InputAccessory {
7936 self.accessory_attached(key, false);
7937 }
7938 if kind == Kind::HeaderItem {
7939 self.mark(parent, dirty::SCREEN);
7940 }
7941 if let Some(layout) = layout {
7942 if self.nodes[parent as usize].list.is_none()
7943 && !self.nodes[key as usize].is_layout_root()
7944 {
7945 let parent_layout = self.nodes[parent as usize]
7946 .layout
7947 .expect("block parent has layout");
7948 self.layout.remove_child(parent_layout, layout);
7949 }
7950 self.needs_layout = true;
7951 if emit_remove
7952 && created
7953 && self.nodes[parent as usize].created
7954 && !self.nodes[key as usize].is_overlay()
7955 {
7956 self.mount.push(MountItem::Remove { id });
7957 self.note_restructured(parent);
7958 }
7959 }
7960 }
7961
7962 fn set_status_bar(&mut self, key: Key, setting: Option<crate::StatusBarSetting>) {
7966 let Some(root) = self.nodes[key as usize].root.as_mut() else {
7967 return;
7968 };
7969 root.status_bar = setting;
7970 let entry = root.status_bar_entry;
7971 match (setting, entry) {
7972 (Some(s), Some(e)) => self.components.status_bars.set(e, s),
7973 (Some(_), None) => {
7974 if !self.status_bar_nodes.contains(&key) {
7975 self.status_bar_nodes.push(key);
7976 }
7977 self.status_bars_moved = true;
7978 }
7979 (None, entry) => {
7980 if let Some(e) = entry {
7981 self.components.status_bars.remove(e);
7982 if let Some(root) = self.nodes[key as usize].root.as_mut() {
7983 root.status_bar_entry = None;
7984 }
7985 }
7986 self.status_bar_nodes.retain(|&k| k != key);
7987 }
7988 }
7989 }
7990
7991 fn sync_status_bars(&mut self) {
7995 if !std::mem::take(&mut self.status_bars_moved) {
7996 return;
7997 }
7998 for i in 0..self.status_bar_nodes.len() {
7999 let key = self.status_bar_nodes[i];
8000 let in_tree = self.is_ancestor(self.root, key);
8001 let Some(root) = self.nodes[key as usize].root.as_mut() else {
8002 continue;
8003 };
8004 match (in_tree, root.status_bar_entry, root.status_bar) {
8005 (true, None, Some(setting)) => {
8006 root.status_bar_entry = Some(self.components.status_bars.add(setting));
8007 }
8008 (false, Some(entry), _) => {
8009 root.status_bar_entry = None;
8010 self.components.status_bars.remove(entry);
8011 }
8012 _ => {}
8013 }
8014 }
8015 }
8016
8017 fn release(&mut self, id: NodeId) -> Result<(), ApplyError> {
8018 if let Some(run) = self.runs.remove(&id) {
8019 if run.block != NO_KEY {
8020 self.folded.remove(&run.block);
8021 self.mark_text_block(run.block);
8022 }
8023 return Ok(());
8024 }
8025 let key = self.key(id)?;
8026 if let Some(run) = self.folded.remove(&key)
8028 && let Some(run) = self.runs.get_mut(&run)
8029 {
8030 run.block = NO_KEY;
8031 }
8032 self.cancel_web_evaluations(id);
8033 self.webview_released(id);
8034 if key == self.root {
8035 return Ok(());
8036 }
8037 if !self.overlay_state.tooltips.is_empty() {
8039 self.tooltip_released(id);
8040 }
8041 if self.nodes[key as usize].bar().is_some() {
8043 self.release_scrollbar(key);
8044 }
8045 if self.nodes[key as usize].parent != NO_KEY {
8046 self.unlink(key, false);
8048 }
8049 if self.nodes[key as usize]
8052 .list
8053 .as_ref()
8054 .is_some_and(|l| l.parent)
8055 {
8056 self.forget_outer(key);
8057 self.parent_lists.retain(|&k| k != key);
8058 }
8059 if self.nodes[key as usize].is_overlay() {
8060 self.dirty_overlays();
8061 }
8062 self.dirty_overlay_listeners();
8063 let node = self.nodes.remove(key as usize);
8064 self.ch_readers -= usize::from(node.reads_ch);
8065 self.slots.remove(id as usize);
8066 if node.class_props.as_ref().and_then(|c| c.pointer_events)
8067 == Some(crate::props::PointerEvents::None)
8068 {
8069 self.pointer_none_classes -= 1;
8070 }
8071 if node.kind == Kind::List {
8072 self.lists.retain(|&k| k != key);
8073 }
8074 if node.sticky.is_some() {
8075 self.sticky_nodes.retain(|&k| k != key);
8076 self.sticky_changed = true;
8077 }
8078 if node.follow.is_some() {
8079 self.release_follower(key);
8080 }
8081 if !self.relators.is_empty() {
8082 self.release_relator(key);
8083 }
8084 if let Some(scroll) = node.scroll.as_ref() {
8085 if !scroll.dependents.is_empty() {
8086 self.outer_released(&scroll.dependents);
8087 }
8088 if scroll.asked.is_some() {
8089 self.outer_asked.retain(|&k| k != key);
8090 }
8091 self.sticky_views.retain(|&k| k != key);
8092 self.sticky_scrollers.retain(|&k| k != key);
8093 }
8094 if let Some((spacer, _)) = node.list.as_ref().and_then(|l| l.spacer) {
8095 self.layout.remove(spacer);
8096 }
8097 if node.kind == Kind::Text {
8098 self.attachment_blocks.retain(|&k| k != key);
8099 }
8100 if node.is_layout_root() {
8101 self.roots.retain(|&k| k != key);
8102 }
8103 if let Some(state) = node.root.as_ref().and_then(|r| r.overlay.as_ref()) {
8104 self.overlay_released(key, state.wrapper, state.host.is_some());
8105 }
8106 if let Some(root) = node.root.as_ref()
8107 && root.status_bar.is_some()
8108 {
8109 if let Some(entry) = root.status_bar_entry {
8110 self.components.status_bars.remove(entry);
8111 }
8112 self.status_bar_nodes.retain(|&k| k != key);
8113 }
8114 self.orientation_pages.retain(|&(k, _)| k != key);
8115 for &c in &node.children {
8118 if let Some(child) = self.nodes.get_mut(c as usize) {
8119 child.parent = NO_KEY;
8120 }
8121 }
8122 if node.states & crate::tailwind::state::FOCUS_WITHIN != 0 {
8123 self.focus_moved = true;
8126 }
8127 if let Some(layout) = node.layout {
8128 self.layout.remove(layout);
8129 }
8130 if node.created {
8131 self.mount.push(MountItem::Delete { id });
8132 }
8133 Ok(())
8134 }
8135
8136 fn set_page_orientations(&mut self, key: Key, bits: u8) {
8139 match self.orientation_pages.iter_mut().find(|(k, _)| *k == key) {
8140 Some(page) if bits != 0 => page.1 = bits,
8141 Some(_) => self.orientation_pages.retain(|&(k, _)| k != key),
8142 None if bits != 0 => self.orientation_pages.push((key, bits)),
8143 None => {}
8144 }
8145 }
8146
8147 fn sync_orientations(&mut self) {
8153 if self.orientation_pages.is_empty() && self.orientations_shown == 0 {
8154 return;
8155 }
8156 let bits = self
8157 .orientation_pages
8158 .iter()
8159 .rev()
8160 .find(|&&(key, _)| self.displayed_in_tree(key))
8161 .map_or(0, |&(_, bits)| bits);
8162 if bits != self.orientations_shown {
8163 self.orientations_shown = bits;
8164 self.commands
8165 .push((crate::ROOT_ID, Command::Orientations(bits)));
8166 }
8167 }
8168
8169 fn displayed_in_tree(&self, mut key: Key) -> bool {
8172 while key != NO_KEY {
8173 if key == self.root {
8174 return true;
8175 }
8176 let node = &self.nodes[key as usize];
8177 if node.layout.is_some_and(|l| self.layout.displays_none(l)) {
8178 return false;
8179 }
8180 key = node.parent;
8181 }
8182 false
8183 }
8184
8185 fn depth_outside(&self, ancestor: Key, mut key: Key) -> Option<u32> {
8188 let mut depth = 0;
8189 while key != NO_KEY {
8190 if key == ancestor {
8191 return None;
8192 }
8193 depth += 1;
8194 key = self.nodes[key as usize].parent;
8195 }
8196 Some(depth)
8197 }
8198
8199 fn count_heights(&mut self, key: Key) -> u32 {
8206 let mut order = vec![key];
8209 let mut next = 0;
8210 while let Some(&at) = order.get(next) {
8211 next += 1;
8212 order.extend_from_slice(&self.nodes[at as usize].children);
8213 }
8214 for &at in order.iter().rev() {
8215 let height = self.nodes[at as usize]
8216 .children
8217 .iter()
8218 .map(|&c| self.nodes[c as usize].height + 1)
8219 .max()
8220 .unwrap_or(0);
8221 self.nodes[at as usize].height = height;
8222 }
8223 self.nodes[key as usize].height
8224 }
8225
8226 fn keymap_with_focus(
8230 &mut self,
8231 keymap: Arc<crate::keymap::Keymap>,
8232 ) -> Arc<crate::keymap::Keymap> {
8233 if !keymap.takes_over_pointer_focus() {
8234 self.pointer_keymap = None;
8235 return keymap;
8236 }
8237 let pointer = self.focus.is_some() && self.focus_by_pointer;
8238 let mounted = Arc::new((*keymap).clone().with_pointer_focus(pointer));
8239 self.pointer_keymap = Some((keymap, pointer));
8240 mounted
8241 }
8242
8243 fn sync_pointer_keymap(&mut self) {
8247 let pointer = self.focus.is_some() && self.focus_by_pointer;
8248 let Some((keymap, sent)) = &self.pointer_keymap else {
8249 return;
8250 };
8251 if *sent == pointer {
8252 return;
8253 }
8254 let keymap = keymap.clone();
8255 let mounted = self.keymap_with_focus(keymap);
8256 self.mount.push(MountItem::Keymap(mounted));
8257 }
8258
8259 fn raise_heights(&mut self, key: Key) {
8263 let mut height = self.nodes[key as usize].height + 1;
8264 let mut at = self.nodes[key as usize].parent;
8265 while at != NO_KEY {
8266 let node = &mut self.nodes[at as usize];
8267 if node.height >= height {
8268 break;
8269 }
8270 node.height = height;
8271 height += 1;
8272 at = node.parent;
8273 }
8274 }
8275
8276 pub(super) fn note_focus_origin(&mut self, to: NodeId) {
8283 let mut origins = std::mem::take(&mut self.focus_origins);
8284 origins.retain(|&(id, _)| id != to && self.key(id).is_ok());
8287 if self.modality == Some(crate::platform::InputModality::Pointer) {
8288 origins.push((to, self.focus));
8289 }
8290 self.focus_origins = origins;
8291 }
8292
8293 fn press_leaves_focus(&self) -> bool {
8298 matches!(
8299 self.components.environment.os,
8300 crate::platform::Os::MacOs | crate::platform::Os::Ios
8301 )
8302 }
8303
8304 fn focus_back_to_origin(&mut self, before: Option<(Key, NodeId)>, from: Option<Key>) {
8310 let outside = |this: &Self, key: Key| from.is_none_or(|from| !this.is_ancestor(from, key));
8311 let alive = |this: &Self, (key, id): (Key, NodeId)| {
8312 this.key(id).is_ok_and(|k| k == key) && this.is_ancestor(this.root, key)
8313 };
8314 if let Some((_, id)) = before.filter(|&b| alive(self, b) && outside(self, b.0)) {
8315 self.commands.push((id, Command::Focus));
8316 } else if let Some((_, id)) = self.focus.filter(|&(key, _)| !outside(self, key)) {
8317 self.commands.push((id, Command::Blur));
8318 }
8319 }
8320
8321 fn focus_opened_modals(&mut self) {
8327 let opened = std::mem::take(&mut self.modals_opened);
8328 if !self.has_window() {
8329 return;
8330 }
8331 for (modal, id) in opened {
8332 let Some(node) = self.nodes.get(modal as usize).filter(|n| n.id == id) else {
8334 continue;
8335 };
8336 if node.kind != Kind::Modal
8337 || !node.created
8338 || node.parent == NO_KEY
8339 || !self.displayed_in_tree(modal)
8340 || self.window_ids.values().any(|(root, _)| *root == node.id)
8342 {
8343 continue;
8344 }
8345 if self
8346 .focus
8347 .is_some_and(|(key, _)| self.is_ancestor(modal, key))
8348 {
8349 continue;
8350 }
8351 let inside = |this: &Self, id: NodeId| {
8352 this.key(id).is_ok_and(|key| this.is_ancestor(modal, key))
8353 };
8354 let asked = self
8355 .commands
8356 .iter()
8357 .any(|(to, c)| matches!(c, Command::Focus) && inside(self, *to))
8358 || self.mount.iter().any(|m| {
8359 matches!(
8360 m,
8361 MountItem::Command {
8362 id: to,
8363 command: Command::Focus,
8364 } if inside(self, *to)
8365 )
8366 });
8367 if asked {
8368 continue;
8369 }
8370 if let Ok(Some(id)) = self.first_control(modal) {
8372 self.commands.push((id, Command::Focus));
8373 self.modal_focus_given = Some(id);
8374 }
8375 }
8376 }
8377
8378 fn first_control(&self, key: Key) -> Result<Option<NodeId>, ()> {
8383 let mut found = None;
8384 let mut stack: Vec<Key> = self.nodes[key as usize]
8385 .children
8386 .iter()
8387 .rev()
8388 .copied()
8389 .collect();
8390 while let Some(k) = stack.pop() {
8391 let node = &self.nodes[k as usize];
8392 if matches!(node.kind, Kind::Overlay | Kind::Modal)
8393 || node.layout.is_some_and(|l| self.layout.displays_none(l))
8394 {
8395 continue;
8396 }
8397 let disabled = node.states & crate::tailwind::state::DISABLED != 0;
8398 let focusable = node.props.as_ref().and_then(|p| p.focusable);
8399 if let Some(input) = node.input.as_ref() {
8400 if input.config.auto_focus {
8401 return Err(());
8402 }
8403 if found.is_none() && !disabled && focusable != Some(false) {
8404 found = Some(node.id);
8405 }
8406 } else if found.is_none()
8407 && !disabled
8408 && (focusable == Some(true)
8409 || (focusable.is_none() && node.mounted_events().contains(EventKind::Press)))
8410 {
8411 found = Some(node.id);
8412 }
8413 stack.extend(node.children.iter().rev().copied());
8414 }
8415 Ok(found)
8416 }
8417
8418 fn tab_neighbor(&self, key: Key, forward: bool, skip: Option<Key>) -> Option<NodeId> {
8426 let mut scope = key;
8427 while self.nodes[scope as usize].parent != NO_KEY
8428 && self.nodes[scope as usize].kind != Kind::Modal
8429 {
8430 scope = self.nodes[scope as usize].parent;
8431 }
8432 let mut stops = Vec::new();
8433 let mut at = None;
8434 let mut stack = vec![scope];
8435 while let Some(k) = stack.pop() {
8436 let node = &self.nodes[k as usize];
8437 let hidden = (k != scope && node.kind == Kind::Modal)
8438 || Some(k) == skip
8439 || (node.kind == Kind::Overlay && self.overlay(k).is_none_or(|s| s.host.is_none()))
8440 || node.layout.is_some_and(|l| self.layout.displays_none(l));
8441 if hidden {
8442 continue;
8443 }
8444 let disabled = node.states & crate::tailwind::state::DISABLED != 0;
8445 let focusable = node.props.as_ref().and_then(|p| p.focusable);
8446 let stop = !disabled
8447 && match node.input {
8448 Some(_) => focusable != Some(false),
8449 None => {
8450 focusable == Some(true)
8451 || (focusable.is_none()
8452 && node.mounted_events().contains(EventKind::Press))
8453 }
8454 };
8455 if k == key {
8456 at = Some(stops.len());
8457 stops.push(node.id);
8458 } else if stop {
8459 stops.push(node.id);
8460 }
8461 stack.extend(node.children.iter().rev().copied());
8462 }
8463 let at = at?;
8464 let n = stops.len();
8465 if n < 2 {
8466 return None;
8467 }
8468 let next = if forward {
8469 (at + 1) % n
8470 } else {
8471 (at + n - 1) % n
8472 };
8473 Some(stops[next])
8474 }
8475
8476 fn is_ancestor(&self, ancestor: Key, mut key: Key) -> bool {
8477 while key != NO_KEY {
8478 if key == ancestor {
8479 return true;
8480 }
8481 key = self.nodes[key as usize].parent;
8482 }
8483 false
8484 }
8485
8486 fn native_before(&self, parent: Key, child: Key) -> Option<NodeId> {
8489 let pos = self.nodes[parent as usize]
8490 .children
8491 .iter()
8492 .inspect(|_| self.placing(1))
8493 .position(|&c| c == child)?;
8494 self.native_before_at(parent, child, pos)
8495 }
8496
8497 fn native_before_at(&self, parent: Key, child: Key, pos: usize) -> Option<NodeId> {
8505 let children = &self.nodes[parent as usize].children;
8506 let z = self.nodes[child as usize].stack_rank();
8507 let in_parent = !self.nodes[child as usize].kind.is_root();
8508 let anchors = |n: &Node| {
8509 n.created && n.layout.is_some() && !n.is_overlay() && !(in_parent && n.kind.is_root())
8510 };
8511 if !self.nodes[parent as usize].ranked_children && z == (0, false) {
8512 let next = children[pos + 1..].iter().find_map(|&c| {
8513 self.placing(1);
8514 let n = &self.nodes[c as usize];
8515 anchors(n).then_some(n.id)
8516 });
8517 return match next {
8518 Some(id) => Some(id),
8519 None if !self.overlays.is_empty() => self.first_overlay_in(parent),
8520 None => None,
8521 };
8522 }
8523 self.placing(children.len());
8524 let mut best: Option<((i32, bool), usize, NodeId)> = None;
8525 for (i, &c) in children.iter().enumerate() {
8526 let n = &self.nodes[c as usize];
8527 if c == child || !anchors(n) {
8528 continue;
8529 }
8530 let rank = n.stack_rank();
8531 if (rank, i) > (z, pos) && best.is_none_or(|b| (rank, i) < (b.0, b.1)) {
8532 best = Some((rank, i, n.id));
8533 }
8534 }
8535 match best {
8537 Some(b) => Some(b.2),
8538 None if !self.overlays.is_empty() => self.first_overlay_in(parent),
8539 None => None,
8540 }
8541 }
8542
8543 fn rank_noted(&mut self, key: Key) {
8546 let node = &self.nodes[key as usize];
8547 let parent = node.parent;
8548 if parent != NO_KEY && node.stack_rank() != (0, false) {
8549 self.nodes[parent as usize].ranked_children = true;
8550 }
8551 }
8552
8553 fn restack(&mut self, key: Key) {
8555 self.rank_noted(key);
8556 let node = &self.nodes[key as usize];
8557 let (parent, id) = (node.parent, node.id);
8558 if parent == NO_KEY
8559 || !node.created
8560 || node.layout.is_none()
8561 || node.inline
8562 || node.is_overlay()
8563 {
8564 return;
8565 }
8566 let p = &self.nodes[parent as usize];
8567 if !p.created || p.list.is_some() {
8568 return;
8569 }
8570 let before = self.native_before(parent, key);
8571 self.mount.push(MountItem::Insert {
8572 parent: p.id,
8573 child: id,
8574 before,
8575 });
8576 }
8577
8578 fn font_settings_changed(&mut self, key: Key) {
8580 match self.nodes[key as usize].kind {
8581 Kind::Text => self.mark_text_block(key),
8582 Kind::Input => {
8583 self.measure_input(key);
8584 self.mark(key, dirty::INPUT);
8585 }
8586 _ => {}
8587 }
8588 }
8589
8590 fn layout_index_at(&self, parent: Key, pos: usize) -> u32 {
8598 let node = &self.nodes[parent as usize];
8599 let layout = node.layout.expect("block parent has layout");
8600 let next = node.children[pos + 1..]
8601 .iter()
8602 .inspect(|_| self.placing(1))
8603 .find_map(|&c| {
8604 let c = &self.nodes[c as usize];
8605 c.layout.filter(|_| !c.is_layout_root())
8606 });
8607 let index = match next {
8608 Some(next) => match position_near(self.layout.children(layout), &next, pos) {
8611 Some((index, looked)) => {
8612 self.placing(looked);
8613 index
8614 }
8615 None => {
8616 debug_assert!(false, "a sibling's layout node is its parent's child");
8617 self.render_index(parent, pos) as usize
8618 }
8619 },
8620 None => self.layout.children_len(layout),
8621 };
8622 debug_assert!(
8623 pos + 1 != node.children.len() || index as u32 == self.rendering_before(parent, pos),
8624 "the layout node's children are its rendering children"
8625 );
8626 index as u32
8627 }
8628
8629 fn render_index(&self, parent: Key, pos: usize) -> u32 {
8633 self.placing(pos);
8634 self.rendering_before(parent, pos)
8635 }
8636
8637 fn rendering_before(&self, parent: Key, pos: usize) -> u32 {
8639 self.nodes[parent as usize].children[..pos]
8640 .iter()
8641 .map(|&c| &self.nodes[c as usize])
8642 .filter(|c| c.layout.is_some() && !c.is_layout_root())
8643 .count() as u32
8644 }
8645
8646 fn set_inline(&mut self, key: Key, inline: bool) {
8648 let node = &mut self.nodes[key as usize];
8649 if node.inline == inline {
8650 return;
8651 }
8652 node.inline = inline;
8653 if node.kind == Kind::Text {
8654 if inline {
8655 if let Some(l) = node.layout.take() {
8658 if node.base_layout.is_none() {
8659 node.base_layout = Some(Box::new(self.layout.style(l).clone()));
8660 }
8661 self.layout.remove(l);
8662 }
8663 if node.created {
8664 node.created = false;
8665 self.mount.push(MountItem::Delete { id: node.id });
8666 }
8667 } else {
8668 let style = if node.fixed_view {
8671 node.base_layout.as_deref().cloned()
8672 } else {
8673 node.base_layout.take().map(|b| *b)
8674 }
8675 .unwrap_or_default();
8676 let cx = LeafContext::Text(Box::new(TextContext::new(Arc::default())));
8677 let layout = self.layout.new_leaf_with_context(style, cx);
8678 self.layout.set_tag(layout, key);
8679 node.layout = Some(layout);
8680 self.mark(key, dirty::TEXT_BUILD);
8681 }
8682 }
8683 self.dirty_overlay_listeners();
8687 }
8688
8689 fn ensure_created(&mut self, key: Key) {
8692 let has_attachments = self.attachment_blocks.contains(&key);
8693 let node = &mut self.nodes[key as usize];
8694 if node.created || node.layout.is_none() {
8695 return;
8696 }
8697 node.created = true;
8698 self.pace.made += 1;
8699 let culled_frame = std::mem::take(&mut node.culled)
8701 .then_some(node.frame)
8702 .filter(|f| !f.origin.x.0.is_nan());
8703 self.tree_order_changed |= self.track_tree_order;
8704 self.tab_places_stale = true;
8705 if node.kind == Kind::Modal {
8706 self.modals_opened.push((key, node.id));
8707 }
8708 if node.kind == Kind::Text {
8709 self.measure_for_real(key);
8710 }
8711 if culled_frame.is_some()
8716 && self.nodes[key as usize].follow.is_some()
8717 && let Some(layout) = self.nodes[key as usize].layout
8718 {
8719 self.layout.mark_dirty(layout);
8720 self.needs_layout = true;
8721 }
8722 let node = &mut self.nodes[key as usize];
8723 if let Some(scroll) = node.scroll.as_mut() {
8724 scroll.content = None;
8725 if !scroll.view_sticky.is_empty() {
8728 self.sticky_views.push(key);
8729 }
8730 scroll.issued = 0;
8732 scroll.target = None;
8733 scroll.pending.clear();
8734 }
8735 let parent_list = node.list.as_ref().is_some_and(|l| l.parent);
8738 let id = node.id;
8739 let kind = node.kind;
8740 let mut flags = self.mount_state(key);
8741 let node = &mut self.nodes[key as usize];
8742 if kind == Kind::Text && has_attachments {
8743 node.attached.clear();
8745 flags |= dirty::TEXT_BUILD;
8746 }
8747 self.mount.push(MountItem::Create {
8748 id,
8749 kind: if parent_list {
8750 ViewKind::View
8751 } else {
8752 kind.view_kind()
8753 },
8754 });
8755 if let Some(component) = self.nodes[key as usize].component.as_mut() {
8756 if let Some(name) = &component.name {
8759 self.mount.push(MountItem::Component {
8760 id,
8761 name: name.clone(),
8762 });
8763 }
8764 if let Some(source) = &component.source {
8767 self.mount.push(MountItem::GpuView {
8768 id,
8769 source: Some(source.clone()),
8770 });
8771 }
8772 }
8773 if let Some(item) = self.creation_tracking(key) {
8774 self.mount.push(item);
8775 }
8776 if let Some(frame) = culled_frame {
8777 self.nodes[key as usize].frame = frame;
8778 self.mount.push(MountItem::Frame { id, frame });
8779 let content = self.nodes[key as usize]
8782 .scroll
8783 .as_mut()
8784 .and_then(|s| s.culled_content.take());
8785 if let Some(size) = content {
8786 self.set_scroll_content(key, size);
8787 }
8788 if kind == Kind::Canvas
8789 && self.nodes[key as usize]
8790 .drawing
8791 .as_ref()
8792 .is_some_and(|d| d.fit().is_some())
8793 {
8794 self.fitted_pending.push(key);
8795 }
8796 if matches!(kind, Kind::Input | Kind::Scroll) {
8800 self.emit_frames(key);
8801 }
8802 }
8803 let projected = self.nodes[key as usize].projected;
8804 if self.mount_projected && projected != 0 {
8805 self.mount.push(MountItem::ProjectStates {
8806 id,
8807 states: projected,
8808 });
8809 }
8810 self.mark(key, flags);
8811 self.dirty_overlays();
8812 if !kind.is_container() {
8813 return;
8814 }
8815 let mut children = std::mem::take(&mut self.nodes[key as usize].children);
8817 let original = children.clone();
8818 if children
8819 .iter()
8820 .any(|&c| self.nodes[c as usize].stack_rank() != (0, false))
8821 {
8822 children.sort_by_key(|&c| self.nodes[c as usize].stack_rank());
8823 }
8824 let scope = self.cull_scope(key);
8826 for &child in &children {
8827 let c = &self.nodes[child as usize];
8828 if c.layout.is_some() && !c.is_overlay() && !self.hold_back(scope, child) {
8829 self.ensure_created(child);
8830 let child_id = self.nodes[child as usize].id;
8831 self.mount.push(MountItem::Insert {
8832 parent: id,
8833 child: child_id,
8834 before: None,
8835 });
8836 }
8837 }
8838 self.nodes[key as usize].children = original;
8839 }
8840
8841 fn mount_state(&mut self, key: Key) -> u32 {
8844 let node = &mut self.nodes[key as usize];
8845 let kind = node.kind;
8846 node.frame = Bounds::UNSET;
8847 node.emitted = None;
8848 if let Some(layout) = node.layout {
8849 self.layout.mark_stale(layout);
8850 }
8851 let node = &mut self.nodes[key as usize];
8852 let parent_list = node.list.as_ref().is_some_and(|l| l.parent);
8855 let mut flags = 0;
8856 if !node.view_style.is_default()
8857 || node.elevation != Points::ZERO
8858 || node.backdrop_material != crate::BackdropMaterial::default()
8859 || node.macos_backdrop.is_some()
8860 || node.windows_backdrop.is_some()
8861 || parent_list
8862 || node.spare
8863 || node.hidden_in_text
8864 {
8865 flags |= dirty::VIEW;
8866 }
8867 if !node.events.is_empty() {
8868 flags |= dirty::EVENTS;
8869 }
8870 if kind == Kind::Text {
8871 flags |= dirty::TEXT_MOUNT;
8872 }
8873 if node.image.as_ref().is_some_and(|i| i.source.is_some()) {
8874 flags |= dirty::IMAGE;
8875 }
8876 if let Some(scroll) = &node.scroll
8877 && !parent_list
8878 {
8879 flags |= dirty::SCROLL;
8880 if scroll.behavior != ScrollBehavior::default() {
8881 flags |= dirty::SCROLL_BEHAVIOR;
8882 }
8883 if scroll.refreshing {
8884 flags |= dirty::REFRESHING;
8885 }
8886 }
8887 if !node.animated.is_empty()
8888 || node.drawing.as_ref().is_some_and(|d| !d.slots.is_empty())
8889 || node.component.as_ref().is_some_and(|c| !c.slots.is_empty())
8890 || node
8891 .shader
8892 .as_ref()
8893 .and_then(|s| s.layer.as_ref())
8894 .is_some_and(|l| !l.nodes.is_empty())
8895 {
8896 flags |= dirty::ANIMATION;
8897 }
8898 if node.drawing.is_some() {
8899 flags |= dirty::CANVAS;
8900 }
8901 if node.shader.as_ref().is_some_and(|s| s.layer.is_some()) {
8902 flags |= dirty::SHADER;
8903 }
8904 if !node.gestures.is_empty() {
8905 flags |= dirty::PAN;
8906 }
8907 if node.props.is_some()
8910 || node.class_pointer != crate::props::PointerEvents::Auto
8911 || node.spare
8912 || node.hidden_in_text
8913 || node.list.as_ref().is_some_and(|l| l.parent)
8914 {
8915 flags |= dirty::VIEW_PROPS;
8916 }
8917 match kind {
8918 Kind::Screen => flags |= dirty::SCREEN,
8919 Kind::Modal => flags |= dirty::MODAL,
8920 _ => {}
8921 }
8922 if node.control.is_some() {
8923 flags |= dirty::NATIVE;
8924 }
8925 if let Some(list) = node.list.as_mut() {
8926 list.dirty = true;
8927 }
8928 if let Some(input) = node.input.as_mut() {
8929 input.content = None;
8930 flags |= dirty::INPUT;
8931 if !input.value.is_empty() {
8932 flags |= dirty::INPUT_VALUE;
8933 }
8934 }
8935 if let Some(component) = node.component.as_mut() {
8936 component.changed = component.props.iter().map(|(k, _)| k.clone()).collect();
8938 component.slots_changed.set(!component.slots.is_empty());
8939 flags |= dirty::COMPONENT;
8940 }
8941 flags
8942 }
8943
8944 #[inline]
8945 fn set_gpu_source(&mut self, key: Key, id: NodeId, source: Option<crate::gpu::GpuSource>) {
8949 let node = &mut self.nodes[key as usize];
8950 let created = node.created;
8951 let Some(component) = node.component.as_mut() else {
8952 return;
8953 };
8954 if component.source == source {
8955 return;
8956 }
8957 component.source = source.clone();
8958 if !created {
8959 return;
8960 }
8961 self.mount.push(MountItem::GpuView { id, source });
8962 component.changed = component.props.iter().map(|(k, _)| k.clone()).collect();
8963 let mut flags = dirty::COMPONENT;
8964 if !component.slots.is_empty() {
8965 component.slots_changed.set(true);
8966 flags |= dirty::ANIMATION;
8967 }
8968 self.mark(key, flags);
8969 }
8970
8971 fn mark(&mut self, key: Key, flags: u32) {
8972 let node = &mut self.nodes[key as usize];
8973 node.dirty |= flags;
8974 if flags & (dirty::VIEW | dirty::ANIMATION) != 0
8978 && (node.culled
8979 || !self.culling.is_empty()
8980 && (!node.animated.is_empty() || !node.view_style.transform.ops().is_empty()))
8981 {
8982 self.cull_dirty = true;
8983 }
8984 if !node.queued {
8985 node.queued = true;
8986 self.queue.push(key);
8987 }
8988 }
8989
8990 fn mark_text_block(&mut self, mut key: Key) {
8992 loop {
8993 let node = &self.nodes[key as usize];
8994 if !node.inline {
8995 if node.kind == Kind::Text {
8996 self.mark(key, dirty::TEXT_BUILD);
8997 }
8998 return;
8999 }
9000 if node.parent == NO_KEY {
9001 return;
9003 }
9004 key = node.parent;
9005 }
9006 }
9007
9008 fn flush_dirty(&mut self) {
9009 loop {
9010 self.flush_positions();
9012 self.flush_dirty_once();
9013 self.check_attachments();
9017 if self.queue.is_empty() {
9018 break;
9019 }
9020 }
9021 }
9022
9023 fn flush_dirty_once(&mut self) {
9024 let mut queue = std::mem::take(&mut self.queue);
9025 for &key in &queue {
9026 let Some(node) = self.nodes.get_mut(key as usize) else {
9027 continue;
9028 };
9029 let mut flags = std::mem::take(&mut node.dirty);
9030 node.queued = false;
9031 if flags & dirty::TEXT_BUILD != 0 && node.layout.is_some() {
9032 if self.rebuild_text(key) {
9033 flags |= dirty::TEXT_MOUNT;
9034 }
9035 self.sync_grid_role(key);
9037 }
9038 let node = &self.nodes[key as usize];
9039 if !node.created {
9040 continue;
9041 }
9042 let id = node.id;
9043 if flags & dirty::VIEW != 0 {
9044 let style = self.mounted_view_style(key);
9045 self.mount.push(MountItem::ViewStyle { id, style });
9046 }
9047 if flags & dirty::EVENTS != 0 {
9048 self.mount.push(MountItem::Events {
9049 id,
9050 events: node.mounted_events(),
9051 });
9052 }
9053 if flags & dirty::IMAGE != 0
9054 && let Some(image) = &node.image
9055 {
9056 let resize_mode = node.object_fit.unwrap_or_default();
9059 let ratio = self.components.environment.pixel_ratio;
9061 self.mount.push(MountItem::Image {
9062 id,
9063 source: image.source.as_ref().map(|s| s.resolved(ratio)),
9064 resize_mode,
9065 options: crate::mount::ImageOptions {
9066 placeholder: image
9067 .options
9068 .placeholder
9069 .as_ref()
9070 .map(|s| s.resolved(ratio)),
9071 blur_radius: image.options.blur_radius,
9072 fade_ms: image.options.fade_ms,
9073 position: node.view_style.object_position,
9074 current_color: image.svg_current_color.then(|| self.resolved_paint(key).1),
9075 },
9076 });
9077 }
9078 if let Some(scroll) = &node.scroll
9079 && node.list.as_ref().is_none_or(|l| !l.parent)
9080 {
9081 if flags & dirty::SCROLL != 0 {
9082 self.mount.push(MountItem::ScrollConfig {
9083 id,
9084 horizontal: scroll.horizontal,
9085 scrollbar_visible: scroll.scrollbar != crate::ScrollbarSetting::Hidden
9087 && scroll.bar.is_none(),
9088 replaced: scroll.bar.is_some(),
9089 scroll_value: scroll.scroll_value,
9090 pull_value: scroll.pull_value,
9091 keyboard_dismiss: scroll.keyboard_dismiss,
9092 mirrored: node.kind == Kind::List && scroll.horizontal && node.rtl,
9093 });
9094 }
9095 if flags & dirty::SCROLL_BEHAVIOR != 0 {
9096 self.mount.push(MountItem::ScrollBehavior {
9097 id,
9098 behavior: Box::new(scroll.behavior.clone()),
9099 });
9100 }
9101 if flags & dirty::REFRESHING != 0 {
9102 self.mount.push(MountItem::Refreshing {
9103 id,
9104 refreshing: scroll.refreshing,
9105 });
9106 }
9107 }
9108 if flags & dirty::ANIMATION != 0 {
9109 let mut bindings = node.animated.clone();
9110 if bindings
9113 .iter()
9114 .any(|(p, _)| matches!(p, AnimationProp::StickyTop | AnimationProp::StickyLeft))
9115 {
9116 if node.sticky.is_none() && !self.inset_warned {
9117 self.inset_warned = true;
9118 log::warn!(
9119 target: "js",
9120 "an animated `top` / `left` only moves a `position: sticky` view's sticking point; it is ignored on view {id}"
9121 );
9122 }
9123 bindings.retain(|(p, _)| {
9124 !matches!(p, AnimationProp::StickyTop | AnimationProp::StickyLeft)
9125 });
9126 }
9127 let steps = self.perspective_steps(key);
9129 if steps > 0 {
9130 for (prop, _) in &mut bindings {
9131 if let AnimationProp::Transform(i) = prop {
9132 *i += steps;
9133 }
9134 }
9135 }
9136 if let Some(d) = &node.drawing {
9137 bindings.extend(
9138 d.slots
9139 .iter()
9140 .enumerate()
9141 .map(|(i, &n)| (AnimationProp::CanvasArg(i as u16), n)),
9142 );
9143 }
9144 if let Some(layer) = node.shader.as_ref().and_then(|s| s.layer.as_ref()) {
9145 bindings.extend(
9146 layer
9147 .nodes
9148 .iter()
9149 .enumerate()
9150 .map(|(i, &n)| (AnimationProp::CanvasArg(i as u16), n)),
9151 );
9152 }
9153 if let Some(component) = &node.component {
9154 bindings.extend(
9155 component
9156 .bound
9157 .iter()
9158 .map(|&(s, n)| (AnimationProp::ComponentSlot(s), n)),
9159 );
9160 }
9161 if let Some(component) = &node.component
9162 && component.slots_changed.replace(false)
9163 {
9164 self.mount.push(MountItem::ComponentPropSlots {
9165 id,
9166 names: component.slots.clone(),
9167 });
9168 }
9169 self.mount
9170 .push(MountItem::AnimationBindings { id, bindings });
9171 }
9172 if flags & dirty::CANVAS != 0
9173 && let Some(drawing) = &node.drawing
9174 {
9175 if drawing.fit().is_some() {
9176 self.fitted_pending.push(key);
9178 } else {
9179 let drawing = self.mounted_drawing(key, drawing);
9180 self.mount.push(MountItem::Canvas { id, drawing });
9181 }
9182 }
9183 if flags & dirty::SHADER != 0
9184 && let Some(shader) = &node.shader
9185 {
9186 self.mount.push(MountItem::Shader {
9187 id,
9188 layer: shader.layer.clone(),
9189 });
9190 }
9191 if flags & dirty::PAN != 0 {
9192 let mut values = node.gestures;
9193 if !node.pan_enabled {
9194 values.pan_x = None;
9195 values.pan_y = None;
9196 }
9197 self.mount.push(MountItem::Gestures { id, values });
9198 }
9199 if flags & dirty::VIEW_PROPS != 0 {
9200 self.mount.push(MountItem::ViewProps {
9201 id,
9202 props: node.mounted_props(),
9203 });
9204 } else if flags & dirty::LABEL != 0 {
9205 let label = node
9206 .props
9207 .as_ref()
9208 .and_then(|p| p.accessibility.label.clone());
9209 self.mount.push(MountItem::AccessibilityLabel { id, label });
9210 }
9211 if flags & dirty::SCREEN != 0
9212 && let Some(config) = self.screen_config(key)
9213 {
9214 self.mount.push(MountItem::ScreenConfig {
9215 id,
9216 config: Box::new(config),
9217 });
9218 }
9219 if flags & dirty::COMPONENT != 0
9220 && self.nodes[key as usize].kind == Kind::Native
9221 && let Some(component) = self.nodes[key as usize].component.as_ref()
9222 && component.name.is_none()
9223 {
9224 log::warn!(target: "js", "a <native> element without `component`");
9225 }
9226 if flags & dirty::COMPONENT != 0
9227 && let Some(component) = self.nodes[key as usize].component.as_mut()
9228 && !component.changed.is_empty()
9229 {
9230 let changed = std::mem::take(&mut component.changed);
9231 let props: Vec<_> = changed
9232 .into_iter()
9233 .filter(|name| !component.is_bound(name))
9235 .map(|name| {
9236 let value = component
9237 .props
9238 .iter()
9239 .find(|(k, _)| *k == name)
9240 .map(|(_, v)| v.clone());
9241 (name, value)
9242 })
9243 .collect();
9244 if !props.is_empty() {
9245 self.mount.push(MountItem::ComponentProps { id, props });
9246 }
9247 }
9248 if flags & dirty::NATIVE != 0 && !self.web_unchecked.is_empty() {
9249 self.settle_web_urls(key);
9250 }
9251 let node = &self.nodes[key as usize];
9252 if flags & dirty::NATIVE != 0
9253 && let Some(control) = &node.control
9254 {
9255 self.mount.push(MountItem::NativeProps {
9256 id,
9257 props: (**control).clone(),
9258 });
9259 }
9260 if flags & dirty::MODAL != 0
9261 && let Some(root) = &node.root
9262 {
9263 let mut config = root.modal.clone();
9264 config.window = self.window_of(key);
9265 let item = MountItem::ModalConfig { id, config };
9270 match self
9271 .mount
9272 .iter()
9273 .position(|m| matches!(m, MountItem::Insert { child, .. } if *child == id))
9274 {
9275 Some(at) => self.mount.insert(at, item),
9276 None => self.mount.push(item),
9277 }
9278 }
9279 if flags & dirty::NAV_SHADER != 0
9280 && let Some(root) = &node.root
9281 {
9282 let shader = root.nav_shader.clone();
9283 self.mount.push(MountItem::NavShader { id, shader });
9284 }
9285 if let Some(input) = &node.input {
9286 if flags & dirty::INPUT != 0 {
9287 let mut config = input.config.clone();
9288 config.accessory = config
9289 .accessory_id
9290 .as_deref()
9291 .and_then(|name| self.accessories.get(name).copied());
9292 config.placeholder_color = config
9296 .placeholder_color
9297 .or(node.text_style.placeholder_color);
9298 config.selection_color =
9299 config.selection_color.or(node.text_style.selection_color);
9300 let class = node.class_props.as_deref();
9301 if let Some(c) = class {
9302 config.placeholder_color = config.placeholder_color.or(c.placeholder_color);
9303 }
9304 config.selection_color =
9305 config.selection_color.or(self.inherited_text_props(key).2);
9306 config.caret_color = config
9307 .caret_color
9308 .or(node.text_style.caret_color)
9309 .or(class.and_then(|c| c.caret_color));
9310 config.style = scaled(
9311 self.inherited_text_style(key).inherit(&node.text_style),
9312 node.paragraph.font_multiplier(self.font_scale),
9313 );
9314 config.align = directed_align(
9315 node.text_style.text_align.unwrap_or_default(),
9316 node.rtl && !node.text_style.text_align_physical,
9317 );
9318 config.rtl = node.text_style.writing_direction.unwrap_or(node.rtl);
9319 config.scrollbar_visible =
9321 input.scrollbar != crate::ScrollbarSetting::Hidden && input.bar.is_none();
9322 config.report_scroll = input.bar.is_some() || input.watched;
9323 self.mount.push(MountItem::Input {
9324 id,
9325 config: Box::new(config),
9326 });
9327 }
9328 if flags & dirty::INPUT_VALUE != 0 {
9329 self.mount.push(MountItem::InputValue {
9330 id,
9331 text: input.value.clone(),
9332 count: input.count,
9333 });
9334 }
9335 }
9336 if flags & dirty::TEXT_MOUNT != 0 {
9337 self.queue_text(key);
9338 }
9339 }
9340 queue.clear();
9341 if self.queue.is_empty() {
9343 self.queue = queue;
9344 }
9345 }
9346
9347 fn report_content_size(&mut self, key: Key, width: f32) {
9352 let node = &self.nodes[key as usize];
9353 let (Some(input), Some(layout)) = (node.input.as_ref(), node.layout) else {
9354 return;
9355 };
9356 let max = input.config.multiline.then_some(width);
9357 let (placeholder, empty_line) = (input.placeholder_measured, input.empty_line);
9358 let Some(LeafContext::Text(cx)) = self.layout.get_node_context_mut(layout) else {
9359 return;
9360 };
9361 let size = if !placeholder {
9362 measure_text(&self.text_engine, &mut self.measure_cache, cx, max)
9363 } else if let Some((hash, size)) = empty_line
9364 && hash == cx.layout_hash
9365 {
9366 size
9367 } else {
9368 let hash = cx.layout_hash;
9370 let mut empty = TextContext::new(Arc::new(self.input_text(key, "")));
9371 let size = measure_text(&self.text_engine, &mut self.measure_cache, &mut empty, max);
9372 let input = self.nodes[key as usize]
9373 .input
9374 .as_mut()
9375 .expect("input state");
9376 input.empty_line = Some((hash, size));
9377 size
9378 };
9379 let node = &mut self.nodes[key as usize];
9380 let input = node.input.as_mut().expect("input state");
9381 if input.content_size == Some(size) {
9382 return;
9383 }
9384 input.content_size = Some(size);
9385 let id = node.id;
9386 self.events.push(crate::element::JsEvent::Event(
9387 id,
9388 EventKind::ContentSizeChange,
9389 EventPayload::Map(vec![
9390 ("width", PayloadValue::Number(size.width.0 as f64)),
9391 ("height", PayloadValue::Number(size.height.0 as f64)),
9392 ]),
9393 ));
9394 }
9395
9396 fn text_cx(&mut self, layout: LayoutId) -> &mut TextContext<M::Prepared> {
9397 match self.layout.get_node_context_mut(layout) {
9398 Some(LeafContext::Text(cx)) => cx,
9399 _ => unreachable!("text block without text context"),
9400 }
9401 }
9402
9403 fn base_text_style(&self) -> ResolvedTextStyle {
9409 ResolvedTextStyle {
9410 font_family: self.default_font,
9411 ..ResolvedTextStyle::default()
9412 }
9413 }
9414
9415 fn sync_accent(&mut self, key: Key) {
9419 let node = &mut self.nodes[key as usize];
9420 let accent = node.view_style.accent_color;
9421 let Some(component) = node.component.as_mut() else {
9422 return;
9423 };
9424 let value = accent.map(|Color(c)| crate::JsonValue::from(format!("#{c:08X}")));
9425 let at = component
9426 .props
9427 .iter()
9428 .position(|(k, _)| &**k == ACCENT_PROP);
9429 if at.map(|i| &component.props[i].1) == value.as_ref() {
9430 return;
9431 }
9432 let name: Arc<str> = Arc::from(ACCENT_PROP);
9433 match (at, value) {
9434 (Some(i), Some(v)) => component.props[i].1 = v,
9435 (None, Some(v)) => component.props.push((name.clone(), v)),
9436 (Some(i), None) => {
9437 component.props.swap_remove(i);
9438 }
9439 (None, None) => return,
9440 }
9441 if !component.changed.contains(&name) {
9442 component.changed.push(name);
9443 }
9444 self.mark(key, dirty::COMPONENT);
9445 }
9446
9447 fn inherited_text_style(&self, key: Key) -> ResolvedTextStyle {
9453 let mut chain: Vec<Key> = Vec::new();
9454 let mut k = self.nodes[key as usize].parent;
9455 while k != NO_KEY {
9456 let node = &self.nodes[k as usize];
9457 let passes = if node.kind == Kind::Text {
9458 node.text_style.color.is_some()
9459 } else {
9460 node.text_style != TextStyle::default()
9461 };
9462 if passes {
9463 chain.push(k);
9464 }
9465 k = node.parent;
9466 }
9467 chain
9468 .iter()
9469 .rev()
9470 .fold(self.base_text_style(), |style, &k| {
9471 let node = &self.nodes[k as usize];
9472 if node.kind == Kind::Text {
9473 ResolvedTextStyle {
9474 color: node.text_style.color.unwrap_or(style.color),
9475 ..style
9476 }
9477 } else {
9478 style.inherit(&node.text_style)
9479 }
9480 })
9481 }
9482
9483 fn inherited_text_props(&self, key: Key) -> (Option<bool>, Option<bool>, Option<Color>) {
9491 let (no_wrap, selectable, highlight, _) = self.inherited_text_wrap(key);
9492 (no_wrap, selectable, highlight)
9493 }
9494
9495 fn inherited_text_wrap(&self, key: Key) -> (Option<bool>, Option<bool>, Option<Color>, bool) {
9499 let (mut no_wrap, mut selectable, mut highlight) = (None, None, None);
9500 let mut pretty = None;
9501 let mut k = key;
9502 while k != NO_KEY && (no_wrap.is_none() || selectable.is_none() || highlight.is_none()) {
9503 let node = &self.nodes[k as usize];
9504 if !matches!(node.kind, Kind::Text | Kind::Input) {
9505 highlight = highlight.or(node.paragraph.selection_color);
9506 }
9507 if let Some(c) = node.class_props.as_deref() {
9508 if no_wrap.is_none() && c.no_wrap.is_some() {
9509 pretty = Some(c.pretty);
9510 }
9511 no_wrap = no_wrap.or(c.no_wrap);
9512 selectable = selectable.or(c.selectable);
9513 highlight = highlight.or(c.selection_color);
9514 }
9515 k = node.parent;
9516 }
9517 (no_wrap, selectable, highlight, pretty.unwrap_or(false))
9518 }
9519
9520 fn inherited_text_align(&self, key: Key) -> Option<(TextAlign, bool)> {
9522 let mut k = self.nodes[key as usize].parent;
9523 while k != NO_KEY {
9524 let node = &self.nodes[k as usize];
9525 if let Some(a) = node.text_style.text_align {
9526 return Some((a, node.text_style.text_align_physical));
9527 }
9528 k = node.parent;
9529 }
9530 None
9531 }
9532
9533 fn inherited_text_indent(&self, key: Key) -> Option<Points> {
9537 let mut k = key;
9538 while k != NO_KEY {
9539 let style = &self.nodes[k as usize].text_style;
9540 if let Some(em) = style.text_indent_em {
9542 return Some(Points(self.font_size_at(k) * em));
9543 }
9544 if let Some(points) = style.text_indent {
9545 return Some(points);
9546 }
9547 k = self.nodes[k as usize].parent;
9548 }
9549 None
9550 }
9551
9552 fn font_size_at(&self, key: Key) -> f32 {
9555 let mut em = 1.0f32;
9556 let mut k = key;
9557 loop {
9558 let style = &self.nodes[k as usize].text_style;
9559 if let Some(scale) = style.font_size_em {
9560 em *= scale;
9561 } else if let Some(size) = style.font_size {
9562 return size.0 * em;
9563 }
9564 let parent = self.nodes[k as usize].parent;
9565 if parent == NO_KEY {
9566 return self.base_text_style().font_size.0 * em;
9567 }
9568 k = parent;
9569 }
9570 }
9571
9572 fn mark_inheriting_text(&mut self, key: Key) {
9574 self.ch_changed(key);
9575 let mut stack: Vec<Key> = self.nodes[key as usize].children.clone();
9576 while let Some(k) = stack.pop() {
9577 match self.nodes[k as usize].kind {
9578 Kind::Text => {
9580 if !self.nodes[k as usize].inline {
9581 self.mark_text_block(k);
9582 }
9583 stack.extend_from_slice(&self.nodes[k as usize].children);
9584 }
9585 Kind::Input => {
9586 self.measure_input(k);
9587 self.mark(k, dirty::INPUT);
9588 }
9589 Kind::RawText => {}
9590 _ => stack.extend_from_slice(&self.nodes[k as usize].children),
9591 }
9592 }
9593 }
9594
9595 fn rebuild_text(&mut self, key: Key) -> bool {
9600 let deferred = !self.nodes[key as usize].created && self.cull_scope(key).is_some();
9603 let node = &self.nodes[key as usize];
9604 let class = node.class_props.as_deref();
9606 let explicit_ellipsize = class.and_then(|c| c.ellipsize);
9607 let ellipsize = explicit_ellipsize.unwrap_or_default();
9608 let inherited = self.inherited_text_style(key);
9609 let (no_wrap, selectable, highlight, pretty) = self.inherited_text_wrap(key);
9610 let clamps_nowrap = no_wrap == Some(true)
9613 && node.view_style.overflow_hidden
9614 && explicit_ellipsize.is_some_and(|mode| mode != crate::EllipsizeMode::Clip);
9615 let max_lines = match class.and_then(|c| c.number_of_lines) {
9616 Some(lines) if lines > 0 => lines,
9617 _ if clamps_nowrap => 1,
9618 _ => 0,
9619 };
9620 let (align, physical) = node
9621 .text_style
9622 .text_align
9623 .map(|align| (align, node.text_style.text_align_physical))
9624 .or_else(|| self.inherited_text_align(key))
9625 .unwrap_or_default();
9626 let base = inherited.inherit(&node.text_style);
9627 let mut text = AttributedText {
9628 paragraph_strut: Some(base),
9629 align: directed_align(align, node.rtl && !physical),
9630 writing_direction: node.text_style.writing_direction,
9631 rtl: node.rtl,
9632 max_lines,
9633 ellipsize,
9634 no_wrap: max_lines == 0 && no_wrap.unwrap_or(false),
9637 shadow: node.text_style.shadow(),
9638 selectable,
9639 selection_color: node
9640 .paragraph
9641 .selection_color
9642 .or(node.text_style.selection_color)
9643 .or(highlight),
9644 ..AttributedText::default()
9645 };
9646 let multiplier = node.paragraph.font_multiplier(self.font_scale);
9647 let options = crate::TextOptions::default().indent(
9648 self.inherited_text_indent(key)
9649 .map(|indent| indent * multiplier),
9650 );
9651 let inserted = self.update_attachments(key);
9652 let baselines = self.attachment_baselines(key);
9653 let mut parts = TextAttachments {
9654 alignments: crate::AttachmentAlignments::default(),
9655 spacers: Vec::new(),
9656 baselines: &baselines,
9657 next_baseline: 0,
9658 };
9659 self.collect_text(key, base, &mut text, &mut parts, false);
9660 let TextAttachments {
9661 alignments,
9662 spacers,
9663 ..
9664 } = parts;
9665 self.hide_attachments(key, false);
9666 if multiplier != 1.0 {
9667 if let Some(strut) = &mut text.paragraph_strut {
9668 *strut = scaled(*strut, multiplier);
9669 }
9670 for span in &mut text.spans {
9671 span.style = scaled(span.style, multiplier);
9672 }
9673 }
9674 let layout = self.nodes[key as usize]
9675 .layout
9676 .expect("text block has layout");
9677 let colors_at_draw = self.text_engine.draws_colors_from_text();
9678 let cx = self.text_cx(layout);
9679 cx.deferred = deferred;
9680 cx.spacers = spacers;
9681 let pretty_changed = cx.pretty.is_some() != pretty;
9682 if pretty_changed {
9683 cx.pretty = pretty.then(|| Box::new((f32::NAN, Points::ZERO)));
9684 cx.laid_out = None;
9685 }
9686 if *cx.text == text && cx.alignments == alignments && cx.options == options {
9687 if inserted {
9688 cx.laid_out = None;
9690 }
9691 return inserted || pretty_changed;
9692 }
9693 if !cx.text.metadata_eq(&text)
9694 && !inserted
9695 && cx.alignments == alignments
9696 && cx.options == options
9697 && cx.text.rendering_eq(&text)
9698 {
9699 cx.text = Arc::new(text);
9700 cx.metadata_changed = true;
9701 return true;
9702 }
9703 if !inserted
9708 && cx.alignments == alignments
9709 && cx.options == options
9710 && colors_at_draw
9711 && cx
9712 .laid_out
9713 .as_ref()
9714 .is_none_or(|l| Arc::ptr_eq(&l.text, &cx.text))
9715 && cx.text.same_but_colors(&text)
9716 {
9717 let text = Arc::new(text);
9718 if let Some(laid) = &mut cx.laid_out {
9719 laid.text = text.clone();
9720 }
9721 cx.text = text;
9722 cx.metadata_changed = true;
9723 return true;
9724 }
9725 cx.metadata_changed = false;
9726 let same_layout =
9727 cx.text.layout_eq(&text) && cx.alignments == alignments && cx.options == options;
9728 cx.alignments = alignments;
9729 cx.options = options;
9730 cx.text = Arc::new(text);
9731 cx.prepared = None;
9734 cx.min_content = None;
9735 cx.laid_out = None;
9736 if let Some(p) = &mut cx.pretty {
9737 p.0 = f32::NAN;
9738 }
9739 if !same_layout {
9740 cx.layout_hash = text_layout_hash(&cx.alignments, &cx.text, &cx.options);
9741 cx.cache = None;
9742 cx.baseline = None;
9743 cx.same_lines = None;
9744 cx.no_ahead = false;
9745 let attachments =
9749 !cx.alignments.is_empty() || !self.nodes[key as usize].attached.is_empty();
9750 let measure = leaf_measure(&self.text_engine, &mut self.measure_cache);
9751 if attachments
9754 || !(self.layout.sized_by_style(layout)
9755 || self.layout.measures_as_before(layout, measure))
9756 {
9757 self.layout.mark_dirty(layout);
9758 self.needs_layout = true;
9759 }
9760 }
9761 true
9762 }
9763
9764 fn collect_text(
9767 &self,
9768 key: Key,
9769 style: ResolvedTextStyle,
9770 out: &mut AttributedText,
9771 parts: &mut TextAttachments<'_>,
9772 in_press: bool,
9773 ) {
9774 if let Some(text) = self.folded_text(key) {
9775 out.push(text, style);
9776 }
9777 for &c in &self.nodes[key as usize].children {
9778 let child = &self.nodes[c as usize];
9779 if child.is_overlay() {
9780 continue;
9781 }
9782 match child.kind {
9783 Kind::RawText => out.push(&child.text, style),
9784 Kind::Text => {
9785 let start = out.len_utf16();
9786 let mut inner = style.inherit(&child.text_style);
9787 if let Some(mut b) = span_background(&child.view_style, child.id) {
9788 (b.top, b.bottom) = span_vertical_padding(child);
9789 inner.background = Some(b);
9790 }
9791 if inner.hidden || child.view_style.hidden {
9794 inner = inner.hide();
9795 }
9796 let press = pressable(child.events);
9797 let hinted = child.overlay_watched & overlay::watch::HINT != 0;
9798 let tracked = child.classes.as_ref().map_or(0, |c| c.tracked_states());
9801 let hovers = tracked & crate::tailwind::state::HOVERED != 0;
9802 let (first, last) = span_padding(child, out.rtl);
9806 let pad = |out: &mut AttributedText, spacers: &mut Vec<u32>, w: f32| {
9807 if w > 0.0 {
9808 spacers.push(out.len_utf16());
9809 out.push_attachment(crate::geometry::size_pt(w, 0.0), inner);
9810 }
9811 };
9812 pad(out, &mut parts.spacers, first);
9813 self.collect_text(c, inner, out, parts, in_press || press);
9814 pad(out, &mut parts.spacers, last);
9815 if !inner.hidden && (press || ((hinted || hovers) && !in_press)) {
9828 let mut events = child.events;
9829 if hinted || hovers {
9830 events.set(EventKind::MouseEnter, true);
9831 events.set(EventKind::MouseLeave, true);
9832 }
9833 if press && tracked & crate::tailwind::state::PRESSED != 0 {
9834 events.set(EventKind::PressDown, true);
9835 events.set(EventKind::PressUp, true);
9836 }
9837 if let Some(href) = child.props.as_ref().and_then(|p| p.href.clone()) {
9840 out.link_hrefs
9841 .push(crate::text::LinkHref::new(out.links.len() as u32, href));
9842 }
9843 out.links.push(crate::text::TextLink {
9844 start,
9845 end: out.len_utf16(),
9846 node: child.id,
9847 events,
9848 focus_stop: press
9849 && child.props.as_ref().is_none_or(|p| p.focus_stop(true)),
9850 });
9851 }
9852 if let Some(test_id) = child.props.as_ref().and_then(|p| p.test_id.clone()) {
9853 out.test_ids.push(crate::text::SpanTestId {
9854 start,
9855 end: out.len_utf16(),
9856 test_id,
9857 });
9858 }
9859 }
9860 Kind::Overlay => {}
9862 _ => {
9864 if let Some(l) = child.layout {
9865 let size = self.rounded_layout(l).size;
9866 if let Some(&(_, baseline)) = parts
9869 .baselines
9870 .get(parts.next_baseline)
9871 .filter(|b| b.0 == c)
9872 {
9873 parts.next_baseline += 1;
9874 parts
9875 .alignments
9876 .set_baseline(out.len_utf16(), Some(baseline));
9877 }
9878 if let Some(copy) = self.attachment_copy_text(c) {
9879 out.copy_texts.push(crate::text::AttachmentCopyText::new(
9880 out.len_utf16(),
9881 copy.clone(),
9882 ));
9883 }
9884 parts.alignments.push(
9885 out,
9886 crate::geometry::size_pt(size.width, size.height),
9887 self.attachment_align(c),
9888 style,
9889 );
9890 }
9891 }
9892 }
9893 }
9894 }
9895
9896 fn attachment_align(&self, key: Key) -> crate::style::VerticalAlign {
9902 use crate::style::VerticalAlign;
9903 let node = &self.nodes[key as usize];
9904 if node.vertical_align != VerticalAlign::Baseline
9905 || !self.components.renders.is_place(node.id)
9906 {
9907 return node.vertical_align;
9908 }
9909 self.render_content(key)
9910 .map_or(VerticalAlign::Baseline, |content| {
9911 self.nodes[content as usize].vertical_align
9912 })
9913 }
9914
9915 fn attachment_copy_text(&self, key: Key) -> Option<&Arc<str>> {
9920 let node = &self.nodes[key as usize];
9921 let copy = match &node.copy_text {
9922 Some(copy) => Some(copy),
9923 None if self.components.renders.is_place(node.id) => self
9924 .render_content(key)
9925 .and_then(|content| self.nodes[content as usize].copy_text.as_ref()),
9926 None => None,
9927 };
9928 copy.filter(|c| !c.is_empty())
9929 }
9930
9931 fn render_content(&self, key: Key) -> Option<Key> {
9934 let mut key = key;
9935 for _ in 0..2 {
9936 let mut children = self.nodes[key as usize]
9937 .children
9938 .iter()
9939 .filter(|&&c| !self.nodes[c as usize].is_overlay());
9940 match (children.next(), children.next()) {
9941 (Some(&only), None) => key = only,
9942 _ => return None,
9943 }
9944 }
9945 Some(key)
9946 }
9947
9948 fn attachment_baselines(&mut self, key: Key) -> Vec<(Key, Points)> {
9956 let mut keys = Vec::new();
9957 self.attachments_of(key, &mut keys);
9958 keys.retain(|&a| self.attachment_align(a) == crate::style::VerticalAlign::Baseline);
9959 keys.into_iter()
9960 .filter_map(|a| Some((a, self.first_text_baseline(a, true)?)))
9961 .collect()
9962 }
9963
9964 fn first_text_baseline(&mut self, key: Key, root: bool) -> Option<Points> {
9968 let node = &self.nodes[key as usize];
9969 if node.is_overlay() {
9970 return None;
9971 }
9972 let layout = node.layout?;
9973 if !root
9977 && (self.layout.displays_none(layout)
9978 || self.layout.style(layout).position == Position::Absolute)
9979 {
9980 return None;
9981 }
9982 let text = node.kind == Kind::Text;
9983 let l = *self.layout.unrounded_layout(layout);
9984 let top = if root { 0.0 } else { l.location.y };
9985 if text {
9986 let width =
9987 l.size.width - l.padding.left - l.padding.right - l.border.left - l.border.right;
9988 let engine = &self.text_engine;
9989 let Some(LeafContext::Text(cx)) = self.layout.get_node_context_mut(layout) else {
9990 return None;
9991 };
9992 let baseline = text_baseline(engine, cx, width.max(0.0))?;
9993 return Some(Points(top + l.border.top + l.padding.top) + baseline);
9994 }
9995 let children = self.nodes[key as usize].children.clone();
9996 children
9997 .into_iter()
9998 .find_map(|c| self.first_text_baseline(c, false))
9999 .map(|inner| Points(top) + inner)
10000 }
10001
10002 fn placed_in_text(&self, key: Key) -> Option<Key> {
10005 let holder = self.nodes[key as usize].parent;
10006 if holder == NO_KEY || !self.is_render_holder(self.nodes[holder as usize].id) {
10007 return None;
10008 }
10009 let place = self.nodes[holder as usize].parent;
10010 (place != NO_KEY && self.nodes[place as usize].inline).then_some(place)
10011 }
10012
10013 fn attachments_of(&self, key: Key, out: &mut Vec<Key>) {
10016 for &c in &self.nodes[key as usize].children {
10017 let child = &self.nodes[c as usize];
10018 if child.is_overlay() {
10019 continue;
10020 }
10021 match child.kind {
10022 Kind::RawText | Kind::Overlay => {}
10023 Kind::Text => self.attachments_of(c, out),
10024 _ if child.layout.is_some() => out.push(c),
10025 _ => {}
10026 }
10027 }
10028 }
10029
10030 fn attachment_block(&self, key: Key) -> Option<Key> {
10032 let node = &self.nodes[key as usize];
10033 if !node.inline || node.layout.is_none() || node.kind == Kind::Text {
10034 return None;
10035 }
10036 let mut k = node.parent;
10037 while k != NO_KEY {
10038 let n = &self.nodes[k as usize];
10039 if !n.inline {
10040 return (n.kind == Kind::Text).then_some(k);
10041 }
10042 k = n.parent;
10043 }
10044 None
10045 }
10046
10047 fn update_attachments(&mut self, key: Key) -> bool {
10051 let mut keys = Vec::new();
10052 self.attachments_of(key, &mut keys);
10053 let block = &self.nodes[key as usize];
10054 if keys.is_empty() && block.attached.is_empty() {
10055 return false;
10056 }
10057 let (block_id, created) = (block.id, block.created);
10058 let old = std::mem::take(&mut self.nodes[key as usize].attached);
10059 let mut inserted = false;
10060 for &a in &keys {
10061 let id = self.nodes[a as usize].id;
10062 let new = !old.contains(&id);
10063 if created && new {
10064 self.ensure_created(a);
10065 self.mount.push(MountItem::Insert {
10066 parent: block_id,
10067 child: id,
10068 before: None,
10069 });
10070 inserted = true;
10071 }
10072 let layout = self.nodes[a as usize].layout.expect("attachment layout");
10073 let dirty = self.layout.dirty(layout);
10074 if dirty {
10075 self.layout_root(
10076 layout,
10077 taffy::Size {
10078 width: AvailableSpace::MaxContent,
10079 height: AvailableSpace::MaxContent,
10080 },
10081 );
10082 }
10083 if created && (dirty || new) {
10084 let children = std::mem::take(&mut self.nodes[a as usize].children);
10086 for &child in &children {
10087 self.emit_frames(child);
10088 }
10089 self.nodes[a as usize].children = children;
10090 }
10091 }
10092 for id in old {
10094 let Ok(k) = self.key(id) else { continue };
10095 let n = &self.nodes[k as usize];
10096 let moved = n.parent != NO_KEY && !n.inline && self.nodes[n.parent as usize].created;
10097 if n.created && !moved && self.attachment_block(k).is_none() {
10098 self.mount.push(MountItem::Remove { id });
10099 }
10100 }
10101 let ids: Vec<NodeId> = keys.iter().map(|&a| self.nodes[a as usize].id).collect();
10102 let has = !ids.is_empty();
10103 self.nodes[key as usize].attached = if created { ids } else { Vec::new() };
10104 match (has, self.attachment_blocks.contains(&key)) {
10105 (true, false) => self.attachment_blocks.push(key),
10106 (false, true) => self.attachment_blocks.retain(|&k| k != key),
10107 _ => {}
10108 }
10109 inserted
10110 }
10111
10112 fn check_attachments(&mut self) {
10114 let mut i = 0;
10115 while i < self.attachment_blocks.len() {
10116 let key = self.attachment_blocks[i];
10117 i += 1;
10118 let Some(node) = self.nodes.get(key as usize) else {
10119 continue;
10120 };
10121 let dirty = node.attached.iter().any(|&id| {
10122 self.key(id).is_ok_and(|k| {
10123 self.nodes[k as usize]
10124 .layout
10125 .is_some_and(|l| self.layout.dirty(l))
10126 })
10127 });
10128 if dirty {
10129 self.mark(key, dirty::TEXT_BUILD);
10130 }
10131 }
10132 }
10133
10134 fn positioning_parent(&self, layout: LayoutId) -> Option<LayoutId> {
10140 let mut parent = self.layout.parent(layout)?;
10141 match self.layout.style(layout).position {
10142 Position::Absolute => {
10143 while !self.layout.style(parent).position.is_positioned() {
10144 let Some(above) = self.layout.parent(parent) else {
10145 break;
10146 };
10147 parent = above;
10148 }
10149 }
10150 Position::Fixed => {
10151 while let Some(above) = self.layout.parent(parent) {
10152 parent = above;
10153 }
10154 }
10155 _ => {}
10156 }
10157 Some(parent)
10158 }
10159
10160 fn layout_origin(&self, layout: LayoutId) -> taffy::Point<f32> {
10161 let mut above = Vec::new();
10162 let mut at = self.positioning_parent(layout);
10163 while let Some(node) = at {
10164 above.push(node);
10165 at = self.positioning_parent(node);
10166 }
10167 above
10168 .iter()
10169 .rev()
10170 .fold(taffy::Point::ZERO, |origin, &node| {
10171 let l = self.layout.unrounded_layout(node);
10172 taffy::Point {
10173 x: origin.x + l.location.x,
10174 y: origin.y + l.location.y,
10175 }
10176 })
10177 }
10178
10179 fn rounded_layout(&self, layout: LayoutId) -> taffy::Layout {
10183 rounded(
10184 self.layout.unrounded_layout(layout),
10185 self.containing_origin(layout),
10186 self.frame_ratio(),
10187 )
10188 }
10189
10190 fn containing_origin(&self, layout: LayoutId) -> Origin {
10193 self.positioning_parent(layout)
10194 .map_or(Origin::default(), |parent| self.box_origin(parent))
10195 }
10196
10197 fn box_origin(&self, layout: LayoutId) -> Origin {
10199 let origin = self.layout_origin(layout);
10200 let l = self.layout.unrounded_layout(layout);
10201 Origin::of(
10202 taffy::Point {
10203 x: origin.x + l.location.x,
10204 y: origin.y + l.location.y,
10205 },
10206 l.size,
10207 self.frame_ratio(),
10208 )
10209 }
10210
10211 fn frame_ratio(&self) -> taffy::Size<f32> {
10215 match self.layout.grid() {
10216 Some(grid) => grid.ratio(),
10217 None => {
10218 let ratio = self.pixel_ratio();
10219 taffy::Size {
10220 width: ratio,
10221 height: ratio,
10222 }
10223 }
10224 }
10225 }
10226
10227 fn cell_changed(&mut self, cell: Option<Size<Points>>, dark: bool) {
10231 let grid = cell
10232 .and_then(terminal_layout::Grid::new)
10233 .map(|g| g.with_page(dark));
10234 let cell = grid.map(|g| Size::new(Points(g.width), Points(g.height)));
10235 if self.measure_cache.set_cell(cell) {
10236 self.fonts_changed();
10237 }
10238 if self.layout.set_grid(grid) {
10239 self.dirty_overlays();
10240 self.needs_layout = true;
10241 }
10242 }
10243
10244 fn pixel_ratio(&self) -> f32 {
10247 self.measure_cache.pixel_ratio()
10248 }
10249
10250 fn pixel_ratio_changed(&mut self, ratio: f32) {
10254 if !self.measure_cache.set_pixel_ratio(ratio) {
10255 return;
10256 }
10257 self.fonts_changed();
10258 let layouts: Vec<LayoutId> = self
10259 .nodes
10260 .iter()
10261 .filter(|(_, n)| n.created)
10262 .filter_map(|(_, n)| n.layout)
10263 .collect();
10264 for layout in layouts {
10265 self.layout.mark_dirty(layout);
10266 }
10267 self.needs_layout = true;
10268 }
10269
10270 fn layout_main(&mut self) -> bool {
10272 let root = self.nodes[self.root as usize].layout.expect("root layout");
10273 let available = taffy::Size {
10274 width: AvailableSpace::Definite(self.viewport.width.0),
10275 height: AvailableSpace::Definite(self.viewport.height.0),
10276 };
10277 let main = self.layout.dirty(root);
10279 if main {
10280 let (fitting, fitted) = self
10283 .windows
10284 .get(&crate::ROOT_ID)
10285 .map_or(((false, false), false), |r| (r.fits(), r.fitted.is_some()));
10286 let mut available = available;
10287 if fitting != (false, false) || fitted {
10288 let mut style = root_style(self.viewport);
10289 if fitting.0 {
10290 available.width = AvailableSpace::MaxContent;
10291 style.size.width = taffy::Dimension::auto();
10292 }
10293 if fitting.1 {
10294 available.height = AvailableSpace::MaxContent;
10295 style.size.height = taffy::Dimension::auto();
10296 }
10297 self.layout.set_style(root, style);
10298 }
10299 self.layout_root(root, available);
10300 self.fit_window(self.root, root);
10301 }
10302 main
10303 }
10304
10305 fn layout_roots(&mut self) {
10309 if self.roots.is_empty() {
10310 return;
10311 }
10312 let mut order: Vec<(u32, Key)> = self
10313 .roots
10314 .iter()
10315 .filter(|&&k| {
10316 let n = &self.nodes[k as usize];
10317 n.created
10318 && n.parent != NO_KEY
10319 && (!n.is_overlay() || self.overlay(k).is_some_and(|s| s.host.is_some()))
10320 })
10321 .map(|&k| (self.root_depth(k), k))
10322 .collect();
10323 order.sort_unstable();
10324 for (_, key) in order {
10325 self.layout_detached(key);
10326 }
10327 }
10328
10329 fn accessory_attached(&mut self, key: Key, attached: bool) {
10332 let node = &self.nodes[key as usize];
10333 let Some(name) = node.root.as_ref().and_then(|r| r.native_id.clone()) else {
10334 return;
10335 };
10336 let id = node.id;
10337 if attached {
10338 self.accessories.insert(name.clone(), id);
10339 } else if self.accessories.get(&name) == Some(&id) {
10340 self.accessories.remove(&name);
10341 } else {
10342 return;
10343 }
10344 let inputs: Vec<Key> = self
10345 .nodes
10346 .iter()
10347 .filter(|(_, n)| {
10348 n.input
10349 .as_ref()
10350 .is_some_and(|i| i.config.accessory_id.as_deref() == Some(&*name))
10351 })
10352 .map(|(k, _)| k as Key)
10353 .collect();
10354 for k in inputs {
10355 self.mark(k, dirty::INPUT);
10356 }
10357 }
10358
10359 fn root_depth(&self, mut key: Key) -> u32 {
10361 let mut depth = 0;
10362 key = self.nodes[key as usize].parent;
10363 while key != NO_KEY {
10364 let n = &self.nodes[key as usize];
10365 if n.is_layout_root() {
10366 depth += 1;
10367 }
10368 key = n.parent;
10369 }
10370 depth
10371 }
10372
10373 fn top_overlap(&self, key: Key) -> f32 {
10376 let mut y = 0.0;
10377 let mut k = key;
10378 loop {
10379 let n = &self.nodes[k as usize];
10380 if k == self.root {
10381 return (self.safe_area.top.0 - y).max(0.0);
10382 }
10383 if n.is_layout_root() {
10384 let inset = match n.kind {
10385 Kind::Modal => n.root.as_ref().map_or(0.0, |r| r.insets.top.0),
10386 _ => 0.0,
10387 };
10388 return (inset - y).max(0.0);
10389 }
10390 if !n.frame.origin.y.0.is_nan() {
10391 y += n.frame.origin.y.0;
10392 }
10393 if n.parent == NO_KEY {
10394 return 0.0;
10395 }
10396 k = n.parent;
10397 }
10398 }
10399
10400 fn native_header(&self) -> bool {
10404 self.header_heights != crate::NO_NATIVE_HEADER
10405 }
10406
10407 fn screen_size(&self, key: Key) -> Option<Size<Points>> {
10409 let parent = self.nodes[key as usize].parent;
10410 let p = self.nodes.get(parent as usize)?;
10411 let stack_layout = p.layout.filter(|_| p.kind == Kind::Stack)?;
10412 let s = self.rounded_layout(stack_layout).size;
10413 Some(size_pt(s.width, s.height))
10414 }
10415
10416 fn header_slot(&self, key: Key) -> Option<Key> {
10418 self.nodes[key as usize]
10419 .children
10420 .iter()
10421 .copied()
10422 .find(|&c| {
10423 let n = &self.nodes[c as usize];
10424 n.kind == Kind::HeaderItem
10425 && n.created
10426 && n.root
10427 .as_ref()
10428 .is_some_and(|r| r.slot == HeaderSlot::Header)
10429 })
10430 }
10431
10432 fn drawn_header(&mut self, key: Key) -> f32 {
10435 let Some(item) = self.header_slot(key) else {
10436 return 0.0;
10437 };
10438 self.layout_detached(item);
10439 self.nodes[item as usize]
10440 .layout
10441 .map_or(0.0, |l| self.rounded_layout(l).size.height)
10442 }
10443
10444 fn layout_detached(&mut self, key: Key) {
10445 if self.nodes[key as usize].is_overlay() {
10446 self.layout_overlay(key);
10447 return;
10448 }
10449 let native_header = self.native_header();
10450 let drawn_header = if !native_header && self.nodes[key as usize].kind == Kind::Screen {
10451 self.drawn_header(key)
10452 } else {
10453 0.0
10454 };
10455 let title_room = {
10456 let n = &self.nodes[key as usize];
10457 let title = native_header
10458 && n.kind == Kind::HeaderItem
10459 && n.root.as_ref().is_some_and(|r| r.slot == HeaderSlot::Title);
10460 let parent = n.parent;
10461 if title && parent != NO_KEY {
10462 self.title_room(parent).unwrap_or(0.0)
10463 } else {
10464 0.0
10465 }
10466 };
10467 let node = &self.nodes[key as usize];
10468 let (Some(layout), kind, parent) = (node.layout, node.kind, node.parent) else {
10469 return;
10470 };
10471 let root = node.root.as_ref().expect("root state");
10472 let (size, header, available) = match kind {
10473 Kind::Screen => {
10474 let Some(size) = self.screen_size(key) else {
10475 return;
10476 };
10477 let c = &root.screen;
10478 let measured = root
10479 .header
10480 .filter(|_| !c.large_title && !c.header_transparent);
10481 let header = if !native_header {
10482 drawn_header
10483 } else if !c.header_visible {
10484 0.0
10485 } else if let Some(measured) = measured {
10486 measured
10487 } else {
10488 let bar = if c.large_title {
10489 self.header_heights.1
10490 } else {
10491 self.header_heights.0
10492 };
10493 bar.0 + self.top_overlap(parent)
10494 };
10495 (size, header, definite(size))
10496 }
10497 Kind::HeaderItem if !native_header && root.slot == HeaderSlot::Header => {
10500 let Some(screen) = self.screen_size(parent) else {
10501 return;
10502 };
10503 (
10504 size_pt(screen.width.0, 0.0),
10505 0.0,
10506 taffy::Size {
10507 width: AvailableSpace::Definite(screen.width.0),
10508 height: AvailableSpace::MaxContent,
10509 },
10510 )
10511 }
10512 Kind::HeaderItem if native_header && root.slot == HeaderSlot::Title => (
10516 Size::default(),
10517 title_room,
10518 taffy::Size {
10519 width: AvailableSpace::MaxContent,
10520 height: AvailableSpace::MaxContent,
10521 },
10522 ),
10523 Kind::Modal => {
10524 let known = self.root_view_size(key);
10526 let size = known.unwrap_or_default();
10527 let mut available = match known {
10528 Some(size) => definite(size),
10529 None => taffy::Size {
10530 width: AvailableSpace::MaxContent,
10531 height: AvailableSpace::MaxContent,
10532 },
10533 };
10534 let (width, height) = self
10537 .windows
10538 .get(&node.id)
10539 .map_or((false, false), |r| r.fits());
10540 if width {
10541 available.width = AvailableSpace::MaxContent;
10542 }
10543 if height {
10544 available.height = AvailableSpace::MaxContent;
10545 }
10546 (size, 0.0, available)
10547 }
10548 Kind::InputAccessory => (
10550 size_pt(self.viewport.width.0, 0.0),
10551 0.0,
10552 taffy::Size {
10553 width: AvailableSpace::Definite(self.viewport.width.0),
10554 height: AvailableSpace::MaxContent,
10555 },
10556 ),
10557 _ => (
10558 Size::default(),
10559 0.0,
10560 taffy::Size {
10561 width: AvailableSpace::MaxContent,
10562 height: AvailableSpace::MaxContent,
10563 },
10564 ),
10565 };
10566 let changed = root.laid_out != Some((size, header));
10567 if !changed && !self.layout.dirty(layout) {
10568 return;
10569 }
10570 if kind == Kind::HeaderItem && native_header && root.slot == HeaderSlot::Title {
10571 let mut style = self.layout.style(layout).clone();
10572 style.max_size.width = if header > 0.0 {
10573 taffy::LengthPercentageAuto::length(header)
10574 } else {
10575 taffy::LengthPercentageAuto::auto()
10576 };
10577 self.layout.set_style(layout, style);
10578 } else if kind == Kind::InputAccessory
10579 || (kind == Kind::HeaderItem && size.width > Points::ZERO)
10580 {
10581 let mut style = self.layout.style(layout).clone();
10582 style.size.width = taffy::Dimension::length(size.width.0);
10583 self.layout.set_style(layout, style);
10584 } else if kind != Kind::HeaderItem {
10585 let config_padding = match kind {
10586 Kind::Screen
10590 if native_header
10591 && (root.screen.header_transparent || root.screen.large_title) =>
10592 {
10593 0.0
10594 }
10595 _ => header,
10596 };
10597 let mut style = self.nodes[key as usize]
10598 .base_layout
10599 .as_deref()
10600 .cloned()
10601 .unwrap_or_default();
10602 style.size = taffy::Size {
10603 width: taffy::Dimension::length(size.width.0),
10604 height: taffy::Dimension::length(size.height.0),
10605 };
10606 if kind == Kind::Modal {
10607 let id = self.nodes[key as usize].id;
10608 let (mut width, mut height) =
10609 self.windows.get(&id).map_or((false, false), |r| r.fits());
10610 if self.root_view_size(key).is_none() {
10611 (width, height) = (true, true);
10612 }
10613 if width {
10614 style.size.width = taffy::Dimension::auto();
10615 }
10616 if height {
10617 style.size.height = taffy::Dimension::auto();
10618 }
10619 }
10620 if config_padding > 0.0 {
10621 let base = match style.padding.top.into_raw() {
10622 raw if raw.tag() == taffy::CompactLength::LENGTH_TAG => raw.value(),
10623 _ => 0.0,
10624 };
10625 style.padding.top = taffy::LengthPercentage::length(base + config_padding);
10626 }
10627 self.layout.set_style(layout, style);
10628 }
10629 let header_changed = root.laid_out.is_none_or(|(_, h)| h != header);
10630 self.nodes[key as usize]
10631 .root
10632 .as_mut()
10633 .expect("root state")
10634 .laid_out = Some((size, header));
10635 self.layout_root(layout, available);
10636 if kind == Kind::Modal {
10637 self.fit_window(key, layout);
10638 }
10639 self.emit_frames(key);
10640 let screen = match kind {
10641 Kind::Screen if header_changed => Some(key),
10642 Kind::HeaderItem if self.header_item_emptied(key) => Some(parent),
10643 _ => None,
10644 };
10645 if let Some(screen) = screen {
10646 let id = self.nodes[screen as usize].id;
10647 if let Some(config) = self.screen_config(screen) {
10648 self.mount.push(MountItem::ScreenConfig {
10649 id,
10650 config: Box::new(config),
10651 });
10652 }
10653 }
10654 }
10655
10656 fn header_item_emptied(&mut self, key: Key) -> bool {
10661 let width = self.nodes[key as usize]
10662 .layout
10663 .map_or(0.0, |l| self.rounded_layout(l).size.width);
10664 let root = self.nodes[key as usize].root.as_mut().expect("root state");
10665 if root.slot == HeaderSlot::Header {
10666 return false;
10667 }
10668 let empty = width <= 0.0;
10669 std::mem::replace(&mut root.empty, empty) != empty
10670 }
10671
10672 fn title_room(&mut self, key: Key) -> Option<f32> {
10676 const INSET: f32 = 16.0;
10678 const BACK: f32 = 56.0;
10680 const BUTTON: f32 = 48.0;
10682 let width = self.screen_size(key)?.width.0;
10683 let items: Vec<(Key, HeaderSlot)> = self.nodes[key as usize]
10684 .children
10685 .iter()
10686 .filter_map(|&c| {
10687 let n = &self.nodes[c as usize];
10688 let slot = n.root.as_ref()?.slot;
10689 (n.kind == Kind::HeaderItem
10690 && n.created
10691 && matches!(slot, HeaderSlot::Left | HeaderSlot::Right))
10692 .then_some((c, slot))
10693 })
10694 .collect();
10695 let mut room = width - 2.0 * INSET;
10696 let (mut left, mut right) = (false, false);
10697 for (item, slot) in items {
10698 self.layout_detached(item);
10699 let w = self.nodes[item as usize]
10700 .layout
10701 .map_or(0.0, |l| self.rounded_layout(l).size.width);
10702 room -= w + INSET;
10703 match slot {
10704 HeaderSlot::Left => left = true,
10705 _ => right = true,
10706 }
10707 }
10708 let screen = &self.nodes[key as usize];
10709 let config = &screen.root.as_ref()?.screen;
10710 if !right && !config.right_items.is_empty() {
10711 room -= config.right_items.len() as f32 * BUTTON;
10712 }
10713 if !left && !config.left_items.is_empty() {
10714 room -= config.left_items.len() as f32 * BUTTON;
10715 }
10716 let first = self.nodes[screen.parent as usize].children.first() == Some(&key);
10718 if !left && config.back_visible && !first {
10719 room -= BACK;
10720 }
10721 Some(room.max(1.0))
10722 }
10723
10724 fn screen_config(&self, key: Key) -> Option<ScreenConfig> {
10726 let node = &self.nodes[key as usize];
10727 let root = node.root.as_ref().filter(|_| node.kind == Kind::Screen)?;
10728 let mut config = root.screen.clone();
10729 config.header_height = Points(root.laid_out.map_or(0.0, |(_, h)| h));
10730 for &c in &node.children {
10731 let child = &self.nodes[c as usize];
10732 if child.kind != Kind::HeaderItem || !child.created {
10733 continue;
10734 }
10735 let slot = child.root.as_ref().map_or(HeaderSlot::Left, |r| r.slot);
10736 let empty = child.root.as_ref().is_some_and(|r| r.empty);
10740 let system = match slot {
10741 HeaderSlot::Left => {
10742 config.left_system_item.is_some() || config.left_symbol.is_some()
10743 }
10744 HeaderSlot::Right => {
10745 config.right_system_item.is_some() || config.right_symbol.is_some()
10746 }
10747 HeaderSlot::Title => false,
10749 HeaderSlot::Header => true,
10750 };
10751 if empty && !system {
10752 continue;
10753 }
10754 let target = match slot {
10755 HeaderSlot::Left => &mut config.left,
10756 HeaderSlot::Right => &mut config.right,
10757 HeaderSlot::Title => &mut config.title_view,
10758 HeaderSlot::Header => &mut config.header_view,
10759 };
10760 *target = Some(child.id);
10761 }
10762 if let Some(style) = self.part_resolved(key, classes::Part::Header) {
10763 let background = style.view.background_color;
10764 config.background_color = (background.0 & 0xff != 0).then_some(background);
10765 config.title_color = style.text.color;
10766 config.tint_color = style.view.tint_color;
10767 }
10768 Some(config)
10769 }
10770
10771 fn layout_cells(&mut self) {
10774 for i in 0..self.lists.len() {
10775 let key = self.lists[i];
10776 let list = &self.nodes[key as usize];
10777 let Some(list_layout) = list.layout else {
10778 continue;
10779 };
10780 let state = list.list.as_ref().expect("list");
10781 let horizontal = state.horizontal;
10782 let l = self.rounded_layout(list_layout);
10783 let size = l.size;
10784 let cross = if !state.parent {
10785 if horizontal { size.height } else { size.width }
10786 } else if horizontal {
10787 (size.height - l.border.top - l.border.bottom - l.padding.top - l.padding.bottom)
10789 .max(0.0)
10790 } else {
10791 (size.width - l.border.left - l.border.right - l.padding.left - l.padding.right)
10792 .max(0.0)
10793 };
10794 let cross = if state.parent {
10797 cross
10798 } else {
10799 let main = if horizontal {
10800 size.width - l.border.left - l.border.right - l.padding.left - l.padding.right
10801 } else {
10802 size.height - l.border.top - l.border.bottom - l.padding.top - l.padding.bottom
10803 };
10804 let room = self.layout.list_bar_room(list_layout, horizontal);
10805 if room > 0.0 && state.content_len() > main + 0.5 {
10806 (cross - room).max(0.0)
10807 } else {
10808 cross
10809 }
10810 };
10811 let cell = self
10812 .layout
10813 .grid()
10814 .map(|g| if horizontal { g.height } else { g.width });
10815 let item_cross = state.column(cross, 0, cell).1;
10816 let extra_cross = state.full_width(cross).1;
10817 let stretch = state
10818 .content
10819 .align_items
10820 .is_none_or(|a| a == taffy::AlignItems::STRETCH);
10821 let available = |c: f32| {
10822 let cross = if stretch {
10823 AvailableSpace::Definite(c)
10824 } else {
10825 AvailableSpace::MaxContent
10826 };
10827 if horizontal {
10828 taffy::Size {
10829 width: AvailableSpace::MaxContent,
10830 height: cross,
10831 }
10832 } else {
10833 taffy::Size {
10834 width: cross,
10835 height: AvailableSpace::MaxContent,
10836 }
10837 }
10838 };
10839 let list_state = self.nodes[key as usize].list.as_mut().expect("list");
10843 let resized = list_state.cells_cross != cross;
10844 list_state.cells_cross = cross;
10845 let cells = std::mem::take(&mut self.nodes[key as usize].children);
10846 for &cell in &cells {
10847 let node = &self.nodes[cell as usize];
10848 let (Some(cell_layout), false) = (node.layout, node.decoration) else {
10850 continue;
10851 };
10852 let c = match node.slot {
10853 Some(CellSlot::Item(_)) | None => item_cross,
10854 Some(_) => extra_cross,
10855 };
10856 self.layout.set_host(cell_layout, list_layout);
10857 if resized || self.layout.dirty(cell_layout) {
10858 self.layout_root(cell_layout, available(c));
10859 self.nodes[cell as usize].relaid = true;
10860 }
10861 }
10862 self.nodes[key as usize].children = cells;
10863 }
10864 }
10865
10866 fn layout_root(&mut self, root: LayoutId, available: taffy::Size<AvailableSpace>) {
10868 let measure = leaf_measure(&self.text_engine, &mut self.measure_cache);
10869 self.layout
10870 .compute_layout_with_measure(root, available, measure);
10871 }
10872
10873 fn relayout_boundaries(&mut self) -> Vec<Key> {
10877 let measure = leaf_measure(&self.text_engine, &mut self.measure_cache);
10878 self.layout.relayout_boundaries(measure)
10879 }
10880
10881 fn displays_none(&self, key: Key) -> bool {
10884 let mut k = key;
10885 while k != NO_KEY {
10886 let n = &self.nodes[k as usize];
10887 if let Some(layout) = n.layout
10888 && self.layout.displays_none(layout)
10889 {
10890 return true;
10891 }
10892 if n.is_layout_root() {
10893 return false;
10894 }
10895 k = n.parent;
10896 }
10897 false
10898 }
10899
10900 #[inline]
10901 fn queue_text(&mut self, key: Key) {
10902 let node = &mut self.nodes[key as usize];
10903 if !node.text_queued {
10904 node.text_queued = true;
10905 self.pending_text.push(key);
10906 }
10907 }
10908
10909 fn flush_text(&mut self) {
10912 let mut pending = std::mem::take(&mut self.pending_text);
10913 let mut placements: Vec<(Key, TextLayout, Bounds<Points>)> = Vec::new();
10915 for &key in &pending {
10916 let Some(node) = self.nodes.get_mut(key as usize) else {
10917 continue;
10918 };
10919 node.text_queued = false;
10920 let align_vertical = node.text_style.align_vertical.unwrap_or_default();
10921 let report_lines = node.events.contains(EventKind::TextLayout);
10922 let fit = node
10924 .paragraph
10925 .fit
10926 .then_some(node.paragraph.min_font_scale.max(0.1));
10927 let (id, created, Some(layout)) = (node.id, node.created, node.layout) else {
10928 continue;
10929 };
10930 if !created {
10931 continue;
10932 }
10933 if let Some(commit) = self.measure_cache.resizing
10934 && let Some(LeafContext::Text(cx)) = self.layout.get_node_context_mut(layout)
10935 && cx.near_screen != commit
10936 && cx
10937 .laid_out
10938 .as_ref()
10939 .is_some_and(|l| Arc::ptr_eq(&l.text, &cx.text))
10940 {
10941 cx.held = true;
10942 continue;
10943 }
10944 let hidden = self.displays_none(key);
10946 let mut content = if hidden {
10947 Bounds::default()
10948 } else {
10949 content_box(&self.rounded_layout(layout))
10950 };
10951 let measured_width = (!hidden && self.layout.grid().is_none())
10955 .then(|| content_box(self.layout.unrounded_layout(layout)).size.width);
10956 let ratio = self.frame_ratio().width;
10957 let engine = &self.text_engine;
10958 let cache = &mut self.measure_cache;
10959 let Some(LeafContext::Text(cx)) = self.layout.get_node_context_mut(layout) else {
10960 continue;
10961 };
10962 let no_wrap = cx.text.no_wrap;
10963 let typeset = |rounded: Points| match measured_width {
10964 Some(measured) if !no_wrap => typeset_width(rounded, measured, ratio),
10965 _ => rounded,
10966 };
10967 if hidden {
10968 if let Some((text, layout)) = cx.remount_metadata(content) {
10973 self.mount.push(MountItem::Text {
10974 id,
10975 text,
10976 layout,
10977 content,
10978 });
10979 continue;
10980 }
10981 if matches!(&cx.laid_out, Some(l) if l.content == content) {
10982 continue;
10983 }
10984 let layout =
10985 engine.layout(&engine.prepare(&AttributedText::default()), content.size);
10986 cx.laid_out = Some(LaidText {
10987 content,
10988 layout: layout.clone(),
10989 text: cx.text.clone(),
10990 });
10991 cx.metadata_changed = false;
10992 self.mount.push(MountItem::Text {
10993 id,
10994 text: cx.text.clone(),
10995 layout,
10996 content,
10997 });
10998 continue;
10999 }
11000 if cx.text.no_wrap {
11001 content.size.width = content
11003 .size
11004 .width
11005 .max(measure_text(engine, cache, cx, None).width);
11006 }
11007 if align_vertical > Percentage(0.0) {
11008 let height =
11010 measure_text(engine, cache, cx, Some(typeset(content.size.width).0)).height;
11011 if height < content.size.height {
11012 content.origin.y += align_vertical.of(content.size.height - height);
11013 content.size.height = height;
11014 }
11015 }
11016 if cx.pretty.is_some() && fit.is_none() {
11017 let width = pretty_width(engine, cx, content.size.width);
11020 let spare = content.size.width - width;
11021 if spare > Points::ZERO {
11022 content.origin.x += match cx.text.align {
11023 TextAlign::Center => spare * 0.5,
11024 TextAlign::Right => spare,
11025 TextAlign::Auto if cx.text.rtl => spare,
11026 _ => Points::ZERO,
11027 };
11028 content.size.width = width;
11029 }
11030 }
11031 if let Some((text, layout)) = cx.remount_metadata(content) {
11032 self.mount.push(MountItem::Text {
11033 id,
11034 text,
11035 layout,
11036 content,
11037 });
11038 continue;
11039 }
11040 let size = content.size;
11041 if let Some(min) = fit {
11042 if matches!(&cx.laid_out, Some(l) if l.content == content) {
11044 continue;
11045 }
11046 let text = Arc::new(fitted(
11047 engine,
11048 &cx.text,
11049 &cx.alignments,
11050 &cx.options,
11051 size,
11052 min,
11053 ));
11054 let prepared = engine.prepare_with(&text, &cx.alignments, &cx.options);
11055 let text_layout = engine.layout(&prepared, size);
11056 cx.laid_out = Some(LaidText {
11057 content,
11058 layout: text_layout.clone(),
11059 text: text.clone(),
11060 });
11061 cx.metadata_changed = false;
11062 if report_lines {
11063 self.events.push(crate::element::JsEvent::Event(
11064 id,
11065 EventKind::TextLayout,
11066 text_lines(engine, &text, &text_layout),
11067 ));
11068 keep_geometry(
11069 &self.geometry_engine,
11070 &mut self.geometries,
11071 id,
11072 &text_layout,
11073 &text,
11074 &cx.spacers,
11075 );
11076 }
11077 if !text.attachments.is_empty() {
11078 placements.push((key, text_layout.clone(), content));
11079 }
11080 self.mount.push(MountItem::Text {
11081 id,
11082 text,
11083 layout: text_layout,
11084 content,
11085 });
11086 continue;
11087 }
11088 if let Some(lines) = lines_in_box(engine, cache, cx, typeset(size.width), size.height) {
11089 if matches!(&cx.laid_out, Some(l) if l.content == content && l.text.max_lines == lines)
11095 {
11096 continue;
11097 }
11098 let mut clamped = (*cx.text).clone();
11099 clamped.max_lines = lines;
11100 let text = Arc::new(clamped);
11101 let prepared = engine.prepare_with(&text, &cx.alignments, &cx.options);
11102 let text_layout =
11103 engine.layout(&prepared, Size::new(typeset(size.width), size.height));
11104 cx.laid_out = Some(LaidText {
11105 content,
11106 layout: text_layout.clone(),
11107 text: text.clone(),
11108 });
11109 cx.metadata_changed = false;
11110 if report_lines {
11111 self.events.push(crate::element::JsEvent::Event(
11112 id,
11113 EventKind::TextLayout,
11114 text_lines(engine, &text, &text_layout),
11115 ));
11116 keep_geometry(
11117 &self.geometry_engine,
11118 &mut self.geometries,
11119 id,
11120 &text_layout,
11121 &text,
11122 &cx.spacers,
11123 );
11124 }
11125 if !text.attachments.is_empty() {
11126 placements.push((key, text_layout.clone(), content));
11127 }
11128 self.mount.push(MountItem::Text {
11129 id,
11130 text,
11131 layout: text_layout,
11132 content,
11133 });
11134 continue;
11135 }
11136 let text_layout = match &cx.laid_out {
11137 Some(l) if l.content == content => continue,
11138 Some(l) if l.content.size == size => l.layout.clone(),
11140 Some(l) if keeps_lines(cx, l, size) => l.layout.clone(),
11143 _ => {
11144 let prepared = cx.prepared.get_or_insert_with(|| {
11145 engine.prepare_with(&cx.text, &cx.alignments, &cx.options)
11146 });
11147 let layout =
11148 engine.layout(prepared, Size::new(typeset(size.width), size.height));
11149 if report_lines {
11150 self.events.push(crate::element::JsEvent::Event(
11151 id,
11152 EventKind::TextLayout,
11153 text_lines(engine, &cx.text, &layout),
11154 ));
11155 keep_geometry(
11156 &self.geometry_engine,
11157 &mut self.geometries,
11158 id,
11159 &layout,
11160 &cx.text,
11161 &cx.spacers,
11162 );
11163 }
11164 layout
11165 }
11166 };
11167 cx.laid_out = Some(LaidText {
11168 content,
11169 layout: text_layout.clone(),
11170 text: cx.text.clone(),
11171 });
11172 cx.metadata_changed = false;
11173 if !cx.text.attachments.is_empty() {
11174 placements.push((key, text_layout.clone(), content));
11175 }
11176 self.mount.push(MountItem::Text {
11177 id,
11178 text: cx.text.clone(),
11179 layout: text_layout,
11180 content,
11181 });
11182 }
11183 pending.clear();
11184 self.pending_text = pending;
11185 for (key, layout, content) in placements {
11186 self.place_attachments(key, &layout, content);
11187 }
11188 }
11189
11190 fn place_attachments(&mut self, key: Key, layout: &TextLayout, content: Bounds<Points>) {
11194 let mut points = self.text_engine.attachments(layout);
11195 if let Some(l) = self.nodes[key as usize].layout {
11196 let cx = self.text_cx(l);
11198 if !cx.spacers.is_empty() {
11199 let mut indices = cx.text.attachments.iter().map(|a| a.index);
11200 points.retain(|_| indices.next().is_none_or(|i| !cx.spacers.contains(&i)));
11201 }
11202 }
11203 let attached = std::mem::take(&mut self.nodes[key as usize].attached);
11204 for (i, &id) in attached.iter().enumerate() {
11205 let Ok(a) = self.key(id) else { continue };
11206 let Some(l) = self.nodes[a as usize].layout else {
11207 continue;
11208 };
11209 let size = self.rounded_layout(l).size;
11210 let (x, y) = match points.get(i).copied().flatten() {
11211 Some(p) => (content.origin.x.0 + p.x.0, content.origin.y.0 + p.y.0),
11212 None => (-100_000.0, 0.0),
11214 };
11215 self.set_frame(a, rect(x, y, size.width, size.height));
11216 }
11217 self.nodes[key as usize].attached = attached;
11218 }
11219
11220 fn emit_frames(&mut self, key: Key) {
11222 let parent = self.nodes[key as usize].parent;
11223 let hidden = parent != NO_KEY && self.displays_none(parent);
11224 let origin = self.nodes[key as usize]
11225 .layout
11226 .and_then(|l| self.layout.parent(l))
11227 .map_or(Origin::default(), |parent| self.box_origin(parent));
11228 self.emit_frames_in(key, hidden, origin);
11229 }
11230
11231 fn emit_frames_in(&mut self, key: Key, hidden: bool, origin: Origin) {
11244 let node = &self.nodes[key as usize];
11245 let Some(layout) = node.layout else { return };
11246 if !node.created {
11247 if node.culled {
11248 self.cull_frames_in(key, hidden, origin);
11249 }
11250 return;
11251 }
11252 let hidden = hidden || self.layout.displays_none(layout);
11253 if hidden {
11254 self.layout.emitted(layout);
11255 self.nodes[key as usize].emitted = None;
11256 if self.nodes[key as usize].follow.is_some() {
11257 self.laid_follower(key, None, false, (0.0, 0.0));
11258 }
11259 self.set_frame(key, Bounds::default());
11260 let node = &mut self.nodes[key as usize];
11264 if let Some(input) = node.input.as_mut()
11265 && input.content.is_some_and(|c| c != Bounds::default())
11266 {
11267 input.content = Some(Bounds::default());
11268 self.mount.push(MountItem::InputContent {
11269 id: node.id,
11270 content: Bounds::default(),
11271 });
11272 }
11273 if self.nodes[key as usize].kind.is_container() {
11274 let children = std::mem::take(&mut self.nodes[key as usize].children);
11275 for &child in &children {
11276 if !self.nodes[child as usize].is_layout_root() {
11277 self.emit_frames_in(child, true, origin);
11278 }
11279 }
11280 self.nodes[key as usize].children = children;
11281 }
11282 return;
11283 }
11284 let node = &self.nodes[key as usize];
11285 let unrounded = *self.layout.unrounded_layout(layout);
11286 let position = self.layout.style(layout).position;
11292 let escaping = position == Position::Fixed
11293 || (position == Position::Absolute
11294 && !self
11295 .layout
11296 .parent(layout)
11297 .is_some_and(|p| self.layout.style(p).position.is_positioned()));
11298 let ratio = self.frame_ratio();
11299 if !self.layout.stale(layout)
11304 && !node.escapes
11305 && !node.is_overlay()
11306 && !node.decoration
11307 && !self.nodes.get(node.parent as usize).is_some_and(|p| p.rtl)
11308 && node.emitted.is_some_and(|(at, r)| {
11309 let moved = |a: f32, b: f32, ratio: f32| {
11310 let d = (a - b) * ratio;
11311 d == d.round()
11312 };
11313 r == ratio
11314 && at.back == origin.back
11315 && moved(origin.at.x, at.at.x, ratio.width)
11316 && moved(origin.at.y, at.at.y, ratio.height)
11317 })
11318 {
11319 self.nodes[key as usize].emitted = Some((origin, ratio));
11320 return;
11321 }
11322 self.layout.emitted(layout);
11323 let containing = if escaping {
11324 self.containing_origin(layout)
11325 } else {
11326 origin
11327 };
11328 let inner = Origin::of(
11329 taffy::Point {
11330 x: containing.at.x + unrounded.location.x,
11331 y: containing.at.y + unrounded.location.y,
11332 },
11333 unrounded.size,
11334 ratio,
11335 );
11336 let l = rounded(&unrounded, containing, ratio);
11337 let offset = origin.to(containing, ratio);
11338 let mut frame = rect(
11339 l.location.x + offset.x,
11340 l.location.y + offset.y,
11341 l.size.width,
11342 l.size.height,
11343 );
11344 if let Some(parent) = self.nodes.get(node.parent as usize)
11347 && !node.decoration
11348 && parent.rtl
11349 && let Some(ScrollState {
11350 horizontal: true,
11351 content: Some(content),
11352 ..
11353 }) = parent.scroll.as_deref()
11354 && parent.kind == Kind::Scroll
11355 {
11356 frame.origin.x = content.width - frame.origin.x - frame.size.width;
11357 }
11358 if node.is_overlay() {
11359 frame.origin = self.overlay_origin(key, frame);
11360 }
11361 let beside = self.nodes[key as usize].beside;
11363 if beside != NO_KEY {
11364 frame.origin = self.nodes[beside as usize].frame.origin;
11365 } else if self.nodes[key as usize].decoration {
11366 let offset = Origin::default().to(origin, ratio);
11370 frame.origin.x.0 += offset.x;
11371 frame.origin.y.0 += offset.y;
11372 }
11373 if self.nodes[key as usize].follow.is_some() {
11374 let column = self.layout.parent(layout).is_some_and(|p| {
11377 let style = self.layout.style(p);
11378 style.display == taffy::Display::Flex
11379 && matches!(
11380 style.flex_direction,
11381 taffy::FlexDirection::Column | taffy::FlexDirection::ColumnReverse
11382 )
11383 });
11384 let m = unrounded.margin;
11385 let margins = if column {
11386 (round(m.top, ratio.height), round(m.bottom, ratio.height))
11387 } else {
11388 (round(m.left, ratio.width), round(m.right, ratio.width))
11389 };
11390 self.laid_follower(key, Some(frame), column, margins);
11391 } else {
11392 self.set_frame(key, frame);
11393 }
11394 self.sync_cell_style(key, layout, &unrounded);
11395 self.sync_focus_ring(key);
11396 let kind = self.nodes[key as usize].kind;
11397 if kind == Kind::Input {
11398 let content = content_box(&l);
11399 let node = &mut self.nodes[key as usize];
11400 let input = node.input.as_mut().expect("input state");
11401 if input.content != Some(content) {
11402 input.content = Some(content);
11403 self.mount.push(MountItem::InputContent {
11404 id: node.id,
11405 content,
11406 });
11407 }
11408 if node.events.contains(EventKind::ContentSizeChange) {
11409 self.report_content_size(key, content.size.width.0);
11410 }
11411 }
11412 if kind == Kind::Scroll {
11413 let horizontal = self.nodes[key as usize]
11414 .scroll
11415 .as_ref()
11416 .is_some_and(|s| s.horizontal);
11417 self.set_scroll_content(key, scroll_extent(&l, horizontal));
11418 }
11419 let mut escapes = escaping;
11422 if kind.is_container() && kind != Kind::List {
11423 let children = std::mem::take(&mut self.nodes[key as usize].children);
11424 for &child in &children {
11425 if !self.nodes[child as usize].is_layout_root() {
11426 self.emit_frames_in(child, false, inner);
11427 escapes |= self.nodes[child as usize].escapes;
11428 }
11429 }
11430 self.nodes[key as usize].children = children;
11431 self.update_overflow(key);
11432 }
11433 let node = &mut self.nodes[key as usize];
11434 node.escapes = escapes;
11435 node.emitted = Some((origin, ratio));
11436 }
11437
11438 fn sync_cell_style(&mut self, key: Key, layout: LayoutId, l: &taffy::Layout) {
11443 let w = self.nodes[key as usize].view_style.borders.widths;
11444 let styled = [w.top, w.right, w.bottom, w.left]
11445 .iter()
11446 .any(|&v| v > Points::ZERO);
11447 let sides = self.layout.grid().filter(|_| styled).map(|_| {
11449 let b = l.border;
11450 [b.top, b.right, b.bottom, b.left]
11451 .iter()
11452 .enumerate()
11453 .fold(0u8, |m, (bit, &v)| m | (u8::from(v > 0.0) << bit))
11454 });
11455 let label = self.layout.labelled(layout);
11456 let node = &mut self.nodes[key as usize];
11457 if node.cell_border == sides && node.cell_label == label {
11458 return;
11459 }
11460 node.cell_border = sides;
11461 node.cell_label = label;
11462 let id = node.id;
11463 let style = self.mounted_view_style(key);
11464 self.mount.push(MountItem::ViewStyle { id, style });
11465 }
11466
11467 fn report_frame(&mut self, key: Key) {
11470 let node = &self.nodes[key as usize];
11471 if !node.frame.origin.x.0.is_nan() {
11472 self.events.push(crate::element::JsEvent::Event(
11473 node.id,
11474 EventKind::Layout,
11475 EventPayload::Layout(node.frame),
11476 ));
11477 }
11478 }
11479
11480 fn set_frame(&mut self, key: Key, frame: Bounds<Points>) {
11481 let node = &mut self.nodes[key as usize];
11482 if node.frame != frame {
11483 let resized = node.frame.size != frame.size;
11484 node.frame = frame;
11485 self.note_resized(key, resized);
11486 self.follow_changed |= !self.followers.is_empty();
11488 let node = &self.nodes[key as usize];
11489 let (id, is_text) = (node.id, node.kind == Kind::Text);
11490 if node.events.contains(EventKind::Layout) {
11491 self.events.push(crate::element::JsEvent::Event(
11492 id,
11493 EventKind::Layout,
11494 EventPayload::Layout(frame),
11495 ));
11496 }
11497 if node.created {
11498 self.mount.push(MountItem::Frame { id, frame });
11499 }
11500 let node = &self.nodes[key as usize];
11501 if self.track_tree_order
11503 && node.parent != NO_KEY
11504 && self.nodes[node.parent as usize].list.is_some()
11505 {
11506 self.tree_order_changed = true;
11507 }
11508 let node = &self.nodes[key as usize];
11509 let parent_perspective = self.perspective_steps(key) > 0;
11512 if node.created && (node.view_style.transform.has_fractions() || parent_perspective) {
11513 let style = self.mounted_view_style(key);
11514 self.mount.push(MountItem::ViewStyle { id, style });
11515 }
11516 if node.child_perspective.is_some() {
11517 let children = node.children.clone();
11519 for c in children {
11520 self.mark(c, dirty::VIEW);
11521 }
11522 }
11523 if is_text {
11524 self.queue_text(key);
11525 }
11526 let node = &self.nodes[key as usize];
11528 if node.kind == Kind::Canvas && node.drawing.as_ref().is_some_and(|d| d.fit().is_some())
11529 {
11530 self.fitted_pending.push(key);
11531 }
11532 }
11533 }
11534
11535 fn set_scroll_content(&mut self, key: Key, size: Size<Points>) {
11536 let node = &mut self.nodes[key as usize];
11537 let (id, rtl, kind, viewport) = (node.id, node.rtl, node.kind, node.frame.size.width.0);
11538 if let Some(scroll) = node.scroll.as_mut()
11539 && scroll.content != Some(size)
11540 {
11541 let old = scroll.content.replace(size);
11542 let batch = self.batches;
11545 let queued = scroll
11546 .content_item
11547 .filter(|&(b, _)| b == batch)
11548 .and_then(|(_, i)| {
11549 let at = self.mount.get(i..)?.iter().position(
11550 |m| matches!(m, MountItem::ScrollContent { id: queued, .. } if *queued == id),
11551 )?;
11552 Some(i + at)
11553 });
11554 let shrunk = old.is_some_and(|old| {
11557 if scroll.horizontal {
11558 size.width < old.width
11559 } else {
11560 size.height < old.height
11561 }
11562 });
11563 let keep_earlier = shrunk
11564 && queued.is_some_and(|j| {
11565 self.mount[j + 1..].iter().any(|item| match item {
11566 MountItem::ScrollBy { id: scrolled, .. } => *scrolled == id,
11567 MountItem::Command {
11568 id: scrolled,
11569 command: Command::ScrollTo { .. },
11570 } => *scrolled == id,
11571 _ => false,
11572 })
11573 });
11574 if let Some(j) = queued
11575 && !keep_earlier
11576 {
11577 self.mount[j] = MountItem::ScrollContent { id, size };
11578 }
11579 if queued.is_none() || keep_earlier {
11580 scroll.content_item = Some((batch, self.mount.len()));
11581 self.mount.push(MountItem::ScrollContent { id, size });
11582 }
11583 if kind == Kind::Scroll && scroll.horizontal && rtl {
11586 match old {
11587 None => self.commands.push((
11588 id,
11589 Command::ScrollTo {
11590 x: (size.width - Points(viewport)).max(Points::ZERO),
11591 y: Points::ZERO,
11592 animated: false,
11593 },
11594 )),
11595 Some(old) if old.width != size.width => {
11596 let dx = size.width - old.width;
11597 self.mount.push(MountItem::ScrollBy {
11598 id,
11599 dx,
11600 dy: Points::ZERO,
11601 });
11602 self.scroll_issued(key, PendingScroll::By(dx.0));
11603 }
11604 Some(_) => {}
11605 }
11606 }
11607 }
11608 }
11609
11610 fn update_lists(&mut self, relayout: bool) {
11613 let mut awaiting = std::mem::take(&mut self.awaiting_renders);
11616 self.cells_awaiting_renders(&mut awaiting);
11617 self.awaiting_renders = awaiting;
11618 for i in 0..self.lists.len() {
11619 let key = self.lists[i];
11620 if self.nodes[key as usize]
11622 .list
11623 .as_ref()
11624 .is_some_and(|l| l.parent)
11625 {
11626 continue;
11627 }
11628 self.update_list(key, relayout, None);
11629 }
11630 if !self.parent_lists.is_empty() {
11631 if self.outer_moved {
11632 self.resolve_outer();
11633 }
11634 for i in 0..self.parent_lists.len() {
11635 let key = self.parent_lists[i];
11636 if !self.nodes[key as usize].created {
11637 continue;
11638 }
11639 let Some(outer) = self.outer_input(key) else {
11641 continue;
11642 };
11643 self.update_list(key, relayout, Some(outer));
11644 }
11645 }
11646 if !self.sticky_nodes.is_empty()
11647 || !self.sticky_scrollers.is_empty()
11648 || !self.decorated.is_empty()
11649 {
11650 self.update_sticky_views(relayout);
11651 }
11652 if !self.sticky_views.is_empty() {
11653 self.send_page_sticky();
11654 }
11655 }
11656
11657 fn hide_attachments(&mut self, key: Key, hidden: bool) {
11661 let count = self.nodes[key as usize].children.len();
11662 for i in 0..count {
11663 let c = self.nodes[key as usize].children[i];
11664 let child = &self.nodes[c as usize];
11665 if child.is_overlay() {
11666 continue;
11667 }
11668 match child.kind {
11669 Kind::RawText | Kind::Overlay => {}
11670 Kind::Text => {
11671 let hidden = hidden || child.view_style.hidden;
11672 self.hide_attachments(c, hidden);
11673 }
11674 _ if child.layout.is_some() => self.set_hidden_in_text(c, hidden),
11675 _ => {}
11676 }
11677 }
11678 }
11679
11680 fn set_hidden_in_text(&mut self, key: Key, hidden: bool) {
11683 let node = &mut self.nodes[key as usize];
11684 if node.hidden_in_text == hidden {
11685 return;
11686 }
11687 node.hidden_in_text = hidden;
11688 if !node.created {
11689 return;
11691 }
11692 let (id, props) = (node.id, node.mounted_props());
11693 let style = self.mounted_view_style(key);
11694 self.mount.push(MountItem::ViewStyle { id, style });
11695 self.mount.push(MountItem::ViewProps { id, props });
11696 }
11697
11698 fn set_spare(&mut self, key: Key, spare: bool) {
11703 let node = &mut self.nodes[key as usize];
11704 if node.spare == spare {
11705 return;
11706 }
11707 node.spare = spare;
11708 self.follow_changed |= !self.followers.is_empty();
11710 let node = &self.nodes[key as usize];
11711 if !node.created {
11712 return;
11714 }
11715 let (id, props) = (node.id, node.mounted_props());
11716 let style = self.mounted_view_style(key);
11717 self.mount.push(MountItem::ViewStyle { id, style });
11718 self.mount.push(MountItem::ViewProps { id, props });
11719 }
11720
11721 fn set_left_behind(&mut self, key: Key, left_behind: bool) {
11726 let node = &mut self.nodes[key as usize];
11727 if node.left_behind == left_behind {
11728 return;
11729 }
11730 node.left_behind = left_behind;
11731 if !node.created || node.spare {
11732 return;
11735 }
11736 let (id, props) = (node.id, node.mounted_props());
11737 self.mount.push(MountItem::ViewProps { id, props });
11738 }
11739
11740 fn update_list(
11743 &mut self,
11744 key: Key,
11745 relayout: bool,
11746 outer: Option<parent_viewport::OuterInput>,
11747 ) {
11748 let moved = match &outer {
11749 Some(o) => self.nodes[key as usize]
11750 .list
11751 .as_mut()
11752 .expect("list")
11753 .set_outer(o.start, o.offset, o.viewport, o.max, o.settled),
11754 None => false,
11755 };
11756 let node = &self.nodes[key as usize];
11757 if !node.created {
11758 return;
11759 }
11760 if self.displays_none(key) {
11764 return;
11765 }
11766 let list = node.list.as_ref().expect("list");
11767 if !(relayout || moved || list.dirty || self.commands.iter().any(|c| c.0 == node.id)) {
11768 return;
11769 }
11770 let (id, events) = (node.id, node.events);
11771 let horizontal = list.horizontal;
11772 let l = self.rounded_layout(node.layout.expect("list layout"));
11773 let (main, cross) = match &outer {
11774 Some(o) => (o.viewport, o.cross),
11776 None if horizontal => (l.size.width, l.size.height),
11777 None => (l.size.height, l.size.width),
11778 };
11779 let main_of = |s: taffy::Size<f32>| if horizontal { s.width } else { s.height };
11780
11781 let mut ready = std::mem::take(&mut self.cells_scratch);
11783 ready.clear();
11784 ready.extend(
11785 list.slots
11786 .iter()
11787 .filter_map(|s| s.ready().map(|i| (i, s.cell))),
11788 );
11789 let extras = list.extras;
11790 self.nodes[key as usize]
11793 .list
11794 .as_mut()
11795 .expect("list")
11796 .loads_at_start = events.contains(EventKind::LoadMoreAtStart);
11797 let mut anchor = 0.0;
11798 for (kind, extra) in [ExtraKind::Header, ExtraKind::Footer, ExtraKind::Empty]
11802 .into_iter()
11803 .zip(extras)
11804 {
11805 if self.awaiting_renders.binary_search(&extra.cell).is_ok() {
11806 continue;
11807 }
11808 if let Some(cell_layout) = self.nodes.get(extra.cell as usize).and_then(|c| c.layout) {
11809 let size = main_of(self.rounded_layout(cell_layout).size);
11810 let list = self.nodes[key as usize].list.as_mut().expect("list");
11811 anchor += list.measured_extra(kind, size);
11812 }
11813 }
11814
11815 for &(index, cell) in &ready {
11816 if self.awaiting_renders.binary_search(&cell).is_ok() {
11821 continue;
11822 }
11823 if let Some(cell_layout) = self.nodes.get(cell as usize).and_then(|c| c.layout) {
11824 let size = main_of(self.rounded_layout(cell_layout).size);
11825 let list = self.nodes[key as usize].list.as_mut().expect("list");
11826 anchor += list.measured(index, size);
11827 }
11828 }
11829
11830 let inset = match (&outer, self.nodes[key as usize].scroll.as_deref()) {
11833 (None, Some(scroll)) => {
11834 let i = scroll.behavior.content_inset;
11835 if horizontal {
11836 (i.left.0, i.right.0)
11837 } else {
11838 (i.top.0, i.bottom.0)
11839 }
11840 }
11841 _ => (0.0, 0.0),
11842 };
11843 let list = self.nodes[key as usize].list.as_mut().expect("list");
11844 let grew = outer.is_none() && list.viewport > 0.0 && main > list.viewport;
11846 list.viewport = main;
11847 list.inset = inset;
11848 list.offset += anchor;
11849 let spliced = list.take_splice_anchor();
11853 anchor += spliced;
11854 let kept = anchor;
11855 let revealing = !self.scoped_layout.is_empty() && {
11859 let scoped = &self.scoped_layout;
11860 scoped.iter().any(|&(scope, ..)| {
11861 self.key(scope)
11862 .is_ok_and(|k| k != key && self.is_within(k, key))
11863 })
11864 };
11865 let list = self.nodes[key as usize].list.as_mut().expect("list");
11866 list.revealing = revealing;
11867 anchor += list.anchor_end(kept);
11870 let mut retarget = None;
11873 match list.follow_pin(anchor) {
11874 Follow::Stay => {}
11875 Follow::By(delta) => anchor += delta,
11876 Follow::To(offset) => retarget = Some(offset),
11877 }
11878 if list.take_animated_end() {
11883 let end = list.target_offset(PinTarget::End);
11884 list.pin(Some(PinTarget::End), end, true);
11885 retarget = Some(end);
11886 }
11887
11888 list.key_ends.clear();
11891 let mut outer_to = None;
11895 let mut scrolls_to = Vec::new();
11901 for (target, command) in &mut self.commands {
11902 if *target != id {
11903 continue;
11904 }
11905 let list = self.nodes[key as usize].list.as_mut().expect("list");
11906 let (pin, animated) = match *command {
11907 Command::ScrollToIndex {
11908 index,
11909 animated,
11910 view_position,
11911 view_offset,
11912 } => (
11913 Some(PinTarget::Index {
11914 index,
11915 view_position: view_position.0,
11916 view_offset: view_offset.0,
11917 }),
11918 animated,
11919 ),
11920 Command::ScrollToEnd { animated } => (Some(PinTarget::End), animated),
11921 Command::ScrollTo { animated, .. } => (None, animated),
11922 _ => continue,
11923 };
11924 let offset = match (pin, &*command) {
11925 (Some(pin), _) => list.target_offset(pin),
11926 (None, &Command::ScrollTo { x, y, .. }) => {
11927 let offset = if horizontal { x.0 } else { y.0 };
11928 if outer.is_some() {
11929 list.clamped(offset)
11930 } else {
11931 offset
11932 }
11933 }
11934 _ => continue,
11935 };
11936 list.pin(pin, offset, animated);
11938 retarget = None;
11940 if !animated {
11941 list.jump(offset);
11942 }
11943 if let Some(o) = &outer {
11944 outer_to = Some((o.start + offset, animated));
11945 continue;
11946 }
11947 scrolls_to.push((offset, animated));
11948 let (x, y) = if horizontal {
11949 (Points(offset), Points::ZERO)
11950 } else {
11951 (Points::ZERO, Points(offset))
11952 };
11953 *command = Command::ScrollTo { x, y, animated };
11954 }
11955 if outer_to.is_some() {
11956 self.commands.retain(|(target, command)| {
11958 *target != id
11959 || !matches!(
11960 command,
11961 Command::ScrollTo { .. }
11962 | Command::ScrollToIndex { .. }
11963 | Command::ScrollToEnd { .. }
11964 )
11965 });
11966 }
11967 if let (Some(offset), Some(o)) = (retarget, &outer) {
11968 outer_to = Some((o.start + offset, true));
11969 } else if let Some(offset) = retarget {
11970 scrolls_to.push((offset, true));
11971 let (x, y) = if horizontal {
11972 (Points(offset), Points::ZERO)
11973 } else {
11974 (Points::ZERO, Points(offset))
11975 };
11976 let command = Command::ScrollTo {
11977 x,
11978 y,
11979 animated: true,
11980 };
11981 self.commands.push((id, command));
11982 }
11983
11984 let paced = !self.components.is_virtual_list(id);
11987 let list = self.nodes[key as usize].list.as_mut().expect("list");
11988 list.paced = paced;
11989 let mut binds = Vec::new();
11990 let edges = list.update_window(&mut binds);
11991 if edges.end {
11992 self.events.push(crate::element::JsEvent::Event(
11993 id,
11994 EventKind::LoadMore,
11995 EventPayload::None,
11996 ));
11997 }
11998 if edges.start && events.contains(EventKind::LoadMoreAtStart) {
11999 self.events.push(crate::element::JsEvent::Event(
12000 id,
12001 EventKind::LoadMoreAtStart,
12002 EventPayload::None,
12003 ));
12004 }
12005 if !binds.is_empty() {
12006 self.list_binds.push(ListBind { list: id, binds });
12007 }
12008 if list.paced && list.has_paced() && !self.paced_lists.contains(&id) {
12009 self.paced_lists.push(id);
12010 }
12011 if events.contains(EventKind::ViewableItemsChange) {
12012 let viewable = list.viewable_items();
12013 if viewable != list.viewable {
12014 list.viewable = viewable;
12015 let (first, last) = viewable.map_or((-1.0, -1.0), |(f, l)| (f as f64, l as f64));
12016 self.events.push(crate::element::JsEvent::Event(
12017 id,
12018 EventKind::ViewableItemsChange,
12019 EventPayload::Map(vec![
12020 ("first", PayloadValue::Number(first)),
12021 ("last", PayloadValue::Number(last)),
12022 ]),
12023 ));
12024 }
12025 }
12026
12027 let list = self.nodes[key as usize].list.as_ref().expect("list");
12031 let sticky = list.sticky_enabled();
12032 ready.clear();
12033 ready.extend(
12034 list.slots
12035 .iter()
12036 .filter_map(|s| s.ready().map(|i| (i, s.cell))),
12037 );
12038 for &(index, cell) in &ready {
12043 if self.awaiting_renders.binary_search(&cell).is_ok() {
12044 continue;
12045 }
12046 if let Some(cell_layout) = self.nodes.get(cell as usize).and_then(|c| c.layout) {
12047 let size = main_of(self.rounded_layout(cell_layout).size);
12048 let list = self.nodes[key as usize].list.as_mut().expect("list");
12049 list.measured_unknown(index, size);
12050 }
12051 }
12052 let list = self.nodes[key as usize].list.as_ref().expect("list");
12053 let content_len = list.content_len();
12054 let blocks = list.blocks();
12055 let (window_start, window_end) = list.render_window();
12066 let motion = outer.is_none() && self.list_motion.active();
12067 if motion {
12068 let cells: Vec<Key> = list
12069 .slots
12070 .iter()
12071 .map(|s| s.cell)
12072 .chain(list.extras.iter().map(|e| e.cell))
12073 .collect();
12074 self.note_cell_starts(cells);
12075 }
12076 let list = self.nodes[key as usize].list.as_ref().expect("list");
12077 let inset = outer.map_or((0.0, 0.0), |o| o.inset);
12080 let unbound: Vec<Key> = list
12081 .slots
12082 .iter()
12083 .filter(|s| s.ready().is_none() && s.cell != u32::MAX)
12084 .map(|s| s.cell)
12085 .collect();
12086 let changed = std::mem::take(
12087 &mut self.nodes[key as usize]
12088 .list
12089 .as_mut()
12090 .expect("list")
12091 .items_changed,
12092 );
12093 for cell in unbound {
12094 let frame = self.nodes[cell as usize].frame;
12095 if frame.size.width.0.is_nan() {
12096 self.set_spare(cell, true);
12098 continue;
12099 }
12100 let (start, size) = if horizontal {
12101 (frame.origin.x.0 - inset.0, frame.size.width.0)
12102 } else {
12103 (frame.origin.y.0 - inset.0, frame.size.height.0)
12104 };
12105 if start + size <= window_start || start >= window_end {
12106 if changed {
12107 self.set_spare(cell, true);
12108 } else {
12109 self.set_left_behind(cell, true);
12110 }
12111 continue;
12112 }
12113 self.set_spare(cell, true);
12114 let away = if horizontal {
12115 Bounds {
12116 origin: Point::new(Points(-HIDDEN), frame.origin.y),
12117 ..frame
12118 }
12119 } else {
12120 Bounds {
12121 origin: Point::new(frame.origin.x, Points(-HIDDEN)),
12122 ..frame
12123 }
12124 };
12125 if frame != away {
12126 self.set_frame(cell, away);
12127 self.nodes[key as usize]
12128 .list
12129 .as_mut()
12130 .expect("list")
12131 .unplace(cell);
12132 }
12133 }
12134 let mut sticky_cells = Vec::new();
12135 let place = |this: &mut Self, cell: Key, at: f32, row: f32, (x, width): (f32, f32)| {
12136 let cell_layout = this.nodes.get(cell as usize).and_then(|c| c.layout)?;
12137 let size = this.rounded_layout(cell_layout).size;
12138 let list = this.nodes[key as usize].list.as_ref().expect("list");
12139 let mut main_at = list.to_content(at, row.max(main_of(size)));
12140 let mut x = x;
12141 if outer.is_some() {
12142 main_at += inset.0;
12143 x += inset.1;
12144 }
12145 let cell_cross = if horizontal { size.height } else { size.width };
12146 x = list.align_cross(x, width, cell_cross);
12147 let frame = if horizontal {
12148 rect(main_at, x, size.width, cell_cross)
12149 } else {
12150 rect(x, main_at, cell_cross, size.height)
12151 };
12152 this.set_frame(cell, frame);
12153 this.set_left_behind(cell, false);
12154 this.set_spare(cell, false);
12155 if std::mem::take(&mut this.nodes[cell as usize].relaid) {
12156 let waits = {
12161 let node = &this.nodes[cell as usize];
12162 !node.created && node.culled
12163 };
12164 let children = std::mem::take(&mut this.nodes[cell as usize].children);
12165 for &child in &children {
12166 if waits {
12167 let node = &mut this.nodes[child as usize];
12168 if !node.created && !node.is_layout_root() {
12169 node.culled = true;
12170 }
12171 }
12172 this.emit_frames(child);
12173 }
12174 this.nodes[cell as usize].children = children;
12175 this.update_overflow(cell);
12176 this.cells_framed = true;
12177 }
12178 Some(main_of(size))
12179 };
12180 let unit = self
12184 .layout
12185 .grid()
12186 .map(|g| if horizontal { g.height } else { g.width });
12187 let columns_cross = {
12188 let laid = self.nodes[key as usize]
12189 .list
12190 .as_ref()
12191 .expect("list")
12192 .cells_cross;
12193 if unit.is_some() && laid.is_finite() {
12194 laid
12195 } else {
12196 cross
12197 }
12198 };
12199 let mut placed = list_motion::Placed::default();
12200 for &(index, cell) in &ready {
12201 let list = self.nodes[key as usize].list.as_ref().expect("list");
12202 let (at, row) = (list.item_at(index), list.row_extent(index));
12203 let column = list.column(columns_cross, list.column_of(index), unit);
12204 let Some(size) = place(self, cell, at, row, column) else {
12205 continue;
12206 };
12207 let list = self.nodes[key as usize].list.as_mut().expect("list");
12208 if list.place(index) {
12209 placed.new.push(cell);
12210 } else {
12211 placed.kept.push(cell);
12212 }
12213 let list = self.nodes[key as usize].list.as_ref().expect("list");
12214 if sticky && list.sticky.binary_search(&index).is_ok() {
12215 let range = list.sticky_range(index, self.nodes[cell as usize].id, size);
12216 sticky_cells.push(range);
12217 }
12218 }
12219 let full = self.nodes[key as usize]
12220 .list
12221 .as_ref()
12222 .expect("list")
12223 .full_width(columns_cross);
12224 for (extra, at) in extras
12225 .iter()
12226 .zip([blocks.header, blocks.footer, blocks.body])
12227 {
12228 if extra.cell != u32::MAX && place(self, extra.cell, at, 0.0, full).is_some() {
12229 placed.kept.push(extra.cell);
12230 }
12231 }
12232 self.cells_scratch = ready;
12233
12234 sticky_cells.sort_by_key(|c| c.cell);
12235 let list = self.nodes[key as usize].list.as_mut().expect("list");
12236 if let Some(o) = &outer {
12237 if sticky_cells != list.sent_sticky {
12239 let old = std::mem::replace(&mut list.sent_sticky, sticky_cells);
12240 self.page_sticky_changed(key, o.view, &old);
12241 }
12242 } else if sticky_cells != list.sent_sticky {
12243 list.sent_sticky = sticky_cells;
12248 self.sticky_views.push(key);
12249 }
12250
12251 if let Some(o) = &outer {
12252 if anchor != 0.0 {
12256 self.ask_outer(o.view, None, anchor);
12257 }
12258 if outer_to.is_some() {
12259 self.ask_outer(o.view, outer_to, 0.0);
12260 }
12261 self.sync_spacer(key, false);
12262 return;
12263 }
12264 let content = if horizontal {
12265 size_pt(content_len, cross)
12266 } else {
12267 size_pt(cross, content_len)
12268 };
12269 let old_len = self.nodes[key as usize]
12272 .scroll
12273 .as_ref()
12274 .and_then(|s| s.content)
12275 .map_or(0.0, |c| if horizontal { c.width.0 } else { c.height.0 });
12276 let list = self.nodes[key as usize].list.as_mut().expect("list");
12277 if anchor != 0.0 {
12278 list.issue_scroll_by(anchor);
12279 }
12280 for (offset, animated) in scrolls_to {
12281 list.issue_scroll_to(offset, animated);
12282 }
12283 let scroll_by = (anchor != 0.0).then(|| {
12284 let (dx, dy) = if horizontal {
12285 (Points(anchor), Points::ZERO)
12286 } else {
12287 (Points::ZERO, Points(anchor))
12288 };
12289 MountItem::ScrollBy { id, dx, dy }
12290 });
12291 let frame_at = grew
12296 .then(|| {
12297 self.mount
12298 .iter()
12299 .position(|m| matches!(m, MountItem::Frame { id: f, .. } if *f == id))
12300 })
12301 .flatten();
12302 match (scroll_by, frame_at) {
12303 (Some(item), Some(at)) if content_len > old_len => {
12308 self.set_scroll_content(key, content);
12309 match self
12310 .mount
12311 .iter()
12312 .rposition(|m| matches!(m, MountItem::ScrollContent { id: c, .. } if *c == id))
12313 {
12314 Some(queued) if queued > at => {
12315 let grown = self.mount.remove(queued);
12316 self.mount.insert(at, grown);
12317 self.mount.insert(at + 1, item);
12318 }
12319 _ => self.mount.insert(at, item),
12320 }
12321 }
12322 (Some(item), Some(at)) => {
12323 self.mount.insert(at, item);
12324 self.set_scroll_content(key, content);
12325 }
12326 (Some(item), None) if content_len < old_len => {
12327 self.mount.push(item);
12328 self.set_scroll_content(key, content);
12329 }
12330 (item, _) => {
12331 self.set_scroll_content(key, content);
12332 self.mount.extend(item);
12333 }
12334 }
12335 if motion {
12336 self.move_list_cells(key, id, horizontal, anchor, placed);
12337 }
12338 }
12339}
12340
12341const HIDDEN: f32 = 1.0e6;
12343
12344fn position_from_ends<T: PartialEq>(items: &[T], x: &T) -> Option<(usize, usize)> {
12347 let (mut front, mut back) = (0, items.len());
12348 while front < back {
12349 if items[front] == *x {
12350 return Some((front, 2 * front + 1));
12351 }
12352 back -= 1;
12353 if items[back] == *x {
12354 return Some((back, 2 * (items.len() - back)));
12355 }
12356 front += 1;
12357 }
12358 None
12359}
12360
12361fn position_near<T: PartialEq>(items: &[T], x: &T, near: usize) -> Option<(usize, usize)> {
12365 let near = near.min(items.len().checked_sub(1)?);
12366 let mut looked = 0;
12367 for distance in 0..items.len() {
12369 let below = near.checked_sub(distance);
12370 let above = (distance > 0)
12371 .then_some(near + distance)
12372 .filter(|&i| i < items.len());
12373 for i in [below, above].into_iter().flatten() {
12374 looked += 1;
12375 if items[i] == *x {
12376 return Some((i, looked));
12377 }
12378 }
12379 }
12380 None
12381}
12382
12383fn round(value: f32, ratio: f32) -> f32 {
12391 (pixel(value, ratio) / f64::from(ratio)) as f32
12392}
12393
12394fn pixel(value: f32, ratio: f32) -> f64 {
12401 (snapped(value, ratio) + 0.5).floor()
12402}
12403
12404fn snapped(value: f32, ratio: f32) -> f64 {
12406 let p = f64::from(value) * f64::from(ratio);
12407 (p * 64.0).round() / 64.0
12408}
12409
12410fn edges(start: f32, len: f32, ratio: f32) -> (f64, f64) {
12419 let end = start + len;
12420 let (from, to) = (pixel(start, ratio), pixel(end, ratio));
12421 let (a, b) = (snapped(start, ratio), snapped(end, ratio));
12422 if from != to || b <= a {
12423 (from, to)
12424 } else if a + b < 2.0 * from {
12425 (from - 1.0, from)
12426 } else {
12427 (from, from + 1.0)
12428 }
12429}
12430
12431#[derive(Clone, Copy, Debug, Default, PartialEq)]
12438struct Origin {
12439 at: taffy::Point<f32>,
12440 back: taffy::Point<bool>,
12441}
12442
12443impl Origin {
12444 fn of(at: taffy::Point<f32>, size: taffy::Size<f32>, ratio: taffy::Size<f32>) -> Origin {
12446 let back =
12447 |start: f32, len: f32, ratio: f32| edges(start, len, ratio).0 < pixel(start, ratio);
12448 Origin {
12449 at,
12450 back: taffy::Point {
12451 x: back(at.x, size.width, ratio.width),
12452 y: back(at.y, size.height, ratio.height),
12453 },
12454 }
12455 }
12456
12457 fn lead(self, ratio: taffy::Size<f32>) -> taffy::Point<f64> {
12459 taffy::Point {
12460 x: pixel(self.at.x, ratio.width) - f64::from(u8::from(self.back.x)),
12461 y: pixel(self.at.y, ratio.height) - f64::from(u8::from(self.back.y)),
12462 }
12463 }
12464
12465 fn to(self, to: Origin, ratio: taffy::Size<f32>) -> taffy::Point<f32> {
12468 let (from, to) = (self.lead(ratio), to.lead(ratio));
12469 taffy::Point {
12470 x: ((to.x - from.x) / f64::from(ratio.width)) as f32,
12471 y: ((to.y - from.y) / f64::from(ratio.height)) as f32,
12472 }
12473 }
12474}
12475
12476fn span(from: f32, to: f32, ratio: f32) -> f32 {
12483 ((pixel(to, ratio) - pixel(from, ratio)) / f64::from(ratio)) as f32
12484}
12485
12486fn typeset_width(rounded: Points, measured: Points, ratio: f32) -> Points {
12497 if measured.0.is_finite() && ((measured.0 - rounded.0) * ratio).abs() < 1.0 {
12498 measured
12499 } else {
12500 rounded
12501 }
12502}
12503
12504fn ceil_to_pixel(value: Points, ratio: f32) -> Points {
12511 let up = (value.0 * ratio - 1.0e-3).ceil().max(0.0) / ratio;
12512 Points(if up < value.0 { up + 1.0 / ratio } else { up })
12513}
12514
12515fn scroll_extent(l: &taffy::Layout, horizontal: bool) -> Size<Points> {
12526 let o = l.scrollable_overflow_rect;
12527 let (width, height) = (l.border.left + o.right(), l.border.top + o.bottom());
12528 if horizontal {
12529 size_pt(width, height.max(l.size.height))
12530 } else {
12531 size_pt(width.max(l.size.width), height)
12532 }
12533}
12534
12535fn rounded(layout: &taffy::Layout, origin: Origin, ratio: taffy::Size<f32>) -> taffy::Layout {
12548 let mut out = *layout;
12549 let (x, y) = (
12550 origin.at.x + layout.location.x,
12551 origin.at.y + layout.location.y,
12552 );
12553 let (rx, ry) = (ratio.width, ratio.height);
12554 let (x0, x1) = edges(x, layout.size.width, rx);
12555 let (y0, y1) = edges(y, layout.size.height, ry);
12556 let lead = origin.lead(ratio);
12557 let points = |pixels: f64, ratio: f32| (pixels / f64::from(ratio)) as f32;
12558 out.location.x = points(x0 - lead.x, rx);
12559 out.location.y = points(y0 - lead.y, ry);
12560 out.size.width = points(x1 - x0, rx);
12561 out.size.height = points(y1 - y0, ry);
12562 out.scrollbar_size.width = round(layout.scrollbar_size.width, rx);
12563 out.scrollbar_size.height = round(layout.scrollbar_size.height, ry);
12564 out.border.left = span(x, x + layout.border.left, rx);
12565 out.border.right = span(
12566 x + layout.size.width - layout.border.right,
12567 x + layout.size.width,
12568 rx,
12569 );
12570 out.border.top = span(y, y + layout.border.top, ry);
12571 out.border.bottom = span(
12572 y + layout.size.height - layout.border.bottom,
12573 y + layout.size.height,
12574 ry,
12575 );
12576 let (left, right) = (
12584 x + layout.border.left,
12585 x + layout.size.width - layout.border.right,
12586 );
12587 let (top, bottom) = (
12588 y + layout.border.top,
12589 y + layout.size.height - layout.border.bottom,
12590 );
12591 out.padding.left = span(left, left + layout.padding.left, rx);
12592 out.padding.right = span(right - layout.padding.right, right, rx);
12593 out.padding.top = span(top, top + layout.padding.top, ry);
12594 out.padding.bottom = span(bottom - layout.padding.bottom, bottom, ry);
12595 let o = layout.scrollable_overflow_rect;
12596 out.scrollable_overflow_rect = taffy::ScrollableOverflow::new(
12599 taffy::Rect {
12600 left: points(pixel(x + o.left(), rx) - x0, rx).min(0.0),
12601 right: points(pixel(x + o.right(), rx) - x0, rx).max(0.0),
12602 top: points(pixel(y + o.top(), ry) - y0, ry).min(0.0),
12603 bottom: points(pixel(y + o.bottom(), ry) - y0, ry).max(0.0),
12604 },
12605 o.is_reversed(),
12606 );
12607 out
12608}
12609
12610fn content_box(l: &taffy::Layout) -> Bounds<Points> {
12611 rect(
12612 l.padding.left + l.border.left,
12613 l.padding.top + l.border.top,
12614 (l.size.width - l.padding.left - l.padding.right - l.border.left - l.border.right).max(0.0),
12615 (l.size.height - l.padding.top - l.padding.bottom - l.border.top - l.border.bottom)
12616 .max(0.0),
12617 )
12618}
12619
12620#[derive(Default)]
12622struct ImageLimits {
12623 min: taffy::Size<Option<f32>>,
12624 max: taffy::Size<Option<f32>>,
12625}
12626
12627impl ImageLimits {
12628 fn width(&self, w: f32) -> f32 {
12629 clamp_side(w, self.min.width, self.max.width)
12630 }
12631
12632 fn height(&self, h: f32) -> f32 {
12633 clamp_side(h, self.min.height, self.max.height)
12634 }
12635}
12636
12637fn clamp_side(v: f32, min: Option<f32>, max: Option<f32>) -> f32 {
12638 let v = max.map_or(v, |max| v.min(max));
12639 min.map_or(v, |min| v.max(min))
12640}
12641
12642fn image_size(
12645 natural: Size<Points>,
12646 w: Option<f32>,
12647 h: Option<f32>,
12648 limits: &ImageLimits,
12649) -> taffy::Size<f32> {
12650 let ratio = if natural.height > Points::ZERO {
12651 natural.width / natural.height
12652 } else {
12653 1.0
12654 };
12655 let (width, height) = match (w, h) {
12656 (Some(w), None) => (w, limits.height(w / ratio)),
12657 (None, Some(h)) => (limits.width(h * ratio), h),
12658 (Some(w), Some(h)) => (w, h),
12659 (None, None) => {
12660 let width = limits.width(natural.width.0);
12661 let height = width / ratio;
12662 let clamped = limits.height(height);
12663 if clamped == height {
12664 (width, height)
12665 } else {
12666 (limits.width(clamped * ratio), clamped)
12667 }
12668 }
12669 };
12670 taffy::Size { width, height }
12671}
12672
12673fn keep_geometry(
12680 engine: &Option<Rc<dyn crate::text::GeometryEngine>>,
12681 geometries: &mut rustc_hash::FxHashMap<NodeId, crate::text::TextGeometry>,
12682 id: NodeId,
12683 layout: &TextLayout,
12684 text: &Arc<AttributedText>,
12685 spacers: &[u32],
12686) {
12687 if let Some(engine) = engine.as_ref().filter(|_| id % 2 == 1) {
12688 geometries.insert(
12689 id,
12690 crate::text::TextGeometry::new(engine.clone(), layout.clone(), text.clone(), spacers),
12691 );
12692 }
12693}
12694
12695fn lines_in_box<M: TextEngine>(
12700 engine: &M,
12701 cache: &mut MeasureCache,
12702 cx: &mut TextContext<M::Prepared>,
12703 width: Points,
12704 height: Points,
12705) -> Option<u32> {
12706 const SLACK: f32 = 0.5;
12708 if cx.text.no_wrap || cx.text.text.is_empty() {
12709 return None;
12710 }
12711 let measured = measure_text(engine, cache, cx, Some(width.0));
12712 if measured.height.0 <= height.0 + SLACK {
12713 return None;
12714 }
12715 let prepared = cx
12716 .prepared
12717 .get_or_insert_with(|| engine.prepare_with(&cx.text, &cx.alignments, &cx.options));
12718 let layout = engine.layout(prepared, Size::new(width, measured.height));
12719 let lines = engine.lines(&layout);
12720 let (fit, total) = match lines.as_slice() {
12721 [] => return None,
12722 [line] if line.height > Points::ZERO => (
12725 ((height.0 + SLACK) / line.height.0).floor() as u32,
12726 (measured.height.0 / line.height.0).round() as u32,
12727 ),
12728 [_] => return None,
12729 lines => (
12730 lines
12731 .iter()
12732 .take_while(|l| (l.y + l.height).0 <= height.0 + SLACK)
12733 .count() as u32,
12734 lines.len() as u32,
12735 ),
12736 };
12737 let fit = fit.max(1);
12738 let limit = cx.text.max_lines;
12739 (fit < total && (limit == 0 || fit < limit)).then_some(fit)
12740}
12741
12742fn text_lines<M: TextEngine>(
12743 engine: &M,
12744 text: &AttributedText,
12745 layout: &TextLayout,
12746) -> EventPayload {
12747 let units: Vec<u16> = text.text.encode_utf16().collect();
12748 let mut lines = engine.lines(layout);
12749 for line in &mut lines {
12750 let (start, end) = (line.start as usize, (line.end as usize).min(units.len()));
12751 if start < end {
12752 line.text = String::from_utf16_lossy(&units[start..end]);
12753 }
12754 }
12755 EventPayload::TextLayout(lines)
12756}
12757
12758fn fitted<M: TextEngine>(
12762 engine: &M,
12763 text: &AttributedText,
12764 alignments: &crate::AttachmentAlignments,
12765 options: &crate::TextOptions,
12766 size: Size<Points>,
12767 min: f32,
12768) -> AttributedText {
12769 let scaled = |scale: f32| {
12770 let mut t = text.clone();
12771 if let Some(strut) = &mut t.paragraph_strut {
12772 strut.font_size *= scale;
12773 strut.line_height *= scale;
12774 }
12775 for span in &mut t.spans {
12776 span.style.font_size *= scale;
12777 span.style.line_height *= scale;
12778 span.style.letter_spacing *= scale;
12779 }
12780 t
12781 };
12782 let fits = |t: &AttributedText| {
12783 let all = AttributedText {
12786 max_lines: 0,
12787 ..t.clone()
12788 };
12789 let full = engine.measure(
12790 &engine.prepare_with(&all, alignments, options),
12791 Some(size.width),
12792 );
12793 let limited = if t.max_lines > 0 {
12794 engine
12795 .measure(
12796 &engine.prepare_with(t, alignments, options),
12797 Some(size.width),
12798 )
12799 .height
12800 } else {
12801 Points(f32::INFINITY)
12802 };
12803 full.height <= size.height.min(limited) + Points(0.5)
12804 && full.width <= size.width + Points(0.5)
12805 };
12806 if fits(text) {
12807 return text.clone();
12808 }
12809 let (mut lo, mut hi) = (min, 1.0f32);
12810 if !fits(&scaled(lo)) {
12811 return scaled(lo);
12812 }
12813 for _ in 0..7 {
12814 let mid = (lo + hi) / 2.0;
12815 if fits(&scaled(mid)) {
12816 lo = mid;
12817 } else {
12818 hi = mid;
12819 }
12820 }
12821 scaled(lo)
12822}
12823
12824fn estimate_text(text: &AttributedText, max_width: Option<f32>) -> Size<Points> {
12831 let (_, line) = text_metrics(text);
12832 let mut width = 0.0f32;
12833 let mut lines = 0u32;
12834 for paragraph in text.text.split('\n') {
12835 let w = estimate_line(text, paragraph).0;
12836 width = width.max(match max_width {
12837 Some(max) => w.min(max),
12838 None => w,
12839 });
12840 lines += match max_width {
12841 Some(max) if max > 0.0 && !text.no_wrap => (w / max).ceil().max(1.0) as u32,
12842 _ => 1,
12843 };
12844 }
12845 if text.max_lines > 0 {
12846 lines = lines.min(text.max_lines);
12847 }
12848 Size::new(Points(width.ceil()), Points((lines as f32 * line).ceil()))
12849}
12850
12851fn estimate_line(text: &AttributedText, run: &str) -> Points {
12854 let (size, _) = text_metrics(text);
12855 Points(
12856 run.chars()
12857 .map(|c| {
12858 if c as u32 >= 0x2e80 {
12859 size
12860 } else {
12861 size * 0.55
12862 }
12863 })
12864 .sum(),
12865 )
12866}
12867
12868fn text_metrics(text: &AttributedText) -> (f32, f32) {
12871 let (font, line) = text.approx_metrics();
12872 (font.0, line.0)
12873}
12874
12875fn min_content_width<M: TextEngine>(
12876 engine: &M,
12877 cache: &mut MeasureCache,
12878 cx: &mut TextContext<M::Prepared>,
12879) -> Points {
12880 if let Some(width) = cx.min_content {
12881 return width;
12882 }
12883 if cx.deferred {
12884 return cx
12886 .text
12887 .text
12888 .split_whitespace()
12889 .map(|word| estimate_line(&cx.text, word))
12890 .fold(Points::ZERO, Points::max);
12891 }
12892 let text = &cx.text;
12893 let mut offsets = Vec::with_capacity(text.text.chars().count() + 1);
12894 let mut utf16 = 0u32;
12895 for (byte, ch) in text.text.char_indices() {
12896 offsets.push((utf16, byte));
12897 utf16 += ch.len_utf16() as u32;
12898 }
12899 offsets.push((utf16, text.text.len()));
12900 let byte_at = |offset: u32| {
12901 offsets[offsets
12902 .binary_search_by_key(&offset, |&(at, _)| at)
12903 .unwrap()]
12904 .1
12905 };
12906 let mut start = 0usize;
12907 let mut width = Points::ZERO;
12908 for (end, _) in unicode_linebreak::linebreaks(&text.text) {
12909 let word = text.text[start..end].trim_end_matches([' ', '\t', '\n', '\r', '\u{000c}']);
12910 let from = offsets[offsets
12911 .binary_search_by_key(&start, |&(_, byte)| byte)
12912 .unwrap()]
12913 .0;
12914 let to = from + word.encode_utf16().count() as u32;
12915 if from < to {
12916 let mut part = AttributedText {
12917 no_wrap: true,
12918 rtl: text.rtl,
12919 writing_direction: text.writing_direction,
12920 ..Default::default()
12921 };
12922 for span in &text.spans {
12923 let (lo, hi) = (from.max(span.start), to.min(span.end));
12924 if lo < hi {
12925 part.push(&text.text[byte_at(lo)..byte_at(hi)], span.style);
12926 }
12927 }
12928 for attachment in &text.attachments {
12929 if (from..to).contains(&attachment.index) {
12930 let mut attachment = *attachment;
12931 attachment.index -= from;
12932 part.attachments.push(attachment);
12933 }
12934 }
12935 let hash = part.layout_hash();
12936 let measured = cache.get(hash, None).unwrap_or_else(|| {
12937 let measured = engine.measure(&engine.prepare(&part), None);
12938 cache.insert(hash, None, measured);
12939 measured
12940 });
12941 width = width.max(measured.width);
12942 }
12943 start = end;
12944 }
12945 cx.min_content = Some(width);
12946 width
12947}
12948
12949fn leaf_measure<'a, M: TextEngine>(
12953 engine: &'a M,
12954 cache: &'a mut MeasureCache,
12955) -> impl FnMut(
12956 taffy::LayoutInput,
12957 LayoutId,
12958 Option<&mut LeafContext<M::Prepared>>,
12959 &taffy::Style,
12960 layout_tree::Aligned,
12961) -> taffy::LayoutOutput
12962+ 'a {
12963 move |input, _, cx, style, aligned| measure_leaf(engine, cache, input, cx, style, aligned)
12964}
12965
12966fn measure_leaf<M: TextEngine>(
12974 engine: &M,
12975 cache: &mut MeasureCache,
12976 input: taffy::LayoutInput,
12977 mut cx: Option<&mut LeafContext<M::Prepared>>,
12978 style: &taffy::Style,
12979 aligned: layout_tree::Aligned,
12980) -> taffy::LayoutOutput {
12981 let mut output = measure_leaf_size(engine, cache, input, cx.as_deref_mut(), style);
12982 if aligned == layout_tree::Aligned::Baseline
12985 && input.run_mode == taffy::RunMode::PerformLayout
12986 && let Some(LeafContext::Text(cx)) = cx
12987 {
12988 use taffy::util::ResolveOrZero;
12989 let resolve = |_: taffy::CalcHandle, _: f32| 0.0;
12990 let padding = style
12991 .padding
12992 .resolve_or_zero(input.parent_size.width, resolve);
12993 let border = style
12994 .border
12995 .resolve_or_zero(input.parent_size.width, resolve);
12996 let width = output.size.width - padding.left - padding.right - border.left - border.right;
12997 if let Some(baseline) = text_baseline(engine, cx, width.max(0.0)) {
12998 output.baselines.first = Some(padding.top + border.top + baseline.0);
12999 }
13000 }
13001 output
13002}
13003
13004fn text_baseline<M: TextEngine>(
13008 engine: &M,
13009 cx: &mut TextContext<M::Prepared>,
13010 width: f32,
13011) -> Option<Points> {
13012 if cx.deferred {
13013 return None;
13014 }
13015 if let Some((w, baseline)) = cx.baseline
13016 && w == width
13017 {
13018 return baseline;
13019 }
13020 let prepared = cx
13021 .prepared
13022 .get_or_insert_with(|| engine.prepare_with(&cx.text, &cx.alignments, &cx.options));
13023 let baseline = engine.first_baseline(prepared, Points(width));
13024 cx.baseline = Some((width, baseline));
13025 baseline
13026}
13027
13028fn measure_leaf_size<M: TextEngine>(
13030 engine: &M,
13031 cache: &mut MeasureCache,
13032 input: taffy::LayoutInput,
13033 cx: Option<&mut LeafContext<M::Prepared>>,
13034 style: &taffy::Style,
13035) -> taffy::LayoutOutput {
13036 use taffy::{MaybeResolve as _, ResolveOrZero as _};
13037 let input_max_height = match &cx {
13043 Some(LeafContext::Text(cx)) if cx.field.is_some() => {
13044 let parent = input.parent_size;
13045 let max: Option<f32> = style
13046 .max_size
13047 .height
13048 .maybe_resolve(parent.height, |_, _| 0.0);
13049 max.map(|max| {
13050 let inset = (style.padding.resolve_or_zero(parent.width, |_, _| 0.0)
13051 + style.border.resolve_or_zero(parent.width, |_, _| 0.0))
13052 .vertical_axis_sum();
13053 match style.box_sizing {
13054 taffy::BoxSizing::BorderBox => (max - inset).max(0.0),
13055 taffy::BoxSizing::ContentBox => max,
13056 }
13057 })
13058 }
13059 _ => None,
13060 };
13061 let inset = {
13067 let parent = input.parent_size.width;
13068 let mut inset = (style.padding.resolve_or_zero(parent, |_, _| 0.0)
13069 + style.border.resolve_or_zero(parent, |_, _| 0.0))
13070 .sum_axes();
13071 if style.overflow.y == taffy::Overflow::Scroll {
13073 inset.width += style.scrollbar_width;
13074 }
13075 if style.overflow.x == taffy::Overflow::Scroll {
13076 inset.height += style.scrollbar_width;
13077 }
13078 inset
13079 };
13080 let image = matches!(cx, Some(LeafContext::Image(_)));
13081 let image_limits = match &cx {
13086 Some(LeafContext::Image(Some(_))) => {
13087 let parent = input.parent_size;
13088 let content = |v: Option<f32>, inset: f32| {
13089 v.map(|v| match style.box_sizing {
13090 taffy::BoxSizing::BorderBox => (v - inset).max(0.0),
13091 taffy::BoxSizing::ContentBox => v,
13092 })
13093 };
13094 let inset = (style.padding.resolve_or_zero(parent.width, |_, _| 0.0)
13095 + style.border.resolve_or_zero(parent.width, |_, _| 0.0))
13096 .sum_axes();
13097 let min: taffy::Size<Option<f32>> = style.min_size.maybe_resolve(parent, |_, _| 0.0);
13098 let max: taffy::Size<Option<f32>> = style.max_size.maybe_resolve(parent, |_, _| 0.0);
13099 ImageLimits {
13100 min: taffy::Size {
13101 width: content(min.width, inset.width),
13102 height: content(min.height, inset.height),
13103 },
13104 max: taffy::Size {
13105 width: content(max.width, inset.width),
13106 height: content(max.height, inset.height),
13107 },
13108 }
13109 }
13110 _ => ImageLimits::default(),
13111 };
13112 let mut output = taffy::compute_leaf_layout(
13113 input,
13114 style,
13115 |_, _| 0.0,
13116 |known, available| {
13117 let known = taffy::Size {
13118 width: known.width.map(|w| (w - inset.width).max(0.0)),
13119 height: known.height.map(|h| (h - inset.height).max(0.0)),
13120 };
13121 let available = taffy::Size {
13128 width: available.width.map_definite_value(|w| w.max(0.0)),
13129 height: available.height.map_definite_value(|h| h.max(0.0)),
13130 };
13131 if let Some(LeafContext::Image(Some(natural))) = cx {
13132 return image_size(*natural, known.width, known.height, &image_limits);
13133 }
13134 measure_content(engine, cache, cx, known, available, input_max_height)
13135 },
13136 );
13137 if image {
13143 let o = output.scrollable_overflow_rect;
13144 let mut rect = o.rect();
13145 rect.right = rect.right.min(output.size.width);
13146 rect.bottom = rect.bottom.min(output.size.height);
13147 output.scrollable_overflow_rect = taffy::ScrollableOverflow::new(rect, o.is_reversed());
13148 }
13149 output
13150}
13151
13152fn measure_content<M: TextEngine>(
13155 engine: &M,
13156 cache: &mut MeasureCache,
13157 cx: Option<&mut LeafContext<M::Prepared>>,
13158 known: taffy::Size<Option<f32>>,
13159 available: taffy::Size<AvailableSpace>,
13160 input_max_height: Option<f32>,
13161) -> taffy::Size<f32> {
13162 match cx {
13163 Some(LeafContext::Text(cx)) => {
13164 let field = cx
13167 .field
13168 .as_deref_mut()
13169 .map(|field| measure_text(engine, cache, field, None));
13170 let field_width = field.map(|size| size.width.0);
13171 let max_width = if cx.text.no_wrap {
13172 None
13173 } else {
13174 known.width.or(match (available.width, field_width) {
13175 (AvailableSpace::Definite(w), Some(field)) => Some(field.min(w)),
13176 (AvailableSpace::Definite(w), None) => Some(w),
13177 (_, Some(field)) => Some(field),
13178 (AvailableSpace::MinContent, None) => {
13179 Some(min_content_width(engine, cache, cx).0)
13180 }
13181 (AvailableSpace::MaxContent, None) => None,
13182 })
13183 };
13184 let width = known.width.or(field_width.and(max_width));
13185 let measured = match field {
13189 Some(sample)
13190 if width.is_some()
13191 && cx.text.max_lines == 1
13192 && engine.uniform_input_line_height() =>
13193 {
13194 sample
13195 }
13196 _ => measure_text(engine, cache, cx, max_width),
13197 };
13198 taffy::Size {
13199 width: width.unwrap_or(measured.width.0),
13200 height: known.height.unwrap_or(match input_max_height {
13201 Some(max) => measured.height.0.min(max),
13202 None => measured.height.0,
13203 }),
13204 }
13205 }
13206 Some(LeafContext::Image(Some(natural))) => {
13207 image_size(*natural, known.width, known.height, &ImageLimits::default())
13208 }
13209 Some(LeafContext::Native(Some(own))) => taffy::Size {
13210 width: known.width.unwrap_or(own.width.0),
13211 height: known.height.unwrap_or(own.height.0),
13212 },
13213 _ => taffy::Size::ZERO,
13214 }
13215}
13216
13217fn measure_text<M: TextEngine>(
13218 engine: &M,
13219 cache: &mut MeasureCache,
13220 cx: &mut TextContext<M::Prepared>,
13221 max_width: Option<f32>,
13222) -> Size<Points> {
13223 if let Some((w, size)) = cx.cache
13224 && w == max_width
13225 {
13226 return size;
13227 }
13228 let typed = max_width.map(Points);
13229 if cx.deferred {
13232 let size = cache.get(cx.layout_hash, typed).unwrap_or_else(|| {
13233 cx.estimated = true;
13234 estimate_text(&cx.text, max_width)
13235 });
13236 cx.cache = Some((max_width, size));
13237 return size;
13238 }
13239 if let (Some(width), Some(same)) = (max_width, cx.same_lines)
13240 && (same.narrowest..=same.widest).contains(&width)
13241 {
13242 cx.cache = Some((max_width, same.size));
13243 return same.size;
13244 }
13245 let greedy = engine.breaks_lines_greedily() && cx.text.max_lines == 0;
13247 let size = match cache.get(cx.layout_hash, typed) {
13248 Some(size) => size,
13249 None => {
13250 if let (Some(commit), Some((_, last))) = (cache.resizing, cx.cache)
13253 && cx.near_screen != commit
13254 {
13255 cx.held = true;
13256 return Size::new(
13257 max_width.map_or(last.width, |w| last.width.min(Points(w))),
13258 last.height,
13259 );
13260 }
13261 let prepared = cx
13262 .prepared
13263 .get_or_insert_with(|| engine.prepare_with(&cx.text, &cx.alignments, &cx.options));
13264 let ratio = cache.pixel_ratio();
13268 let on_pixels = |size: Size<Points>| {
13269 cache
13270 .on_cells(size)
13271 .unwrap_or_else(|| size.map(|v| ceil_to_pixel(v, ratio)))
13272 };
13273 let ahead = max_width.filter(|width| {
13276 greedy && !cx.no_ahead && cx.same_lines.is_some_and(|same| *width > same.widest)
13277 });
13278 let ahead = ahead.and_then(|width| {
13279 let wider = Points(width + SAME_LINES_AHEAD);
13280 let size = on_pixels(engine.measure(prepared, Some(wider)));
13281 cx.no_ahead = size.width.0 > width;
13282 (size.width.0 <= width).then_some((wider.0, size))
13283 });
13284 let (measured, size) = match ahead {
13285 Some(found) => found,
13286 None => (
13287 max_width.unwrap_or(f32::INFINITY),
13288 on_pixels(engine.measure(prepared, typed)),
13289 ),
13290 };
13291 cache.insert(cx.layout_hash, typed, size);
13292 if greedy && size.width.0 <= measured {
13293 cx.same_lines = Some(SameLines {
13294 narrowest: size.width.0,
13295 widest: measured,
13296 size,
13297 });
13298 }
13299 size
13300 }
13301 };
13302 cx.cache = Some((max_width, size));
13303 size
13304}
13305
13306fn pretty_width<M: TextEngine>(
13316 engine: &M,
13317 cx: &mut TextContext<M::Prepared>,
13318 width: Points,
13319) -> Points {
13320 if let Some(&(w, out)) = cx.pretty.as_deref()
13321 && w == width.0
13322 {
13323 return out;
13324 }
13325 let out = narrower_lines(engine, cx, width).unwrap_or(width);
13326 if let Some(p) = &mut cx.pretty {
13327 **p = (width.0, out);
13328 }
13329 out
13330}
13331
13332const PRETTY_LAST_LINE: f32 = 0.25;
13334
13335fn narrower_lines<M: TextEngine>(
13336 engine: &M,
13337 cx: &mut TextContext<M::Prepared>,
13338 width: Points,
13339) -> Option<Points> {
13340 let text = &cx.text;
13341 if text.no_wrap || text.max_lines > 0 || width <= Points::ZERO || text.text.contains('\n') {
13342 return None;
13343 }
13344 let prepared = cx
13345 .prepared
13346 .get_or_insert_with(|| engine.prepare_with(&cx.text, &cx.alignments, &cx.options));
13347 let height = engine.measure(prepared, Some(width)).height;
13348 let short = |w: Points| -> Option<bool> {
13350 let size = engine.measure(prepared, Some(w));
13351 if size.height > height {
13352 return None;
13353 }
13354 let lines = engine.lines(&engine.layout(prepared, Size { width: w, height }));
13355 let last = lines.last()?;
13356 Some(lines.len() > 1 && last.width < w * PRETTY_LAST_LINE)
13357 };
13358 if short(width) != Some(true) {
13359 return None;
13360 }
13361 let lines = engine
13365 .lines(&engine.layout(prepared, Size { width, height }))
13366 .len();
13367 let (mut lo, mut hi) = (width * ((lines - 1) as f32 / lines as f32), width);
13368 let mut found = None;
13369 for _ in 0..8 {
13370 let mid = (lo + hi) * 0.5;
13371 match short(mid) {
13372 Some(false) => {
13373 found = Some(mid);
13374 lo = mid;
13375 }
13376 Some(true) => hi = mid,
13377 None => lo = mid,
13378 }
13379 if hi - lo < Points(1.0) {
13380 break;
13381 }
13382 }
13383 found
13384}
13385
13386fn keeps_lines<P>(cx: &TextContext<P>, laid: &LaidText, size: Size<Points>) -> bool {
13387 let Some(same) = cx.same_lines else {
13388 return false;
13389 };
13390 let widths = same.narrowest..=same.widest;
13391 laid.content.size.height == size.height
13392 && widths.contains(&laid.content.size.width.0)
13393 && widths.contains(&size.width.0)
13394 && Arc::ptr_eq(&laid.text, &cx.text)
13395 && lines_start_left(&cx.text)
13396}
13397
13398fn lines_start_left(text: &AttributedText) -> bool {
13402 match text.align {
13403 TextAlign::Left => !text.text.chars().any(is_right_to_left),
13404 TextAlign::Auto => {
13405 !text.rtl
13406 && text.writing_direction != Some(true)
13407 && !text.text.chars().any(is_right_to_left)
13408 }
13409 TextAlign::Center | TextAlign::Right | TextAlign::Justify => false,
13410 }
13411}
13412
13413fn is_right_to_left(c: char) -> bool {
13415 matches!(
13416 c as u32,
13417 0x0590..=0x08FF | 0xFB1D..=0xFDFF | 0xFE70..=0xFEFF | 0x10800..=0x10FFF | 0x1E800..=0x1EFFF
13418 )
13419}
13420
13421fn definite(size: Size<Points>) -> taffy::Size<AvailableSpace> {
13422 taffy::Size {
13423 width: AvailableSpace::Definite(size.width.0),
13424 height: AvailableSpace::Definite(size.height.0),
13425 }
13426}
13427
13428fn web_url(prop: &Prop) -> Option<&str> {
13431 match prop {
13432 Prop::Native(
13433 NativeProp::Src(Some(url))
13434 | NativeProp::BaseUrl(Some(url))
13435 | NativeProp::Source(
13436 crate::WebSource::Uri(url)
13437 | crate::WebSource::Html {
13438 base_url: Some(url),
13439 ..
13440 },
13441 ),
13442 ) => Some(url),
13443 _ => None,
13444 }
13445}
13446
13447fn not_granted(what: &str, uri: &str, capability: &str) -> String {
13448 let advice = crate::access::grant_advice(uri, capability);
13449 format!("{what} {uri} is not granted: {advice}")
13450}
13451
13452fn media_not_granted(what: &str, uri: &str, base: Option<&str>) -> String {
13455 let advice = crate::access::media_grant_advice(uri, base);
13456 format!("{what} {uri} is not granted: {advice}")
13457}
13458
13459fn apply_native(control: &mut NativeProps, prop: NativeProp) {
13462 use NativeProp as P;
13463 match (control, prop) {
13464 (NativeProps::WebView(p), P::Source(v)) => p.source = v,
13465 (NativeProps::WebView(p), P::Src(Some(url))) => {
13468 if !matches!(p.source, crate::WebSource::Html { .. }) {
13469 p.source = crate::WebSource::Uri(url.clone());
13470 }
13471 p.src = Some(url);
13472 }
13473 (NativeProps::WebView(p), P::Src(None)) => {
13474 p.src = None;
13475 if matches!(p.source, crate::WebSource::Uri(_)) {
13476 p.source = crate::WebSource::None;
13477 }
13478 }
13479 (NativeProps::WebView(p), P::Html(Some(html))) => {
13480 p.source = crate::WebSource::Html {
13481 html,
13482 base_url: p.base_url.clone(),
13483 };
13484 }
13485 (NativeProps::WebView(p), P::Html(None)) => {
13486 if matches!(p.source, crate::WebSource::Html { .. }) {
13487 p.source = match &p.src {
13488 Some(url) => crate::WebSource::Uri(url.clone()),
13489 None => crate::WebSource::None,
13490 };
13491 }
13492 }
13493 (NativeProps::WebView(p), P::BaseUrl(url)) => {
13494 if let crate::WebSource::Html { base_url, .. } = &mut p.source {
13495 base_url.clone_from(&url);
13496 }
13497 p.base_url = url;
13498 }
13499 (NativeProps::WebView(p), P::AllowOrigin(v)) => {
13500 p.allow_origin = v.and_then(|o| crate::access::WebOrigin::parse(&o).ok());
13501 }
13502 (NativeProps::WebView(p), P::AllowNavigation(v)) => {
13503 p.allow_navigation = v.and_then(|h| crate::access::WebHosts::parse(&h).ok());
13504 }
13505 (NativeProps::WebView(p), P::InjectedJavaScript(v)) => p.injected_js = v,
13506 (NativeProps::WebView(p), P::InjectedJavaScriptBefore(v)) => p.injected_js_before = v,
13507 (NativeProps::WebView(p), P::UserAgent(v)) => p.user_agent = v,
13508 (NativeProps::WebView(p), P::Scrollable(v)) => p.scrollable = v,
13509 (NativeProps::WebView(p), P::JavaScriptEnabled(v)) => p.javascript_enabled = v,
13510 (NativeProps::WebView(p), P::BackForwardGestures(v)) => p.back_forward_gestures = v,
13511 (NativeProps::WebView(p), P::Incognito(v)) => p.incognito = v,
13512 (NativeProps::WebView(p), P::Zoomable(v)) => p.zoomable = v,
13513 (NativeProps::WebView(p), P::UrlSchemes(v)) => p.url_schemes = v,
13514 (NativeProps::WebView(p), P::DeferDownloads(v)) => p.defer_downloads = v,
13515 (NativeProps::Video(p), P::Source(v)) => {
13516 p.source = match v {
13517 crate::WebSource::Uri(uri) => Some(uri),
13518 _ => None,
13519 }
13520 }
13521 (NativeProps::Video(p), P::Src(v)) => p.source = v,
13522 (NativeProps::Video(p), P::Poster(v)) => p.poster = v,
13523 (NativeProps::Video(p), P::Paused(v)) => p.paused = v,
13524 (NativeProps::Video(p), P::Muted(v)) => p.muted = v,
13525 (NativeProps::Video(p), P::Volume(v)) => p.volume = v.clamp(0.0, 1.0),
13526 (NativeProps::Video(p), P::Rate(v)) => p.rate = v.max(0.0),
13527 (NativeProps::Video(p), P::Repeat(v)) => p.repeat = v,
13528 (NativeProps::Video(p), P::VideoResizeMode(v)) => p.resize_mode = v,
13529 (NativeProps::Video(p), P::Controls(v)) => p.controls = v,
13530 (NativeProps::Video(p), P::ProgressInterval(v)) => p.progress_interval_ms = v.max(16.0),
13531 (NativeProps::Video(p), P::AudioSession(v)) => p.audio_session = v,
13532 _ => {}
13533 }
13534}
13535
13536fn scaled(mut style: ResolvedTextStyle, multiplier: f32) -> ResolvedTextStyle {
13538 if multiplier != 1.0 {
13539 style.font_size *= multiplier;
13540 style.line_height *= multiplier;
13541 }
13542 style
13543}
13544
13545fn root_style(viewport: Size<Points>) -> taffy::Style {
13546 let mut style = taffy::Style {
13547 size: taffy::Size {
13548 width: taffy::Dimension::length(viewport.width.0),
13549 height: taffy::Dimension::length(viewport.height.0),
13550 },
13551 ..Style::default().layout
13552 };
13553 crate::style::resolve_normal_alignment(&mut style);
13554 style
13555}
13556
13557fn text_layout_hash(
13560 alignments: &crate::AttachmentAlignments,
13561 text: &crate::AttributedText,
13562 options: &crate::TextOptions,
13563) -> u64 {
13564 use std::hash::{Hash as _, Hasher as _};
13565 let mut h = std::collections::hash_map::DefaultHasher::new();
13566 alignments.layout_hash(text).hash(&mut h);
13567 options.indent.map(|indent| indent.0.to_bits()).hash(&mut h);
13568 h.finish()
13569}
13570
13571fn directed_align(align: TextAlign, rtl: bool) -> TextAlign {
13574 match (align, rtl) {
13575 (TextAlign::Left, true) => TextAlign::Right,
13576 (TextAlign::Right, true) => TextAlign::Left,
13577 (align, _) => align,
13578 }
13579}
13580
13581const HANDLED: [EventKind; 7] = [
13586 EventKind::PanStart,
13587 EventKind::PanEnd,
13588 EventKind::PinchStart,
13589 EventKind::PinchEnd,
13590 EventKind::RotationStart,
13591 EventKind::RotationEnd,
13592 EventKind::Touch,
13593];
13594
13595const PRESSES: [EventKind; 4] = [
13596 EventKind::Press,
13597 EventKind::LongPress,
13598 EventKind::PressDown,
13599 EventKind::PressUp,
13600];
13601
13602const DISABLED_OFF: [EventKind; 8] = [
13604 EventKind::Press,
13605 EventKind::LongPress,
13606 EventKind::PressDown,
13607 EventKind::PressUp,
13608 EventKind::ContextMenu,
13609 EventKind::FileDragEnter,
13610 EventKind::FileDragLeave,
13611 EventKind::FileDrop,
13612];
13613
13614fn disabling_changes(events: EventMask) -> bool {
13616 DISABLED_OFF.iter().any(|&e| events.contains(e))
13617}
13618
13619fn span_padding(node: &Node, rtl: bool) -> (f32, f32) {
13623 let Some(style) = node.base_layout.as_deref() else {
13624 return (0.0, 0.0);
13625 };
13626 let len = |p: taffy::LengthPercentage| match p.into_raw().tag() {
13627 taffy::CompactLength::LENGTH_TAG => p.into_raw().value().max(0.0),
13628 _ => 0.0,
13629 };
13630 let (left, right) = (len(style.padding.left), len(style.padding.right));
13631 if rtl { (right, left) } else { (left, right) }
13632}
13633
13634fn span_vertical_padding(node: &Node) -> (Points, Points) {
13638 let Some(style) = node.base_layout.as_deref() else {
13639 return (Points::ZERO, Points::ZERO);
13640 };
13641 let len = |p: taffy::LengthPercentage| match p.into_raw().tag() {
13642 taffy::CompactLength::LENGTH_TAG => Points(p.into_raw().value().max(0.0)),
13643 _ => Points::ZERO,
13644 };
13645 (len(style.padding.top), len(style.padding.bottom))
13646}
13647
13648fn span_background(style: &ViewStyle, node: NodeId) -> Option<crate::text::TextBackground> {
13650 (style.background_color.0 & 0xff != 0).then_some(crate::text::TextBackground {
13651 color: style.background_color,
13652 radius: style.border_radius.max(Points::ZERO),
13653 node,
13654 top: Points::ZERO,
13655 bottom: Points::ZERO,
13656 })
13657}
13658
13659fn pressable(events: EventMask) -> bool {
13661 PRESSES.iter().any(|&e| events.contains(e))
13662}
13663
13664fn broken_runs(content: &str) -> std::borrow::Cow<'_, str> {
13675 let mut broken: Option<String> = None;
13676 let (mut start, mut from) = (0, 0);
13677 for (end, _) in unicode_linebreak::linebreaks(content) {
13678 let mut run = 0;
13679 for (offset, c) in content[start..end].char_indices() {
13680 let i = start + offset;
13681 if run == MEASURED_RUN && i + c.len_utf8() < end {
13684 let broken = broken.get_or_insert_with(|| {
13685 String::with_capacity(content.len() + content.len() / MEASURED_RUN)
13686 });
13687 broken.push_str(&content[from..i]);
13688 broken.push('\n');
13689 (run, from) = (0, i);
13690 }
13691 run += 1;
13692 }
13693 start = end;
13694 }
13695 match broken {
13696 Some(mut broken) => {
13697 broken.push_str(&content[from..]);
13698 broken.into()
13699 }
13700 None => content.into(),
13701 }
13702}
13703
13704trait StyleSlot<T: SharedDefault>: Sized {
13710 fn get(&self) -> &T;
13711 fn same(&self, held: &Sparse<T>) -> bool;
13713 fn install(self, held: &mut Sparse<T>);
13714}
13715
13716impl<T: SharedDefault + Clone> StyleSlot<T> for T {
13717 fn get(&self) -> &T {
13718 self
13719 }
13720
13721 fn same(&self, held: &Sparse<T>) -> bool {
13722 **held == *self
13723 }
13724
13725 fn install(self, held: &mut Sparse<T>) {
13726 held.set(self);
13727 }
13728}
13729
13730impl<T: SharedDefault + Clone> StyleSlot<T> for Option<Rc<T>> {
13731 fn get(&self) -> &T {
13732 self.as_deref().unwrap_or_else(|| T::shared_default())
13733 }
13734
13735 fn same(&self, held: &Sparse<T>) -> bool {
13736 match (&held.0, self) {
13737 (None, None) => true,
13738 (Some(a), Some(b)) => Rc::ptr_eq(a, b) || **a == **b,
13739 (Some(a), None) => **a == *T::shared_default(),
13740 (None, Some(b)) => *T::shared_default() == **b,
13741 }
13742 }
13743
13744 fn install(self, held: &mut Sparse<T>) {
13745 held.0 = self;
13746 }
13747}
13748
13749trait LayoutSlot: Sized {
13752 fn get(&self) -> &taffy::Style;
13753 fn to_mut(&mut self) -> &mut taffy::Style;
13755 fn into_owned(self) -> taffy::Style;
13756 fn set_on<C>(self, tree: &mut LayoutTree<C>, node: LayoutId) -> bool;
13758}
13759
13760impl LayoutSlot for taffy::Style {
13761 fn get(&self) -> &taffy::Style {
13762 self
13763 }
13764
13765 fn to_mut(&mut self) -> &mut taffy::Style {
13766 self
13767 }
13768
13769 fn into_owned(self) -> taffy::Style {
13770 self
13771 }
13772
13773 fn set_on<C>(self, tree: &mut LayoutTree<C>, node: LayoutId) -> bool {
13774 tree.set_style(node, self)
13775 }
13776}
13777
13778impl LayoutSlot for Rc<taffy::Style> {
13779 fn get(&self) -> &taffy::Style {
13780 self
13781 }
13782
13783 fn to_mut(&mut self) -> &mut taffy::Style {
13784 Rc::make_mut(self)
13785 }
13786
13787 fn into_owned(self) -> taffy::Style {
13788 Rc::unwrap_or_clone(self)
13789 }
13790
13791 fn set_on<C>(self, tree: &mut LayoutTree<C>, node: LayoutId) -> bool {
13792 tree.set_style_shared(node, self)
13793 }
13794}
13795
13796struct StyleRecord<L, V, X> {
13799 layout: L,
13800 view: V,
13801 text: X,
13802 paint: Option<Rc<PaintStyle>>,
13803 animated: Vec<(AnimationProp, crate::animation::NodeId)>,
13804 sticky: Option<taffy::Rect<taffy::LengthPercentageAuto>>,
13806 perspective: Option<Points>,
13807 object_fit: Option<ResizeMode>,
13808 wants_fixed: bool,
13809 env: crate::style::EnvEdges,
13810 z_index: i32,
13811 vertical_align: crate::style::VerticalAlign,
13812 has_logical: bool,
13813 rtl: bool,
13814}
13815
13816fn prepare_layout(
13822 layout: &mut taffy::Style,
13823 view: &mut ViewStyle,
13824 logical: &crate::style::Logical,
13825 rtl: bool,
13826 sticky: bool,
13827) -> Option<taffy::Rect<taffy::LengthPercentageAuto>> {
13828 crate::style::resolve_normal_alignment(layout);
13829 crate::style::apply_direction(layout, view, logical, rtl);
13830 sticky.then(|| {
13831 let auto = taffy::LengthPercentageAuto::auto();
13832 std::mem::replace(
13833 &mut layout.inset,
13834 taffy::Rect {
13835 left: auto,
13836 right: auto,
13837 top: auto,
13838 bottom: auto,
13839 },
13840 )
13841 })
13842}
13843
13844fn clip_overflow(layout: &mut taffy::Style, clip: bool) {
13854 let clip = if clip {
13855 taffy::Overflow::Clip
13856 } else {
13857 taffy::Overflow::Visible
13858 };
13859 layout.overflow = taffy::Point { x: clip, y: clip };
13860}
13861
13862fn opt_rc_eq<T: PartialEq>(a: Option<&Rc<T>>, b: Option<&Rc<T>>) -> bool {
13864 match (a, b) {
13865 (None, None) => true,
13866 (Some(a), Some(b)) => Rc::ptr_eq(a, b) || **a == **b,
13867 _ => false,
13868 }
13869}
13870
13871fn leaf_context<P>(kind: Kind) -> Option<LeafContext<P>> {
13875 match kind {
13876 Kind::Text | Kind::Input => Some(LeafContext::Text(Box::new(TextContext::new(
13877 Arc::default(),
13878 )))),
13879 Kind::Image => Some(LeafContext::Image(None)),
13880 Kind::Native => Some(LeafContext::Native(None)),
13881 _ => None,
13882 }
13883}
13884
13885enum Shown {
13888 Nothing,
13893 View(NodeId),
13895 Everywhere,
13898}
13899
13900fn shown_by(item: &MountItem) -> Shown {
13901 use MountItem as M;
13902 match item {
13903 M::Events { .. }
13904 | M::Keymap(_)
13905 | M::Gestures { .. }
13906 | M::AccessibilityLabel { .. }
13907 | M::ShaderInput { .. }
13908 | M::LayoutAnimation(_)
13909 | M::Animation(_)
13910 | M::ComponentPropSlots { .. }
13911 | M::TrackStates { .. }
13912 | M::InputContent { .. }
13913 | M::Remove { .. }
13914 | M::Delete { .. } => Shown::Nothing,
13915 M::Insert { child, .. } => Shown::View(*child),
13916 M::ProjectStates { id, .. }
13917 | M::ScrollConfig { id, .. }
13918 | M::ScrollBy { id, .. }
13919 | M::StickyCells { id, .. }
13920 | M::ScrollBehavior { id, .. }
13921 | M::Refreshing { id, .. }
13922 | M::AnimationBindings { id, .. }
13923 | M::ScreenConfig { id, .. }
13924 | M::ModalConfig { id, .. } => Shown::View(*id),
13925 M::Command { id, command } => {
13926 use crate::ops::Command as C;
13927 match command {
13928 C::ExitApp
13931 | C::PostMessage { .. }
13932 | C::SendInput { .. }
13933 | C::SetJsResponder { .. }
13934 | C::ClearJsResponder
13935 | C::Announce { .. }
13936 | C::ImageInfo { .. }
13937 | C::AccessibilityFocus
13938 | C::Measure { .. }
13939 | C::MeasureScrollPosition { .. }
13940 | C::SetClipboard { .. }
13941 | C::SetClipboardItem(_)
13942 | C::ReadClipboard { .. }
13943 | C::SetClipboardImage { .. }
13944 | C::ReadClipboardImage { .. }
13945 | C::ReadClipboardFiles { .. }
13946 | C::PickImages { .. }
13947 | C::PickFiles { .. }
13948 | C::OpenUrl { .. }
13949 | C::OpenAppSettings { .. }
13950 | C::PickScreenColor { .. }
13951 | C::RenderCanvas { .. }
13952 | C::FileRequest { .. }
13953 | C::Audio { .. }
13954 | C::Notification { .. }
13955 | C::Desktop { .. }
13956 | C::HostCall { .. }
13957 | C::HostPost { .. } => Shown::Nothing,
13958 C::Tokens { .. } => Shown::Everywhere,
13960 _ => Shown::View(*id),
13961 }
13962 }
13963 item => item.view().map_or(Shown::Everywhere, Shown::View),
13964 }
13965}
13966
13967struct TextAttachments<'a> {
13970 alignments: crate::AttachmentAlignments,
13972 spacers: Vec<u32>,
13974 baselines: &'a [(Key, Points)],
13977 next_baseline: usize,
13980}