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 = if laid.text.spans == self.text.spans {
1267 self.text.clone()
1268 } else {
1269 let mut text = (*laid.text).clone();
1272 text.set_metadata(&self.text);
1273 Arc::new(text)
1274 };
1275 laid.text = text.clone();
1276 self.metadata_changed = false;
1277 Some((text, laid.layout.clone()))
1278 }
1279}
1280
1281const FIELD_SAMPLE: &str = "00000000000000000000";
1284
1285enum LeafContext<P> {
1287 Text(Box<TextContext<P>>),
1290 Image(Option<Size<Points>>),
1291 Native(Option<Size<Points>>),
1293}
1294
1295#[derive(Debug, Clone, PartialEq, Eq)]
1297pub struct ListBind {
1298 pub list: NodeId,
1300 pub binds: Vec<(u32, u32)>,
1302}
1303
1304fn take_queued_binds(binds: &mut Vec<ListBind>, list: NodeId) -> Vec<u32> {
1311 let mut slots = Vec::new();
1312 binds.retain(|b| {
1313 if b.list != list {
1314 return true;
1315 }
1316 slots.extend(b.binds.iter().map(|&(slot, _)| slot));
1317 false
1318 });
1319 slots
1320}
1321
1322pub const MAX_TREE_DEPTH: usize = 1024;
1330
1331#[derive(Debug, Clone, Copy, PartialEq, Eq)]
1334pub enum ApplyError {
1335 UnknownNode(NodeId),
1337 DuplicateNode(NodeId),
1339 NotAChild(NodeId),
1341 BadAnchor(NodeId),
1343 Cycle(NodeId),
1345 TooManyNodes(usize),
1347 TooDeep(usize),
1350 IdOutOfRange(NodeId),
1353}
1354
1355impl ApplyError {
1356 pub fn is_fatal(&self) -> bool {
1359 matches!(
1360 self,
1361 ApplyError::TooManyNodes(_) | ApplyError::TooDeep(_) | ApplyError::IdOutOfRange(_)
1362 )
1363 }
1364}
1365
1366#[derive(Default)]
1369struct Retags {
1370 made: rustc_hash::FxHashSet<NodeId>,
1372 seen: usize,
1374 retagged: rustc_hash::FxHashMap<NodeId, usize>,
1377}
1378
1379pub struct Core<M: TextEngine> {
1386 nodes: Slab<Node>,
1387 slots: crate::id_table::IdTable<Key>,
1389 admitted_id_extent: usize,
1391 runs: rustc_hash::FxHashMap<NodeId, Run>,
1395 folded: rustc_hash::FxHashMap<Key, NodeId>,
1397 layout: LayoutTree<LeafContext<M::Prepared>>,
1398 text_engine: Rc<M>,
1399 geometry_engine: Option<Rc<dyn crate::text::GeometryEngine>>,
1402 geometries: rustc_hash::FxHashMap<NodeId, crate::text::TextGeometry>,
1405 measure_cache: MeasureCache,
1406 resizing_commit: u32,
1408 resize_settling: bool,
1412 pending_text: Vec<Key>,
1414 attachment_blocks: Vec<Key>,
1417 lists: Vec<Key>,
1419 parent_lists: Vec<Key>,
1422 outer_moved: bool,
1424 extent_changed: bool,
1426 culls_content: bool,
1428 culling: Vec<Key>,
1430 cull_dirty: bool,
1432 cull_made: bool,
1435 cells_framed: bool,
1438 cull_scratch: Vec<(Key, f32, f32, f32, f32)>,
1442 reach: crate::animation::Reach,
1446 pace: pace::Pace,
1448 list_motion: list_motion::ListMotion,
1450 placeholders: Vec<(Key, NodeId)>,
1453 asked_rows: Vec<NodeId>,
1456 placeholders_resized: bool,
1459 outer_asked: Vec<Key>,
1461 sticky_views: Vec<Key>,
1463 sticky_nodes: Vec<Key>,
1465 sticky_scrollers: Vec<Key>,
1467 builtin_scrollbars: Option<(crate::element::ScrollbarSource, crate::element::AnyValue)>,
1470 scrollbars_pending: Vec<Key>,
1473 watched_inputs: Vec<NodeId>,
1476 fitted_pending: Vec<Key>,
1480 decorated: Vec<Key>,
1482 sticky_changed: bool,
1485 followers: Vec<Key>,
1487 relators: Vec<relations::Relator>,
1490 follow_changed: bool,
1493 sticky_warned: bool,
1495 inset_warned: bool,
1498 shaders: rustc_hash::FxHashMap<u64, Result<crate::shader::Shader, crate::shader::ShaderError>>,
1501 web_unchecked: rustc_hash::FxHashSet<(Key, NodeId)>,
1506 transition_starts: Vec<MountItem>,
1509 pictured: rustc_hash::FxHashSet<NodeId>,
1511 unlinked_from: Vec<NodeId>,
1515 roots: Vec<Key>,
1517 accessories: rustc_hash::FxHashMap<Box<str>, NodeId>,
1519 header_heights: (Points, Points),
1521 safe_area: EdgeInsets,
1525 overlay_bounds: Option<crate::geometry::Bounds<Points>>,
1529 snap_to_window_margin: Points,
1532 list_binds: Vec<ListBind>,
1533 kept_lists: Vec<Key>,
1535 selection_kept: Vec<NodeId>,
1537 kept_scratch: Vec<Key>,
1539 paced_lists: Vec<NodeId>,
1542 paced_scratch: Vec<(u32, u32)>,
1544 events: Vec<crate::element::JsEvent>,
1547 cells_scratch: Vec<(u32, Key)>,
1549 awaiting_renders: Vec<Key>,
1552 root: Key,
1553 viewport: Size<Points>,
1554 mount: Vec<MountItem>,
1555 track_tree_order: bool,
1556 tree_order_changed: bool,
1557 tab_places_stale: bool,
1560 key_ancestry_dirty: bool,
1564 mount_projected: bool,
1567 batches: u64,
1570 retags: Option<Box<Retags>>,
1573 commands: Vec<(NodeId, Command)>,
1575 focus_back: Option<(NodeId, Option<NodeId>)>,
1579 focus_origins: Vec<(NodeId, Option<(Key, NodeId)>)>,
1584 pointer_focus_back: Option<NodeId>,
1588 layout_animation: Option<LayoutAnimation>,
1590 scoped_layout: Vec<(NodeId, crate::LayoutTransition, bool)>,
1593 resized: Vec<Key>,
1595 restructured: Vec<Key>,
1597 env_styled: rustc_hash::FxHashSet<NodeId>,
1599 env_scratch: Vec<NodeId>,
1601 keyboard_moved: bool,
1605 status_bar_nodes: Vec<Key>,
1608 status_bars_moved: bool,
1611 orientation_pages: Vec<(Key, u8)>,
1614 orientations_shown: u8,
1616 pointer_none_classes: u32,
1619 pointer_pending: Vec<Key>,
1626 slop_moved: Vec<Key>,
1630 focus: Option<(Key, NodeId)>,
1633 focus_chain: Vec<(Key, NodeId)>,
1636 focus_scratch: Vec<(Key, NodeId)>,
1638 focus_moved: bool,
1642 blur_held: bool,
1648 focus_within_changed: bool,
1651 modality: Option<crate::platform::InputModality>,
1654 focus_visible: bool,
1657 focus_by_keyboard: bool,
1663 focus_by_pointer: bool,
1667 pointer_keymap: Option<(Arc<crate::keymap::Keymap>, bool)>,
1672 restoring_modal_focus: bool,
1675 modals_opened: Vec<(Key, NodeId)>,
1678 modal_focus_given: Option<NodeId>,
1683 focus_visible_on: Option<(Key, NodeId)>,
1686 focus_visible_moved: bool,
1689 projected_focus: Vec<(Key, NodeId)>,
1694 pressed_impulses: Vec<(Key, NodeId, crate::time::Instant)>,
1697 passed_hovers: rustc_hash::FxHashMap<NodeId, Vec<NodeId>>,
1700 fixed_changed: Vec<(Key, NodeId)>,
1703 zero_advances: rustc_hash::FxHashMap<(Option<crate::style::FontFamily>, u32, u16, bool), f32>,
1706 ch_styled: Vec<(Key, NodeId)>,
1710 ch_readers: usize,
1712 color_changed: Vec<(Key, NodeId)>,
1715 font_scale: f32,
1717 default_font: Option<crate::style::FontFamily>,
1721 queue: Vec<Key>,
1722 position_parents: Vec<Key>,
1726 needs_layout: bool,
1727 tailwind: Tailwind,
1729 resolved_styles:
1733 rustc_hash::FxHashMap<classes::ResolvedKey, std::rc::Rc<classes::ResolvedClassStyle>>,
1734 #[cfg(test)]
1736 resolve_uncached: bool,
1737 class_env: ClassEnvironment,
1740 appearance: crate::platform::Appearance,
1742 system_dark: bool,
1744 max_nodes: usize,
1746 fold_runs: bool,
1748 access: Arc<crate::access::Access>,
1750 base_url: Option<Arc<str>>,
1753 media_files: Arc<crate::access::MediaFiles>,
1756 canvas_images: rustc_hash::FxHashMap<Arc<str>, Option<Arc<str>>>,
1761 denied: rustc_hash::FxHashSet<String>,
1763 windows: rustc_hash::FxHashMap<NodeId, crate::desktop::window::WindowRecord>,
1766 window_ids: rustc_hash::FxHashMap<String, (NodeId, bool)>,
1769 quit_mode: Option<crate::desktop::QuitMode>,
1773 default_quit_mode: crate::desktop::QuitMode,
1777 main_window_options: Option<crate::desktop::MainWindowOptions>,
1781 launch_defaults_applied: bool,
1784 keep_main_placement: bool,
1787 main_shown: bool,
1790 clipboard: Option<Arc<dyn crate::clipboard::ClipboardBackend>>,
1793 picker: Option<Arc<dyn crate::picker::PickerBackend>>,
1796 window_backend: Option<Arc<dyn crate::desktop::WindowBackend>>,
1799 audio: Option<Arc<dyn crate::audio::AudioBackend>>,
1801 login_item: Option<crate::desktop::LoginItems>,
1804 components: components::Components,
1806 overlays: Vec<Key>,
1809 overlay_state: overlay::Overlays,
1811}
1812
1813impl<M: TextEngine + 'static> Core<M> {
1814 pub fn new(text_engine: M, viewport: Size<Points>) -> Self {
1816 let mut core = Self::with_engine(text_engine, viewport);
1817 core.geometry_engine = Some(core.text_engine.clone());
1818 let engine = core.text_engine.clone();
1820 core.components
1821 .runtime
1822 .set_measure(Rc::new(move |font, text| {
1823 crate::canvas::line_metrics(&*engine, font, text)
1824 }));
1825 core
1826 }
1827}
1828
1829impl<M: TextEngine> Core<M> {
1830 fn with_engine(text_engine: M, viewport: Size<Points>) -> Self {
1831 let mut layout = LayoutTree::with_capacity(256);
1832 let root_layout = layout.new_leaf(root_style(viewport));
1833 let mut nodes = Slab::with_capacity(256);
1834 let mut root = Node::new(ROOT_ID, Kind::View);
1835 root.layout = Some(root_layout);
1836 root.created = true;
1838 let root = nodes.insert(root) as Key;
1839 layout.set_tag(root_layout, root);
1840 layout.set_role(
1842 root_layout,
1843 terminal_layout::Role {
1844 root: true,
1845 ..terminal_layout::Role::default()
1846 },
1847 );
1848 let mut slots = crate::id_table::IdTable::new();
1849 slots.insert(ROOT_ID as usize, root);
1850 Self {
1851 nodes,
1852 admitted_id_extent: slots.extent(),
1853 slots,
1854 layout,
1855 text_engine: Rc::new(text_engine),
1856 geometry_engine: None,
1857 geometries: Default::default(),
1858 measure_cache: MeasureCache::default(),
1859 resizing_commit: 0,
1860 resize_settling: false,
1861 pending_text: Vec::new(),
1862 attachment_blocks: Vec::new(),
1863 max_nodes: usize::MAX,
1864 fold_runs: true,
1865 access: Arc::default(),
1866 base_url: None,
1867 media_files: Arc::default(),
1868 canvas_images: Default::default(),
1869 denied: Default::default(),
1870 windows: Default::default(),
1871 window_ids: Default::default(),
1872 runs: Default::default(),
1873 folded: Default::default(),
1874 quit_mode: None,
1878 default_quit_mode: crate::desktop::QuitMode::Explicit,
1879 main_window_options: None,
1880 launch_defaults_applied: false,
1881 keep_main_placement: false,
1882 main_shown: false,
1883 clipboard: None,
1884 picker: None,
1885 window_backend: None,
1886 audio: None,
1887 login_item: None,
1888 components: components::Components::for_viewport(viewport),
1889 lists: Vec::new(),
1890 parent_lists: Vec::new(),
1891 outer_moved: false,
1892 extent_changed: false,
1893 culls_content: true,
1894 culling: Vec::new(),
1895 cull_dirty: false,
1896 reach: crate::animation::Reach::default(),
1897 cull_made: false,
1898 cells_framed: false,
1899 cull_scratch: Vec::new(),
1900 pace: pace::Pace::default(),
1901 list_motion: list_motion::ListMotion::default(),
1902 placeholders: Vec::new(),
1903 asked_rows: Vec::new(),
1904 placeholders_resized: false,
1905 outer_asked: Vec::new(),
1906 sticky_views: Vec::new(),
1907 sticky_nodes: Vec::new(),
1908 sticky_scrollers: Vec::new(),
1909 builtin_scrollbars: None,
1910 scrollbars_pending: Vec::new(),
1911 watched_inputs: Vec::new(),
1912 fitted_pending: Vec::new(),
1913 decorated: Vec::new(),
1914 sticky_changed: false,
1915 followers: Vec::new(),
1916 relators: Vec::new(),
1917 follow_changed: false,
1918 sticky_warned: false,
1919 inset_warned: false,
1920 shaders: Default::default(),
1921 web_unchecked: Default::default(),
1922 transition_starts: Vec::new(),
1923 pictured: Default::default(),
1924 unlinked_from: Vec::new(),
1925 roots: Vec::new(),
1926 accessories: Default::default(),
1927 header_heights: (Points(44.0), Points(96.0)),
1928 safe_area: EdgeInsets::default(),
1929 overlay_bounds: None,
1930 snap_to_window_margin: crate::overlay::DEFAULT_SNAP_TO_WINDOW_MARGIN,
1931 list_binds: Vec::new(),
1932 kept_lists: Vec::new(),
1933 selection_kept: Vec::new(),
1934 kept_scratch: Vec::new(),
1935 paced_lists: Vec::new(),
1936 paced_scratch: Vec::new(),
1937 events: Vec::new(),
1938 cells_scratch: Vec::new(),
1939 awaiting_renders: Vec::new(),
1940 root,
1941 viewport,
1942 mount: Vec::new(),
1943 track_tree_order: false,
1944 tree_order_changed: false,
1945 tab_places_stale: false,
1946 key_ancestry_dirty: false,
1947 mount_projected: false,
1948 batches: 0,
1949 retags: None,
1950 commands: Vec::new(),
1951 focus_back: None,
1952 focus_origins: Vec::new(),
1953 pointer_focus_back: None,
1954 layout_animation: None,
1955 scoped_layout: Vec::new(),
1956 resized: Vec::new(),
1957 restructured: Vec::new(),
1958 env_styled: Default::default(),
1959 env_scratch: Vec::new(),
1960 keyboard_moved: false,
1961 status_bar_nodes: Vec::new(),
1962 status_bars_moved: false,
1963 orientation_pages: Vec::new(),
1964 orientations_shown: 0,
1965 pointer_none_classes: 0,
1966 pointer_pending: Vec::new(),
1967 slop_moved: Vec::new(),
1968 focus: None,
1969 focus_chain: Vec::new(),
1970 focus_scratch: Vec::new(),
1971 focus_moved: false,
1972 blur_held: false,
1973 focus_within_changed: false,
1974 modality: None,
1975 focus_visible: false,
1976 focus_by_keyboard: false,
1977 focus_by_pointer: false,
1978 pointer_keymap: None,
1979 restoring_modal_focus: false,
1980 modals_opened: Vec::new(),
1981 modal_focus_given: None,
1982 focus_visible_on: None,
1983 focus_visible_moved: false,
1984 projected_focus: Vec::new(),
1985 pressed_impulses: Vec::new(),
1986 passed_hovers: Default::default(),
1987 fixed_changed: Vec::new(),
1988 zero_advances: Default::default(),
1989 ch_styled: Vec::new(),
1990 ch_readers: 0,
1991 color_changed: Vec::new(),
1992 font_scale: 1.0,
1993 default_font: None,
1994 queue: Vec::new(),
1995 position_parents: Vec::new(),
1996 needs_layout: true,
1997 tailwind: Tailwind::new(),
1998 resolved_styles: rustc_hash::FxHashMap::default(),
1999 #[cfg(test)]
2000 resolve_uncached: false,
2001 class_env: ClassEnvironment::default(),
2002 appearance: crate::platform::Appearance::System,
2003 system_dark: false,
2004 overlays: Vec::new(),
2005 overlay_state: overlay::Overlays::default(),
2006 }
2007 }
2008
2009 pub fn set_header_heights(&mut self, normal: Points, large: Points) {
2012 if self.header_heights != (normal, large) {
2013 self.header_heights = (normal, large);
2014 self.needs_layout = true;
2015 }
2016 }
2017
2018 pub fn set_safe_area(&mut self, insets: EdgeInsets) {
2020 if self.safe_area != insets {
2021 self.safe_area = insets;
2022 self.needs_layout = true;
2023 }
2024 }
2025
2026 pub fn set_overlay_area(&mut self, area: Option<crate::geometry::Bounds<Points>>) {
2035 if self.overlay_bounds == area {
2036 return;
2037 }
2038 self.overlay_bounds = area;
2039 if self.root_overlay_shown() {
2042 self.needs_layout = true;
2043 }
2044 }
2045
2046 pub fn set_snap_to_window_margin(&mut self, margin: Points) {
2051 let margin = Points(margin.0.max(0.0));
2052 if self.snap_to_window_margin == margin {
2053 return;
2054 }
2055 self.snap_to_window_margin = margin;
2056 for (_, node) in &mut self.nodes {
2057 if let Some(root) = node.root.as_mut()
2058 && let Some(overlay) = root.overlay.as_mut()
2059 && !overlay.margin_set
2060 {
2061 overlay.placed = None;
2062 root.laid_out = None;
2063 }
2064 }
2065 self.needs_layout = true;
2066 }
2067
2068 pub fn set_root_size(&mut self, id: NodeId, size: Size<Points>, insets: EdgeInsets) {
2071 let Ok(key) = self.key(id) else { return };
2072 if let Some(root) = self.nodes[key as usize].root.as_mut()
2073 && (root.reported != Some(size) || root.insets != insets)
2074 {
2075 root.reported = Some(size);
2076 root.insets = insets;
2077 self.needs_layout = true;
2078 }
2079 }
2080
2081 pub fn set_screen_header(&mut self, id: NodeId, height: Option<Points>) {
2086 let Ok(key) = self.key(id) else { return };
2087 let height = height.map(|h| h.0).filter(|h| h.is_finite() && *h >= 0.0);
2088 if let Some(root) = self.nodes[key as usize].root.as_mut()
2089 && root.header != height
2090 {
2091 root.header = height;
2092 self.needs_layout = true;
2093 }
2094 }
2095
2096 pub fn set_font_scale(&mut self, scale: f32) {
2099 let scale = if scale.is_finite() && scale > 0.0 {
2100 scale
2101 } else {
2102 1.0
2103 };
2104 if scale == self.font_scale {
2105 return;
2106 }
2107 self.font_scale = scale;
2108 self.ch_changed(self.root);
2109 self.relayout_text();
2110 }
2111
2112 pub(crate) fn set_default_font(&mut self, family: Option<crate::style::FontFamily>) {
2115 if family == self.default_font {
2116 return;
2117 }
2118 self.default_font = family;
2119 self.ch_changed(self.root);
2120 self.relayout_text();
2121 }
2122
2123 fn relayout_text(&mut self) {
2125 let blocks: Vec<(Key, Kind)> = self
2126 .nodes
2127 .iter()
2128 .filter(|(_, n)| matches!(n.kind, Kind::Text | Kind::Input) && !n.inline)
2129 .map(|(k, n)| (k as Key, n.kind))
2130 .collect();
2131 for (key, kind) in blocks {
2132 if kind == Kind::Text {
2133 self.mark(key, dirty::TEXT_BUILD);
2134 } else {
2135 self.measure_input(key);
2136 self.mark(key, dirty::INPUT);
2137 }
2138 }
2139 }
2140
2141 fn repick_images(&mut self, old: f32, new: f32) {
2144 let changes = |s: &Option<ImageSource>| {
2145 s.as_ref()
2146 .is_some_and(|s| !s.scales.is_empty() && s.variant(old) != s.variant(new))
2147 };
2148 let images: Vec<Key> = self
2149 .nodes
2150 .iter()
2151 .filter(|(_, n)| {
2152 n.image
2153 .as_ref()
2154 .is_some_and(|i| changes(&i.source) || changes(&i.options.placeholder))
2155 })
2156 .map(|(k, _)| k as Key)
2157 .collect();
2158 for key in images {
2159 self.mark(key, dirty::IMAGE);
2160 }
2161 }
2162
2163 pub fn node_count(&self) -> usize {
2165 self.nodes.len()
2166 }
2167
2168 pub fn node_id_room(&self) -> usize {
2172 self.slots.len()
2173 }
2174
2175 pub fn set_access(&mut self, access: Arc<crate::access::Access>) {
2178 {
2180 let _entered = self.components.runtime.enter();
2181 crate::element::global::<crate::element::desktop::WindowAccess>()
2182 .set(crate::element::desktop::WindowAccess(Some(access.clone())));
2183 }
2184 self.components.runtime.set_access(access.clone());
2185 self.access = access;
2186 self.canvas_images.clear();
2187 }
2188
2189 pub fn set_base_url(&mut self, url: Option<Arc<str>>) {
2196 self.base_url = url;
2197 self.canvas_images.clear();
2198 }
2199
2200 pub fn set_media_files(&mut self, files: Arc<crate::access::MediaFiles>) {
2205 self.media_files = files;
2206 self.canvas_images.clear();
2207 }
2208
2209 #[cfg(not(target_arch = "wasm32"))]
2214 pub fn set_image_context(&mut self, context: crate::image::loader::Context) {
2215 crate::image::loader::set_context(context);
2216 }
2217
2218 pub fn set_clipboard(&mut self, backend: Option<Arc<dyn crate::clipboard::ClipboardBackend>>) {
2221 self.clipboard = backend;
2222 }
2223
2224 pub fn set_picker(&mut self, backend: Option<Arc<dyn crate::picker::PickerBackend>>) {
2228 self.picker = backend;
2229 }
2230
2231 pub fn set_quit_mode(&mut self, mode: crate::desktop::QuitMode) {
2235 self.quit_mode = Some(mode);
2236 }
2237
2238 #[doc(hidden)]
2243 pub fn __set_default_quit_mode(&mut self, mode: crate::desktop::QuitMode) {
2244 self.default_quit_mode = mode;
2245 }
2246
2247 pub fn set_main_window(&mut self, options: &crate::desktop::MainWindowOptions) {
2256 self.main_window_options = Some(options.clone());
2257 self.keep_main_placement = options.restore_bounds;
2258 self.main_shown |= options.visible_at_launch();
2259 if let Some(state) = self.components.environment.window_state {
2260 self.keep_window_placement(crate::ROOT_ID, &state);
2261 }
2262 if options.attributes.is_empty() {
2263 return;
2264 }
2265 if self.key(crate::ROOT_ID).is_ok() {
2268 self.window_command(
2269 crate::ROOT_ID,
2270 crate::desktop::DesktopCommand::SetAttributes(Box::new(options.attributes.clone())),
2271 true,
2272 );
2273 }
2274 }
2275
2276 pub fn set_window_backend(&mut self, backend: Option<Arc<dyn crate::desktop::WindowBackend>>) {
2281 self.window_backend = backend;
2282 }
2283
2284 pub fn set_audio(&mut self, backend: Option<Arc<dyn crate::audio::AudioBackend>>) {
2288 self.audio = backend;
2289 }
2290
2291 pub fn set_login_item(&mut self, backend: Option<Arc<dyn crate::desktop::LoginItemBackend>>) {
2296 self.login_item = backend.map(crate::desktop::LoginItems::new);
2297 }
2298
2299 pub fn set_storage(&mut self, backend: Option<Arc<dyn crate::storage::StorageBackend>>) {
2302 self.components
2303 .runtime
2304 .set_storage(crate::storage::Store::new(backend));
2305 }
2306
2307 pub fn set_data_dir(&mut self, dir: Option<std::path::PathBuf>) {
2310 self.components.runtime.set_data_dir(dir);
2311 }
2312
2313 pub fn set_app_info(&mut self, info: Option<crate::platform::AppInfo>) {
2317 self.components.runtime.set_app_info(info);
2318 }
2319
2320 pub fn set_updater(
2324 &mut self,
2325 updater: Option<std::sync::Arc<dyn crate::runtime::UpdaterHost>>,
2326 ) {
2327 self.components.runtime.set_updater(updater);
2328 }
2329
2330 fn deny(&mut self, what: String) {
2332 if self.denied.len() < 256 && self.denied.insert(what.clone()) {
2333 log::warn!(target: "js", "{what}");
2334 }
2335 }
2336
2337 pub fn set_max_nodes(&mut self, max: usize) {
2340 self.max_nodes = max.max(1);
2341 }
2342
2343 pub fn set_resizing(&mut self, resizing: bool) {
2349 if resizing == self.measure_cache.resizing.is_some() {
2350 return;
2351 }
2352 if resizing {
2353 self.resizing_commit = self.resizing_commit.wrapping_add(1).max(1);
2354 self.measure_cache.resizing = Some(self.resizing_commit);
2355 return;
2356 }
2357 self.measure_cache.resizing = None;
2358 let keys: Vec<(Key, LayoutId)> = self
2359 .nodes
2360 .iter()
2361 .filter_map(|(key, node)| Some((key as Key, node.layout?)))
2362 .collect();
2363 for (key, layout) in keys {
2364 let Some(LeafContext::Text(cx)) = self.layout.get_node_context_mut(layout) else {
2365 continue;
2366 };
2367 if std::mem::take(&mut cx.held) {
2368 self.layout.mark_dirty(layout);
2369 self.needs_layout = true;
2370 self.resize_settling = true;
2371 self.queue_text(key);
2372 }
2373 }
2374 }
2375
2376 fn mark_near_screen(&mut self) {
2380 self.resizing_commit = self.resizing_commit.wrapping_add(1).max(1);
2381 self.measure_cache.resizing = Some(self.resizing_commit);
2382 let (width, height) = (self.viewport.width.0, self.viewport.height.0);
2383 let mut stack = vec![(self.root, 0.0f32, 0.0f32)];
2384 while let Some((key, x, y)) = stack.pop() {
2385 let node = &self.nodes[key as usize];
2386 let frame = node.frame;
2387 let (mut x, mut y) = (x, y);
2388 if !frame.origin.x.0.is_nan() {
2392 x += frame.origin.x.0;
2393 y += frame.origin.y.0;
2394 let (w, h) = (frame.size.width.0, frame.size.height.0);
2395 let sized = w > 0.0 && h > 0.0;
2396 if sized
2397 && (x + w < -width || x > 2.0 * width || y + h < -height || y > 2.0 * height)
2398 {
2399 continue;
2400 }
2401 }
2402 if let Some(scroll) = node.scroll.as_deref() {
2403 x -= scroll.offset.0;
2404 y -= scroll.offset.1;
2405 }
2406 stack.extend(node.children.iter().map(|&child| (child, x, y)));
2407 if let Some(layout) = node.layout
2408 && let Some(LeafContext::Text(cx)) = self.layout.get_node_context_mut(layout)
2409 {
2410 cx.near_screen = self.resizing_commit;
2411 if std::mem::take(&mut cx.held) {
2412 self.layout.mark_dirty(layout);
2413 self.queue_text(key);
2414 }
2415 }
2416 }
2417 }
2418
2419 pub fn set_viewport(&mut self, viewport: Size<Points>) {
2421 if viewport != self.viewport {
2422 self.viewport = viewport;
2423 self.resize_settling = true;
2424 let root = self.nodes[self.root as usize].layout.expect("root layout");
2425 self.layout.set_style(root, root_style(viewport));
2426 self.needs_layout = true;
2427 self.components_viewport(viewport);
2429 }
2430 }
2431
2432 pub fn set_scroll_offset(&mut self, id: NodeId, offset: Point<Points>, applied: u32) {
2436 let (x, y) = (offset.x.0, offset.y.0);
2437 let Ok(key) = self.key(id) else { return };
2438 let node = &mut self.nodes[key as usize];
2439 let horizontal = node.scroll.as_ref().is_some_and(|s| s.horizontal);
2440 let mut dependents = false;
2441 let mut moved = false;
2442 if let Some(scroll) = node.scroll.as_mut() {
2443 moved = scroll.offset != (x, y);
2444 let issued = scroll.target.is_some_and(|(n, _)| n <= applied);
2446 scroll.step = match issued {
2447 true => (0.0, 0.0),
2448 false => (x - scroll.offset.0, y - scroll.offset.1),
2449 };
2450 scroll.offset = (x, y);
2451 if issued {
2452 scroll.target = None;
2453 }
2454 if !scroll.dependents.is_empty() {
2455 scroll.pending.retain(|&(n, _)| n > applied);
2456 dependents = true;
2457 }
2458 }
2459 if let Some(list) = node.list.as_mut() {
2460 list.reported(if horizontal { x } else { y }, applied);
2461 }
2462 self.cull_moved(key);
2463 if dependents {
2464 self.dependents_dirty(key);
2465 }
2466 self.follow_changed |= moved && !self.followers.is_empty();
2469 if moved && !self.overlays.is_empty() {
2472 self.overlay_scrolled(key);
2473 }
2474 }
2475
2476 pub fn key_scrolled(&mut self, id: NodeId, key_move: crate::scroll::KeyMove) {
2486 let Ok(key) = self.key(id) else { return };
2487 let queued = self.commands.iter().filter(|(to, _)| *to == id).count() as u32;
2488 let Some(list) = self.nodes[key as usize].list.as_mut() else {
2489 return;
2490 };
2491 if !list.follows_end_key() {
2492 return;
2493 }
2494 if key_move == crate::scroll::KeyMove::End {
2495 let repeat = match list.key_ends.last() {
2497 Some(&n) => n + 1 == queued,
2498 None => queued == 0 && list.follows_end(),
2499 };
2500 if !repeat {
2501 list.key_ends.push(queued);
2502 self.commands
2503 .push((id, Command::ScrollToEnd { animated: true }));
2504 }
2505 return;
2506 }
2507 list.unpin();
2508 let ends = std::mem::take(&mut list.key_ends);
2509 for &n in ends.iter().rev() {
2511 let at = self
2512 .commands
2513 .iter()
2514 .enumerate()
2515 .filter(|(_, (to, _))| *to == id)
2516 .nth(n as usize)
2517 .map(|(at, _)| at);
2518 if let Some(at) = at {
2519 self.commands.remove(at);
2520 }
2521 }
2522 }
2523
2524 pub fn set_kept(&mut self, nodes: &[NodeId]) {
2531 self.selection_kept.clear();
2532 self.selection_kept.extend_from_slice(nodes);
2533 self.sync_kept();
2534 }
2535
2536 fn sync_kept(&mut self) {
2548 let mut holders = std::mem::take(&mut self.kept_scratch);
2549 holders.clear();
2550 holders.extend(
2551 self.selection_kept
2552 .iter()
2553 .filter_map(|&id| self.key(id).ok()),
2554 );
2555 let focus = self
2556 .focus
2557 .filter(|&(key, id)| self.nodes.get(key as usize).is_some_and(|n| n.id == id))
2558 .map(|(key, _)| key);
2559 holders.extend(focus);
2560 holders.extend(self.overlays.iter().copied().filter(|&key| {
2561 self.overlay(key)
2562 .is_some_and(|o| o.host.is_some() && o.config.hint.is_none())
2563 }));
2564 let mut kept: Vec<(Key, u32)> = Vec::new();
2565 for &holder in &holders {
2566 let mut key = holder;
2567 loop {
2570 let parent = self.nodes[key as usize].parent;
2571 if parent == NO_KEY {
2572 break;
2573 }
2574 if let Some(list) = self.nodes[parent as usize].list.as_ref()
2575 && let Some(index) = list
2576 .slots
2577 .iter()
2578 .find(|s| s.cell == key)
2579 .and_then(|s| s.index)
2580 {
2581 kept.push((parent, index));
2582 if focus == Some(holder) {
2583 if index > 0 {
2584 kept.push((parent, index - 1));
2585 }
2586 if index + 1 < list.count {
2587 kept.push((parent, index + 1));
2588 }
2589 }
2590 }
2591 key = parent;
2592 }
2593 }
2594 self.kept_scratch = holders;
2595 if kept.is_empty() && self.kept_lists.is_empty() {
2596 return;
2597 }
2598 let mut lists: Vec<Key> = kept.iter().map(|&(list, _)| list).collect();
2599 lists.sort_unstable();
2600 lists.dedup();
2601 for &list in self.kept_lists.iter().filter(|l| !lists.contains(l)) {
2602 if let Some(state) = self
2603 .nodes
2604 .get_mut(list as usize)
2605 .and_then(|n| n.list.as_mut())
2606 {
2607 state.set_kept(Vec::new());
2608 }
2609 }
2610 for &list in &lists {
2611 let items = kept
2612 .iter()
2613 .filter(|&&(l, _)| l == list)
2614 .map(|&(_, i)| i)
2615 .collect();
2616 if let Some(state) = self.nodes[list as usize].list.as_mut() {
2617 state.set_kept(items);
2618 }
2619 }
2620 self.kept_lists = lists;
2621 }
2622
2623 pub fn set_input_scroll(
2627 &mut self,
2628 id: NodeId,
2629 offset: Point<Points>,
2630 content: Size<Points>,
2631 viewport: Size<Points>,
2632 ) {
2633 let Ok(key) = self.key(id) else { return };
2634 if let Some(input) = self.nodes[key as usize].input.as_mut() {
2635 input.scroll = Some(InputScroll {
2636 offset,
2637 content,
2638 viewport,
2639 });
2640 }
2641 }
2642
2643 pub fn set_zoom(&mut self, id: NodeId, scale: f32) {
2645 let Ok(key) = self.key(id) else { return };
2646 if let Some(scroll) = self.nodes[key as usize].scroll.as_mut() {
2647 scroll.zoom = scale;
2648 }
2649 }
2650
2651 pub fn set_component_size(&mut self, id: NodeId, size: Size<Points>) {
2654 let Ok(key) = self.key(id) else { return };
2655 let Some(layout) = self.nodes[key as usize].layout else {
2656 return;
2657 };
2658 if let Some(LeafContext::Native(own)) = self.layout.get_node_context_mut(layout)
2659 && *own != Some(size)
2660 {
2661 *own = Some(size);
2662 self.layout.mark_dirty(layout);
2663 self.needs_layout = true;
2664 }
2665 }
2666
2667 pub fn scroll_listener(&self, id: NodeId) -> Option<(f32, Size<Points>, Size<Points>, f32)> {
2671 let node = &self.nodes[self.key(id).ok()? as usize];
2672 if !node.events.contains(EventKind::Scroll) {
2673 return None;
2674 }
2675 let scroll = node.scroll.as_ref()?;
2676 let frame = node.frame.size;
2677 let content = scroll.content.unwrap_or(frame);
2678 let z = scroll.zoom;
2679 Some((scroll.event_throttle_ms, content * z, frame, z))
2680 }
2681
2682 pub fn take_list_binds(&mut self, out: &mut Vec<ListBind>) {
2687 out.append(&mut self.list_binds);
2688 }
2689
2690 pub fn has_paced_list_binds(&self) -> bool {
2692 !self.paced_lists.is_empty()
2693 }
2694
2695 pub fn take_paced_list_binds(&mut self, cells: usize, out: &mut Vec<ListBind>) {
2700 let mut left = cells;
2701 let mut lists = std::mem::take(&mut self.paced_lists);
2702 let mut one = std::mem::take(&mut self.paced_scratch);
2703 let start = out.len();
2704 while left > 0 && !lists.is_empty() {
2705 lists.retain(|&id| {
2706 if left == 0 {
2707 return true;
2708 }
2709 let Some(list) = self
2710 .key(id)
2711 .ok()
2712 .and_then(|key| self.nodes[key as usize].list.as_mut())
2713 else {
2714 return false;
2715 };
2716 one.clear();
2717 left -= list.take_paced(1, &mut one);
2718 if let Some((slot, index)) = one.pop() {
2719 match out[start..].iter_mut().find(|b| b.list == id) {
2720 Some(bind) => bind.binds.push((slot, index)),
2721 None => out.push(ListBind {
2722 list: id,
2723 binds: vec![(slot, index)],
2724 }),
2725 }
2726 }
2727 list.has_paced()
2728 });
2729 }
2730 self.paced_lists = lists;
2731 self.paced_scratch = one;
2732 }
2733
2734 pub fn has_events(&self) -> bool {
2736 !self.events.is_empty()
2737 }
2738
2739 pub fn take_events(&mut self, out: &mut Vec<crate::element::JsEvent>) {
2743 if !self.asked_rows.is_empty() {
2744 let rows = std::mem::take(&mut self.asked_rows);
2745 self.events.push(crate::element::JsEvent::Rows(rows));
2746 }
2747 out.append(&mut self.events);
2748 self.components.executor.hand_answers();
2751 }
2752
2753 pub fn has_due_answers(&self) -> bool {
2757 self.components.executor.has_due_answers()
2758 }
2759
2760 pub fn register_font(&mut self, data: &[u8]) -> Result<(), String> {
2763 self.text_engine
2764 .register_font(&crate::text::font_data(data)?)?;
2765 self.fonts_changed();
2766 Ok(())
2767 }
2768
2769 pub fn fonts_changed(&mut self) {
2773 self.zero_advances.clear();
2774 self.ch_changed(self.root);
2775 self.measure_cache.clear();
2776 let blocks: Vec<Key> = self
2777 .nodes
2778 .iter()
2779 .filter(|(_, n)| {
2780 matches!(n.kind, Kind::Text | Kind::Input) && !n.inline && n.layout.is_some()
2781 })
2782 .map(|(k, _)| k as Key)
2783 .collect();
2784 for key in blocks {
2785 let layout = self.nodes[key as usize].layout.expect("text layout");
2786 let cx = self.text_cx(layout);
2787 cx.prepared = None;
2788 cx.min_content = None;
2789 cx.cache = None;
2790 cx.baseline = None;
2791 cx.same_lines = None;
2792 cx.no_ahead = false;
2793 cx.laid_out = None;
2794 if let Some(field) = &mut cx.field {
2795 field.prepared = None;
2796 field.cache = None;
2797 }
2798 self.layout.mark_dirty(layout);
2799 self.needs_layout = true;
2800 if self.nodes[key as usize].kind == Kind::Text {
2801 self.queue_text(key);
2802 } else {
2803 self.mark(key, dirty::INPUT);
2805 }
2806 }
2807 }
2808
2809 pub fn remount(&mut self) {
2814 self.fonts_changed();
2815 let keys: Vec<Key> = self
2816 .nodes
2817 .iter()
2818 .filter(|(_, n)| n.created)
2819 .map(|(k, _)| k as Key)
2820 .collect();
2821 for key in keys {
2822 let flags = self.mount_state(key);
2823 self.mark(key, flags);
2824 let node = &mut self.nodes[key as usize];
2825 if let Some(root) = node.root.as_mut() {
2826 root.laid_out = None;
2827 }
2828 let id = node.id;
2833 if let Some(scroll) = node.scroll.as_mut()
2834 && let Some(size) = scroll.content
2835 {
2836 scroll.content_item = Some((self.batches, self.mount.len()));
2837 self.mount.push(MountItem::ScrollContent { id, size });
2838 }
2839 if let Some(layout) = node.layout {
2840 self.layout.mark_dirty(layout);
2842 }
2843 let ranges = self.sticky_ranges(key);
2847 if !ranges.is_empty() {
2848 self.mount.push(MountItem::StickyCells {
2849 id,
2850 cells: ranges
2851 .into_iter()
2852 .map(|r| StickyCell {
2853 cell: r.cell,
2854 start: Points(r.start),
2855 end: Points(r.end),
2856 offset: r.offset,
2857 })
2858 .collect(),
2859 });
2860 }
2861 }
2862 self.needs_layout = true;
2863 }
2864
2865 pub fn limit_paste(&self, id: NodeId, payload: &mut EventPayload) {
2870 let EventPayload::Paste(paste) = payload else {
2871 return;
2872 };
2873 let max = self
2874 .key(id)
2875 .ok()
2876 .and_then(|key| self.nodes[key as usize].input.as_ref())
2877 .and_then(|input| input.config.paste_max_size);
2878 if let Some(max) = max {
2879 paste.limit_files(max);
2880 }
2881 }
2882
2883 pub fn input_changed(&mut self, id: NodeId, text: &str, count: u32) {
2886 let Ok(key) = self.key(id) else { return };
2887 let Some(input) = self.nodes[key as usize].input.as_mut() else {
2888 return;
2889 };
2890 input.count = count;
2891 if input.value != text {
2892 input.value.clear();
2893 input.value.push_str(text);
2894 self.measure_input(key);
2895 }
2896 }
2897
2898 pub fn input_composing(&mut self, id: NodeId, shown: Option<&str>) {
2904 let Ok(key) = self.key(id) else { return };
2905 let Some(input) = self.nodes[key as usize].input.as_mut() else {
2906 return;
2907 };
2908 if input.composing.as_deref() == shown {
2909 return;
2910 }
2911 input.composing = shown.map(str::to_owned);
2912 self.measure_input(key);
2913 }
2914
2915 pub fn apply(&mut self, op: Op) -> Result<(), ApplyError> {
2917 let _entered = self.components.runtime.enter();
2918 if self.components.instances.is_empty()
2923 && !matches!(
2924 op,
2925 Op::Command {
2926 command: Command::Native { .. },
2927 ..
2928 } | Op::Listen {
2929 id: ROOT_ID,
2930 event: EventKind::BackPress | EventKind::BackProgress | EventKind::KeyCommand,
2931 ..
2932 } | Op::SetProp {
2933 id: ROOT_ID,
2934 prop: Prop::Keymap(_),
2935 }
2936 )
2937 {
2938 return self.apply_op(op);
2939 }
2940 match self.intercept(op)? {
2941 Some(op) => self.apply_op(op),
2942 None => Ok(()),
2943 }
2944 }
2945
2946 fn apply_op(&mut self, op: Op) -> Result<(), ApplyError> {
2948 if !self.runs.is_empty()
2949 && let Op::Evaluate { id, .. }
2950 | Op::Draw { id, .. }
2951 | Op::SetStyle { id, .. }
2952 | Op::SetProp { id, .. }
2953 | Op::Listen { id, .. }
2954 | Op::Placeholder { id }
2955 | Op::Command { id, .. } = op
2956 {
2957 self.materialize_run(id)?;
2958 }
2959 match op {
2960 Op::Evaluate {
2961 id,
2962 call,
2963 script,
2964 timeout,
2965 } => {
2966 self.start_js_web_evaluation(id, call, script, timeout);
2967 Ok(())
2968 }
2969 Op::RenderCanvas { call, request } => {
2970 self.start_js_canvas_render(call, *request);
2971 Ok(())
2972 }
2973 Op::Rust(op) => {
2974 self.run_rust(op);
2975 Ok(())
2976 }
2977 Op::Create { id, tag } => self.create(id, tag),
2978 Op::CreateText { id, text } => {
2979 let idx = id as usize;
2980 if self.slots.contains(idx) || self.runs.contains_key(&id) {
2981 return Err(ApplyError::DuplicateNode(id));
2982 }
2983 self.check_id_range(id)?;
2984 if self.fold_runs {
2985 if self.nodes.len().saturating_add(self.runs.len()) >= self.max_nodes {
2986 return Err(ApplyError::TooManyNodes(self.max_nodes));
2987 }
2988 self.runs.insert(
2989 id,
2990 Run {
2991 text,
2992 block: NO_KEY,
2993 },
2994 );
2995 self.admitted_id_extent = self.admitted_id_extent.max(idx.saturating_add(1));
2996 return Ok(());
2997 }
2998 let key = self.alloc(id, Kind::RawText)?;
2999 self.nodes[key as usize].text = text;
3000 Ok(())
3001 }
3002 Op::SetText { id, text } => {
3003 if let Some(run) = self.runs.get_mut(&id) {
3004 if run.text != text {
3005 run.text = text;
3006 let block = run.block;
3007 if block != NO_KEY {
3008 self.mark_text_block(block);
3009 }
3010 }
3011 return Ok(());
3012 }
3013 let key = self.key(id)?;
3014 let node = &mut self.nodes[key as usize];
3015 if node.text != text {
3016 node.text = text;
3017 if node.inline {
3018 self.mark_text_block(key);
3019 }
3020 }
3021 Ok(())
3022 }
3023 Op::SetStyle { id, style, patch } => self.set_inline_style(id, style, patch),
3024 Op::SetProp { id, prop } => {
3025 let role = matches!(
3026 prop,
3027 Prop::Accessibility(
3028 AccessibilityProp::Role(_)
3029 | AccessibilityProp::Label(_)
3030 | AccessibilityProp::State(_)
3031 ) | Prop::Scrollbar(_)
3032 | Prop::Horizontal(_)
3033 );
3034 let result = self.set_prop(id, prop);
3035 if role && let Ok(key) = self.key(id) {
3036 self.sync_grid_role(key);
3037 }
3038 result
3039 }
3040 Op::Listen { id, event, enabled } => {
3041 let key = self.key(id)?;
3042 let node = &mut self.nodes[key as usize];
3043 let before = node.events;
3044 node.events.set(event, enabled);
3045 if PRESSES.contains(&event) || HANDLED.contains(&event) {
3046 self.sync_grid_role(key);
3047 }
3048 if event == EventKind::Layout && enabled && !before.contains(event) {
3049 self.report_frame(key);
3050 }
3051 let node = &self.nodes[key as usize];
3052 let key_events = matches!(event, EventKind::KeyDown | EventKind::KeyUp);
3053 if node.events != before {
3054 let relink = node.inline && (pressable(before) || pressable(node.events));
3055 self.mark(key, dirty::EVENTS);
3056 if key_events {
3057 self.key_ancestry_dirty = true;
3058 }
3059 if relink {
3061 self.mark_text_block(key);
3062 }
3063 }
3064 if enabled
3067 && matches!(
3068 event,
3069 EventKind::Scroll
3070 | EventKind::Refresh
3071 | EventKind::ScrollEnd
3072 | EventKind::ScrollDragStart
3073 | EventKind::ScrollDragEnd
3074 | EventKind::MomentumStart
3075 | EventKind::MomentumEnd
3076 )
3077 && self.nodes[key as usize]
3078 .list
3079 .as_ref()
3080 .is_some_and(|l| l.parent)
3081 {
3082 self.warn_ignored(key);
3083 }
3084 Ok(())
3085 }
3086 Op::Insert {
3087 parent,
3088 child,
3089 before,
3090 } => self.insert(parent, child, before),
3091 Op::Remove { parent, child } => {
3092 let parent = self.key(parent)?;
3093 if let Some(run) = self.runs.get(&child) {
3094 if run.block != parent {
3095 return Err(ApplyError::NotAChild(child));
3096 }
3097 self.unfold_run(child);
3098 return Ok(());
3099 }
3100 let child = self.key(child)?;
3101 if self.nodes[child as usize].parent != parent {
3102 return Err(ApplyError::NotAChild(self.nodes[child as usize].id));
3103 }
3104 self.detach(child);
3105 Ok(())
3106 }
3107 Op::Release { id } => self.release(id),
3108 Op::Placeholder { id } => {
3109 let key = self.key(id)?;
3110 self.placeholder(key);
3111 Ok(())
3112 }
3113 Op::Animation(op) => {
3114 if self.reach.apply(&op) && !self.culling.is_empty() {
3117 self.cull_dirty = true;
3118 }
3119 self.mount.push(MountItem::Animation(op));
3120 Ok(())
3121 }
3122 Op::Draw { id, mut drawing } => {
3123 let key = self.key(id)?;
3124 if self.nodes[key as usize].kind != Kind::Canvas {
3125 return Ok(());
3126 }
3127 self.check_canvas_images(&mut drawing);
3128 let node = &mut self.nodes[key as usize];
3129 let slots_changed = node
3130 .drawing
3131 .as_ref()
3132 .map_or(!drawing.slots.is_empty(), |d| d.slots != drawing.slots);
3133 if node.drawing.as_deref() == Some(&*drawing) {
3134 return Ok(());
3135 }
3136 if node.drawing.is_none() && drawing.ops.is_empty() && drawing.nodes.is_empty() {
3139 return Ok(());
3140 }
3141 let background_moved = node.drawing.as_ref().is_some_and(|d| d.paints_background())
3144 != drawing.paints_background();
3145 let natural = drawing.fit().map(|fit| fit.size);
3148 if node
3149 .drawing
3150 .as_ref()
3151 .and_then(|d| d.fit())
3152 .map(|fit| fit.size)
3153 != natural
3154 && let Some(layout) = node.layout
3155 {
3156 self.layout
3157 .set_node_context(layout, natural.map(|n| LeafContext::Image(Some(n))));
3158 self.layout.mark_dirty(layout);
3159 self.needs_layout = true;
3160 }
3161 let node = &mut self.nodes[key as usize];
3162 node.drawing = Some(Arc::from(drawing));
3163 let flags = dirty::CANVAS
3164 | if slots_changed { dirty::ANIMATION } else { 0 }
3165 | if background_moved { dirty::VIEW } else { 0 };
3166 self.mark(key, flags);
3167 Ok(())
3168 }
3169 Op::Command {
3170 id: crate::ROOT_ID,
3171 command: Command::LayoutAnimation(animation),
3172 } => {
3173 self.layout_animation = Some(animation);
3174 Ok(())
3175 }
3176 Op::Command {
3178 id,
3179 command: Command::LayoutAnimation(animation),
3180 } => {
3181 self.key(id)?;
3182 if let Some(transition) = animation.update {
3183 self.scope_layout_animation(id, transition);
3184 }
3185 Ok(())
3186 }
3187 Op::Command {
3188 id: crate::ROOT_ID,
3189 command: Command::SetStatusBar(patch),
3190 } => {
3191 self.components.status_bars.set_base(patch);
3192 Ok(())
3193 }
3194 Op::Command {
3197 id,
3198 command: Command::SetJsResponder { block },
3199 } => {
3200 self.key(id)?;
3201 self.block_native(touch::Side::Js, block.then_some(id));
3202 Ok(())
3203 }
3204 Op::Command {
3205 id,
3206 command: Command::CancelPress,
3207 } => {
3208 self.key(id)?;
3209 self.cancel_press(id);
3210 Ok(())
3211 }
3212 Op::Command {
3213 command: Command::ClearJsResponder,
3214 ..
3215 } => {
3216 self.block_native(touch::Side::Js, None);
3217 Ok(())
3218 }
3219 Op::Command {
3221 id,
3222 command: Command::Measure { call },
3223 } if self.key(id).is_err() => {
3224 self.answer_measure(id, call);
3225 Ok(())
3226 }
3227 Op::Command {
3228 id,
3229 command: Command::MeasureScrollPosition { call },
3230 } if self.key(id).is_err() => {
3231 self.answer_scroll_position(id, call);
3232 Ok(())
3233 }
3234 Op::Command {
3237 id,
3238 command: Command::Desktop(desktop),
3239 } if desktop.is_core_handled() => {
3240 self.key(id)?;
3241 self.window_command(id, *desktop, false);
3242 Ok(())
3243 }
3244 Op::Command { id, command } => {
3245 self.key(id)?;
3246 self.commands.push((id, command));
3247 Ok(())
3248 }
3249 }
3250 }
3251
3252 fn window_command(
3257 &mut self,
3258 id: NodeId,
3259 command: crate::desktop::DesktopCommand,
3260 launch: bool,
3261 ) {
3262 use crate::desktop::{
3263 DesktopCommand, WindowPlacement, WindowRequest,
3264 window::{WindowRecord, placement_key},
3265 };
3266 match command {
3267 DesktopCommand::SetQuitMode(_) if !self.access.allows_application() => {
3270 self.deny(
3271 "the application (its main window, menu, tray, global shortcuts, quitting and restarting) is not granted: add `\"application\": true` to capabilities in nsh.json".into(),
3272 );
3273 }
3274 DesktopCommand::SetAttributes(_)
3277 if id == crate::ROOT_ID && !launch && !self.access.allows_application() =>
3278 {
3279 self.deny(
3280 "the application (its main window, menu, tray, global shortcuts, quitting and restarting) is not granted: add `\"application\": true` to capabilities in nsh.json".into(),
3281 );
3282 }
3283 DesktopCommand::Request(WindowRequest::SetPlacement(_))
3284 if id == crate::ROOT_ID && !self.access.allows_application() =>
3285 {
3286 self.deny(
3287 "the application (its main window, menu, tray, global shortcuts, quitting and restarting) is not granted: add `\"application\": true` to capabilities in nsh.json".into(),
3288 );
3289 }
3290 DesktopCommand::SetAttributes(_) if !self.has_window() => {
3291 log::debug!("window attributes of view {id}: the surface has no window");
3292 }
3293 DesktopCommand::SetAttributes(mut attributes) => {
3294 attributes.sanitize();
3295 let denied = self.access.deny_window_attributes(&mut attributes);
3296 if !denied.is_empty() {
3297 self.deny(format!(
3298 "nsh/desktop: the window attributes {} are not granted by capabilities.windows: left as they are",
3299 denied.join(", ")
3300 ));
3301 }
3302 if attributes.size_to_content.is_some()
3305 && let Ok(key) = self.key(id)
3306 && let Some(layout) = self.nodes[key as usize].layout
3307 {
3308 self.layout.mark_dirty(layout);
3309 self.needs_layout = true;
3310 }
3311 self.windows
3312 .entry(id)
3313 .or_default()
3314 .pending
3315 .merge(&attributes);
3316 }
3317 DesktopCommand::SetQuitMode(mode) => {
3318 self.quit_mode = Some(mode);
3319 }
3320 DesktopCommand::OpenWindow(mut open) => {
3321 let options = &mut open.options;
3322 let open_now = self
3325 .window_ids
3326 .values()
3327 .filter(|(node, _)| *node != id && self.key(*node).is_ok())
3328 .count();
3329 if !self.launch_defaults_applied {
3335 if let Some(defaults) = self.main_window_options.clone() {
3336 if options.default_size.is_none() {
3337 options.default_size = defaults.default_size;
3338 }
3339 if options.default_position.is_none() {
3340 options.default_position = defaults.default_position;
3341 }
3342 if options.display.is_none() {
3343 options.display = defaults.display;
3344 }
3345 if options.default_mode.is_none() {
3346 options.default_mode = defaults.default_mode;
3347 }
3348 if !options.restore_bounds {
3349 options.restore_bounds = defaults.restore_bounds;
3350 }
3351 let mut attributes = defaults.attributes;
3352 attributes.merge(&options.attributes);
3353 options.attributes = attributes;
3354 }
3355 if let Some(state) = self.components.environment.window_state {
3356 if options.default_size.is_none() {
3357 options.default_size = Some(state.content_bounds.size);
3358 }
3359 if options.default_position.is_none() {
3360 options.default_position =
3361 Some(crate::desktop::WindowPosition::At(state.bounds.origin));
3362 }
3363 }
3364 }
3365 if !open.implicit
3368 && let Err(message) =
3369 self.access
3370 .check_window(options.kind, &options.attributes, open_now)
3371 {
3372 self.deny(format!("nsh/desktop: {message}: the window does not open"));
3373 return;
3374 }
3375 self.launch_defaults_applied = true;
3378 options.attributes.sanitize();
3379 options.attributes =
3380 crate::desktop::WindowAttributes::resolve(options.kind, &options.attributes);
3381 open.parent = options
3384 .parent
3385 .as_deref()
3386 .and_then(|parent| self.window_ids.get(parent).map(|(node, _)| *node));
3387 if options.restore_bounds {
3388 let _entered = self.components.runtime.enter();
3389 open.placement = crate::storage::Storage::get_item(&placement_key(&options.id))
3390 .and_then(|json| serde_json::from_str::<WindowPlacement>(&json).ok())
3391 .map(|p| self.components.runtime.fit_window_placement(p));
3392 }
3393 let size = open
3394 .placement
3395 .map(|p| p.bounds.size)
3396 .or(options.default_size);
3397 self.windows.insert(
3398 id,
3399 WindowRecord::opened(options.attributes.clone(), size, open.implicit),
3400 );
3401 self.window_ids
3402 .insert(options.id.clone(), (id, options.restore_bounds));
3403 self.key_ancestry_dirty = true;
3404 self.commands.push((
3405 id,
3406 Command::Desktop(Box::new(DesktopCommand::OpenWindow(open))),
3407 ));
3408 }
3409 DesktopCommand::Request(WindowRequest::SetPlacement(placement)) => {
3412 let placement = self.components.runtime.fit_window_placement(placement);
3413 self.commands.push((
3414 id,
3415 Command::Desktop(Box::new(DesktopCommand::Request(
3416 WindowRequest::SetPlacement(placement),
3417 ))),
3418 ));
3419 }
3420 other => self.commands.push((id, Command::Desktop(Box::new(other)))),
3421 }
3422 }
3423
3424 fn flush_windows(&mut self) {
3427 if self.windows.is_empty() {
3428 return;
3429 }
3430 let had_windows = !self.window_ids.is_empty();
3431 let gone: Vec<NodeId> = self
3432 .windows
3433 .keys()
3434 .copied()
3435 .filter(|&id| {
3439 !self
3440 .key(id)
3441 .is_ok_and(|k| id == crate::ROOT_ID || self.nodes[k as usize].parent != NO_KEY)
3442 })
3443 .collect();
3444 let mut closed_implicit = false;
3445 for id in gone {
3446 if let Some(record) = self.windows.remove(&id) {
3447 closed_implicit |= record.implicit;
3448 }
3449 self.window_ids.retain(|_, (node, _)| *node != id);
3450 }
3451 if had_windows && self.window_ids.is_empty() {
3466 self.last_window_closed();
3467 let mode = self.quit_mode.unwrap_or(if closed_implicit {
3468 crate::desktop::QuitMode::LastWindowClosed
3469 } else {
3470 self.default_quit_mode
3471 });
3472 if mode.quits(self.components.environment.os) {
3473 self.commands.push((
3474 ROOT_ID,
3475 Command::Desktop(Box::new(crate::desktop::DesktopCommand::Quit)),
3476 ));
3477 }
3478 }
3479 let mut ids: Vec<NodeId> = self.windows.keys().copied().collect();
3480 ids.sort_unstable();
3481 for id in ids {
3482 let Some(diff) = self.windows.get_mut(&id).and_then(|r| r.take_diff()) else {
3483 continue;
3484 };
3485 let at = self
3488 .commands
3489 .iter()
3490 .position(|(to, c)| {
3491 *to == id
3492 && matches!(c, Command::Desktop(d)
3493 if matches!(**d, crate::desktop::DesktopCommand::Request(_)))
3494 })
3495 .unwrap_or(self.commands.len());
3496 self.commands.insert(
3497 at,
3498 (
3499 id,
3500 Command::Desktop(Box::new(crate::desktop::DesktopCommand::SetAttributes(
3501 Box::new(diff),
3502 ))),
3503 ),
3504 );
3505 }
3506 }
3507
3508 fn fit_window(&mut self, key: Key, layout: LayoutId) {
3513 let id = self.nodes[key as usize].id;
3514 let Some(record) = self.windows.get_mut(&id) else {
3515 return;
3516 };
3517 let (width, height) = record.fits();
3518 if !width && !height {
3519 record.fitted = None;
3520 return;
3521 }
3522 let laid_out = self.layout.unrounded_layout(layout).size;
3523 let size = crate::geometry::size(
3524 Points(laid_out.width.ceil()),
3525 Points(laid_out.height.ceil()),
3526 );
3527 if record.fitted == Some(size) {
3528 return;
3529 }
3530 record.fitted = Some(size);
3531 self.commands.push((
3532 id,
3533 Command::Desktop(Box::new(crate::desktop::DesktopCommand::Request(
3534 crate::desktop::WindowRequest::SetContentSize {
3535 width: width.then_some(size.width),
3536 height: height.then_some(size.height),
3537 },
3538 ))),
3539 ));
3540 }
3541
3542 pub(crate) fn root_view_size(&self, key: Key) -> Option<Size<Points>> {
3550 let node = &self.nodes[key as usize];
3551 if let Some(size) = node.root.as_ref().and_then(|r| r.reported) {
3552 return Some(size);
3553 }
3554 if self.window_ids.values().any(|(id, _)| *id == node.id) {
3555 return self.windows.get(&node.id).and_then(|r| r.fitted.or(r.size));
3556 }
3557 Some(self.viewport)
3558 }
3559
3560 pub(crate) fn window_of(&self, key: Key) -> NodeId {
3563 if self.window_ids.is_empty() {
3564 return crate::ROOT_ID;
3565 }
3566 let mut k = self.nodes[key as usize].parent;
3567 while k != NO_KEY {
3568 let n = &self.nodes[k as usize];
3569 if n.kind == Kind::Modal && self.window_ids.values().any(|(node, _)| *node == n.id) {
3570 return n.id;
3571 }
3572 k = n.parent;
3573 }
3574 crate::ROOT_ID
3575 }
3576
3577 fn has_window(&self) -> bool {
3583 let os = self.components.environment.os;
3584 os.is_desktop() || os == crate::platform::Os::Web
3585 }
3586
3587 pub(crate) fn keep_window_placement(
3597 &mut self,
3598 id: NodeId,
3599 state: &crate::desktop::WindowState,
3600 ) {
3601 if id == crate::ROOT_ID {
3602 self.main_shown |= state.visible;
3603 if !self.main_shown {
3604 return;
3605 }
3606 }
3607 let key = if id == crate::ROOT_ID {
3608 self.keep_main_placement
3609 .then(|| crate::desktop::window::placement_key("main"))
3610 } else {
3611 self.window_ids
3612 .iter()
3613 .find(|(_, (node, keep))| *node == id && *keep)
3614 .map(|(key, _)| crate::desktop::window::placement_key(key))
3615 };
3616 let Some(key) = key else {
3617 return;
3618 };
3619 if let Ok(json) = serde_json::to_string(&state.placement) {
3620 let _entered = self.components.runtime.enter();
3621 if crate::storage::Storage::get_item(&key).as_deref() != Some(json.as_str()) {
3622 let _ = crate::storage::Storage::set_item(key, json);
3623 }
3624 }
3625 }
3626
3627 pub fn content_height(&self) -> Option<Points> {
3635 self.nodes[self.root as usize]
3636 .children
3637 .iter()
3638 .filter_map(|&key| {
3639 let node = &self.nodes[key as usize];
3640 let layout = node.layout?;
3641 if node.is_layout_root()
3642 || self.layout.displays_none(layout)
3643 || matches!(
3644 self.layout.style(layout).position,
3645 Position::Absolute | Position::Fixed
3646 )
3647 || node.frame.origin.y.0.is_nan()
3648 {
3649 return None;
3650 }
3651 Some(node.frame.origin.y.0 + node.frame.size.height.0)
3652 })
3653 .reduce(f32::max)
3654 .map(Points)
3655 }
3656
3657 pub fn commit(&mut self) -> Option<MountBatch> {
3660 self.geometries.clear();
3663 self.poll_downloads();
3666 if self.components.executor.has_due_answers() {
3670 self.run_answers();
3671 }
3672 self.pace_commit();
3673 self.sync_quit_requests();
3674 self.commit_round();
3675 for _ in 0..MAX_VIRTUAL_ROUNDS {
3682 let watched = self.sync_watches();
3683 if !self.bind_virtual_lists()
3686 && !std::mem::take(&mut self.extent_changed)
3687 && !watched
3688 && !std::mem::take(&mut self.cull_made)
3689 && !std::mem::take(&mut self.placeholders_resized)
3690 && self.scrollbars_pending.is_empty()
3691 {
3692 break;
3693 }
3694 self.commit_round();
3695 }
3696 if !self.outer_asked.is_empty() {
3697 self.send_outer_scrolls();
3698 }
3699 if self.sync_quit_requests() {
3701 self.commit_round();
3702 }
3703 self.split_scoped_frames();
3704 self.mark_shader_inputs();
3705 if !self.transition_starts.is_empty() {
3706 let starts = std::mem::take(&mut self.transition_starts);
3709 self.mount.splice(0..0, starts);
3710 }
3711 if std::mem::take(&mut self.tab_places_stale) && !self.overlays.is_empty() {
3712 self.order_overlays_for_tab();
3713 }
3714 if std::mem::take(&mut self.tree_order_changed) {
3715 let mut order = Vec::new();
3716 let mut pending = vec![self.root];
3717 let mut cells = Vec::new();
3718 while let Some(key) = pending.pop() {
3719 let node = &self.nodes[key as usize];
3720 if node.created {
3721 order.push(node.id);
3722 }
3723 match &node.list {
3724 Some(list) if node.children.len() > 1 => {
3728 cells.clear();
3729 cells.extend_from_slice(&node.children);
3730 let start = |k: &Key| {
3731 let at = self.nodes[*k as usize].frame.origin;
3732 if list.horizontal {
3733 (at.x.0, at.y.0)
3734 } else {
3735 (at.y.0, at.x.0)
3736 }
3737 };
3738 cells.sort_by(|a, b| {
3739 let (a, b) = (start(a), start(b));
3740 a.0.total_cmp(&b.0).then(a.1.total_cmp(&b.1))
3741 });
3742 pending.extend(cells.iter().rev().copied());
3743 }
3744 _ => pending.extend(node.children.iter().rev().copied()),
3745 }
3746 }
3747 self.mount.push(MountItem::TreeOrder(order));
3748 }
3749 if self.mount.is_empty() || matches!(self.mount[..], [MountItem::LayoutAnimation(_)]) {
3750 self.mount.clear();
3751 None
3752 } else {
3753 self.batches += 1;
3754 Some(MountBatch {
3755 items: std::mem::take(&mut self.mount),
3756 })
3757 }
3758 }
3759
3760 pub fn set_tree_order_tracking(&mut self, enabled: bool) {
3763 self.track_tree_order = enabled;
3764 self.tree_order_changed = enabled;
3765 }
3766
3767 pub fn set_projected_state_mounting(&mut self, enabled: bool) {
3773 self.mount_projected = enabled;
3774 }
3775
3776 fn commit_round(&mut self) {
3779 if !self.components.hovers.is_empty() {
3781 self.pass_hovers();
3782 }
3783 if !self.scrollbars_pending.is_empty() {
3785 self.sync_scrollbars();
3786 }
3787 self.render_components();
3789 self.flush_positions();
3793 self.prepare_reveals();
3794 let visible_moved = std::mem::take(&mut self.focus_visible_moved);
3798 let held = self.blur_held && self.focus.is_none() && !self.focus_chain.is_empty();
3800 if self.focus_moved && !held {
3801 self.update_focus_within();
3802 self.update_focus_visible();
3803 if !self.overlays.is_empty() {
3805 self.focus_hints();
3806 }
3807 } else if visible_moved {
3808 self.update_focus_visible();
3811 }
3812 self.sync_pointer_keymap();
3813 self.sync_colors();
3814 self.sync_ch();
3815 self.sync_fixed();
3816 self.sync_overlays();
3817 if std::mem::take(&mut self.key_ancestry_dirty) {
3818 self.sync_key_parents();
3819 self.sync_key_contents();
3820 }
3821 if self.focus.is_some() || !self.overlays.is_empty() || !self.kept_lists.is_empty() {
3824 self.sync_kept();
3825 }
3826 self.sync_back();
3827 self.sync_back_progress();
3828 self.sync_keys();
3829 self.sync_env();
3832 if let Some(animation) = self.layout_animation.take() {
3833 self.note_list_motion(animation);
3834 self.mount.insert(0, MountItem::LayoutAnimation(animation));
3835 }
3836 self.flush_pointer_events();
3837 if !self.relators.is_empty() {
3838 self.sync_relations();
3839 }
3840 self.flush_dirty();
3841 let relayout = self.needs_layout;
3842 if relayout {
3843 self.needs_layout = false;
3844 let settling = std::mem::take(&mut self.resize_settling);
3845 let anchors = if settling || self.measure_cache.resizing.is_some() {
3846 self.resize_anchors()
3847 } else {
3848 Vec::new()
3849 };
3850 if self.measure_cache.resizing.is_some() {
3851 self.mark_near_screen();
3852 }
3853 let relaid = self.relayout_boundaries();
3856 if self.layout_main() {
3859 let root = self.root;
3860 let children = std::mem::take(&mut self.nodes[root as usize].children);
3861 for &child in &children {
3862 if !self.nodes[child as usize].is_layout_root() {
3863 self.emit_frames(child);
3864 }
3865 }
3866 self.nodes[root as usize].children = children;
3867 }
3868 self.layout_roots();
3870 self.layout_cells();
3871 for key in relaid {
3872 self.emit_frames(key);
3873 }
3874 self.keep_resize_anchors(anchors);
3875 }
3876 let sized = relayout && !self.placeholders.is_empty() && self.size_placeholders();
3879 if sized {
3880 self.cull_dirty = true;
3881 } else if self.cull_dirty || (relayout && !self.culling.is_empty()) {
3882 self.sync_culled();
3884 }
3885 self.update_lists(relayout);
3886 if std::mem::take(&mut self.cells_framed) && !sized && !self.culling.is_empty() {
3893 self.sync_culled();
3894 }
3895 if !self.slop_moved.is_empty() {
3896 self.update_slop_overflow();
3897 }
3898 if !self.pace.waiting.is_empty() {
3901 self.sync_paced();
3902 }
3903 self.place_followers(relayout);
3905 if !self.decorated.is_empty() {
3906 self.layout_scrollbars();
3907 }
3908 if !self.overlays.is_empty() {
3909 self.place_overlays();
3910 }
3911 if !self.fitted_pending.is_empty() {
3912 self.send_fitted();
3913 }
3914 self.flush_text();
3915 self.sync_status_bars();
3917 if let Some(config) = self.components.status_bars.take_changed() {
3918 self.commands
3919 .push((crate::ROOT_ID, Command::StatusBar(config)));
3920 }
3921 self.sync_orientations();
3922 self.flush_windows();
3924 for (id, answer) in std::mem::take(&mut self.components.measures) {
3926 answer.borrow_mut().deliver(self.measure(id));
3927 }
3928 for (id, answer) in std::mem::take(&mut self.components.scroll_positions) {
3929 answer.borrow_mut().deliver(self.list_scroll_position(id));
3930 }
3931 for (id, answer) in std::mem::take(&mut self.components.transition_times) {
3933 answer.borrow_mut().deliver(self.transition_time(id));
3934 }
3935 for (id, answer) in std::mem::take(&mut self.components.text_contents) {
3937 answer.borrow_mut().deliver(self.text_content(id));
3938 }
3939 if self
3942 .commands
3943 .iter()
3944 .any(|(_, c)| matches!(c, Command::Reveal(_)))
3945 {
3946 let mut projected = Vec::new();
3947 for (id, command) in std::mem::take(&mut self.commands) {
3948 let commands = match command {
3949 Command::Reveal(options) => self.reveal_scrolls(id, options, &projected),
3950 command => vec![(id, command)],
3951 };
3952 for (id, command) in commands {
3953 if let Some(to) = self.scrolled_to(id, &command) {
3954 projected.push((id, to));
3955 }
3956 self.commands.push((id, command));
3957 }
3958 }
3959 }
3960 for (id, press, answer) in std::mem::take(&mut self.components.presses) {
3962 let target = self.press_target(id, press.page_position);
3963 if let Some((node, position)) = target {
3964 self.events.push(crate::element::JsEvent::Event(
3965 node,
3966 EventKind::Press,
3967 EventPayload::Press(crate::PressEvent { position, ..press }),
3968 ));
3969 }
3970 answer.borrow_mut().deliver(target.is_some());
3971 }
3972 self.sync_download_listeners();
3976 self.focus_opened_modals();
3977 if let Some((id, from)) = self.focus_back.take() {
3983 let origin = self
3984 .focus_origins
3985 .iter()
3986 .position(|&(to, _)| to == id)
3987 .map(|i| self.focus_origins.swap_remove(i).1);
3988 let from = from.and_then(|from| self.key(from).ok());
3989 let moved_out = |to: NodeId| {
3990 self.key(to)
3991 .is_ok_and(|key| from.is_none_or(|from| !self.is_ancestor(from, key)))
3992 };
3993 let moved = self
3994 .commands
3995 .iter()
3996 .any(|(to, c)| matches!(c, Command::Focus) && moved_out(*to))
3997 || self.mount.iter().any(|m| {
3998 matches!(
3999 m,
4000 MountItem::Command {
4001 id: to,
4002 command: Command::Focus,
4003 } if moved_out(*to)
4004 )
4005 });
4006 if !moved {
4007 match origin {
4008 None => self.commands.push((id, Command::Focus)),
4011 Some(before) if self.press_leaves_focus() => {
4012 self.focus_back_to_origin(before, from);
4013 }
4014 Some(_) => {
4018 self.commands.push((id, Command::Focus));
4019 self.pointer_focus_back = Some(id);
4020 }
4021 }
4022 }
4023 }
4024 let mut kept = Vec::new();
4026 for (id, mut command) in std::mem::take(&mut self.commands) {
4027 if let Command::Measure { call } = command {
4030 self.answer_measure(id, call);
4031 continue;
4032 }
4033 if let Command::MeasureScrollPosition { call } = command {
4034 self.answer_scroll_position(id, call);
4035 continue;
4036 }
4037 let Ok(key) = self.key(id) else {
4038 continue;
4042 };
4043 if !self.nodes[key as usize].created && !self.uncull(key) {
4045 continue;
4046 }
4047 let node = &self.nodes[key as usize];
4048 if id != crate::ROOT_ID
4049 && let Some(backend) = &self.window_backend
4050 && let Command::Desktop(desktop) = &command
4051 && desktop.is_window_command()
4052 {
4053 backend.command(id, desktop);
4054 continue;
4055 }
4056 if node.list.as_ref().is_some_and(|l| l.parent)
4059 && matches!(
4060 command,
4061 Command::ScrollTo { .. }
4062 | Command::ScrollToIndex { .. }
4063 | Command::ScrollToEnd { .. }
4064 )
4065 {
4066 kept.push((id, command));
4067 continue;
4068 }
4069 if let Command::ImageInfo { id: request, uri } = &mut command {
4072 match self.media_source(uri) {
4073 Some(granted) => {
4074 if let Some(url) = granted {
4075 *uri = url.to_string();
4076 }
4077 }
4078 None => {
4079 let message = media_not_granted(
4080 "Image.getSize / prefetch of",
4081 uri,
4082 self.base_url.as_deref(),
4083 );
4084 self.answer_image_info(*request, Err(message.clone()));
4085 self.deny(message);
4086 continue;
4087 }
4088 }
4089 }
4090 if let Command::Desktop(desktop) = &mut command {
4093 self.check_menu_icons(desktop);
4094 if id == crate::ROOT_ID {
4095 self.remember_app_menu(desktop);
4096 }
4097 }
4098 match &command {
4101 Command::SetClipboard(_)
4102 | Command::SetClipboardItem(_)
4103 | Command::ReadClipboard { .. }
4104 | Command::SetClipboardImage(_)
4105 | Command::ReadClipboardImage { .. }
4106 | Command::ReadClipboardFiles { .. }
4107 if !self.access.allows_clipboard() =>
4108 {
4109 if let Command::ReadClipboard { id: request, .. }
4110 | Command::ReadClipboardImage { id: request, .. }
4111 | Command::ReadClipboardFiles { id: request } = &command
4112 {
4113 self.answer_clipboard(*request, components::ClipboardAnswer::default());
4114 }
4115 if matches!(
4116 command,
4117 Command::SetClipboard(_) | Command::SetClipboardItem(_)
4118 ) {
4119 self.answer_clipboard_write(crate::element::ClipboardWrite::Failed);
4120 }
4121 self.deny("the clipboard is not granted: add `\"clipboard\": true` to capabilities in nsh.json".into());
4122 continue;
4123 }
4124 Command::SetClipboard(_)
4127 | Command::SetClipboardItem(_)
4128 | Command::ReadClipboard { .. }
4129 | Command::SetClipboardImage(_)
4130 | Command::ReadClipboardImage { .. }
4131 | Command::ReadClipboardFiles { .. }
4132 if self.clipboard.is_some() =>
4133 {
4134 let clipboard = self.clipboard.clone().expect("a clipboard");
4135 match &command {
4136 Command::SetClipboard(text) => {
4137 clipboard.set_text(Some(text.clone()));
4138 self.answer_clipboard_write(crate::element::ClipboardWrite::Written);
4139 }
4140 Command::SetClipboardItem(item) => {
4141 clipboard.set_item(Some(item.clone()));
4142 self.answer_clipboard_write(crate::element::ClipboardWrite::Written);
4143 }
4144 Command::SetClipboardImage(_) => clipboard.set_item(None),
4145 Command::ReadClipboard {
4146 id: request,
4147 has_only,
4148 } => {
4149 let text = clipboard.text();
4150 let answer = components::ClipboardAnswer {
4151 has: text.is_some(),
4152 text: text.filter(|_| !has_only),
4153 ..Default::default()
4154 };
4155 self.answer_clipboard(*request, answer);
4156 }
4157 Command::ReadClipboardImage { id: request, .. }
4158 | Command::ReadClipboardFiles { id: request } => {
4159 self.answer_clipboard(*request, components::ClipboardAnswer::default());
4160 }
4161 _ => {}
4162 }
4163 continue;
4164 }
4165 Command::SetClipboard(_) | Command::SetClipboardItem(_)
4168 if !self.components.environment.clipboard_write_result =>
4169 {
4170 self.answer_clipboard_write(crate::element::ClipboardWrite::Requested);
4171 }
4172 Command::HostCall { name, .. } | Command::HostPost { name, .. } => {
4175 if let Some(error) = crate::host_channel::refusal(&self.access, name) {
4176 self.deny(error.to_string());
4177 if let Command::HostCall { id: call, .. } = command {
4178 self.answer_host(call, Err(error));
4179 }
4180 continue;
4181 }
4182 }
4183 Command::SendInput(_) if !self.access.allows_web_input() => {
4184 self.deny("trusted web view input is not granted: add `\"input\": true` to capabilities.webview in nsh.json".into());
4185 continue;
4186 }
4187 Command::Load(load)
4190 if !self
4191 .access
4192 .allows_webview_with(&load.src, self.web_origin(key)) =>
4193 {
4194 self.deny(not_granted("the web page", &load.src, "webview.hosts"));
4195 continue;
4196 }
4197 Command::StatusBar(_) if !self.access.allows_status_bar() => {
4198 self.deny("the status bar is not granted: add `\"statusBar\": true` to capabilities in nsh.json".into());
4199 continue;
4200 }
4201 Command::Desktop(desktop)
4212 if !self.access.allows_application()
4213 && !desktop.is_core_handled()
4214 && !matches!(
4215 **desktop,
4216 crate::desktop::DesktopCommand::PopupMenu { .. }
4217 | crate::desktop::DesktopCommand::Request(
4218 crate::desktop::WindowRequest::SetContentSize { .. }
4219 )
4220 )
4221 && (id == crate::ROOT_ID || !desktop.is_window_command()) =>
4222 {
4223 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());
4224 continue;
4225 }
4226 _ => {}
4227 }
4228 let node = &self.nodes[key as usize];
4229 let id = node.id;
4230 match command {
4231 Command::ScrollToEnd { animated } => {
4232 let Some(content) = node.scroll.as_ref().and_then(|s| s.content) else {
4233 continue;
4234 };
4235 let horizontal = node.scroll.as_ref().is_some_and(|s| s.horizontal);
4236 let frame = node.frame;
4237 let (x, y) = if horizontal {
4238 (
4239 (content.width - frame.size.width).max(Points::ZERO),
4240 Points::ZERO,
4241 )
4242 } else {
4243 (
4244 Points::ZERO,
4245 (content.height - frame.size.height).max(Points::ZERO),
4246 )
4247 };
4248 command = Command::ScrollTo { x, y, animated };
4249 }
4250 Command::ScrollToIndex { .. } => continue,
4251 _ => {}
4252 }
4253 if let Command::ScrollTo { x, y, animated } = command
4255 && self.nodes[key as usize].kind == Kind::Scroll
4256 {
4257 let horizontal = self.nodes[key as usize]
4258 .scroll
4259 .as_ref()
4260 .is_some_and(|s| s.horizontal);
4261 let to = if horizontal { x.0 } else { y.0 };
4262 self.scroll_issued(
4263 key,
4264 PendingScroll::To {
4265 offset: to,
4266 animated,
4267 },
4268 );
4269 if let Some(scroll) = self.nodes[key as usize].scroll.as_mut() {
4270 scroll.target = Some((scroll.issued, (x.0, y.0)));
4271 }
4272 }
4273 self.mount.push(MountItem::Command { id, command });
4274 }
4275 self.commands.append(&mut kept);
4276 }
4277
4278 #[inline]
4279 fn key(&self, id: NodeId) -> Result<Key, ApplyError> {
4280 match self.slots.get(id as usize) {
4281 Some(&k) => Ok(k),
4282 None => Err(ApplyError::UnknownNode(id)),
4283 }
4284 }
4285
4286 fn check_id_range(&self, id: NodeId) -> Result<(), ApplyError> {
4287 if id as usize > self.admitted_id_extent.saturating_add(self.max_nodes) {
4288 return Err(ApplyError::IdOutOfRange(id));
4289 }
4290 Ok(())
4291 }
4292
4293 fn insert_key(&mut self, idx: usize, key: Key) {
4294 self.slots.insert(idx, key);
4295 self.admitted_id_extent = self.admitted_id_extent.max(self.slots.extent());
4296 }
4297
4298 fn alloc(&mut self, id: NodeId, kind: Kind) -> Result<Key, ApplyError> {
4299 let idx = id as usize;
4300 if self.nodes.len().saturating_add(self.runs.len()) >= self.max_nodes {
4301 return Err(ApplyError::TooManyNodes(self.max_nodes));
4302 }
4303 self.check_id_range(id)?;
4304 if self.slots.contains(idx) || self.runs.contains_key(&id) {
4305 return Err(ApplyError::DuplicateNode(id));
4306 }
4307 let key = self.nodes.insert(Node::new(id, kind)) as Key;
4308 self.insert_key(idx, key);
4309 Ok(key)
4310 }
4311
4312 pub(super) fn alias(&mut self, alias: NodeId, id: NodeId) -> Result<(), ApplyError> {
4317 let key = self.key(id)?;
4318 let idx = alias as usize;
4319 self.check_id_range(alias)?;
4320 if self.slots.contains(idx) {
4321 return Err(ApplyError::DuplicateNode(alias));
4322 }
4323 self.insert_key(idx, key);
4324 Ok(())
4325 }
4326
4327 pub(super) fn is_alias(&self, id: NodeId) -> bool {
4329 self.key(id).is_ok_and(|k| self.nodes[k as usize].id != id)
4330 }
4331
4332 pub(super) fn unalias(&mut self, id: NodeId) {
4334 if self.is_alias(id) {
4335 self.slots.remove(id as usize);
4336 }
4337 }
4338
4339 pub(super) fn native_id(&self, id: NodeId) -> NodeId {
4341 self.key(id).map_or(id, |k| self.nodes[k as usize].id)
4342 }
4343
4344 fn create(&mut self, id: NodeId, tag: Tag) -> Result<(), ApplyError> {
4345 let kind = Kind::of(tag);
4346 let key = self.alloc(id, kind)?;
4347 let mut custom_layout = None;
4348 if let Some(role) = shader_role(tag) {
4349 self.nodes[key as usize]
4350 .shader
4351 .as_mut()
4352 .expect("a shader node")
4353 .role = role;
4354 if matches!(
4355 role,
4356 crate::shader::ShaderRole::Screen | crate::shader::ShaderRole::ScreenTransition
4357 ) {
4358 let mut style = crate::style::unstyled_layout();
4360 style.position = taffy::Position::Absolute;
4361 style.size = taffy::Size {
4362 width: taffy::Dimension::length(0.0),
4363 height: taffy::Dimension::length(0.0),
4364 };
4365 custom_layout = Some(style);
4366 }
4367 }
4368 let context = leaf_context(kind);
4369 let layout = match custom_layout {
4370 Some(style) => match context {
4371 Some(context) => self.layout.new_leaf_with_context(style, context),
4372 None => self.layout.new_leaf(style),
4373 },
4374 None => self.layout.new_default_leaf(context),
4375 };
4376 self.layout.set_tag(layout, key);
4377 self.nodes[key as usize].layout = Some(layout);
4378 self.sync_grid_role(key);
4379 self.became(key);
4380 if kind == Kind::WebView && !self.components.environment.web_views {
4381 self.web_view_unavailable(id);
4382 }
4383 Ok(())
4384 }
4385
4386 fn web_view_unavailable(&mut self, id: NodeId) {
4390 self.events.push(crate::element::JsEvent::Event(
4391 id,
4392 EventKind::Error,
4393 EventPayload::Map(vec![
4394 (
4395 "message",
4396 PayloadValue::Str("web views are not available on this platform".into()),
4397 ),
4398 (
4399 "code",
4400 PayloadValue::Str(crate::element::codes::UNAVAILABLE.into()),
4401 ),
4402 ]),
4403 ));
4404 }
4405
4406 fn is_control(&self, key: Key) -> bool {
4411 use crate::AccessibilityRole as R;
4412 let node = &self.nodes[key as usize];
4413 node.kind == Kind::Input
4414 || (!node.inline && pressable(node.events))
4415 || node.props.as_ref().is_some_and(|p| {
4416 matches!(
4417 p.accessibility.role,
4418 R::Button
4419 | R::ImageButton
4420 | R::Link
4421 | R::Search
4422 | R::Textbox
4423 | R::Checkbox
4424 | R::Radio
4425 | R::Switch
4426 | R::Tab
4427 | R::Menuitem
4428 | R::MenuItemCheckbox
4429 | R::MenuItemRadio
4430 | R::Option
4431 | R::Combobox
4432 | R::Adjustable
4433 | R::Spinbutton
4434 )
4435 })
4436 }
4437
4438 fn grid_role(&self, key: Key) -> terminal_layout::Role {
4445 let kind = self.nodes[key as usize].kind;
4446 let left_out = match kind {
4447 Kind::Image => terminal_layout::LeftOut::Picture,
4450 Kind::Video | Kind::WebView | Kind::Shader | Kind::GpuView | Kind::Canvas => {
4451 terminal_layout::LeftOut::IfIcon
4452 }
4453 _ => terminal_layout::LeftOut::No,
4454 };
4455 let control = self.is_control(key);
4456 let popup = control
4459 && self.nodes[key as usize].props.as_ref().is_some_and(|p| {
4460 p.accessibility.state.expanded.is_some() && p.accessibility.state.has_popup
4461 });
4462 let (label, word) = control
4463 .then(|| self.nodes[key as usize].props.as_ref())
4464 .flatten()
4465 .map_or((0, 0), |p| {
4466 let cols = |t: &str| terminal_layout::columns(t).min(u16::MAX as usize) as u16;
4467 let name = p
4468 .accessibility
4469 .label
4470 .as_deref()
4471 .map(str::trim)
4472 .filter(|l| !l.is_empty());
4473 match (p.accessibility.state.expanded, name) {
4474 (Some(_), _) if !popup => (1, 1),
4478 (Some(_), None) => (1, 1),
4479 (Some(_), Some(l)) => {
4484 let first = l.split_whitespace().next().unwrap_or("");
4485 (cols(l).saturating_add(2), cols(first).saturating_add(2))
4486 }
4487 (None, l) => l.map_or((0, 0), |l| {
4488 (cols(l), cols(l.split_whitespace().next().unwrap_or("")))
4489 }),
4490 }
4491 });
4492 let node = &self.nodes[key as usize];
4493 let view = &node.view_style;
4494 let c = view.corner_radius;
4495 let radius = [c.top_left, c.top_right, c.bottom_right, c.bottom_left]
4496 .into_iter()
4497 .map(|r| r.unwrap_or(view.border_radius).0)
4498 .fold(0.0, f32::max);
4499 let w = view.borders.widths;
4500 let border_color = [w.top, w.right, w.bottom, w.left]
4501 .iter()
4502 .position(|&v| v > Points::ZERO)
4503 .map_or(crate::Color::TRANSPARENT, |i| view.borders.colors[i]);
4504 let glyphs = kind == Kind::Text
4507 && node
4508 .layout
4509 .and_then(|l| self.layout.get_node_context(l))
4510 .is_some_and(|cx| match cx {
4511 LeafContext::Text(cx) => cx.text.text.chars().any(|ch| !ch.is_whitespace()),
4512 _ => false,
4513 });
4514 let worded = kind == Kind::Text
4516 && node
4517 .layout
4518 .and_then(|l| self.layout.get_node_context(l))
4519 .is_some_and(|cx| match cx {
4520 LeafContext::Text(cx) => cx.text.text.chars().any(char::is_alphanumeric),
4521 _ => false,
4522 });
4523 let clamped = kind == Kind::Text
4525 && node
4526 .layout
4527 .and_then(|l| self.layout.get_node_context(l))
4528 .is_some_and(|cx| match cx {
4529 LeafContext::Text(cx) => cx.text.max_lines > 0,
4530 _ => false,
4531 });
4532 let disclosure = control
4533 && self.nodes[key as usize].props.as_ref().is_some_and(|p| {
4534 p.accessibility.state.expanded.is_some() && !p.accessibility.state.has_popup
4535 });
4536 let marked = kind == Kind::Text
4538 && node
4539 .layout
4540 .and_then(|l| self.layout.get_node_context(l))
4541 .is_some_and(|cx| match cx {
4542 LeafContext::Text(cx) => {
4543 cx.text.text.trim_start().starts_with(['â–¸', 'â–¾', 'â–¹', 'â–¿'])
4544 }
4545 _ => false,
4546 });
4547 terminal_layout::Role {
4548 control,
4549 label,
4550 word,
4551 popup,
4552 disclosure,
4553 marked,
4554 text: matches!(kind, Kind::Text | Kind::Input),
4555 scroll: matches!(kind, Kind::Scroll | Kind::List),
4556 root: key == self.root,
4557 fills: matches!(kind, Kind::Screen | Kind::Modal),
4558 sized: matches!(
4559 kind,
4560 Kind::Native
4561 | Kind::List
4562 | Kind::Image
4563 | Kind::Video
4564 | Kind::WebView
4565 | Kind::Shader
4566 | Kind::GpuView
4567 ),
4568 input: kind == Kind::Input,
4569 glyphs,
4570 worded,
4571 clamped,
4572 radius,
4573 fill: node.resting_fill.unwrap_or(view.background_color),
4574 interactive: {
4575 let events = self.nodes[key as usize].events;
4576 pressable(events) || HANDLED.iter().any(|&e| events.contains(e))
4577 },
4578 animated_fill: self.nodes[key as usize]
4579 .animated
4580 .iter()
4581 .any(|(p, _)| matches!(p, AnimationProp::BackgroundColor)),
4582 border_color,
4583 splitter: match view.cursor {
4584 crate::Cursor::ColResize => terminal_layout::Splitter::Columns,
4585 crate::Cursor::RowResize => terminal_layout::Splitter::Rows,
4586 _ => terminal_layout::Splitter::No,
4587 },
4588 left_out,
4589 overlay: kind == Kind::Overlay,
4590 meter: node.props.as_ref().is_some_and(|p| {
4591 p.accessibility.role == crate::element::AccessibilityRole::Progressbar
4592 }),
4593 indicator: match node.scroll.as_deref() {
4596 Some(scroll)
4597 if scroll.scrollbar != crate::ScrollbarSetting::Hidden
4598 && scroll.bar.is_none() =>
4599 {
4600 if scroll.horizontal {
4601 terminal_layout::Indicator::Horizontal
4602 } else {
4603 terminal_layout::Indicator::Vertical
4604 }
4605 }
4606 _ => terminal_layout::Indicator::No,
4607 },
4608 }
4609 }
4610
4611 fn sync_grid_role(&mut self, key: Key) {
4614 if let Some(layout) = self.nodes[key as usize].layout {
4615 let role = self.grid_role(key);
4616 if self.layout.set_role(layout, role) {
4617 self.needs_layout = true;
4618 }
4619 }
4620 }
4621
4622 fn became(&mut self, key: Key) {
4624 let kind = self.nodes[key as usize].kind;
4625 if kind.derives_layout() {
4626 let style = self.nodes[key as usize]
4627 .layout
4628 .map(|l| self.layout.style(l).clone())
4629 .unwrap_or_else(crate::style::unstyled_layout);
4630 self.nodes[key as usize].base_layout = Some(Box::new(style));
4631 }
4632 let node = &mut self.nodes[key as usize];
4633 if kind == Kind::Text {
4634 node.dirty |= dirty::TEXT_BUILD;
4635 }
4636 if kind == Kind::List {
4637 self.lists.push(key);
4638 }
4639 if matches!(kind, Kind::Scroll | Kind::List | Kind::Input)
4640 && self.builtin_scrollbars.is_some()
4641 {
4642 self.scrollbars_pending.push(key);
4643 }
4644 if kind.is_root() {
4645 self.roots.push(key);
4646 }
4647 if kind == Kind::Input {
4648 self.measure_input(key);
4649 }
4650 if kind == Kind::Overlay
4651 && let Some(layout) = self.nodes[key as usize].layout
4652 {
4653 self.overlay_made(key, layout);
4654 }
4655 self.sync_layout_style(key);
4656 }
4657
4658 pub(super) fn retag(&mut self, id: NodeId, tag: Tag) -> bool {
4663 let Ok(key) = self.key(id) else {
4664 return false;
4665 };
4666 let kind = Kind::of(tag);
4667 let node = &self.nodes[key as usize];
4668 if node.kind == kind {
4669 return true;
4670 }
4671 let id = node.id;
4672 if node.kind != Kind::View || !node.children.is_empty() {
4673 return false;
4674 }
4675 if node.created && !self.made_in_this_batch(id) {
4676 return false;
4677 }
4678 let node = &self.nodes[key as usize];
4679 let parent = node.parent;
4681 let at = (parent != NO_KEY).then(|| {
4682 let siblings = &self.nodes[parent as usize].children;
4683 let i = siblings.iter().position(|&c| c == key).expect("child");
4684 let next = siblings.get(i + 1).map(|&c| self.nodes[c as usize].id);
4685 (self.nodes[parent as usize].id, next)
4686 });
4687 if parent != NO_KEY {
4688 self.unlink(key, false);
4689 }
4690 let retags = self.retags.get_or_insert_default();
4693 retags.made.remove(&id);
4694 retags.retagged.insert(id, self.mount.len());
4695 let fresh = Node::new(id, kind);
4697 let node = &mut self.nodes[key as usize];
4698 node.created = false;
4699 node.kind = kind;
4700 node.image = fresh.image;
4701 node.scroll = fresh.scroll;
4702 node.list = fresh.list;
4703 node.input = fresh.input;
4704 node.root = fresh.root;
4705 node.control = fresh.control;
4706 node.component = fresh.component;
4707 let layout = node.layout.expect("a view has a layout");
4708 self.layout.set_node_context(layout, leaf_context(kind));
4709 self.became(key);
4710 self.sync_accent(key);
4712 self.sync_grid_role(key);
4715 if let Some((parent, before)) = at {
4716 let _ = self.insert(parent, id, before);
4717 }
4718 true
4719 }
4720
4721 fn made_in_this_batch(&mut self, id: NodeId) -> bool {
4725 let retags = self.retags.get_or_insert_default();
4726 let from = retags.seen;
4727 retags
4728 .made
4729 .extend(self.mount[from..].iter().filter_map(|m| match m {
4730 MountItem::Create { id, .. } => Some(*id),
4731 _ => None,
4732 }));
4733 retags.seen = self.mount.len();
4734 let made = retags.made.contains(&id);
4735 self.retagging(self.mount.len() - from);
4736 made
4737 }
4738
4739 pub(super) fn drop_retagged(&mut self) {
4742 let Some(retags) = self.retags.as_deref_mut() else {
4743 return;
4744 };
4745 if retags.retagged.is_empty() {
4746 return;
4747 }
4748 let retagged = std::mem::take(&mut retags.retagged);
4749 let (seen, made) = (retags.seen, &mut retags.made);
4750 let mut at = 0;
4751 self.mount.retain(|m| {
4752 let i = at;
4753 at += 1;
4754 let (MountItem::Create { id, .. } | MountItem::Insert { child: id, .. }) = m else {
4755 return true;
4756 };
4757 if retagged.get(id).is_some_and(|&then| i < then) {
4758 return false;
4759 }
4760 if i >= seen && matches!(m, MountItem::Create { .. }) {
4761 made.insert(*id);
4762 }
4763 true
4764 });
4765 retags.seen = self.mount.len();
4766 self.retagging(at);
4767 }
4768
4769 pub(super) fn end_retags(&mut self) {
4773 self.drop_retagged();
4774 #[cfg(test)]
4775 if self.retags.is_some() {
4776 let rounds = &self.components.retag_rounds;
4777 rounds.set(rounds.get() + 1);
4778 }
4779 self.retags = None;
4780 }
4781
4782 fn measure_input(&mut self, key: Key) {
4786 let node = &self.nodes[key as usize];
4787 let (Some(input), Some(layout)) = (&node.input, node.layout) else {
4788 return;
4789 };
4790 let shown = input.composing.as_deref().unwrap_or(&input.value);
4791 let placeholder = shown.is_empty() && !input.config.placeholder.is_empty();
4792 let text = self.input_text(
4793 key,
4794 if placeholder {
4795 &input.config.placeholder
4796 } else {
4797 shown
4798 },
4799 );
4800 let field = self.input_text(key, FIELD_SAMPLE);
4801 let cx = self.text_cx(layout);
4802 let same = cx.text.layout_eq(&text);
4803 let same_field = cx.field.as_ref().is_some_and(|f| f.text.layout_eq(&field));
4804 let input = self.nodes[key as usize]
4805 .input
4806 .as_mut()
4807 .expect("input state");
4808 if same && same_field && input.placeholder_measured == placeholder {
4811 return;
4812 }
4813 input.placeholder_measured = placeholder;
4814 let cx = self.text_cx(layout);
4815 if !same {
4816 let kept = cx.field.take();
4817 *cx = TextContext::new(Arc::new(text));
4818 cx.field = kept;
4819 }
4820 if !same_field {
4821 cx.field = Some(Box::new(TextContext::new(Arc::new(field))));
4822 }
4823 self.layout.mark_dirty(layout);
4824 self.needs_layout = true;
4825 }
4826
4827 fn input_text(&self, key: Key, content: &str) -> AttributedText {
4829 let node = &self.nodes[key as usize];
4830 let multiline = node.input.as_ref().is_some_and(|i| i.config.multiline);
4831 let mut text = AttributedText {
4832 max_lines: if multiline { 0 } else { 1 },
4833 ..AttributedText::default()
4834 };
4835 let style = scaled(
4836 self.inherited_text_style(key).inherit(&node.text_style),
4837 node.paragraph.font_multiplier(self.font_scale),
4838 );
4839 text.paragraph_strut = Some(style);
4840 if multiline {
4841 text.push(&broken_runs(content), style);
4842 } else {
4843 text.push(content, style);
4844 }
4845 if content.is_empty() || (multiline && content.ends_with('\n')) {
4848 text.push("\u{200b}", style);
4849 }
4850 text
4851 }
4852
4853 pub(super) fn lay_out_through(&mut self, key: Key) {
4860 let node = &self.nodes[key as usize];
4861 if node.kind == Kind::View
4862 && let Some(layout) = node.layout
4863 {
4864 self.layout.set_holder(layout);
4865 self.needs_layout = true;
4866 }
4867 }
4868
4869 fn sync_layout_style(&mut self, key: Key) {
4872 let node = &self.nodes[key as usize];
4873 let (Some(layout), Some(base)) = (node.layout, node.base_layout.as_deref()) else {
4874 return;
4875 };
4876 let mut style = base.clone();
4877 let kind = node.kind;
4878 if let Some(root) = self.nodes[key as usize].root.as_mut() {
4879 root.laid_out = None;
4881 }
4882 let node = &self.nodes[key as usize];
4883 match kind {
4884 Kind::Scroll => {
4885 let horizontal = node.scroll.as_ref().is_some_and(|s| s.horizontal);
4888 if horizontal {
4889 style.flex_direction = taffy::FlexDirection::Row;
4890 style.overflow.x = Overflow::Scroll;
4891 if node.rtl {
4892 std::mem::swap(&mut style.padding.left, &mut style.padding.right);
4896 std::mem::swap(&mut style.border.left, &mut style.border.right);
4897 style.direction = taffy::Direction::Ltr;
4898 }
4899 } else {
4900 style.overflow.y = Overflow::Scroll;
4901 }
4902 }
4903 Kind::List => {
4904 style.overflow = taffy::Point {
4905 x: Overflow::Hidden,
4906 y: Overflow::Hidden,
4907 }
4908 }
4909 Kind::Cell => {
4910 let horizontal = self
4915 .nodes
4916 .get(node.parent as usize)
4917 .and_then(|p| p.scroll.as_ref())
4918 .is_some_and(|s| s.horizontal);
4919 style.position = Position::Relative;
4920 if horizontal {
4921 style.size.height = taffy::Dimension::percent(1.0);
4922 } else {
4923 style.size.width = taffy::Dimension::percent(1.0);
4924 }
4925 }
4926 Kind::Overlay => style.position = Position::Absolute,
4928 _ => {}
4929 }
4930 if node.fixed_view {
4931 style.position = Position::Fixed;
4932 }
4933 if self.layout.set_style(layout, style) {
4934 self.needs_layout = true;
4935 }
4936 }
4937
4938 fn set_inline_style(
4939 &mut self,
4940 id: NodeId,
4941 style: Box<Style>,
4942 patch: StylePatch,
4943 ) -> Result<(), ApplyError> {
4944 let key = self.key(id)?;
4945 let node = &mut self.nodes[key as usize];
4946 node.inline_style = patch;
4947 if node.classes.is_some() || node.spaced || node.inline_style.reads_current_color() {
4948 self.restyle(key);
4949 return Ok(());
4950 }
4951 let mut props = node.class_props.as_deref().cloned().unwrap_or_default();
4952 style.node_props(&mut props);
4953 self.set_class_props(key, props);
4954 self.set_style(id, *style)
4955 }
4956
4957 fn set_style(&mut self, id: NodeId, style: Style) -> Result<(), ApplyError> {
4958 let key = self.key(id)?;
4959 let Style {
4960 mut layout,
4961 mut view,
4962 text,
4963 paint,
4964 animated,
4965 z_index,
4966 vertical_align,
4967 direction,
4968 logical,
4969 pending,
4970 perspective,
4971 } = style;
4972 if animated
4973 .iter()
4974 .any(|(p, _)| matches!(p, AnimationProp::BackgroundColor))
4975 {
4976 view.clear_background_images();
4979 }
4980 if key != self.root {
4981 self.nodes[key as usize].direction = direction;
4982 }
4983 let rtl = self.resolved_rtl(key);
4984 let sticky = prepare_layout(
4985 &mut layout,
4986 &mut view,
4987 &logical,
4988 rtl,
4989 pending.sticky_position,
4990 );
4991 let input = self.nodes[key as usize].kind == Kind::Input;
4995 clip_overflow(&mut layout, view.overflow_hidden || input);
4996 self.install_style(
4997 key,
4998 StyleRecord {
4999 layout,
5000 view,
5001 text,
5002 paint: (paint != PaintStyle::default()).then(|| Rc::new(paint)),
5003 animated,
5004 sticky,
5005 perspective,
5006 object_fit: pending.object_fit,
5007 wants_fixed: pending.fixed_position,
5008 env: pending.env,
5009 z_index,
5010 vertical_align,
5011 has_logical: !logical.is_empty(),
5012 rtl,
5013 },
5014 );
5015 Ok(())
5016 }
5017
5018 fn apply_resolved_style(&mut self, key: Key, resolved: &classes::ResolvedClassStyle) {
5021 self.set_class_props_shared(key, resolved.props.as_ref());
5022 self.install_style(
5023 key,
5024 StyleRecord {
5025 layout: resolved.layout.clone(),
5026 view: resolved.view.clone(),
5027 text: resolved.text.clone(),
5028 paint: resolved.paint.clone(),
5029 animated: Vec::new(),
5030 sticky: resolved.sticky,
5031 perspective: resolved.perspective,
5032 object_fit: resolved.object_fit,
5033 wants_fixed: resolved.wants_fixed,
5034 env: crate::style::EnvEdges::default(),
5035 z_index: resolved.z_index,
5036 vertical_align: resolved.vertical_align,
5037 has_logical: resolved.has_logical,
5038 rtl: resolved.rtl,
5039 },
5040 );
5041 }
5042
5043 fn install_style(
5047 &mut self,
5048 key: Key,
5049 record: StyleRecord<impl LayoutSlot, impl StyleSlot<ViewStyle>, impl StyleSlot<TextStyle>>,
5050 ) {
5051 let StyleRecord {
5052 mut layout,
5053 view,
5054 text,
5055 paint,
5056 animated,
5057 sticky,
5058 perspective,
5059 object_fit,
5060 wants_fixed,
5061 env,
5062 z_index,
5063 vertical_align,
5064 has_logical,
5065 rtl,
5066 } = record;
5067 let node = &mut self.nodes[key as usize];
5068 node.has_logical = has_logical;
5069 if node.sticky.as_deref() != sticky.as_ref() {
5070 self.set_sticky(key, sticky.map(Box::new));
5071 }
5072 let node = &mut self.nodes[key as usize];
5073 if node.child_perspective != perspective {
5074 node.child_perspective = perspective;
5075 let children = node.children.clone();
5078 for c in children {
5079 self.mark(c, dirty::VIEW | dirty::ANIMATION);
5080 }
5081 }
5082 let node = &mut self.nodes[key as usize];
5083 if node.object_fit != object_fit {
5084 node.object_fit = object_fit;
5085 if node.image.is_some() {
5086 self.mark(key, dirty::IMAGE);
5087 } else if let Some(control) = node.control.as_mut() {
5088 let fit = object_fit.unwrap_or(ResizeMode::Contain);
5090 apply_native(control, NativeProp::VideoResizeMode(fit));
5091 self.mark(key, dirty::NATIVE);
5092 }
5093 }
5094 let node = &mut self.nodes[key as usize];
5095 if node.wants_fixed != wants_fixed {
5096 node.wants_fixed = wants_fixed;
5100 let id = node.id;
5101 if node.parent == NO_KEY {
5102 self.fix_or_unfix(key);
5103 } else {
5104 self.fixed_changed.push((key, id));
5105 }
5106 }
5107 let env = (!env.is_empty()).then(|| (env, self.env_insets(key, &env)));
5110 let node = &mut self.nodes[key as usize];
5111 let id = node.id;
5112 match env {
5113 Some(env) => {
5114 node.env = Some(Box::new(env));
5115 self.env_styled.insert(id);
5116 }
5117 None => {
5118 if node.env.take().is_some() {
5119 self.env_styled.remove(&id);
5120 }
5121 }
5122 }
5123 let node = &mut self.nodes[key as usize];
5124 let mut extra = node.insets.as_deref().copied();
5125 if let Some((_, applied)) = node.env.as_deref() {
5126 let sum = |a: EdgeInsets, b: EdgeInsets| EdgeInsets {
5127 top: a.top + b.top,
5128 right: a.right + b.right,
5129 bottom: a.bottom + b.bottom,
5130 left: a.left + b.left,
5131 };
5132 let [p, m] = extra.unwrap_or_default();
5133 extra = Some([sum(p, applied[0]), sum(m, applied[1])]);
5134 }
5135 if let Some([padding, margin]) = extra.as_ref() {
5136 let layout = layout.to_mut();
5137 let add = |p: &mut taffy::LengthPercentage, d: f32| {
5139 if let taffy::style::ExpandedLengthPercentage::Length(v) = p.expand() {
5140 *p = taffy::LengthPercentage::length(v + d);
5141 }
5142 };
5143 add(&mut layout.padding.top, padding.top.0);
5144 add(&mut layout.padding.right, padding.right.0);
5145 add(&mut layout.padding.bottom, padding.bottom.0);
5146 add(&mut layout.padding.left, padding.left.0);
5147 let add = |m: &mut taffy::LengthPercentageAuto, d: f32| {
5149 if let taffy::style::ExpandedLengthPercentageAuto::Length(v) = m.expand() {
5150 *m = taffy::LengthPercentageAuto::length(v + d);
5151 }
5152 };
5153 add(&mut layout.margin.top, margin.top.0);
5154 add(&mut layout.margin.right, margin.right.0);
5155 add(&mut layout.margin.bottom, margin.bottom.0);
5156 add(&mut layout.margin.left, margin.left.0);
5157 }
5158 let node = &mut self.nodes[key as usize];
5159 let flipped = node.rtl != rtl;
5160 node.rtl = rtl;
5161 let view_same = view.same(&node.view_style);
5164 let new_view = view.get();
5165 let position_changed =
5167 !view_same && node.view_style.object_position != new_view.object_position;
5168 let view_changed = !view_same
5169 && (!position_changed
5170 || node.view_style
5171 != ViewStyle {
5172 object_position: node.view_style.object_position,
5173 ..new_view.clone()
5174 });
5175 let span_drawing_changed = !view_same
5177 && node.inline
5178 && node.kind == Kind::Text
5179 && (span_background(&node.view_style, node.id) != span_background(new_view, node.id)
5180 || node.view_style.hidden != new_view.hidden);
5181 let text_same = text.same(&node.text_style);
5182 let text_changed = !text_same || span_drawing_changed;
5183 let passed_color = |node: &Node, text: &TextStyle| text.color.or(node.inherited_color);
5185 let color_passed =
5186 !text_same && passed_color(node, &node.text_style) != passed_color(node, text.get());
5187 let animation_changed = node.animated != animated;
5188 let paint_changed = !opt_rc_eq(node.paint.as_ref(), paint.as_ref());
5189 let z_changed = node.z_index != z_index;
5190 let align_changed =
5192 node.vertical_align != vertical_align && node.inline && node.kind != Kind::Text;
5193 let content_align_changed = node.vertical_align != vertical_align && !node.inline;
5195 let accent_changed = !view_same && node.view_style.accent_color != new_view.accent_color;
5196 view.install(&mut node.view_style);
5197 text.install(&mut node.text_style);
5198 if paint_changed {
5199 node.paint = paint;
5200 }
5201 node.animated = animated;
5202 node.z_index = z_index;
5203 node.vertical_align = vertical_align;
5204 self.sync_grid_role(key);
5206 if align_changed {
5207 self.mark_text_block(key);
5208 } else if content_align_changed && let Some(place) = self.placed_in_text(key) {
5209 self.mark_text_block(place);
5210 }
5211 if z_changed {
5212 self.restack(key);
5213 }
5214 let node = &mut self.nodes[key as usize];
5215 fn keep_base(slot: &mut Option<Box<taffy::Style>>, layout: impl LayoutSlot) {
5216 match slot {
5217 Some(base) => **base = layout.into_owned(),
5218 None => *slot = Some(Box::new(layout.into_owned())),
5219 }
5220 }
5221 if node.kind.derives_layout() || node.fixed_view {
5222 keep_base(&mut node.base_layout, layout);
5223 self.sync_layout_style(key);
5224 } else if let Some(l) = node.layout {
5225 if layout.set_on(&mut self.layout, l) {
5227 self.needs_layout = true;
5228 }
5229 } else if node.kind == Kind::Text {
5230 let padding = |l: &taffy::Style| l.padding;
5234 let padded = node.base_layout.as_deref().map(padding) != Some(padding(layout.get()));
5235 keep_base(&mut node.base_layout, layout);
5236 if padded && node.inline {
5237 self.mark_text_block(key);
5238 }
5239 }
5240 let mut flags = 0;
5241 if view_changed {
5242 flags |= dirty::VIEW;
5243 if self.nodes[key as usize]
5246 .drawing
5247 .as_ref()
5248 .is_some_and(|d| d.paints_background())
5249 {
5250 flags |= dirty::CANVAS;
5251 }
5252 }
5253 if position_changed && self.nodes[key as usize].image.is_some() {
5254 flags |= dirty::IMAGE;
5255 }
5256 if accent_changed {
5257 self.sync_accent(key);
5258 }
5259 self.sticky_changed |= animation_changed && self.nodes[key as usize].sticky.is_some();
5261 let parent = self.nodes[key as usize].parent;
5262 let in_perspective =
5263 parent != NO_KEY && self.nodes[parent as usize].child_perspective.is_some();
5264 if animation_changed
5265 || view_changed && in_perspective && !self.nodes[key as usize].animated.is_empty()
5266 {
5267 flags |= dirty::ANIMATION;
5269 }
5270 if flags != 0 {
5271 self.mark(key, flags);
5272 }
5273 if text_changed || flipped {
5274 match self.nodes[key as usize].kind {
5275 Kind::Text => {
5276 self.mark_text_block(key);
5277 if color_passed {
5279 self.mark_inheriting_text(key);
5280 }
5281 }
5282 Kind::Input => {
5283 self.measure_input(key);
5284 self.mark(key, dirty::INPUT);
5285 }
5286 _ if text_changed => self.mark_inheriting_text(key),
5288 _ => {}
5289 }
5290 }
5291 if color_passed {
5292 let node = &self.nodes[key as usize];
5293 let color = node.text_style.color.or(node.inherited_color);
5294 self.inherit_color(key, color);
5295 }
5296 if paint_changed || text_changed {
5299 self.mark_view_painted(key);
5300 }
5301 if flipped {
5302 self.update_children_direction(key);
5303 if self.reads_direction(key) {
5306 self.restyle(key);
5307 }
5308 }
5309 }
5310
5311 fn mark_view_painted(&mut self, key: Key) {
5314 let mut stack = vec![key];
5315 while let Some(k) = stack.pop() {
5316 let node = &self.nodes[k as usize];
5317 match node.kind {
5318 Kind::Canvas => {
5319 if node
5320 .drawing
5321 .as_ref()
5322 .is_some_and(|d| !d.view_paints.is_empty())
5323 {
5324 self.mark(k, dirty::CANVAS);
5325 }
5326 }
5327 Kind::Text | Kind::RawText | Kind::Input => {}
5328 _ if node.image.as_ref().is_some_and(|i| i.svg_current_color) => {
5330 self.mark(k, dirty::IMAGE);
5331 }
5332 _ => stack.extend_from_slice(&self.nodes[k as usize].children),
5333 }
5334 }
5335 }
5336
5337 fn mounted_drawing(
5341 &self,
5342 key: Key,
5343 drawing: &Arc<crate::canvas::Drawing>,
5344 ) -> Arc<crate::canvas::Drawing> {
5345 if drawing.view_paints.is_empty() {
5346 return drawing.clone();
5347 }
5348 let node = &self.nodes[key as usize];
5349 let (paint, current) = self.resolved_paint(key);
5350 let style = &node.view_style;
5351 let images = style
5352 .effects
5353 .as_deref()
5354 .map_or(&[][..], |e| &e.background_images[..]);
5355 let size = if node.frame == Bounds::UNSET {
5356 Size::default()
5357 } else {
5358 node.frame.size
5359 };
5360 Arc::new(drawing.painted(&paint, current, style.background_color, images, size))
5361 }
5362
5363 fn send_fitted(&mut self) {
5366 let mut pending = std::mem::take(&mut self.fitted_pending);
5367 pending.sort_unstable();
5368 pending.dedup();
5369 for &key in &pending {
5370 let Some(node) = self.nodes.get(key as usize) else {
5371 continue;
5372 };
5373 if !node.created {
5374 continue;
5375 }
5376 let Some(drawing) = &node.drawing else {
5377 continue;
5378 };
5379 let (id, drawing) = (node.id, self.mounted_drawing(key, drawing));
5380 self.mount.push(MountItem::Canvas { id, drawing });
5381 }
5382 pending.clear();
5383 self.fitted_pending = pending;
5384 }
5385
5386 fn resolved_paint(&self, key: Key) -> (PaintStyle, crate::style::Color) {
5390 let node = &self.nodes[key as usize];
5391 let mut paint = node.paint.as_deref().cloned().unwrap_or_default();
5392 let mut k = node.parent;
5393 while k != NO_KEY {
5394 if let Some(p) = self.nodes[k as usize].paint.as_deref() {
5395 paint = paint.inherit(p);
5396 }
5397 k = self.nodes[k as usize].parent;
5398 }
5399 let color = node
5400 .text_style
5401 .color
5402 .unwrap_or_else(|| self.inherited_text_style(key).color);
5403 (paint, color)
5404 }
5405
5406 pub(super) fn resolved_rtl(&self, key: Key) -> bool {
5409 let node = &self.nodes[key as usize];
5410 if let Some(rtl) = node.direction {
5411 return rtl;
5412 }
5413 match node.parent {
5414 NO_KEY => key != self.root && self.nodes[self.root as usize].rtl,
5415 parent => self.nodes[parent as usize].rtl,
5416 }
5417 }
5418
5419 fn update_direction(&mut self, key: Key) {
5422 let rtl = self.resolved_rtl(key);
5423 if self.nodes[key as usize].rtl == rtl {
5424 return;
5425 }
5426 self.flip_direction(key, rtl);
5427 self.update_children_direction(key);
5428 }
5429
5430 fn update_children_direction(&mut self, key: Key) {
5431 let children = self.nodes[key as usize].children.clone();
5432 for child in children {
5433 self.update_direction(child);
5434 }
5435 }
5436
5437 fn flip_direction(&mut self, key: Key, rtl: bool) {
5441 let direction = if rtl {
5442 taffy::Direction::Rtl
5443 } else {
5444 taffy::Direction::Ltr
5445 };
5446 let node = &mut self.nodes[key as usize];
5447 node.rtl = rtl;
5448 if let Some(list) = node.list.as_mut() {
5449 let mirrored = rtl && list.horizontal;
5450 list.set_mirrored(mirrored);
5451 }
5452 let logical = node.has_logical || node.spaced;
5454 let kind = node.kind;
5455 if let Some(base) = node.base_layout.as_deref_mut() {
5456 base.direction = direction;
5457 self.sync_layout_style(key);
5458 } else if let Some(l) = node.layout {
5459 let mut layout = self.layout.style(l).clone();
5460 layout.direction = direction;
5461 self.layout.set_style(l, layout);
5462 self.needs_layout = true;
5463 }
5464 self.mark(key, dirty::VIEW);
5465 if logical || self.reads_direction(key) {
5466 self.restyle(key);
5467 }
5468 let node = &mut self.nodes[key as usize];
5469 let id = node.id;
5470 if let Some(scroll) = node.scroll.as_mut()
5471 && scroll.horizontal
5472 && node.list.as_ref().is_none_or(|l| !l.parent)
5473 {
5474 scroll.content = None;
5477 if !rtl {
5478 self.commands.push((
5479 id,
5480 Command::ScrollTo {
5481 x: Points::ZERO,
5482 y: Points::ZERO,
5483 animated: false,
5484 },
5485 ));
5486 }
5487 self.mark(key, dirty::SCROLL);
5488 }
5489 match kind {
5490 Kind::Text => self.mark_text_block(key),
5491 Kind::Input => {
5492 self.measure_input(key);
5493 self.mark(key, dirty::INPUT);
5494 }
5495 _ => {}
5496 }
5497 }
5498
5499 fn media_source(&self, uri: &str) -> Option<Option<Arc<str>>> {
5503 match self
5504 .access
5505 .media_url(uri, self.base_url.as_deref(), Some(&self.media_files))?
5506 {
5507 std::borrow::Cow::Borrowed(_) => Some(None),
5508 std::borrow::Cow::Owned(url) => Some(Some(url.into())),
5509 }
5510 }
5511
5512 fn check_canvas_images(&mut self, drawing: &mut crate::canvas::Drawing) {
5522 if self.access.is_unrestricted() {
5523 return;
5524 }
5525 let access = self.access.clone();
5526 let base = self.base_url.clone();
5527 let files = self.media_files.clone();
5528 let mut refused = Vec::new();
5529 let checked = &mut self.canvas_images;
5530 let mut files_here: rustc_hash::FxHashMap<Arc<str>, Option<Arc<str>>> =
5534 rustc_hash::FxHashMap::default();
5535 drawing.ops.retain_mut(|op| match op {
5536 crate::canvas::CanvasOp::DrawImage { image, .. } => {
5537 let granted = match checked
5538 .get(&image.uri)
5539 .or_else(|| files_here.get(&image.uri))
5540 {
5541 Some(granted) => granted.clone(),
5542 None => {
5543 let granted = access
5544 .media_url(&image.uri, base.as_deref(), Some(&files))
5545 .map(|url| match url {
5546 std::borrow::Cow::Owned(url) => Arc::from(url),
5547 std::borrow::Cow::Borrowed(_) => image.uri.clone(),
5548 });
5549 if crate::access::media_capability(&image.uri, base.as_deref()) == "network"
5550 {
5551 if checked.len() >= CANVAS_IMAGES {
5552 checked.clear();
5553 }
5554 checked.insert(image.uri.clone(), granted.clone());
5555 } else {
5556 files_here.insert(image.uri.clone(), granted.clone());
5557 }
5558 granted
5559 }
5560 };
5561 match granted {
5562 Some(url) => {
5563 image.uri = url;
5564 true
5565 }
5566 None => {
5567 refused.push(image.uri.clone());
5568 false
5569 }
5570 }
5571 }
5572 _ => true,
5573 });
5574 refused.sort_unstable();
5576 refused.dedup();
5577 for uri in refused {
5578 self.deny(media_not_granted(
5579 "a canvas image",
5580 &uri,
5581 self.base_url.as_deref(),
5582 ));
5583 }
5584 }
5585
5586 fn remember_app_menu(&mut self, desktop: &crate::desktop::DesktopCommand) {
5592 use crate::desktop::DesktopCommand;
5593 let change: Box<dyn FnOnce(&mut crate::element::menus::AppMenu)> = match desktop {
5594 DesktopCommand::SetMenu(items) => {
5595 let items = items.clone();
5596 Box::new(move |m| m.items = items)
5597 }
5598 DesktopCommand::SetMenuLabels(labels) => {
5599 let labels = (**labels).clone();
5600 Box::new(move |m| m.labels = labels)
5601 }
5602 _ => return,
5603 };
5604 let _entered = self.components.runtime.enter();
5605 let signal = crate::element::menus::app_menu(&self.components.executor.menus);
5606 signal.update(change);
5607 }
5608
5609 fn check_menu_icons(&mut self, desktop: &mut crate::desktop::DesktopCommand) {
5610 use crate::{
5611 ImageSource,
5612 desktop::{DesktopCommand, MenuItem},
5613 };
5614 if self.access.is_unrestricted() {
5615 return;
5616 }
5617 let mut check = |icon: &mut Option<ImageSource>| {
5618 let Some(source) = icon else { return };
5619 match self.media_source(&source.uri) {
5620 Some(Some(url)) => source.uri = url,
5621 Some(None) => {}
5622 None => {
5623 let message =
5624 media_not_granted("the menu icon", &source.uri, self.base_url.as_deref());
5625 *icon = None;
5626 self.deny(message);
5627 }
5628 }
5629 };
5630 fn each(items: &mut [MenuItem], check: &mut impl FnMut(&mut Option<ImageSource>)) {
5631 for item in items {
5632 match item {
5633 MenuItem::Action(action) => check(&mut action.icon),
5634 MenuItem::Submenu { items, icon, .. } => {
5635 check(icon);
5636 each(items, check);
5637 }
5638 MenuItem::Separator => {}
5639 }
5640 }
5641 }
5642 let checked = |items: &Arc<[MenuItem]>, check: &mut dyn FnMut(&mut Option<ImageSource>)| {
5643 let mut items = items.to_vec();
5644 each(&mut items, &mut |icon| check(icon));
5645 Arc::<[MenuItem]>::from(items)
5646 };
5647 match desktop {
5648 DesktopCommand::SetMenu(Some(items)) | DesktopCommand::PopupMenu { items, .. } => {
5649 *items = checked(items, &mut check);
5650 }
5651 DesktopCommand::SetTray(Some(tray)) => {
5652 check(&mut tray.icon);
5653 tray.menu = checked(&tray.menu, &mut check);
5654 }
5655 _ => {}
5656 }
5657 }
5658
5659 fn check_prop(&mut self, key: Key, prop: Prop) -> Prop {
5663 let prop = match prop {
5664 Prop::Native(NativeProp::AllowOrigin(Some(origin))) => {
5665 Prop::Native(NativeProp::AllowOrigin(self.check_allow_origin(&origin)))
5666 }
5667 Prop::Native(NativeProp::AllowNavigation(Some(hosts))) => {
5668 match crate::access::WebHosts::parse(&hosts) {
5669 Ok(_) => Prop::Native(NativeProp::AllowNavigation(Some(hosts))),
5670 Err(e) => {
5671 self.deny(format!("`allowNavigation`: {e}"));
5672 Prop::Native(NativeProp::AllowNavigation(None))
5673 }
5674 }
5675 }
5676 prop => prop,
5677 };
5678 if self.access.is_unrestricted() {
5679 return prop;
5680 }
5681 let node = &self.nodes[key as usize];
5682 let (id, kind) = (node.id, node.kind);
5683 if kind == Kind::WebView
5687 && self.access.allows_runtime_origin()
5688 && let Some(url) = web_url(&prop)
5689 && !url.is_empty()
5690 && !self.access.allows_webview_with(url, self.web_origin(key))
5691 {
5692 self.web_unchecked.insert((key, id));
5693 return prop;
5694 }
5695 let report = |core: &mut Self, message: String| core.report_access_denied(id, message);
5698 let refuse = |core: &mut Self, what: &str, uri: &str, capability: &str| {
5699 report(core, not_granted(what, uri, capability));
5700 };
5701 let refuse_media = |core: &mut Self, what: &str, uri: &str| {
5702 let message = media_not_granted(what, uri, core.base_url.as_deref());
5703 report(core, message);
5704 };
5705 let no_webviews = |core: &mut Self| {
5706 report(
5707 core,
5708 "web views are not granted: add `webview` to capabilities in nsh.json".into(),
5709 );
5710 };
5711 match prop {
5712 Prop::Source(Some(mut source)) => match self.media_source(&source.uri) {
5714 Some(granted) => {
5715 source.uri = granted.unwrap_or(source.uri);
5716 Prop::Source(Some(source))
5717 }
5718 None => {
5719 refuse_media(self, "the image", &source.uri);
5720 Prop::Source(None)
5721 }
5722 },
5723 Prop::Image(ImageProp::Placeholder(Some(mut source))) => {
5724 match self.media_source(&source.uri) {
5725 Some(granted) => {
5726 source.uri = granted.unwrap_or(source.uri);
5727 Prop::Image(ImageProp::Placeholder(Some(source)))
5728 }
5729 None => {
5730 refuse_media(self, "the placeholder", &source.uri);
5731 Prop::Image(ImageProp::Placeholder(None))
5732 }
5733 }
5734 }
5735 Prop::Native(NativeProp::Src(Some(url))) if kind == Kind::Video => {
5736 match self.media_source(&url) {
5737 Some(granted) => Prop::Native(NativeProp::Src(Some(granted.unwrap_or(url)))),
5738 None => {
5739 refuse_media(self, "the video", &url);
5740 Prop::Native(NativeProp::Src(None))
5741 }
5742 }
5743 }
5744 Prop::Native(NativeProp::Poster(Some(url))) if kind == Kind::Video => {
5745 match self.media_source(&url) {
5746 Some(granted) => Prop::Native(NativeProp::Poster(Some(granted.unwrap_or(url)))),
5747 None => {
5748 refuse_media(self, "the poster", &url);
5749 Prop::Native(NativeProp::Poster(None))
5750 }
5751 }
5752 }
5753 Prop::Native(NativeProp::Src(Some(url)))
5754 if kind == Kind::WebView
5755 && !self.access.allows_webview_with(&url, self.web_origin(key)) =>
5756 {
5757 refuse(self, "the web page", &url, "webview.hosts");
5758 Prop::Native(NativeProp::Src(None))
5759 }
5760 Prop::Native(NativeProp::Html(Some(_)))
5761 if kind == Kind::WebView && !self.access.allows_webviews() =>
5762 {
5763 no_webviews(self);
5764 Prop::Native(NativeProp::Html(None))
5765 }
5766 Prop::Native(NativeProp::Source(crate::WebSource::Uri(uri))) if kind == Kind::Video => {
5767 match self.media_source(&uri) {
5768 Some(granted) => Prop::Native(NativeProp::Source(crate::WebSource::Uri(
5769 granted.unwrap_or(uri),
5770 ))),
5771 None => {
5772 refuse_media(self, "the video", &uri);
5773 Prop::Native(NativeProp::Source(crate::WebSource::None))
5774 }
5775 }
5776 }
5777 Prop::Native(NativeProp::Source(crate::WebSource::Uri(uri)))
5778 if kind == Kind::WebView
5779 && !self.access.allows_webview_with(&uri, self.web_origin(key)) =>
5780 {
5781 refuse(self, "the web page", &uri, "webview.hosts");
5782 Prop::Native(NativeProp::Source(crate::WebSource::None))
5783 }
5784 Prop::Native(NativeProp::Source(crate::WebSource::Html { .. }))
5785 if kind == Kind::WebView && !self.access.allows_webviews() =>
5786 {
5787 no_webviews(self);
5788 Prop::Native(NativeProp::Source(crate::WebSource::None))
5789 }
5790 Prop::Native(NativeProp::BaseUrl(Some(url)))
5797 if kind == Kind::WebView
5798 && !url.is_empty()
5799 && self.access.allows_webviews()
5800 && !self.access.allows_webview_with(&url, self.web_origin(key)) =>
5801 {
5802 refuse(self, "the base URL", &url, "webview.hosts");
5803 Prop::Native(NativeProp::BaseUrl(None))
5804 }
5805 Prop::Native(NativeProp::Source(crate::WebSource::Html {
5806 html,
5807 base_url: Some(url),
5808 })) if kind == Kind::WebView
5809 && !url.is_empty()
5810 && !self.access.allows_webview_with(&url, self.web_origin(key)) =>
5811 {
5812 refuse(self, "the base URL", &url, "webview.hosts");
5813 Prop::Native(NativeProp::Source(crate::WebSource::Html {
5814 html,
5815 base_url: None,
5816 }))
5817 }
5818 prop => prop,
5819 }
5820 }
5821
5822 fn check_allow_origin(&mut self, origin: &str) -> Option<Arc<str>> {
5826 match crate::access::WebOrigin::parse(origin) {
5827 Err(e) => {
5828 self.deny(format!("`allowOrigin`: {e}"));
5829 None
5830 }
5831 Ok(_) if !self.access.is_unrestricted() && !self.access.allows_runtime_origin() => {
5832 self.deny(
5833 "`allowOrigin` is not granted: add `\"runtimeOrigin\": true` to capabilities.webview in nsh.json"
5834 .into(),
5835 );
5836 None
5837 }
5838 Ok(o) => Some(o.to_string().into()),
5839 }
5840 }
5841
5842 fn web_origin(&self, key: Key) -> Option<&crate::access::WebOrigin> {
5844 match self.nodes[key as usize].control.as_deref() {
5845 Some(NativeProps::WebView(p)) => p.allow_origin.as_ref(),
5846 _ => None,
5847 }
5848 }
5849
5850 fn settle_web_urls(&mut self, key: Key) {
5855 let id = self.nodes[key as usize].id;
5856 if !self.web_unchecked.remove(&(key, id)) {
5857 return;
5858 }
5859 let access = &self.access;
5860 let Some(NativeProps::WebView(p)) = self.nodes[key as usize].control.as_deref_mut() else {
5861 return;
5862 };
5863 let origin = p.allow_origin.clone();
5864 let refuses =
5865 |url: &str| !url.is_empty() && !access.allows_webview_with(url, origin.as_ref());
5866 let mut messages = Vec::new();
5867 let src = p.src.take_if(|url| refuses(url));
5869 if let Some(url) = &src {
5870 messages.push(not_granted("the web page", url, "webview.hosts"));
5871 }
5872 if let crate::WebSource::Uri(url) = &p.source
5874 && refuses(url)
5875 {
5876 if src.as_ref() != Some(url) {
5877 messages.push(not_granted("the web page", url, "webview.hosts"));
5878 }
5879 p.source = crate::WebSource::None;
5880 }
5881 let base = p.base_url.take_if(|url| refuses(url));
5882 if let Some(url) = &base {
5883 messages.push(not_granted("the base URL", url, "webview.hosts"));
5884 }
5885 if let crate::WebSource::Html { base_url, .. } = &mut p.source
5886 && let Some(url) = base_url.take_if(|url| refuses(url))
5887 && base.as_ref() != Some(&url)
5888 {
5889 messages.push(not_granted("the base URL", &url, "webview.hosts"));
5890 }
5891 for message in messages {
5892 self.report_access_denied(id, message);
5893 }
5894 }
5895
5896 fn report_access_denied(&mut self, id: NodeId, message: String) {
5899 self.events.push(crate::element::JsEvent::Event(
5900 id,
5901 EventKind::Error,
5902 EventPayload::Map(vec![
5903 ("message", PayloadValue::Str(message.clone())),
5904 (
5905 "code",
5906 PayloadValue::Str(crate::element::codes::ACCESS_DENIED.into()),
5907 ),
5908 ]),
5909 ));
5910 self.deny(message);
5911 }
5912
5913 fn compile(
5917 &mut self,
5918 source: &str,
5919 ) -> Result<crate::shader::Shader, crate::shader::ShaderError> {
5920 let hash = crate::shader::source_hash(source);
5921 let cached = self.shaders.get(&hash).filter(|c| match c {
5922 Ok(shader) => shader.source() == source,
5923 Err(_) => true,
5924 });
5925 if let Some(compiled) = cached {
5926 return compiled.clone();
5927 }
5928 let compiled = crate::shader::compile_source(source);
5929 if self.shaders.len() >= 64 {
5931 self.shaders.clear();
5932 }
5933 self.shaders.insert(hash, compiled.clone());
5934 compiled
5935 }
5936
5937 fn set_nav_shader(&mut self, key: Key, spec: Option<crate::shader::NavShaderSpec>) {
5940 let id = self.nodes[key as usize].id;
5941 if self.nodes[key as usize].root.is_none() {
5942 log::warn!(target: "js", "`transitionShader` is a page's or a dialog's; node {id} is neither");
5943 return;
5944 }
5945 let shader = spec.and_then(|spec| {
5946 let shader = self
5947 .compile(&spec.source)
5948 .map_err(|e| log::warn!(target: "js", "the transitionShader of node {id}: {e}"))
5949 .ok()?;
5950 let mut warnings = Vec::new();
5951 let layer = crate::shader::ShaderLayer::new(shader, &spec.uniforms.0, &mut warnings)
5952 .with_role(crate::shader::ShaderRole::Transition);
5953 for warning in warnings {
5954 log::warn!(target: "js", "the transitionShader of node {id}: {warning}");
5955 }
5956 let ms = spec.duration.unwrap_or(DEFAULT_NAV_SHADER_MS).max(0.0);
5957 Some(crate::NavShader {
5958 layer: Arc::new(layer),
5959 duration: std::time::Duration::from_micros((f64::from(ms) * 1000.0).round() as u64),
5960 })
5961 });
5962 let root = self.nodes[key as usize]
5963 .root
5964 .as_mut()
5965 .expect("checked above");
5966 if root.nav_shader != shader {
5967 root.nav_shader = shader;
5968 self.mark(key, dirty::NAV_SHADER);
5969 }
5970 }
5971
5972 fn mark_shader_inputs(&mut self) {
5981 let unlinked_from = std::mem::take(&mut self.unlinked_from);
5982 if self.pictured.is_empty()
5985 || self
5986 .mount
5987 .iter()
5988 .all(|item| matches!(item, MountItem::LayoutAnimation(_)))
5989 {
5990 return;
5991 }
5992 use crate::shader::{ShaderInput as I, ShaderRole as R};
5993 let ids: Vec<NodeId> = self.pictured.iter().copied().collect();
5994 let mut marked: Vec<NodeId> = Vec::new();
5995 let mut subtrees: Vec<(NodeId, Key)> = Vec::new();
5996 let mut backdrops: Vec<(NodeId, Key)> = Vec::new();
5997 for id in ids {
5998 let Ok(key) = self.key(id) else {
5999 self.pictured.remove(&id);
6000 continue;
6001 };
6002 let Some(layer) = self.nodes[key as usize]
6003 .shader
6004 .as_ref()
6005 .and_then(|s| s.layer.as_ref())
6006 else {
6007 continue;
6008 };
6009 let inputs = layer.shader.inputs();
6010 if matches!(layer.role, R::Screen | R::ScreenTransition) {
6011 marked.push(id);
6012 continue;
6013 }
6014 if inputs.contains(I::Backdrop) {
6015 backdrops.push((id, key));
6016 }
6017 if matches!(layer.role, R::Effect | R::Transition) {
6018 subtrees.push((id, key));
6019 }
6020 }
6021 if !backdrops.is_empty() {
6022 let mut everywhere = false;
6025 let mut changed: Vec<Key> = Vec::new();
6026 let mut seen = rustc_hash::FxHashSet::default();
6027 for item in &self.mount {
6028 match shown_by(item) {
6029 Shown::Nothing => {}
6030 Shown::Everywhere => {
6031 everywhere = true;
6032 break;
6033 }
6034 Shown::View(id) => {
6035 if seen.insert(id)
6036 && let Ok(key) = self.key(id)
6037 {
6038 changed.push(key);
6039 }
6040 }
6041 }
6042 }
6043 for &id in &unlinked_from {
6044 if seen.insert(id)
6045 && let Ok(key) = self.key(id)
6046 {
6047 changed.push(key);
6048 }
6049 }
6050 for &(id, key) in &backdrops {
6051 if everywhere || self.draws_before(&changed, key) {
6052 marked.push(id);
6053 }
6054 }
6055 }
6056 if !subtrees.is_empty() {
6057 let mut seen = rustc_hash::FxHashSet::default();
6058 let views = self.mount.iter().filter_map(MountItem::view);
6061 for view in views.chain(unlinked_from) {
6062 if !seen.insert(view) {
6063 continue;
6064 }
6065 let Ok(mut key) = self.key(view) else {
6066 continue;
6067 };
6068 loop {
6069 if let Some(&(id, _)) = subtrees.iter().find(|(_, k)| *k == key)
6070 && !marked.contains(&id)
6071 {
6072 marked.push(id);
6073 }
6074 let parent = self.nodes[key as usize].parent;
6075 if parent == NO_KEY {
6076 break;
6077 }
6078 key = parent;
6079 }
6080 }
6081 }
6082 for id in marked {
6083 self.mount.push(MountItem::ShaderInput { id });
6084 }
6085 }
6086
6087 fn draws_before(&self, views: &[Key], reader: Key) -> bool {
6094 if views.is_empty() {
6095 return false;
6096 }
6097 let mut up: Vec<Key> = Vec::new();
6099 let mut key = reader;
6100 while key != NO_KEY {
6101 up.push(key);
6102 key = self.nodes[key as usize].parent;
6103 }
6104 let at: rustc_hash::FxHashMap<Key, usize> =
6105 up.iter().enumerate().map(|(i, &k)| (k, i)).collect();
6106 views.iter().any(|&view| {
6107 let mut below = NO_KEY;
6108 let mut key = view;
6109 while key != NO_KEY {
6110 if let Some(&i) = at.get(&key) {
6111 if i == 0 {
6112 return false;
6114 }
6115 if below == NO_KEY {
6116 return true;
6118 }
6119 return self.stacks_before(key, below, up[i - 1]);
6122 }
6123 below = key;
6124 key = self.nodes[key as usize].parent;
6125 }
6126 true
6127 })
6128 }
6129
6130 fn stacks_before(&self, parent: Key, a: Key, b: Key) -> bool {
6132 let children = &self.nodes[parent as usize].children;
6133 let rank = |k: Key| {
6134 let index = children.iter().position(|&c| c == k).unwrap_or(usize::MAX);
6135 (self.nodes[k as usize].stack_rank(), index)
6136 };
6137 rank(a) < rank(b)
6138 }
6139
6140 fn set_shader_prop(&mut self, key: Key, prop: Prop) {
6144 let id = self.nodes[key as usize].id;
6145 let Some(state) = self.nodes[key as usize].shader.as_mut() else {
6146 log::warn!(target: "js", "shader props are a `<Shader>`'s; node {id} is not one");
6147 return;
6148 };
6149 match prop {
6150 Prop::ShaderSource(source) => {
6151 if state.source == source {
6152 return;
6153 }
6154 state.source = source.clone();
6155 state.shader = None;
6156 if let Some(source) = source {
6157 let compiled = self.compile(&source);
6158 let state = self.nodes[key as usize]
6159 .shader
6160 .as_mut()
6161 .expect("shader node");
6162 match compiled {
6163 Ok(shader) => state.shader = Some(shader),
6164 Err(error) => log::warn!(target: "js", "the shader of node {id}: {error}"),
6165 }
6166 }
6167 }
6168 Prop::Shader(shader) => {
6169 state.source = None;
6170 state.shader = shader;
6171 }
6172 Prop::Uniforms(uniforms) => state.uniforms = uniforms,
6173 Prop::ShaderPaused(paused) => state.paused = paused,
6174 Prop::ShaderProgress(progress) => state.progress = progress,
6175 Prop::MaxSampleOffset(overflow) => state.overflow = overflow.max(Points::ZERO),
6176 Prop::TransitionValue(value) => state.value = value,
6177 Prop::TransitionDuration(duration) => state.duration = duration,
6178 Prop::TransitionFallback(fallback) => state.fallback = fallback,
6179 _ => return,
6180 }
6181 let state = self.nodes[key as usize]
6182 .shader
6183 .as_mut()
6184 .expect("shader node");
6185 use crate::shader::ShaderRole as R;
6186 let transition = matches!(state.role, R::Transition | R::ScreenTransition);
6187 let program = state.shader.clone().or_else(|| {
6189 (transition && state.fallback == crate::TransitionFallback::Fade)
6190 .then(crate::shader::crossfade)
6191 .flatten()
6192 });
6193 let layer = program.map(|shader| {
6194 let mut warnings = Vec::new();
6195 let (progress, animated) = match state.progress {
6196 crate::shader::ShaderProgress::Number(n) => (n, None),
6197 crate::shader::ShaderProgress::Animated(node) => (Percentage(0.0), Some(node)),
6198 };
6199 let layer = crate::shader::ShaderLayer::new(shader, &state.uniforms.0, &mut warnings)
6200 .with_paused(state.paused)
6201 .with_role(state.role)
6202 .with_overflow(state.overflow)
6203 .with_progress(progress, animated);
6204 for warning in warnings {
6205 log::warn!(target: "js", "the shader of node {id}: {warning}");
6206 }
6207 Arc::new(layer)
6208 });
6209 if transition && state.value != state.shown {
6210 let before = std::mem::replace(&mut state.shown, state.value.clone());
6211 let ms = state.duration.unwrap_or(DEFAULT_TRANSITION_MS).max(0.0);
6212 if before.is_some() && layer.is_some() && ms > 0.0 {
6213 self.transition_starts.push(MountItem::ShaderTransition {
6214 id,
6215 duration: std::time::Duration::from_micros(
6216 (f64::from(ms) * 1000.0).round() as u64
6217 ),
6218 });
6219 }
6220 }
6221 let state = self.nodes[key as usize]
6222 .shader
6223 .as_mut()
6224 .expect("shader node");
6225 if layer.as_ref().is_some_and(|l| {
6226 !l.shader.inputs().is_empty() || matches!(l.role, R::Screen | R::ScreenTransition)
6227 }) {
6228 self.pictured.insert(id);
6229 } else {
6230 self.pictured.remove(&id);
6231 }
6232 if layer == state.layer {
6233 return;
6234 }
6235 let nodes_of = |l: &Option<Arc<crate::shader::ShaderLayer>>| {
6236 l.as_ref().map_or(&[][..], |l| &l.nodes[..]).to_vec()
6237 };
6238 let slots_changed = nodes_of(&layer) != nodes_of(&state.layer);
6239 state.layer = layer;
6240 self.mark(
6241 key,
6242 dirty::SHADER | if slots_changed { dirty::ANIMATION } else { 0 },
6243 );
6244 }
6245
6246 fn set_prop(&mut self, id: NodeId, prop: Prop) -> Result<(), ApplyError> {
6247 let key = self.key(id)?;
6248 let prop = match prop {
6251 Prop::Component(name) if self.nodes[key as usize].kind == Kind::View => {
6252 self.create_instance(id, name);
6253 return Ok(());
6254 }
6255 Prop::Component(name) if self.nodes[key as usize].kind == Kind::GpuView => {
6257 let source = self.components.gpu_renderer(&name);
6258 if source.is_none() {
6259 log::warn!(target: "js", "no GPU renderer is registered as `{name}`; the view draws nothing");
6260 }
6261 self.set_gpu_source(key, id, source);
6262 return Ok(());
6263 }
6264 Prop::GpuRenderer(source) => {
6265 if self.nodes[key as usize].kind == Kind::GpuView {
6266 self.set_gpu_source(key, id, source);
6267 } else {
6268 log::warn!("a GPU renderer on node {id}, which is no GPU view");
6269 }
6270 return Ok(());
6271 }
6272 Prop::ComponentSlot(name) => {
6273 self.set_slot_name(id, name);
6274 self.lay_out_through(key);
6275 return Ok(());
6276 }
6277 Prop::ComponentRender(slot) => {
6278 self.set_render_holder(id, slot);
6279 self.lay_out_through(key);
6280 return Ok(());
6281 }
6282 Prop::RustProp(name, value) => {
6283 if !self.set_component_prop(id, name, value) {
6284 log::warn!(target: "js", "a Rust component's prop on node {id}, which hosts none");
6285 }
6286 return Ok(());
6287 }
6288 Prop::Follow(target) => {
6289 self.set_follow_target(key, target);
6290 return Ok(());
6291 }
6292 Prop::PassPosition(pass) => {
6293 self.set_pass_position(key, pass);
6294 return Ok(());
6295 }
6296 Prop::FollowTransition(transition) => {
6297 self.set_follow_transition(key, transition);
6298 return Ok(());
6299 }
6300 Prop::Accessibility(AccessibilityProp::ActiveDescendant(target)) => {
6301 self.set_relation(key, relations::Relation::ActiveDescendant, target);
6302 return Ok(());
6303 }
6304 Prop::Accessibility(AccessibilityProp::Controls(target)) => {
6305 self.set_relation(key, relations::Relation::Controls, target);
6306 return Ok(());
6307 }
6308 Prop::Accessibility(AccessibilityProp::DescribedBy(target)) => {
6309 self.set_relation(key, relations::Relation::DescribedBy, target);
6310 return Ok(());
6311 }
6312 Prop::ScrollEdgeElement(target) => {
6313 self.set_scroll_edge(key, target);
6314 return Ok(());
6315 }
6316 Prop::Accessibility(AccessibilityProp::Description(description))
6319 if !self.relators.is_empty() && self.set_own_description(key, &description) =>
6320 {
6321 return Ok(());
6322 }
6323 prop => prop,
6324 };
6325 let prop = self.check_prop(key, prop);
6326 if let Prop::ShaderSource(_)
6327 | Prop::Shader(_)
6328 | Prop::Uniforms(_)
6329 | Prop::ShaderPaused(_)
6330 | Prop::ShaderProgress(_)
6331 | Prop::MaxSampleOffset(_)
6332 | Prop::TransitionValue(_)
6333 | Prop::TransitionDuration(_)
6334 | Prop::TransitionFallback(_) = prop
6335 {
6336 self.set_shader_prop(key, prop);
6337 return Ok(());
6338 }
6339 if let Prop::TransitionShader(spec) = prop {
6340 self.set_nav_shader(key, spec);
6341 return Ok(());
6342 }
6343 if let Prop::Screen(ScreenProp::StatusBar(setting)) = prop {
6344 self.set_status_bar(key, setting);
6345 return Ok(());
6346 }
6347 if let Prop::Screen(ScreenProp::Orientations(bits)) = prop {
6348 self.set_page_orientations(key, bits);
6349 return Ok(());
6350 }
6351 if let Prop::ListViewport(mode) = prop {
6352 self.set_list_viewport(key, mode);
6353 return Ok(());
6354 }
6355 if matches!(
6358 prop,
6359 Prop::Scroll(_)
6360 | Prop::KeyboardDismissMode(_)
6361 | Prop::Scrollbar(_)
6362 | Prop::Refreshing(_)
6363 | Prop::ScrollValue(_)
6364 | Prop::PullValue(_)
6365 | Prop::Native(NativeProp::Scrollable(_))
6366 ) && let Some(list) = self.nodes[key as usize].list.as_mut().filter(|l| l.parent)
6367 {
6368 list.ignored |= match prop {
6369 Prop::Scroll(ScrollProp::RefreshIndicator(None)) => 0,
6370 Prop::Scroll(ScrollProp::RefreshIndicator(Some(_))) | Prop::PullValue(Some(_)) => {
6371 list::ignored::REFRESH
6372 }
6373 Prop::Scroll(_)
6374 | Prop::KeyboardDismissMode(
6375 KeyboardDismissMode::OnDrag | KeyboardDismissMode::Interactive,
6376 )
6377 | Prop::Native(NativeProp::Scrollable(false)) => list::ignored::BEHAVIOR,
6378 Prop::Scrollbar(
6379 crate::ScrollbarSetting::Hidden
6380 | crate::ScrollbarSetting::Themed(_)
6381 | crate::ScrollbarSetting::ThemeValue(_),
6382 ) => list::ignored::SCROLLBAR,
6383 Prop::Refreshing(true) => list::ignored::REFRESH,
6384 Prop::ScrollValue(Some(_)) => list::ignored::SCROLL_VALUE,
6385 _ => 0,
6386 };
6387 self.warn_ignored(key);
6388 return Ok(());
6389 }
6390 let node = &mut self.nodes[key as usize];
6391 let mut flags = 0;
6392 let mut key_ancestry = false;
6393 let mut rebuild_span = false;
6394 let mut copy_text_changed = false;
6395 let mut slop_moved = false;
6396 match prop {
6397 Prop::Source(source) => {
6398 if let Some(image) = node.image.as_mut() {
6399 let source = source.map(ImageSource::inline);
6402 let size = source.as_ref().and_then(ImageSource::natural_size);
6403 image.source = source;
6404 flags |= dirty::IMAGE;
6405 let layout = node.layout.expect("image layout");
6406 if let Some(LeafContext::Image(natural)) =
6407 self.layout.get_node_context_mut(layout)
6408 && *natural != size
6409 {
6410 *natural = size;
6411 self.layout.mark_dirty(layout);
6412 self.needs_layout = true;
6413 }
6414 }
6415 }
6416 Prop::Image(option) => {
6417 if let Some(image) = node.image.as_mut() {
6418 match option {
6419 ImageProp::Placeholder(source) => {
6420 image.options.placeholder = source.map(ImageSource::inline)
6421 }
6422 ImageProp::BlurRadius(r) => image.options.blur_radius = r.max(Points::ZERO),
6423 ImageProp::FadeDuration(ms) => image.options.fade_ms = ms,
6424 ImageProp::SvgCurrentColor(on) => image.svg_current_color = on,
6425 }
6426 flags |= dirty::IMAGE;
6427 }
6428 }
6429 Prop::Horizontal(horizontal) => {
6430 if let Some(scroll) = node.scroll.as_mut()
6431 && scroll.horizontal != horizontal
6432 {
6433 scroll.horizontal = horizontal;
6434 flags |= dirty::SCROLL;
6435 let rtl = node.rtl;
6436 if let Some(list) = node.list.as_mut() {
6437 list.set_mirrored(horizontal && rtl);
6438 list.set_horizontal(horizontal);
6439 }
6440 let children = node.children.clone();
6441 self.sync_layout_style(key);
6442 for child in children {
6443 self.sync_layout_style(child);
6444 }
6445 if self.nodes[key as usize]
6446 .list
6447 .as_ref()
6448 .is_some_and(|l| l.parent)
6449 {
6450 self.sync_spacer(key, true);
6451 self.outer_moved = true;
6452 flags |= dirty::VIEW_PROPS;
6454 }
6455 }
6456 }
6457 Prop::Scrollbar(setting) => {
6458 if let Some(scroll) = node.scroll.as_mut() {
6459 scroll.scrollbar = setting;
6460 flags |= dirty::SCROLL;
6461 self.scrollbars_pending.push(key);
6462 } else if let Some(input) = node.input.as_mut() {
6463 input.scrollbar = setting;
6464 flags |= dirty::INPUT;
6465 self.scrollbars_pending.push(key);
6466 }
6467 }
6468 Prop::Scroll(prop) => {
6469 if let Some(scroll) = node.scroll.as_mut() {
6470 let b = &mut scroll.behavior;
6471 match prop {
6472 ScrollProp::Paging(on) => b.paging = on,
6473 ScrollProp::SnapInterval(v) => b.snap_interval = v.max(Points::ZERO),
6474 ScrollProp::SnapOffsets(v) => b.snap_offsets = v,
6475 ScrollProp::SnapAlignment(a) => b.snap_alignment = a,
6476 ScrollProp::Deceleration(r) => b.deceleration = r,
6477 ScrollProp::Bounces(on) => b.bounces = on,
6478 ScrollProp::ScrollsToTop(on) => b.scrolls_to_top = on,
6479 ScrollProp::SmoothWheel(on) => b.smooth_wheel = on,
6480 ScrollProp::WheelLineHeight(h) => b.wheel_line_height = h.max(Points::ZERO),
6481 ScrollProp::ContentInset(i) => b.content_inset = i,
6482 ScrollProp::ScrollbarInset(i) => {
6483 b.scrollbar_inset = i.map(|v| Points(v.0.max(0.0)));
6485 if scroll.bar.is_some() {
6487 self.needs_layout = true;
6488 }
6489 }
6490 ScrollProp::KeyboardTaps(t) => b.keyboard_taps = t,
6491 ScrollProp::DisableIntervalMomentum(on) => b.one_step = on,
6492 ScrollProp::MinZoom(v) => b.min_zoom = v.max(0.01),
6493 ScrollProp::MaxZoom(v) => b.max_zoom = v.max(0.01),
6494 ScrollProp::BouncesZoom(on) => b.bounces_zoom = on,
6495 ScrollProp::Pinch(on) => b.pinch = on,
6496 ScrollProp::CenterContent(on) => b.center_content = on,
6497 ScrollProp::RefreshIndicator(h) => {
6498 b.refresh_indicator = h.filter(|h| h.0 > 0.0);
6500 }
6501 ScrollProp::Zoom(scale) => {
6502 let id = node.id;
6505 self.commands.push((
6506 id,
6507 Command::ZoomTo {
6508 scale,
6509 center: None,
6510 animated: false,
6511 },
6512 ));
6513 }
6514 ScrollProp::EventThrottle(ms) => scroll.event_throttle_ms = ms.max(0.0),
6515 ScrollProp::ContentOffset(offset) => {
6516 let id = node.id;
6518 self.commands.push((
6519 id,
6520 Command::ScrollTo {
6521 x: offset.x,
6522 y: offset.y,
6523 animated: false,
6524 },
6525 ));
6526 }
6527 }
6528 flags |= dirty::SCROLL_BEHAVIOR;
6529 }
6530 }
6531 Prop::Refreshing(refreshing) => {
6532 if let Some(scroll) = node.scroll.as_mut() {
6533 scroll.refreshing = refreshing;
6534 flags |= dirty::REFRESHING;
6535 }
6536 }
6537 Prop::ScrollValue(value) => {
6538 if let Some(value) = value {
6539 self.reach.drive(value);
6540 }
6541 if let Some(scroll) = node.scroll.as_mut() {
6542 scroll.scroll_value = value;
6543 flags |= dirty::SCROLL;
6544 }
6545 }
6546 Prop::PullValue(value) => {
6547 if let Some(value) = value {
6548 self.reach.drive(value);
6549 }
6550 if let Some(scroll) = node.scroll.as_mut() {
6551 scroll.pull_value = value;
6552 flags |= dirty::SCROLL;
6553 }
6554 }
6555 Prop::Count(count) => {
6556 if let Some(list) = node.list.as_mut()
6557 && list.count != count
6558 {
6559 list.unrequest(&take_queued_binds(&mut self.list_binds, node.id));
6560 list.set_count(count);
6561 }
6562 }
6563 Prop::EstimatedItemSize(size) => {
6564 if let Some(list) = node.list.as_mut() {
6565 list.set_estimated(size.0);
6566 }
6567 }
6568 Prop::Slot(slot) => {
6569 node.slot = Some(slot);
6570 let parent = node.parent;
6571 if let Some(list) = self
6572 .nodes
6573 .get_mut(parent as usize)
6574 .and_then(|p| p.list.as_mut())
6575 {
6576 list.add_slot_cell(slot, key);
6577 }
6578 }
6579 Prop::Splice(at, removed, inserted) => {
6580 let loads_at_start = node.events.contains(EventKind::LoadMoreAtStart);
6581 if let Some(list) = node.list.as_mut() {
6582 list.loads_at_start = loads_at_start;
6583 list.unrequest(&take_queued_binds(&mut self.list_binds, node.id));
6584 list.splice(at, removed, inserted);
6585 }
6586 }
6587 Prop::ListDiff(diff) => {
6588 let loads_at_start = node.events.contains(EventKind::LoadMoreAtStart);
6589 if let Some(list) = node.list.as_mut() {
6590 list.loads_at_start = loads_at_start;
6591 list.unrequest(&take_queued_binds(&mut self.list_binds, node.id));
6592 list.reorder(&diff);
6593 }
6594 }
6595 Prop::Columns(columns) => {
6596 if let Some(list) = node.list.as_mut()
6597 && list.set_columns(columns)
6598 {
6599 self.needs_layout = true;
6602 }
6603 }
6604 Prop::Inverted(inverted) => {
6605 if let Some(list) = node.list.as_mut() {
6606 list.set_inverted(inverted);
6607 if list.parent {
6608 self.warn_ignored(key);
6609 }
6610 }
6611 }
6612 Prop::FollowEnd(threshold, animated) => {
6613 if let Some(list) = node.list.as_mut() {
6614 list.set_follow_end(threshold.map(|t| t.0), animated);
6615 if list.parent {
6616 self.warn_ignored(key);
6617 }
6618 }
6619 }
6620 Prop::ListAlignment(alignment) => {
6621 if let Some(list) = node.list.as_mut() {
6622 list.set_alignment(alignment);
6623 if list.parent {
6624 self.warn_ignored(key);
6625 }
6626 }
6627 }
6628 Prop::StickyIndices(indices) => {
6629 if let Some(list) = node.list.as_mut() {
6630 list.set_sticky(indices);
6631 if list.parent {
6632 self.warn_ignored(key);
6633 }
6634 }
6635 }
6636 Prop::StickyOffset(offset) => {
6637 if let Some(list) = node.list.as_mut() {
6638 list.set_sticky_node(None);
6639 list.set_sticky_offset(offset.0);
6640 if list.parent {
6641 self.warn_ignored(key);
6642 }
6643 }
6644 }
6645 Prop::StickyOffsetNode(node_id) => {
6646 if let Some(list) = node.list.as_mut() {
6647 list.set_sticky_offset(0.0);
6648 list.set_sticky_node(node_id);
6649 }
6650 }
6651 Prop::ListContent(content) => {
6652 if let Some(list) = node.list.as_mut()
6653 && list.set_content(content)
6654 {
6655 self.needs_layout = true;
6656 }
6657 }
6658 Prop::Viewability(config) => {
6659 if let Some(list) = node.list.as_mut()
6660 && list.viewability != config
6661 {
6662 list.viewability = config;
6663 list.dirty = true;
6664 }
6665 }
6666 Prop::LoadMoreThreshold(threshold) => {
6667 if let Some(list) = node.list.as_mut() {
6668 list.end_threshold = threshold.max(0.0);
6669 }
6670 }
6671 Prop::LoadMoreAtStartThreshold(threshold) => {
6672 if let Some(list) = node.list.as_mut() {
6673 list.start_threshold = threshold.max(0.0);
6674 }
6675 }
6676 Prop::CellIndex(index) => {
6677 let parent = node.parent;
6678 if let Some(list) = self
6679 .nodes
6680 .get_mut(parent as usize)
6681 .and_then(|p| p.list.as_mut())
6682 {
6683 list.rendered(key, index);
6684 }
6685 }
6686 Prop::PanValues(x, y) => {
6687 for value in [x, y].into_iter().flatten() {
6689 self.reach.drive(value);
6690 }
6691 (node.gestures.pan_x, node.gestures.pan_y) = (x, y);
6692 flags |= dirty::PAN;
6693 }
6694 Prop::PanEnabled(enabled) => {
6695 if node.pan_enabled != enabled {
6696 node.pan_enabled = enabled;
6697 flags |= dirty::PAN | dirty::EVENTS;
6698 }
6699 }
6700 Prop::PanScrollHandoff(value) => {
6701 let props = node.props.get_or_insert_default();
6702 if props.pan_scroll_handoff != value {
6703 props.pan_scroll_handoff = value;
6704 flags |= dirty::VIEW_PROPS;
6705 }
6706 }
6707 Prop::PinchValue(value) => {
6708 if let Some(value) = value {
6709 self.reach.drive(value);
6710 }
6711 node.gestures.pinch = value;
6712 flags |= dirty::PAN;
6713 }
6714 Prop::RotationValue(value) => {
6715 if let Some(value) = value {
6716 self.reach.drive(value);
6717 }
6718 node.gestures.rotation = value;
6719 flags |= dirty::PAN;
6720 }
6721 Prop::AllowFontScaling(allow) => {
6722 if node.paragraph.allow_font_scaling != allow {
6723 node.paragraph.allow_font_scaling = allow;
6724 self.font_settings_changed(key);
6725 }
6726 }
6727 Prop::SelectionColor(color) if node.input.is_none() => {
6728 if node.paragraph.selection_color != color {
6729 node.paragraph.selection_color = color;
6730 if node.kind == Kind::Text {
6731 self.mark_text_block(key);
6732 } else {
6733 self.mark_inheriting_text(key);
6736 }
6737 }
6738 }
6739 Prop::AdjustsFontSizeToFit(_) | Prop::MinimumFontScale(_) => {
6740 let before = (node.paragraph.fit, node.paragraph.min_font_scale);
6741 match prop {
6742 Prop::AdjustsFontSizeToFit(on) => node.paragraph.fit = on,
6743 Prop::MinimumFontScale(min) => node.paragraph.min_font_scale = min,
6744 _ => {}
6745 }
6746 if (node.paragraph.fit, node.paragraph.min_font_scale) != before {
6747 self.queue_text(key);
6748 if let Some(layout) = self.nodes[key as usize].layout
6749 && let Some(LeafContext::Text(cx)) =
6750 self.layout.get_node_context_mut(layout)
6751 {
6752 cx.laid_out = None;
6753 }
6754 }
6755 }
6756 Prop::MaxFontSizeMultiplier(max) => {
6757 if node.paragraph.max_font_multiplier != max {
6758 node.paragraph.max_font_multiplier = max;
6759 self.font_settings_changed(key);
6760 }
6761 }
6762 Prop::PointerEvents(value) => {
6763 let props = node.props.get_or_insert_default();
6764 if props.pointer_events != value {
6765 props.pointer_events = value;
6766 flags |= dirty::VIEW_PROPS;
6767 }
6768 }
6769 Prop::HitSlop(value) => {
6770 let props = node.props.get_or_insert_default();
6771 if props.hit_slop != value {
6772 props.hit_slop = value;
6773 flags |= dirty::VIEW_PROPS;
6774 slop_moved = true;
6775 }
6776 }
6777 Prop::Href(value) => {
6778 let value = value.filter(|href| !href.is_empty());
6779 let props = node.props.get_or_insert_default();
6780 if props.href != value {
6781 props.href = value;
6782 flags |= dirty::VIEW_PROPS;
6783 if node.kind == Kind::Text && node.inline {
6785 rebuild_span = true;
6786 }
6787 }
6788 }
6789 Prop::PanActivation(value) => {
6790 let props = node.props.get_or_insert_default();
6791 if props.pan_activation != value {
6792 props.pan_activation = value;
6793 flags |= dirty::VIEW_PROPS;
6794 }
6795 }
6796 Prop::InsetPadding(insets) | Prop::InsetMargin(insets) => {
6797 let slot = usize::from(matches!(prop, Prop::InsetMargin(_)));
6798 let mut all = node.insets.as_deref().copied().unwrap_or_default();
6799 if all[slot] != insets {
6800 all[slot] = insets;
6801 node.insets = (all != <[EdgeInsets; 2]>::default()).then(|| Box::new(all));
6802 self.restyle(key);
6803 }
6804 return Ok(());
6805 }
6806 Prop::Class(names) => {
6807 self.set_classes(key, Some(names), None);
6808 return Ok(());
6809 }
6810 Prop::ClassList(list) => {
6811 self.set_classes(key, None, Some(list));
6812 return Ok(());
6813 }
6814 Prop::TailwindTheme(json) => {
6815 self.set_tailwind_theme(&json);
6816 return Ok(());
6817 }
6818 Prop::UiTheme(json) => {
6819 self.set_ui_theme(&json);
6820 return Ok(());
6821 }
6822 Prop::SnapToWindowMargin(margin) => {
6823 self.set_snap_to_window_margin(margin);
6824 return Ok(());
6825 }
6826 Prop::LayoutDirection(rtl) => {
6827 if key == self.root && node.direction != Some(rtl) {
6830 node.direction = Some(rtl);
6831 self.mount.push(MountItem::LayoutDirection { rtl });
6832 self.update_direction(key);
6833 self.root_direction_changed(rtl);
6834 }
6835 return Ok(());
6836 }
6837 Prop::Appearance(appearance) => {
6838 if key == self.root {
6841 self.set_appearance(appearance);
6842 }
6843 return Ok(());
6844 }
6845 Prop::Keymap(keymap) => {
6846 if key == self.root {
6848 let keymap = self.keymap_with_focus(keymap);
6849 self.mount.push(MountItem::Keymap(keymap));
6850 }
6851 return Ok(());
6852 }
6853 Prop::LongPressDelay(value) => {
6854 let props = node.props.get_or_insert_default();
6855 if props.long_press_delay != value {
6856 props.long_press_delay = value;
6857 flags |= dirty::VIEW_PROPS;
6858 }
6859 }
6860 Prop::Ripple(value) => {
6861 let props = node.props.get_or_insert_default();
6862 if props.ripple != value {
6863 props.ripple = value;
6864 flags |= dirty::VIEW_PROPS;
6865 }
6866 }
6867 Prop::Elevation(value) => {
6868 let value = value.max(Points::ZERO);
6869 if node.elevation != value {
6870 node.elevation = value;
6871 flags |= dirty::VIEW;
6872 }
6873 }
6874 Prop::BackdropMaterial(value) => {
6875 if node.backdrop_material != value {
6876 node.backdrop_material = value;
6877 flags |= dirty::VIEW;
6878 }
6879 }
6880 Prop::MacOsBackdrop(value) => {
6881 if node.macos_backdrop != value {
6882 node.macos_backdrop = value;
6883 flags |= dirty::VIEW;
6884 }
6885 }
6886 Prop::WindowsBackdrop(value) => {
6887 if node.windows_backdrop != value {
6888 node.windows_backdrop = value;
6889 flags |= dirty::VIEW;
6890 }
6891 }
6892 Prop::ActiveStyle(patch) => {
6893 self.set_part_style(key, classes::Part::Active, patch);
6894 return Ok(());
6895 }
6896 Prop::HoverStyle(patch) => {
6897 self.set_part_style(key, classes::Part::Hover, patch);
6898 return Ok(());
6899 }
6900 Prop::FocusStyle(patch) => {
6901 self.set_part_style(key, classes::Part::Focus, patch);
6902 return Ok(());
6903 }
6904 Prop::DisabledStyle(patch) => {
6905 self.set_part_style(key, classes::Part::Disabled, patch);
6906 return Ok(());
6907 }
6908 Prop::SelectedStyle(patch) => {
6909 self.set_part_style(key, classes::Part::Selected, patch);
6910 return Ok(());
6911 }
6912 Prop::CheckedStyle(patch) => {
6913 self.set_part_style(key, classes::Part::Checked, patch);
6914 return Ok(());
6915 }
6916 Prop::IndeterminateStyle(patch) => {
6917 self.set_part_style(key, classes::Part::Indeterminate, patch);
6918 return Ok(());
6919 }
6920 Prop::PressedStyle(patch) => {
6921 self.set_part_style(key, classes::Part::Pressed, patch);
6922 return Ok(());
6923 }
6924 Prop::ExpandedStyle(patch) => {
6925 self.set_part_style(key, classes::Part::Expanded, patch);
6926 return Ok(());
6927 }
6928 Prop::FocusWithinStyle(patch) => {
6929 self.set_part_style(key, classes::Part::FocusWithin, patch);
6930 return Ok(());
6931 }
6932 Prop::FocusVisibleStyle(patch) => {
6933 self.set_part_style(key, classes::Part::FocusVisible, patch);
6934 return Ok(());
6935 }
6936 Prop::ProjectedStates(states) => {
6937 self.set_projected_states(key, states);
6938 return Ok(());
6939 }
6940 Prop::ProjectedData(data) => {
6941 self.set_projected_data(key, data);
6942 return Ok(());
6943 }
6944 Prop::ProjectedActive(group) => {
6945 self.set_projected_active(key, group);
6946 return Ok(());
6947 }
6948 Prop::HeaderStyle(patch) => {
6949 self.set_part_style(key, classes::Part::Header, patch);
6950 return Ok(());
6951 }
6952 Prop::HeaderClass(names) => {
6953 self.set_part_class(key, classes::Part::Header, &names);
6954 return Ok(());
6955 }
6956 Prop::HeaderClassList(list) => {
6957 self.set_part_class_list(key, classes::Part::Header, list);
6958 return Ok(());
6959 }
6960 Prop::ListContentClass(names) => {
6961 self.set_part_class(key, classes::Part::Content, &names);
6962 return Ok(());
6963 }
6964 Prop::TestId(value) => {
6965 let props = node.props.get_or_insert_default();
6966 if props.test_id != value {
6967 props.test_id = value;
6968 flags |= dirty::VIEW_PROPS;
6969 if node.kind == Kind::Text && node.inline {
6971 rebuild_span = true;
6972 }
6973 }
6974 }
6975 Prop::ClearsKeyboard(value) => {
6976 if node.clears_keyboard != value {
6977 node.clears_keyboard = value;
6981 }
6982 }
6983 Prop::CopyText(value) => {
6984 if node.copy_text != value {
6985 node.copy_text = value;
6986 copy_text_changed = true;
6989 }
6990 }
6991 Prop::WebElement(value) => {
6992 let props = node.props.get_or_insert_default();
6993 if props.web_element != value {
6994 props.web_element = value;
6995 flags |= dirty::VIEW_PROPS;
6996 }
6997 }
6998 Prop::WindowDrag(value) => {
6999 let props = node.props.get_or_insert_default();
7000 if props.window_drag != value {
7001 props.window_drag = value;
7002 flags |= dirty::VIEW_PROPS;
7003 }
7004 }
7005 Prop::WindowControl(value) => {
7006 let props = node.props.get_or_insert_default();
7007 if props.window_control != value {
7008 props.window_control = value;
7009 flags |= dirty::VIEW_PROPS;
7010 }
7011 }
7012 Prop::WindowResize(value) => {
7013 let props = node.props.get_or_insert_default();
7014 if props.window_resize != value {
7015 props.window_resize = value;
7016 flags |= dirty::VIEW_PROPS;
7017 }
7018 }
7019 Prop::Focusable(value) => {
7020 let props = node.props.get_or_insert_default();
7021 if props.focusable != value {
7022 props.focusable = value;
7023 flags |= dirty::VIEW_PROPS;
7024 }
7025 }
7026 Prop::KeyCapture(value) => {
7027 let props = node.props.get_or_insert_default();
7028 if props.key_capture != value {
7029 props.key_capture = value;
7030 flags |= dirty::VIEW_PROPS;
7031 key_ancestry = true;
7032 }
7033 }
7034 Prop::SelectableView(value) => {
7035 let props = node.props.get_or_insert_default();
7036 if props.selectable_view != value {
7037 props.selectable_view = value;
7038 flags |= dirty::VIEW_PROPS;
7039 }
7040 }
7041 Prop::SelectionMenu(items) => {
7042 let items: std::sync::Arc<[crate::desktop::MenuItem]> =
7043 crate::desktop::MenuItem::selection_menu(&items).into();
7044 let props = node.props.get_or_insert_default();
7045 if props.selection_menu != items {
7046 props.selection_menu = items;
7047 flags |= dirty::VIEW_PROPS;
7048 }
7049 }
7050 Prop::ContinuesText(value) => {
7051 let props = node.props.get_or_insert_default();
7052 if props.continues_text != value {
7053 props.continues_text = value;
7054 flags |= dirty::VIEW_PROPS;
7055 }
7056 }
7057 Prop::Accessibility(prop) => {
7058 let label_only =
7061 node.props.is_some() && matches!(prop, AccessibilityProp::Label(_));
7062 let props = node.props.get_or_insert_default();
7063 let a = &mut props.accessibility;
7064 let before = a.clone();
7065 match prop {
7066 AccessibilityProp::Accessible(v) => a.accessible = v,
7067 AccessibilityProp::Label(v) => a.label = v,
7068 AccessibilityProp::Hint(v) => a.hint = v,
7069 AccessibilityProp::Description(v) => a.description = v,
7070 AccessibilityProp::Role(v) => a.role = v,
7071 AccessibilityProp::State(v) => a.state = v,
7072 AccessibilityProp::Value(v) => a.value = v,
7073 AccessibilityProp::Hidden(v) => a.hidden = v,
7074 AccessibilityProp::Important(accessible, hidden) => {
7075 a.accessible = accessible;
7076 a.hidden = hidden;
7077 }
7078 AccessibilityProp::LiveRegion(v) => a.live_region = v,
7079 AccessibilityProp::Actions(v) => a.actions = v,
7080 AccessibilityProp::Level(v) => a.level = v,
7081 AccessibilityProp::Orientation(v) => a.orientation = v,
7082 AccessibilityProp::ActiveDescendant(_)
7084 | AccessibilityProp::Controls(_)
7085 | AccessibilityProp::DescribedBy(_) => {}
7086 }
7087 let states = classes::accessibility_states(&a.state);
7088 let states_changed = states != classes::accessibility_states(&before.state);
7089 if *a != before {
7090 flags |= if label_only {
7091 dirty::LABEL
7092 } else {
7093 dirty::VIEW_PROPS
7094 };
7095 }
7096 if states_changed {
7097 if flags != 0 {
7098 self.mark(key, flags);
7099 }
7100 self.set_accessibility_states(key, states);
7101 return Ok(());
7102 }
7103 }
7104 Prop::KeyboardDismissMode(mode) => {
7105 if let Some(scroll) = node.scroll.as_mut() {
7106 scroll.keyboard_dismiss = mode;
7107 flags |= dirty::SCROLL;
7108 }
7109 }
7110 Prop::Screen(ScreenProp::Animation(a)) if node.kind == Kind::Modal => {
7112 if let Some(root) = node.root.as_mut() {
7113 root.modal.animation = match a {
7114 ScreenAnimation::Default => ModalAnimation::Slide,
7115 ScreenAnimation::Fade => ModalAnimation::Fade,
7116 ScreenAnimation::None => ModalAnimation::None,
7117 };
7118 flags |= dirty::MODAL;
7119 }
7120 }
7121 Prop::Screen(prop) => {
7122 if let Some(root) = node.root.as_mut() {
7123 let c = &mut root.screen;
7124 match prop {
7125 ScreenProp::Title(v) => c.title = v,
7126 ScreenProp::HeaderVisible(v) => c.header_visible = v,
7127 ScreenProp::HeaderLargeTitle(v) => c.large_title = v,
7128 ScreenProp::HeaderTransparent(v) => c.header_transparent = v,
7129 ScreenProp::HeaderShadowVisible(v) => c.header_shadow_visible = v,
7130 ScreenProp::HeaderTitleAlign(v) => c.title_align = v,
7131 ScreenProp::HeaderBackgroundOnScroll(v) => {
7132 c.header_background_on_scroll = v
7133 }
7134 ScreenProp::HidesBottomBarWhenPushed(v) => {
7135 c.hides_bottom_bar_when_pushed = v
7136 }
7137 ScreenProp::HeaderBackTitle(v) => c.back_title = v,
7138 ScreenProp::HeaderBackVisible(v) => c.back_visible = v,
7139 ScreenProp::HeaderRightSystemItem(v) => c.right_system_item = v,
7140 ScreenProp::HeaderRightSymbol(v) => c.right_symbol = v,
7141 ScreenProp::HeaderLeftSystemItem(v) => c.left_system_item = v,
7142 ScreenProp::HeaderLeftSymbol(v) => c.left_symbol = v,
7143 ScreenProp::HeaderRightItems(v) => c.right_items = v,
7144 ScreenProp::HeaderLeftItems(v) => c.left_items = v,
7145 ScreenProp::PopOnSwipe(v) => c.gesture_enabled = v,
7146 ScreenProp::PopOnBack(v) => c.prevent_back = !v,
7147 ScreenProp::Animation(v) => c.animation = v,
7148 ScreenProp::StatusBar(_) | ScreenProp::Orientations(_) => {}
7150 }
7151 root.laid_out = None;
7153 self.needs_layout = true;
7154 flags |= dirty::SCREEN;
7155 }
7156 }
7157 Prop::NativeId(name) => {
7158 if node.kind == Kind::InputAccessory {
7159 let attached = node.parent != NO_KEY;
7160 if attached {
7161 self.accessory_attached(key, false);
7162 }
7163 if let Some(root) = self.nodes[key as usize].root.as_mut() {
7164 root.native_id = name;
7165 }
7166 if attached {
7167 self.accessory_attached(key, true);
7168 }
7169 return Ok(());
7170 }
7171 let value: Option<Arc<str>> = name.as_deref().map(Into::into);
7174 let props = node.props.get_or_insert_default();
7175 if props.native_id != value {
7176 props.native_id = value;
7177 flags |= dirty::VIEW_PROPS;
7178 }
7179 }
7180 Prop::Modal(prop) => {
7181 if let Some(root) = node.root.as_mut() {
7182 let c = &mut root.modal;
7183 match prop {
7184 ModalProp::Animation(v) => c.animation = v,
7185 ModalProp::Presentation(v) => c.presentation = v,
7186 ModalProp::StatusBarTranslucent(v) => c.status_bar_translucent = v,
7187 ModalProp::Orientations(v) => c.orientations = v,
7188 ModalProp::CloseOnEscape(v) => c.close_on_escape = v,
7189 ModalProp::CloseOnBackdropPress(v) => c.close_on_backdrop_press = v,
7190 ModalProp::CloseOnSwipe(v) => c.close_on_swipe = v,
7191 ModalProp::Detents(v) => c.detents = v,
7192 ModalProp::Detent(v) => c.detent = v,
7193 ModalProp::DefaultDetent(v) => c.default_detent = v,
7194 ModalProp::Grabber(v) => c.grabber = v,
7195 ModalProp::LargestUndimmedDetent(v) => c.largest_undimmed_detent = v,
7196 }
7197 flags |= dirty::MODAL;
7198 }
7199 }
7200 Prop::Overlay(prop) => {
7201 use crate::OverlayProp;
7202 let parent = node.parent;
7205 if matches!(prop, OverlayProp::Hint(_))
7206 && parent != NO_KEY
7207 && self.nodes[parent as usize]
7208 .positional
7209 .has(Positional::CHILDREN)
7210 {
7211 self.queue_positions(parent);
7212 }
7213 self.set_overlay_config(key, |c| match prop {
7214 OverlayProp::Anchor(v) => c.anchor = v,
7215 OverlayProp::Placement(v) => c.placement = v,
7216 OverlayProp::Align(v) => c.align = v,
7217 OverlayProp::Offset(v) => c.offset = v,
7218 OverlayProp::Margin(v) => c.margin = v,
7219 OverlayProp::Hint(v) => c.hint = v,
7220 OverlayProp::Open(v) => c.open = v,
7221 OverlayProp::Cover(v) => c.cover = v,
7222 });
7223 if matches!(prop, OverlayProp::Margin(_))
7224 && let Some(state) = self.overlay_mut(key)
7225 && !state.margin_set
7226 {
7227 state.margin_set = true;
7228 state.placed = None;
7229 self.needs_layout = true;
7230 }
7231 return Ok(());
7232 }
7233 Prop::Tooltip(content) => {
7234 self.set_tooltip(key, content);
7235 return Ok(());
7236 }
7237 Prop::HeaderSlot(slot) => {
7238 if let Some(root) = node.root.as_mut()
7239 && root.slot != slot
7240 {
7241 root.slot = slot;
7242 let parent = node.parent;
7243 if parent != NO_KEY {
7244 self.mark(parent, dirty::SCREEN);
7245 }
7246 }
7247 }
7248 Prop::Native(NativeProp::Scrollable(on)) if node.scroll.is_some() => {
7250 if let Some(scroll) = node.scroll.as_mut() {
7251 scroll.behavior.enabled = on;
7252 flags |= dirty::SCROLL_BEHAVIOR;
7253 }
7254 }
7255 Prop::Component(name) => {
7256 let created = node.created;
7257 if let Some(component) = node.component.as_mut() {
7258 match &component.name {
7259 None if created => {
7264 component.name = Some(name.clone());
7265 component.changed =
7266 component.props.iter().map(|(k, _)| k.clone()).collect();
7267 self.mount.push(MountItem::Component { id, name });
7268 flags |= dirty::COMPONENT;
7269 if !component.slots.is_empty() {
7270 component.slots_changed.set(true);
7271 flags |= dirty::ANIMATION;
7272 }
7273 }
7274 None => component.name = Some(name),
7275 Some(old) if *old != name => log::warn!(
7276 target: "js",
7277 "a native component cannot change from `{old}` to `{name}`; render a new element"
7278 ),
7279 Some(_) => {}
7280 }
7281 }
7282 }
7283 Prop::ComponentPropBinding(name, value) => {
7284 if let Some(component) = node.component.as_mut() {
7285 let slot = match component.slots.iter().position(|k| *k == name) {
7286 Some(s) => Some(s as u16),
7287 None if value.is_none() => None,
7288 None => {
7289 component.slots.push(name.clone());
7290 component.slots_changed.set(true);
7291 Some((component.slots.len() - 1) as u16)
7292 }
7293 };
7294 if let Some(slot) = slot {
7295 let at = component.bound.iter().position(|(s, _)| *s == slot);
7296 match (at, value) {
7297 (Some(i), Some(n)) => component.bound[i].1 = n,
7298 (None, Some(n)) => component.bound.push((slot, n)),
7299 (Some(i), None) => {
7300 component.bound.remove(i);
7301 if !component.changed.contains(&name) {
7303 component.changed.push(name);
7304 }
7305 flags |= dirty::COMPONENT;
7306 }
7307 (None, None) => {}
7308 }
7309 flags |= dirty::ANIMATION;
7310 }
7311 }
7312 }
7313 Prop::ComponentProp(name, value) => {
7314 if let Some(component) = node.component.as_mut() {
7315 let at = component.props.iter().position(|(k, _)| *k == name);
7316 match (at, value) {
7317 (Some(i), Some(v)) => component.props[i].1 = v,
7318 (None, Some(v)) => component.props.push((name.clone(), v)),
7319 (Some(i), None) => {
7320 component.props.swap_remove(i);
7321 }
7322 (None, None) => {}
7323 }
7324 if !component.changed.contains(&name) {
7325 component.changed.push(name);
7326 }
7327 flags |= dirty::COMPONENT;
7328 }
7329 }
7330 Prop::Native(prop) => {
7331 if let NativeProp::Disabled(d) = prop {
7332 self.set_disabled(key, d);
7334 }
7335 let node = &mut self.nodes[key as usize];
7336 if node.created
7339 && let Some(NativeProps::WebView(p)) = node.control.as_deref()
7340 {
7341 let changed = match &prop {
7342 NativeProp::Incognito(on) => Some(("`incognito` is", *on != p.incognito)),
7343 NativeProp::Zoomable(on) => Some(("`zoomable` is", *on != p.zoomable)),
7344 NativeProp::UrlSchemes(schemes) => Some((
7347 "URL schemes are",
7348 !schemes
7349 .iter()
7350 .map(|s| s.scheme())
7351 .eq(p.url_schemes.iter().map(|s| s.scheme())),
7352 )),
7353 _ => None,
7354 };
7355 if let Some((what, changed)) = changed {
7356 if changed {
7357 log::warn!(
7358 target: "js",
7359 "a web view's {what} read when it is made; render a new element to change it"
7360 );
7361 }
7362 return Ok(());
7363 }
7364 }
7365 if let Some(control) = node.control.as_mut() {
7366 apply_native(control, prop);
7367 flags |= dirty::NATIVE;
7368 }
7369 }
7370 Prop::Value(value) => {
7371 if let Some(input) = node.input.as_mut() {
7372 input.value_set = true;
7373 if input.value != value {
7374 input.value = value;
7375 flags |= dirty::INPUT_VALUE;
7376 self.measure_input(key);
7377 }
7378 }
7379 }
7380 Prop::DefaultValue(value) => {
7381 if let Some(input) = node.input.as_mut()
7382 && !input.value_set
7383 {
7384 input.value_set = true;
7385 input.value = value;
7386 flags |= dirty::INPUT_VALUE;
7387 self.measure_input(key);
7388 }
7389 }
7390 prop => {
7391 let Some(input) = node.input.as_mut() else {
7392 return Ok(());
7393 };
7394 let c = &mut input.config;
7395 let remeasure = match prop {
7396 Prop::Placeholder(text) => {
7397 c.placeholder = text;
7398 true
7399 }
7400 Prop::Multiline(multiline) => {
7401 c.multiline = multiline;
7402 self.scrollbars_pending.push(key);
7404 true
7405 }
7406 Prop::PlaceholderColor(color) => {
7407 c.placeholder_color = color;
7408 false
7409 }
7410 Prop::Secure(secure) => {
7411 c.secure = secure;
7412 false
7413 }
7414 Prop::KeyboardType(keyboard) => {
7415 c.keyboard = keyboard;
7416 false
7417 }
7418 Prop::KeyboardAppearance(appearance) => {
7419 c.keyboard_appearance = appearance;
7420 false
7421 }
7422 Prop::ReturnKeyType(key) => {
7423 c.return_key = key;
7424 false
7425 }
7426 Prop::AutoCapitalize(mode) => {
7427 c.auto_capitalize = mode;
7428 false
7429 }
7430 Prop::AutoCorrect(on) => {
7431 c.auto_correct = on;
7432 false
7433 }
7434 Prop::MaxLength(len) => {
7435 c.max_length = len;
7436 false
7437 }
7438 Prop::Readonly(on) => {
7439 c.editable = !on;
7440 false
7441 }
7442 Prop::SubmitBehavior(behavior) => {
7443 c.submit_behavior = behavior;
7444 false
7445 }
7446 Prop::PasteBehavior(behavior) => {
7447 c.paste_behavior = behavior;
7448 false
7449 }
7450 Prop::PasteMaxSize(max) => {
7451 c.paste_max_size = max;
7452 false
7453 }
7454 Prop::AutoFocus(on) => {
7455 c.auto_focus = on;
7456 false
7457 }
7458 Prop::SelectTextOnFocus(on) => {
7459 c.select_text_on_focus = on;
7460 false
7461 }
7462 Prop::Caret(on) => {
7463 c.caret_hidden = !on;
7464 false
7465 }
7466 Prop::InputAccessoryViewId(name) => {
7467 c.accessory_id = name;
7468 false
7469 }
7470 Prop::SelectionColor(color) => {
7471 c.selection_color = color;
7472 false
7473 }
7474 Prop::CaretColor(color) => {
7475 c.caret_color = color;
7476 false
7477 }
7478 Prop::AutoFill(fill) => {
7479 c.auto_fill = fill;
7480 false
7481 }
7482 Prop::Selection(start, end) => {
7483 let id = node.id;
7485 self.commands
7486 .push((id, Command::SetSelection { start, end }));
7487 return Ok(());
7488 }
7489 _ => return Ok(()),
7490 };
7491 flags |= dirty::INPUT;
7492 if remeasure {
7493 self.measure_input(key);
7494 }
7495 }
7496 }
7497 if flags != 0 {
7498 self.mark(key, flags);
7499 }
7500 if slop_moved {
7501 self.slop_moved.push(key);
7502 }
7503 if rebuild_span {
7504 self.mark_text_block(key);
7505 }
7506 if copy_text_changed {
7507 if self.nodes[key as usize].inline {
7508 self.mark_text_block(key);
7509 } else if let Some(place) = self.placed_in_text(key) {
7510 self.mark_text_block(place);
7511 }
7512 }
7513 if key_ancestry {
7514 self.key_ancestry_dirty = true;
7515 }
7516 Ok(())
7517 }
7518
7519 fn fold_run(
7522 &mut self,
7523 parent: Key,
7524 parent_id: NodeId,
7525 child_id: NodeId,
7526 before: Option<NodeId>,
7527 ) -> bool {
7528 let node = &self.nodes[parent as usize];
7529 if before.is_some()
7530 || node.kind != Kind::Text
7531 || !node.children.is_empty()
7532 || self.folded.contains_key(&parent)
7533 || self.components.slot_hosts.contains_key(&parent_id)
7534 {
7535 return false;
7536 }
7537 let Some(run) = self.runs.get_mut(&child_id) else {
7538 return false;
7539 };
7540 let from = std::mem::replace(&mut run.block, parent);
7542 if from != NO_KEY {
7543 self.folded.remove(&from);
7544 self.mark_text_block(from);
7545 }
7546 self.folded.insert(parent, child_id);
7547 self.mark_text_block(parent);
7548 true
7549 }
7550
7551 fn unfold_run(&mut self, id: NodeId) {
7553 let Some(run) = self.runs.get_mut(&id) else {
7554 return;
7555 };
7556 let block = std::mem::replace(&mut run.block, NO_KEY);
7557 if block != NO_KEY {
7558 self.folded.remove(&block);
7559 self.mark_text_block(block);
7560 }
7561 }
7562
7563 pub(super) fn materialize_run(&mut self, id: NodeId) -> Result<(), ApplyError> {
7568 let Some(run) = self.runs.remove(&id) else {
7569 return Ok(());
7570 };
7571 let key = match self.alloc(id, Kind::RawText) {
7572 Ok(key) => key,
7573 Err(e) => {
7574 self.runs.insert(id, run);
7575 return Err(e);
7576 }
7577 };
7578 self.nodes[key as usize].text = run.text;
7579 if run.block != NO_KEY {
7580 self.folded.remove(&run.block);
7581 let parent = self.nodes[run.block as usize].id;
7582 let _ = self.insert(parent, id, None);
7583 }
7584 Ok(())
7585 }
7586
7587 fn folded_text(&self, key: Key) -> Option<&str> {
7589 if self.folded.is_empty() {
7590 return None;
7591 }
7592 let id = self.folded.get(&key)?;
7593 self.runs.get(id).map(|r| r.text.as_str())
7594 }
7595
7596 fn insert(
7597 &mut self,
7598 parent_id: NodeId,
7599 child_id: NodeId,
7600 before: Option<NodeId>,
7601 ) -> Result<(), ApplyError> {
7602 let parent = self.key(parent_id)?;
7603 if !self.runs.is_empty() || !self.folded.is_empty() {
7604 if self.fold_run(parent, parent_id, child_id, before) {
7605 return Ok(());
7606 }
7607 self.materialize_run(child_id)?;
7608 if let Some(b) = before {
7609 self.materialize_run(b)?;
7610 }
7611 if let Some(&run) = self.folded.get(&parent) {
7612 self.materialize_run(run)?;
7613 }
7614 }
7615 let child = self.key(child_id)?;
7616 let from = self.nodes[child as usize].parent;
7617 if from != NO_KEY {
7618 self.input_bar_moves(child);
7619 self.note_move(from, parent);
7620 }
7621 let mut before = before.map(|b| self.key(b)).transpose()?;
7622 if before.is_none()
7624 && let Some((bar, _)) = self.nodes[parent as usize]
7625 .scroll
7626 .as_ref()
7627 .and_then(|s| s.bar.as_ref())
7628 && let Ok(bar) = self.key(*bar)
7629 && bar != child
7630 {
7631 before = Some(bar);
7632 }
7633 let Some(depth) = self
7634 .depth_outside(child, parent)
7635 .filter(|_| child != self.root)
7636 else {
7637 return Err(ApplyError::Cycle(child_id));
7638 };
7639 let max = MAX_TREE_DEPTH as u32;
7640 if depth + self.nodes[child as usize].height > max {
7641 if depth + self.count_heights(child) > max {
7643 return Err(ApplyError::TooDeep(MAX_TREE_DEPTH));
7644 }
7645 }
7646 if self.nodes[parent as usize]
7647 .shader
7648 .as_ref()
7649 .is_some_and(|s| {
7650 matches!(
7651 s.role,
7652 crate::shader::ShaderRole::Screen | crate::shader::ShaderRole::ScreenTransition
7653 )
7654 })
7655 {
7656 log::warn!(
7659 target: "js",
7660 "node {child_id} in screen effect {parent_id}: a screen effect or transition has no children"
7661 );
7662 }
7663 if let Some(b) = before
7664 && (b == child || self.nodes[b as usize].parent != parent)
7665 {
7666 return Err(ApplyError::BadAnchor(self.nodes[b as usize].id));
7667 }
7668
7669 let parent_created = self.nodes[parent as usize].created;
7673 if self.nodes[child as usize].parent != NO_KEY {
7674 self.unlink(child, !parent_created);
7675 }
7676
7677 let p = &self.nodes[parent as usize];
7678 let inline = p.kind == Kind::Text && !self.nodes[child as usize].fixed_view;
7681 let pos = match before {
7682 Some(b) => {
7683 let (pos, looked) = position_from_ends(&p.children, &b).expect("anchor is a child");
7684 self.placing(looked);
7685 pos
7686 }
7687 None => p.children.len(),
7688 };
7689 self.set_inline(child, inline);
7690 if !inline {
7691 self.set_hidden_in_text(child, false);
7694 }
7695 self.nodes[child as usize].parent = parent;
7696 if self.nodes[child as usize].kind == Kind::Overlay {
7697 self.key_ancestry_dirty = true;
7699 }
7700 self.nodes[parent as usize].children.insert(pos, child);
7701 self.raise_heights(child);
7702 self.key_content_changed(parent);
7703 self.rank_noted(child);
7704 self.tree_order_changed |= self.track_tree_order;
7705 self.tab_places_stale = true;
7706 if self.nodes[child as usize].states & crate::tailwind::state::FOCUS_WITHIN != 0 {
7707 self.focus_moved = true;
7709 }
7710 self.ch_changed(child);
7711 self.status_bars_moved |= !self.status_bar_nodes.is_empty();
7712 self.outer_moved |= !self.parent_lists.is_empty() && self.may_hold_page_list(child);
7713 self.sticky_changed |= !self.sticky_nodes.is_empty();
7714 self.update_direction(child);
7715 if self.nodes[parent as usize].child_perspective.is_some() {
7716 self.mark(child, dirty::VIEW | dirty::ANIMATION);
7717 }
7718 let node = &self.nodes[parent as usize];
7719 let color = node.text_style.color.or(node.inherited_color);
7720 if self.nodes[child as usize].inherited_color != color {
7721 self.inherit_color_from(child, color);
7722 }
7723 self.groups_changed(child, parent);
7724 let child_node = &self.nodes[child as usize];
7725 if child_node
7726 .classes
7727 .as_ref()
7728 .is_some_and(|c| c.deps() & crate::tailwind::deps::POSITION != 0)
7729 || (child_node.positional.has(Positional::PASS)
7731 && child_node.positional.has(Positional::CHILDREN))
7732 {
7733 self.reads_positions(parent);
7734 }
7735 if self.nodes[parent as usize]
7736 .positional
7737 .has(Positional::CHILDREN)
7738 {
7739 self.queue_positions(parent);
7740 }
7741 self.spacing_changed(parent, child);
7742 if self.pointer_none_classes > 0 {
7743 self.pointer_events_moved(parent);
7744 }
7745
7746 if inline {
7747 if self.nodes[child as usize].placeholder {
7748 self.ask_row(child);
7749 }
7750 self.mark_text_block(parent);
7751 return Ok(());
7752 }
7753 if self.nodes[parent as usize].list.is_some() {
7756 if let Some(slot) = self.nodes[child as usize].slot {
7757 self.nodes[parent as usize]
7758 .list
7759 .as_mut()
7760 .expect("list")
7761 .add_slot_cell(slot, child);
7762 }
7763 self.sync_layout_style(child);
7764 }
7765 let child_kind = self.nodes[child as usize].kind;
7766 if child_kind == Kind::InputAccessory {
7767 self.accessory_attached(child, true);
7768 }
7769 if child_kind == Kind::HeaderItem {
7770 self.mark(parent, dirty::SCREEN);
7771 }
7772 if let Some(child_layout) = self.nodes[child as usize].layout {
7773 if self.nodes[parent as usize].list.is_none()
7776 && !self.nodes[child as usize].is_layout_root()
7777 {
7778 let index = self.layout_index_at(parent, pos);
7779 let parent_layout = self.nodes[parent as usize]
7780 .layout
7781 .expect("block parent has layout");
7782 self.layout
7783 .insert_child_at_index(parent_layout, index as usize, child_layout);
7784 }
7785 self.needs_layout = true;
7786 let parent_created = parent_created
7789 || (child_kind == Kind::Modal
7790 && self.nodes[parent as usize].culled
7791 && self.uncull(parent));
7792 if parent_created
7795 && !self.nodes[child as usize].is_overlay()
7796 && !{
7797 let scope = self.cull_scope(parent);
7798 self.hold_back(scope, child)
7799 }
7800 {
7801 self.ensure_created(child);
7802 let before = match self.nodes[parent as usize].list.as_ref() {
7803 Some(list) if list.parent && !list.sent_sticky.is_empty() => {
7806 self.below_sticky(parent, child)
7807 }
7808 _ => self.native_before_at(parent, child, pos),
7809 };
7810 self.mount.push(MountItem::Insert {
7812 parent: self.nodes[parent as usize].id,
7813 child: self.nodes[child as usize].id,
7814 before,
7815 });
7816 }
7817 }
7818 Ok(())
7819 }
7820
7821 fn detach(&mut self, key: Key) {
7823 self.input_bar_moves(key);
7824 self.unlink(key, true);
7825 }
7826
7827 fn input_bar_moves(&mut self, key: Key) {
7830 let node = &self.nodes[key as usize];
7831 if node.input.as_ref().is_some_and(|i| i.bar.is_some()) {
7832 self.release_scrollbar(key);
7833 self.scrollbars_pending.push(key);
7834 }
7835 }
7836
7837 fn unlink(&mut self, key: Key, emit_remove: bool) {
7840 if self.nodes[key as usize].kind == Kind::Modal && self.nodes[key as usize].created {
7841 self.restoring_modal_focus = true;
7842 }
7843 let parent = self.nodes[key as usize].parent;
7844 let siblings = &mut self.nodes[parent as usize].children;
7845 let pos = siblings
7846 .iter()
7847 .position(|&c| c == key)
7848 .expect("child of parent");
7849 siblings.remove(pos);
7850 self.key_content_changed(parent);
7851 self.tree_order_changed |= self.track_tree_order;
7852 self.tab_places_stale = true;
7853 if let Some(list) = self.nodes[parent as usize].list.as_mut() {
7854 list.remove_cell(key);
7855 }
7856 if self.nodes[parent as usize]
7857 .positional
7858 .has(Positional::CHILDREN)
7859 {
7860 self.queue_positions(parent);
7861 }
7862 self.nodes[key as usize].parent = NO_KEY;
7863 if self.nodes[key as usize].states & crate::tailwind::state::FOCUS_WITHIN != 0 {
7864 self.focus_moved = true;
7866 }
7867 if self.nodes[parent as usize].child_perspective.is_some() {
7868 self.mark(key, dirty::VIEW | dirty::ANIMATION);
7870 }
7871 self.spacing_changed(parent, NO_KEY);
7872 if self.pointer_none_classes > 0 && self.pointer_region(parent).is_some() {
7873 self.pointer_pending.push(key);
7875 self.pointer_events_moved(parent);
7876 }
7877 self.groups_changed(key, parent);
7878 self.status_bars_moved |= !self.status_bar_nodes.is_empty();
7879 self.outer_moved |= !self.parent_lists.is_empty() && self.may_hold_page_list(key);
7880 self.sticky_changed |= !self.sticky_nodes.is_empty();
7881 if !self.pictured.is_empty() {
7882 self.unlinked_from.push(self.nodes[parent as usize].id);
7883 }
7884 let node = &self.nodes[key as usize];
7885 let (inline, layout, created, id) = (node.inline, node.layout, node.created, node.id);
7886 self.resize_settling |= node.row_asked;
7889 if inline {
7890 self.mark_text_block(parent);
7891 return;
7892 }
7893 let kind = self.nodes[key as usize].kind;
7894 if kind == Kind::InputAccessory {
7895 self.accessory_attached(key, false);
7896 }
7897 if kind == Kind::HeaderItem {
7898 self.mark(parent, dirty::SCREEN);
7899 }
7900 if let Some(layout) = layout {
7901 if self.nodes[parent as usize].list.is_none()
7902 && !self.nodes[key as usize].is_layout_root()
7903 {
7904 let parent_layout = self.nodes[parent as usize]
7905 .layout
7906 .expect("block parent has layout");
7907 self.layout.remove_child(parent_layout, layout);
7908 }
7909 self.needs_layout = true;
7910 if emit_remove
7911 && created
7912 && self.nodes[parent as usize].created
7913 && !self.nodes[key as usize].is_overlay()
7914 {
7915 self.mount.push(MountItem::Remove { id });
7916 self.note_restructured(parent);
7917 }
7918 }
7919 }
7920
7921 fn set_status_bar(&mut self, key: Key, setting: Option<crate::StatusBarSetting>) {
7925 let Some(root) = self.nodes[key as usize].root.as_mut() else {
7926 return;
7927 };
7928 root.status_bar = setting;
7929 let entry = root.status_bar_entry;
7930 match (setting, entry) {
7931 (Some(s), Some(e)) => self.components.status_bars.set(e, s),
7932 (Some(_), None) => {
7933 if !self.status_bar_nodes.contains(&key) {
7934 self.status_bar_nodes.push(key);
7935 }
7936 self.status_bars_moved = true;
7937 }
7938 (None, entry) => {
7939 if let Some(e) = entry {
7940 self.components.status_bars.remove(e);
7941 if let Some(root) = self.nodes[key as usize].root.as_mut() {
7942 root.status_bar_entry = None;
7943 }
7944 }
7945 self.status_bar_nodes.retain(|&k| k != key);
7946 }
7947 }
7948 }
7949
7950 fn sync_status_bars(&mut self) {
7954 if !std::mem::take(&mut self.status_bars_moved) {
7955 return;
7956 }
7957 for i in 0..self.status_bar_nodes.len() {
7958 let key = self.status_bar_nodes[i];
7959 let in_tree = self.is_ancestor(self.root, key);
7960 let Some(root) = self.nodes[key as usize].root.as_mut() else {
7961 continue;
7962 };
7963 match (in_tree, root.status_bar_entry, root.status_bar) {
7964 (true, None, Some(setting)) => {
7965 root.status_bar_entry = Some(self.components.status_bars.add(setting));
7966 }
7967 (false, Some(entry), _) => {
7968 root.status_bar_entry = None;
7969 self.components.status_bars.remove(entry);
7970 }
7971 _ => {}
7972 }
7973 }
7974 }
7975
7976 fn release(&mut self, id: NodeId) -> Result<(), ApplyError> {
7977 if let Some(run) = self.runs.remove(&id) {
7978 if run.block != NO_KEY {
7979 self.folded.remove(&run.block);
7980 self.mark_text_block(run.block);
7981 }
7982 return Ok(());
7983 }
7984 let key = self.key(id)?;
7985 if let Some(run) = self.folded.remove(&key)
7987 && let Some(run) = self.runs.get_mut(&run)
7988 {
7989 run.block = NO_KEY;
7990 }
7991 self.cancel_web_evaluations(id);
7992 self.webview_released(id);
7993 if key == self.root {
7994 return Ok(());
7995 }
7996 if !self.overlay_state.tooltips.is_empty() {
7998 self.tooltip_released(id);
7999 }
8000 if self.nodes[key as usize].bar().is_some() {
8002 self.release_scrollbar(key);
8003 }
8004 if self.nodes[key as usize].parent != NO_KEY {
8005 self.unlink(key, false);
8007 }
8008 if self.nodes[key as usize]
8011 .list
8012 .as_ref()
8013 .is_some_and(|l| l.parent)
8014 {
8015 self.forget_outer(key);
8016 self.parent_lists.retain(|&k| k != key);
8017 }
8018 let node = self.nodes.remove(key as usize);
8019 self.ch_readers -= usize::from(node.reads_ch);
8020 self.slots.remove(id as usize);
8021 if node.class_props.as_ref().and_then(|c| c.pointer_events)
8022 == Some(crate::props::PointerEvents::None)
8023 {
8024 self.pointer_none_classes -= 1;
8025 }
8026 if node.kind == Kind::List {
8027 self.lists.retain(|&k| k != key);
8028 }
8029 if node.sticky.is_some() {
8030 self.sticky_nodes.retain(|&k| k != key);
8031 self.sticky_changed = true;
8032 }
8033 if node.follow.is_some() {
8034 self.release_follower(key);
8035 }
8036 if !self.relators.is_empty() {
8037 self.release_relator(key);
8038 }
8039 if let Some(scroll) = node.scroll.as_ref() {
8040 if !scroll.dependents.is_empty() {
8041 self.outer_released(&scroll.dependents);
8042 }
8043 if scroll.asked.is_some() {
8044 self.outer_asked.retain(|&k| k != key);
8045 }
8046 self.sticky_views.retain(|&k| k != key);
8047 self.sticky_scrollers.retain(|&k| k != key);
8048 }
8049 if let Some((spacer, _)) = node.list.as_ref().and_then(|l| l.spacer) {
8050 self.layout.remove(spacer);
8051 }
8052 if node.kind == Kind::Text {
8053 self.attachment_blocks.retain(|&k| k != key);
8054 }
8055 if node.is_layout_root() {
8056 self.roots.retain(|&k| k != key);
8057 }
8058 if let Some(state) = node.root.as_ref().and_then(|r| r.overlay.as_ref()) {
8059 self.overlay_released(key, state.wrapper);
8060 }
8061 if let Some(root) = node.root.as_ref()
8062 && root.status_bar.is_some()
8063 {
8064 if let Some(entry) = root.status_bar_entry {
8065 self.components.status_bars.remove(entry);
8066 }
8067 self.status_bar_nodes.retain(|&k| k != key);
8068 }
8069 self.orientation_pages.retain(|&(k, _)| k != key);
8070 for &c in &node.children {
8073 if let Some(child) = self.nodes.get_mut(c as usize) {
8074 child.parent = NO_KEY;
8075 }
8076 }
8077 if node.states & crate::tailwind::state::FOCUS_WITHIN != 0 {
8078 self.focus_moved = true;
8081 }
8082 if let Some(layout) = node.layout {
8083 self.layout.remove(layout);
8084 }
8085 if node.created {
8086 self.mount.push(MountItem::Delete { id });
8087 }
8088 Ok(())
8089 }
8090
8091 fn set_page_orientations(&mut self, key: Key, bits: u8) {
8094 match self.orientation_pages.iter_mut().find(|(k, _)| *k == key) {
8095 Some(page) if bits != 0 => page.1 = bits,
8096 Some(_) => self.orientation_pages.retain(|&(k, _)| k != key),
8097 None if bits != 0 => self.orientation_pages.push((key, bits)),
8098 None => {}
8099 }
8100 }
8101
8102 fn sync_orientations(&mut self) {
8108 if self.orientation_pages.is_empty() && self.orientations_shown == 0 {
8109 return;
8110 }
8111 let bits = self
8112 .orientation_pages
8113 .iter()
8114 .rev()
8115 .find(|&&(key, _)| self.displayed_in_tree(key))
8116 .map_or(0, |&(_, bits)| bits);
8117 if bits != self.orientations_shown {
8118 self.orientations_shown = bits;
8119 self.commands
8120 .push((crate::ROOT_ID, Command::Orientations(bits)));
8121 }
8122 }
8123
8124 fn displayed_in_tree(&self, mut key: Key) -> bool {
8127 while key != NO_KEY {
8128 if key == self.root {
8129 return true;
8130 }
8131 let node = &self.nodes[key as usize];
8132 if node.layout.is_some_and(|l| self.layout.displays_none(l)) {
8133 return false;
8134 }
8135 key = node.parent;
8136 }
8137 false
8138 }
8139
8140 fn depth_outside(&self, ancestor: Key, mut key: Key) -> Option<u32> {
8143 let mut depth = 0;
8144 while key != NO_KEY {
8145 if key == ancestor {
8146 return None;
8147 }
8148 depth += 1;
8149 key = self.nodes[key as usize].parent;
8150 }
8151 Some(depth)
8152 }
8153
8154 fn count_heights(&mut self, key: Key) -> u32 {
8161 let mut order = vec![key];
8164 let mut next = 0;
8165 while let Some(&at) = order.get(next) {
8166 next += 1;
8167 order.extend_from_slice(&self.nodes[at as usize].children);
8168 }
8169 for &at in order.iter().rev() {
8170 let height = self.nodes[at as usize]
8171 .children
8172 .iter()
8173 .map(|&c| self.nodes[c as usize].height + 1)
8174 .max()
8175 .unwrap_or(0);
8176 self.nodes[at as usize].height = height;
8177 }
8178 self.nodes[key as usize].height
8179 }
8180
8181 fn keymap_with_focus(
8185 &mut self,
8186 keymap: Arc<crate::keymap::Keymap>,
8187 ) -> Arc<crate::keymap::Keymap> {
8188 if !keymap.takes_over_pointer_focus() {
8189 self.pointer_keymap = None;
8190 return keymap;
8191 }
8192 let pointer = self.focus.is_some() && self.focus_by_pointer;
8193 let mounted = Arc::new((*keymap).clone().with_pointer_focus(pointer));
8194 self.pointer_keymap = Some((keymap, pointer));
8195 mounted
8196 }
8197
8198 fn sync_pointer_keymap(&mut self) {
8202 let pointer = self.focus.is_some() && self.focus_by_pointer;
8203 let Some((keymap, sent)) = &self.pointer_keymap else {
8204 return;
8205 };
8206 if *sent == pointer {
8207 return;
8208 }
8209 let keymap = keymap.clone();
8210 let mounted = self.keymap_with_focus(keymap);
8211 self.mount.push(MountItem::Keymap(mounted));
8212 }
8213
8214 fn raise_heights(&mut self, key: Key) {
8218 let mut height = self.nodes[key as usize].height + 1;
8219 let mut at = self.nodes[key as usize].parent;
8220 while at != NO_KEY {
8221 let node = &mut self.nodes[at as usize];
8222 if node.height >= height {
8223 break;
8224 }
8225 node.height = height;
8226 height += 1;
8227 at = node.parent;
8228 }
8229 }
8230
8231 pub(super) fn note_focus_origin(&mut self, to: NodeId) {
8238 let mut origins = std::mem::take(&mut self.focus_origins);
8239 origins.retain(|&(id, _)| id != to && self.key(id).is_ok());
8242 if self.modality == Some(crate::platform::InputModality::Pointer) {
8243 origins.push((to, self.focus));
8244 }
8245 self.focus_origins = origins;
8246 }
8247
8248 fn press_leaves_focus(&self) -> bool {
8253 matches!(
8254 self.components.environment.os,
8255 crate::platform::Os::MacOs | crate::platform::Os::Ios
8256 )
8257 }
8258
8259 fn focus_back_to_origin(&mut self, before: Option<(Key, NodeId)>, from: Option<Key>) {
8265 let outside = |this: &Self, key: Key| from.is_none_or(|from| !this.is_ancestor(from, key));
8266 let alive = |this: &Self, (key, id): (Key, NodeId)| {
8267 this.key(id).is_ok_and(|k| k == key) && this.is_ancestor(this.root, key)
8268 };
8269 if let Some((_, id)) = before.filter(|&b| alive(self, b) && outside(self, b.0)) {
8270 self.commands.push((id, Command::Focus));
8271 } else if let Some((_, id)) = self.focus.filter(|&(key, _)| !outside(self, key)) {
8272 self.commands.push((id, Command::Blur));
8273 }
8274 }
8275
8276 fn focus_opened_modals(&mut self) {
8282 let opened = std::mem::take(&mut self.modals_opened);
8283 if !self.has_window() {
8284 return;
8285 }
8286 for (modal, id) in opened {
8287 let Some(node) = self.nodes.get(modal as usize).filter(|n| n.id == id) else {
8289 continue;
8290 };
8291 if node.kind != Kind::Modal
8292 || !node.created
8293 || node.parent == NO_KEY
8294 || !self.displayed_in_tree(modal)
8295 || self.window_ids.values().any(|(root, _)| *root == node.id)
8297 {
8298 continue;
8299 }
8300 if self
8301 .focus
8302 .is_some_and(|(key, _)| self.is_ancestor(modal, key))
8303 {
8304 continue;
8305 }
8306 let inside = |this: &Self, id: NodeId| {
8307 this.key(id).is_ok_and(|key| this.is_ancestor(modal, key))
8308 };
8309 let asked = self
8310 .commands
8311 .iter()
8312 .any(|(to, c)| matches!(c, Command::Focus) && inside(self, *to))
8313 || self.mount.iter().any(|m| {
8314 matches!(
8315 m,
8316 MountItem::Command {
8317 id: to,
8318 command: Command::Focus,
8319 } if inside(self, *to)
8320 )
8321 });
8322 if asked {
8323 continue;
8324 }
8325 if let Ok(Some(id)) = self.first_control(modal) {
8327 self.commands.push((id, Command::Focus));
8328 self.modal_focus_given = Some(id);
8329 }
8330 }
8331 }
8332
8333 fn first_control(&self, key: Key) -> Result<Option<NodeId>, ()> {
8338 let mut found = None;
8339 let mut stack: Vec<Key> = self.nodes[key as usize]
8340 .children
8341 .iter()
8342 .rev()
8343 .copied()
8344 .collect();
8345 while let Some(k) = stack.pop() {
8346 let node = &self.nodes[k as usize];
8347 if matches!(node.kind, Kind::Overlay | Kind::Modal)
8348 || node.layout.is_some_and(|l| self.layout.displays_none(l))
8349 {
8350 continue;
8351 }
8352 let disabled = node.states & crate::tailwind::state::DISABLED != 0;
8353 let focusable = node.props.as_ref().and_then(|p| p.focusable);
8354 if let Some(input) = node.input.as_ref() {
8355 if input.config.auto_focus {
8356 return Err(());
8357 }
8358 if found.is_none() && !disabled && focusable != Some(false) {
8359 found = Some(node.id);
8360 }
8361 } else if found.is_none()
8362 && !disabled
8363 && (focusable == Some(true)
8364 || (focusable.is_none() && node.mounted_events().contains(EventKind::Press)))
8365 {
8366 found = Some(node.id);
8367 }
8368 stack.extend(node.children.iter().rev().copied());
8369 }
8370 Ok(found)
8371 }
8372
8373 fn is_ancestor(&self, ancestor: Key, mut key: Key) -> bool {
8374 while key != NO_KEY {
8375 if key == ancestor {
8376 return true;
8377 }
8378 key = self.nodes[key as usize].parent;
8379 }
8380 false
8381 }
8382
8383 fn native_before(&self, parent: Key, child: Key) -> Option<NodeId> {
8386 let pos = self.nodes[parent as usize]
8387 .children
8388 .iter()
8389 .inspect(|_| self.placing(1))
8390 .position(|&c| c == child)?;
8391 self.native_before_at(parent, child, pos)
8392 }
8393
8394 fn native_before_at(&self, parent: Key, child: Key, pos: usize) -> Option<NodeId> {
8402 let children = &self.nodes[parent as usize].children;
8403 let z = self.nodes[child as usize].stack_rank();
8404 let in_parent = !self.nodes[child as usize].kind.is_root();
8405 let anchors = |n: &Node| {
8406 n.created && n.layout.is_some() && !n.is_overlay() && !(in_parent && n.kind.is_root())
8407 };
8408 if !self.nodes[parent as usize].ranked_children && z == (0, false) {
8409 let next = children[pos + 1..].iter().find_map(|&c| {
8410 self.placing(1);
8411 let n = &self.nodes[c as usize];
8412 anchors(n).then_some(n.id)
8413 });
8414 return match next {
8415 Some(id) => Some(id),
8416 None if !self.overlays.is_empty() => self.first_overlay_in(parent),
8417 None => None,
8418 };
8419 }
8420 self.placing(children.len());
8421 let mut best: Option<((i32, bool), usize, NodeId)> = None;
8422 for (i, &c) in children.iter().enumerate() {
8423 let n = &self.nodes[c as usize];
8424 if c == child || !anchors(n) {
8425 continue;
8426 }
8427 let rank = n.stack_rank();
8428 if (rank, i) > (z, pos) && best.is_none_or(|b| (rank, i) < (b.0, b.1)) {
8429 best = Some((rank, i, n.id));
8430 }
8431 }
8432 match best {
8434 Some(b) => Some(b.2),
8435 None if !self.overlays.is_empty() => self.first_overlay_in(parent),
8436 None => None,
8437 }
8438 }
8439
8440 fn rank_noted(&mut self, key: Key) {
8443 let node = &self.nodes[key as usize];
8444 let parent = node.parent;
8445 if parent != NO_KEY && node.stack_rank() != (0, false) {
8446 self.nodes[parent as usize].ranked_children = true;
8447 }
8448 }
8449
8450 fn restack(&mut self, key: Key) {
8452 self.rank_noted(key);
8453 let node = &self.nodes[key as usize];
8454 let (parent, id) = (node.parent, node.id);
8455 if parent == NO_KEY
8456 || !node.created
8457 || node.layout.is_none()
8458 || node.inline
8459 || node.is_overlay()
8460 {
8461 return;
8462 }
8463 let p = &self.nodes[parent as usize];
8464 if !p.created || p.list.is_some() {
8465 return;
8466 }
8467 let before = self.native_before(parent, key);
8468 self.mount.push(MountItem::Insert {
8469 parent: p.id,
8470 child: id,
8471 before,
8472 });
8473 }
8474
8475 fn font_settings_changed(&mut self, key: Key) {
8477 match self.nodes[key as usize].kind {
8478 Kind::Text => self.mark_text_block(key),
8479 Kind::Input => {
8480 self.measure_input(key);
8481 self.mark(key, dirty::INPUT);
8482 }
8483 _ => {}
8484 }
8485 }
8486
8487 fn layout_index_at(&self, parent: Key, pos: usize) -> u32 {
8495 let node = &self.nodes[parent as usize];
8496 let layout = node.layout.expect("block parent has layout");
8497 let next = node.children[pos + 1..]
8498 .iter()
8499 .inspect(|_| self.placing(1))
8500 .find_map(|&c| {
8501 let c = &self.nodes[c as usize];
8502 c.layout.filter(|_| !c.is_layout_root())
8503 });
8504 let index = match next {
8505 Some(next) => match position_near(self.layout.children(layout), &next, pos) {
8508 Some((index, looked)) => {
8509 self.placing(looked);
8510 index
8511 }
8512 None => {
8513 debug_assert!(false, "a sibling's layout node is its parent's child");
8514 self.render_index(parent, pos) as usize
8515 }
8516 },
8517 None => self.layout.children_len(layout),
8518 };
8519 debug_assert!(
8520 pos + 1 != node.children.len() || index as u32 == self.rendering_before(parent, pos),
8521 "the layout node's children are its rendering children"
8522 );
8523 index as u32
8524 }
8525
8526 fn render_index(&self, parent: Key, pos: usize) -> u32 {
8530 self.placing(pos);
8531 self.rendering_before(parent, pos)
8532 }
8533
8534 fn rendering_before(&self, parent: Key, pos: usize) -> u32 {
8536 self.nodes[parent as usize].children[..pos]
8537 .iter()
8538 .map(|&c| &self.nodes[c as usize])
8539 .filter(|c| c.layout.is_some() && !c.is_layout_root())
8540 .count() as u32
8541 }
8542
8543 fn set_inline(&mut self, key: Key, inline: bool) {
8545 let node = &mut self.nodes[key as usize];
8546 if node.inline == inline {
8547 return;
8548 }
8549 node.inline = inline;
8550 if node.kind != Kind::Text {
8551 return;
8553 }
8554 if inline {
8555 if let Some(l) = node.layout.take() {
8558 if node.base_layout.is_none() {
8559 node.base_layout = Some(Box::new(self.layout.style(l).clone()));
8560 }
8561 self.layout.remove(l);
8562 }
8563 if node.created {
8564 node.created = false;
8565 self.mount.push(MountItem::Delete { id: node.id });
8566 }
8567 } else {
8568 let style = if node.fixed_view {
8571 node.base_layout.as_deref().cloned()
8572 } else {
8573 node.base_layout.take().map(|b| *b)
8574 }
8575 .unwrap_or_default();
8576 let cx = LeafContext::Text(Box::new(TextContext::new(Arc::default())));
8577 let layout = self.layout.new_leaf_with_context(style, cx);
8578 self.layout.set_tag(layout, key);
8579 node.layout = Some(layout);
8580 self.mark(key, dirty::TEXT_BUILD);
8581 }
8582 }
8583
8584 fn ensure_created(&mut self, key: Key) {
8587 let has_attachments = self.attachment_blocks.contains(&key);
8588 let node = &mut self.nodes[key as usize];
8589 if node.created || node.layout.is_none() {
8590 return;
8591 }
8592 node.created = true;
8593 self.pace.made += 1;
8594 let culled_frame = std::mem::take(&mut node.culled)
8596 .then_some(node.frame)
8597 .filter(|f| !f.origin.x.0.is_nan());
8598 self.tree_order_changed |= self.track_tree_order;
8599 self.tab_places_stale = true;
8600 if node.kind == Kind::Modal {
8601 self.modals_opened.push((key, node.id));
8602 }
8603 if node.kind == Kind::Text {
8604 self.measure_for_real(key);
8605 }
8606 if culled_frame.is_some()
8611 && self.nodes[key as usize].follow.is_some()
8612 && let Some(layout) = self.nodes[key as usize].layout
8613 {
8614 self.layout.mark_dirty(layout);
8615 self.needs_layout = true;
8616 }
8617 let node = &mut self.nodes[key as usize];
8618 if let Some(scroll) = node.scroll.as_mut() {
8619 scroll.content = None;
8620 if !scroll.view_sticky.is_empty() {
8623 self.sticky_views.push(key);
8624 }
8625 scroll.issued = 0;
8627 scroll.target = None;
8628 scroll.pending.clear();
8629 }
8630 let parent_list = node.list.as_ref().is_some_and(|l| l.parent);
8633 let id = node.id;
8634 let kind = node.kind;
8635 let mut flags = self.mount_state(key);
8636 let node = &mut self.nodes[key as usize];
8637 if kind == Kind::Text && has_attachments {
8638 node.attached.clear();
8640 flags |= dirty::TEXT_BUILD;
8641 }
8642 self.mount.push(MountItem::Create {
8643 id,
8644 kind: if parent_list {
8645 ViewKind::View
8646 } else {
8647 kind.view_kind()
8648 },
8649 });
8650 if let Some(component) = self.nodes[key as usize].component.as_mut() {
8651 if let Some(name) = &component.name {
8654 self.mount.push(MountItem::Component {
8655 id,
8656 name: name.clone(),
8657 });
8658 }
8659 if let Some(source) = &component.source {
8662 self.mount.push(MountItem::GpuView {
8663 id,
8664 source: Some(source.clone()),
8665 });
8666 }
8667 }
8668 if let Some(item) = self.creation_tracking(key) {
8669 self.mount.push(item);
8670 }
8671 if let Some(frame) = culled_frame {
8672 self.nodes[key as usize].frame = frame;
8673 self.mount.push(MountItem::Frame { id, frame });
8674 let content = self.nodes[key as usize]
8677 .scroll
8678 .as_mut()
8679 .and_then(|s| s.culled_content.take());
8680 if let Some(size) = content {
8681 self.set_scroll_content(key, size);
8682 }
8683 if kind == Kind::Canvas
8684 && self.nodes[key as usize]
8685 .drawing
8686 .as_ref()
8687 .is_some_and(|d| d.fit().is_some())
8688 {
8689 self.fitted_pending.push(key);
8690 }
8691 if matches!(kind, Kind::Input | Kind::Scroll) {
8695 self.emit_frames(key);
8696 }
8697 }
8698 let projected = self.nodes[key as usize].projected;
8699 if self.mount_projected && projected != 0 {
8700 self.mount.push(MountItem::ProjectStates {
8701 id,
8702 states: projected,
8703 });
8704 }
8705 self.mark(key, flags);
8706 if !kind.is_container() {
8707 return;
8708 }
8709 let mut children = std::mem::take(&mut self.nodes[key as usize].children);
8711 let original = children.clone();
8712 if children
8713 .iter()
8714 .any(|&c| self.nodes[c as usize].stack_rank() != (0, false))
8715 {
8716 children.sort_by_key(|&c| self.nodes[c as usize].stack_rank());
8717 }
8718 let scope = self.cull_scope(key);
8720 for &child in &children {
8721 let c = &self.nodes[child as usize];
8722 if c.layout.is_some() && !c.is_overlay() && !self.hold_back(scope, child) {
8723 self.ensure_created(child);
8724 let child_id = self.nodes[child as usize].id;
8725 self.mount.push(MountItem::Insert {
8726 parent: id,
8727 child: child_id,
8728 before: None,
8729 });
8730 }
8731 }
8732 self.nodes[key as usize].children = original;
8733 }
8734
8735 fn mount_state(&mut self, key: Key) -> u32 {
8738 let node = &mut self.nodes[key as usize];
8739 let kind = node.kind;
8740 node.frame = Bounds::UNSET;
8741 node.emitted = None;
8742 if let Some(layout) = node.layout {
8743 self.layout.mark_stale(layout);
8744 }
8745 let node = &mut self.nodes[key as usize];
8746 let parent_list = node.list.as_ref().is_some_and(|l| l.parent);
8749 let mut flags = 0;
8750 if !node.view_style.is_default()
8751 || node.elevation != Points::ZERO
8752 || node.backdrop_material != crate::BackdropMaterial::default()
8753 || node.macos_backdrop.is_some()
8754 || node.windows_backdrop.is_some()
8755 || parent_list
8756 || node.spare
8757 || node.hidden_in_text
8758 {
8759 flags |= dirty::VIEW;
8760 }
8761 if !node.events.is_empty() {
8762 flags |= dirty::EVENTS;
8763 }
8764 if kind == Kind::Text {
8765 flags |= dirty::TEXT_MOUNT;
8766 }
8767 if node.image.as_ref().is_some_and(|i| i.source.is_some()) {
8768 flags |= dirty::IMAGE;
8769 }
8770 if let Some(scroll) = &node.scroll
8771 && !parent_list
8772 {
8773 flags |= dirty::SCROLL;
8774 if scroll.behavior != ScrollBehavior::default() {
8775 flags |= dirty::SCROLL_BEHAVIOR;
8776 }
8777 if scroll.refreshing {
8778 flags |= dirty::REFRESHING;
8779 }
8780 }
8781 if !node.animated.is_empty()
8782 || node.drawing.as_ref().is_some_and(|d| !d.slots.is_empty())
8783 || node.component.as_ref().is_some_and(|c| !c.slots.is_empty())
8784 || node
8785 .shader
8786 .as_ref()
8787 .and_then(|s| s.layer.as_ref())
8788 .is_some_and(|l| !l.nodes.is_empty())
8789 {
8790 flags |= dirty::ANIMATION;
8791 }
8792 if node.drawing.is_some() {
8793 flags |= dirty::CANVAS;
8794 }
8795 if node.shader.as_ref().is_some_and(|s| s.layer.is_some()) {
8796 flags |= dirty::SHADER;
8797 }
8798 if !node.gestures.is_empty() {
8799 flags |= dirty::PAN;
8800 }
8801 if node.props.is_some()
8804 || node.class_pointer != crate::props::PointerEvents::Auto
8805 || node.spare
8806 || node.hidden_in_text
8807 || node.list.as_ref().is_some_and(|l| l.parent)
8808 {
8809 flags |= dirty::VIEW_PROPS;
8810 }
8811 match kind {
8812 Kind::Screen => flags |= dirty::SCREEN,
8813 Kind::Modal => flags |= dirty::MODAL,
8814 _ => {}
8815 }
8816 if node.control.is_some() {
8817 flags |= dirty::NATIVE;
8818 }
8819 if let Some(list) = node.list.as_mut() {
8820 list.dirty = true;
8821 }
8822 if let Some(input) = node.input.as_mut() {
8823 input.content = None;
8824 flags |= dirty::INPUT;
8825 if !input.value.is_empty() {
8826 flags |= dirty::INPUT_VALUE;
8827 }
8828 }
8829 if let Some(component) = node.component.as_mut() {
8830 component.changed = component.props.iter().map(|(k, _)| k.clone()).collect();
8832 component.slots_changed.set(!component.slots.is_empty());
8833 flags |= dirty::COMPONENT;
8834 }
8835 flags
8836 }
8837
8838 #[inline]
8839 fn set_gpu_source(&mut self, key: Key, id: NodeId, source: Option<crate::gpu::GpuSource>) {
8843 let node = &mut self.nodes[key as usize];
8844 let created = node.created;
8845 let Some(component) = node.component.as_mut() else {
8846 return;
8847 };
8848 if component.source == source {
8849 return;
8850 }
8851 component.source = source.clone();
8852 if !created {
8853 return;
8854 }
8855 self.mount.push(MountItem::GpuView { id, source });
8856 component.changed = component.props.iter().map(|(k, _)| k.clone()).collect();
8857 let mut flags = dirty::COMPONENT;
8858 if !component.slots.is_empty() {
8859 component.slots_changed.set(true);
8860 flags |= dirty::ANIMATION;
8861 }
8862 self.mark(key, flags);
8863 }
8864
8865 fn mark(&mut self, key: Key, flags: u32) {
8866 let node = &mut self.nodes[key as usize];
8867 node.dirty |= flags;
8868 if flags & (dirty::VIEW | dirty::ANIMATION) != 0
8872 && (node.culled
8873 || !self.culling.is_empty()
8874 && (!node.animated.is_empty() || !node.view_style.transform.ops().is_empty()))
8875 {
8876 self.cull_dirty = true;
8877 }
8878 if !node.queued {
8879 node.queued = true;
8880 self.queue.push(key);
8881 }
8882 }
8883
8884 fn mark_text_block(&mut self, mut key: Key) {
8886 loop {
8887 let node = &self.nodes[key as usize];
8888 if !node.inline {
8889 if node.kind == Kind::Text {
8890 self.mark(key, dirty::TEXT_BUILD);
8891 }
8892 return;
8893 }
8894 if node.parent == NO_KEY {
8895 return;
8897 }
8898 key = node.parent;
8899 }
8900 }
8901
8902 fn flush_dirty(&mut self) {
8903 loop {
8904 self.flush_positions();
8906 self.flush_dirty_once();
8907 self.check_attachments();
8911 if self.queue.is_empty() {
8912 break;
8913 }
8914 }
8915 }
8916
8917 fn flush_dirty_once(&mut self) {
8918 let mut queue = std::mem::take(&mut self.queue);
8919 for &key in &queue {
8920 let Some(node) = self.nodes.get_mut(key as usize) else {
8921 continue;
8922 };
8923 let mut flags = std::mem::take(&mut node.dirty);
8924 node.queued = false;
8925 if flags & dirty::TEXT_BUILD != 0 && node.layout.is_some() {
8926 if self.rebuild_text(key) {
8927 flags |= dirty::TEXT_MOUNT;
8928 }
8929 self.sync_grid_role(key);
8931 }
8932 let node = &self.nodes[key as usize];
8933 if !node.created {
8934 continue;
8935 }
8936 let id = node.id;
8937 if flags & dirty::VIEW != 0 {
8938 let style = self.mounted_view_style(key);
8939 self.mount.push(MountItem::ViewStyle { id, style });
8940 }
8941 if flags & dirty::EVENTS != 0 {
8942 self.mount.push(MountItem::Events {
8943 id,
8944 events: node.mounted_events(),
8945 });
8946 }
8947 if flags & dirty::IMAGE != 0
8948 && let Some(image) = &node.image
8949 {
8950 let resize_mode = node.object_fit.unwrap_or_default();
8953 let ratio = self.components.environment.pixel_ratio;
8955 self.mount.push(MountItem::Image {
8956 id,
8957 source: image.source.as_ref().map(|s| s.resolved(ratio)),
8958 resize_mode,
8959 options: crate::mount::ImageOptions {
8960 placeholder: image
8961 .options
8962 .placeholder
8963 .as_ref()
8964 .map(|s| s.resolved(ratio)),
8965 blur_radius: image.options.blur_radius,
8966 fade_ms: image.options.fade_ms,
8967 position: node.view_style.object_position,
8968 current_color: image.svg_current_color.then(|| self.resolved_paint(key).1),
8969 },
8970 });
8971 }
8972 if let Some(scroll) = &node.scroll
8973 && node.list.as_ref().is_none_or(|l| !l.parent)
8974 {
8975 if flags & dirty::SCROLL != 0 {
8976 self.mount.push(MountItem::ScrollConfig {
8977 id,
8978 horizontal: scroll.horizontal,
8979 scrollbar_visible: scroll.scrollbar != crate::ScrollbarSetting::Hidden
8981 && scroll.bar.is_none(),
8982 replaced: scroll.bar.is_some(),
8983 scroll_value: scroll.scroll_value,
8984 pull_value: scroll.pull_value,
8985 keyboard_dismiss: scroll.keyboard_dismiss,
8986 mirrored: node.kind == Kind::List && scroll.horizontal && node.rtl,
8987 });
8988 }
8989 if flags & dirty::SCROLL_BEHAVIOR != 0 {
8990 self.mount.push(MountItem::ScrollBehavior {
8991 id,
8992 behavior: Box::new(scroll.behavior.clone()),
8993 });
8994 }
8995 if flags & dirty::REFRESHING != 0 {
8996 self.mount.push(MountItem::Refreshing {
8997 id,
8998 refreshing: scroll.refreshing,
8999 });
9000 }
9001 }
9002 if flags & dirty::ANIMATION != 0 {
9003 let mut bindings = node.animated.clone();
9004 if bindings
9007 .iter()
9008 .any(|(p, _)| matches!(p, AnimationProp::StickyTop | AnimationProp::StickyLeft))
9009 {
9010 if node.sticky.is_none() && !self.inset_warned {
9011 self.inset_warned = true;
9012 log::warn!(
9013 target: "js",
9014 "an animated `top` / `left` only moves a `position: sticky` view's sticking point; it is ignored on view {id}"
9015 );
9016 }
9017 bindings.retain(|(p, _)| {
9018 !matches!(p, AnimationProp::StickyTop | AnimationProp::StickyLeft)
9019 });
9020 }
9021 let steps = self.perspective_steps(key);
9023 if steps > 0 {
9024 for (prop, _) in &mut bindings {
9025 if let AnimationProp::Transform(i) = prop {
9026 *i += steps;
9027 }
9028 }
9029 }
9030 if let Some(d) = &node.drawing {
9031 bindings.extend(
9032 d.slots
9033 .iter()
9034 .enumerate()
9035 .map(|(i, &n)| (AnimationProp::CanvasArg(i as u16), n)),
9036 );
9037 }
9038 if let Some(layer) = node.shader.as_ref().and_then(|s| s.layer.as_ref()) {
9039 bindings.extend(
9040 layer
9041 .nodes
9042 .iter()
9043 .enumerate()
9044 .map(|(i, &n)| (AnimationProp::CanvasArg(i as u16), n)),
9045 );
9046 }
9047 if let Some(component) = &node.component {
9048 bindings.extend(
9049 component
9050 .bound
9051 .iter()
9052 .map(|&(s, n)| (AnimationProp::ComponentSlot(s), n)),
9053 );
9054 }
9055 if let Some(component) = &node.component
9056 && component.slots_changed.replace(false)
9057 {
9058 self.mount.push(MountItem::ComponentPropSlots {
9059 id,
9060 names: component.slots.clone(),
9061 });
9062 }
9063 self.mount
9064 .push(MountItem::AnimationBindings { id, bindings });
9065 }
9066 if flags & dirty::CANVAS != 0
9067 && let Some(drawing) = &node.drawing
9068 {
9069 if drawing.fit().is_some() {
9070 self.fitted_pending.push(key);
9072 } else {
9073 let drawing = self.mounted_drawing(key, drawing);
9074 self.mount.push(MountItem::Canvas { id, drawing });
9075 }
9076 }
9077 if flags & dirty::SHADER != 0
9078 && let Some(shader) = &node.shader
9079 {
9080 self.mount.push(MountItem::Shader {
9081 id,
9082 layer: shader.layer.clone(),
9083 });
9084 }
9085 if flags & dirty::PAN != 0 {
9086 let mut values = node.gestures;
9087 if !node.pan_enabled {
9088 values.pan_x = None;
9089 values.pan_y = None;
9090 }
9091 self.mount.push(MountItem::Gestures { id, values });
9092 }
9093 if flags & dirty::VIEW_PROPS != 0 {
9094 self.mount.push(MountItem::ViewProps {
9095 id,
9096 props: node.mounted_props(),
9097 });
9098 } else if flags & dirty::LABEL != 0 {
9099 let label = node
9100 .props
9101 .as_ref()
9102 .and_then(|p| p.accessibility.label.clone());
9103 self.mount.push(MountItem::AccessibilityLabel { id, label });
9104 }
9105 if flags & dirty::SCREEN != 0
9106 && let Some(config) = self.screen_config(key)
9107 {
9108 self.mount.push(MountItem::ScreenConfig {
9109 id,
9110 config: Box::new(config),
9111 });
9112 }
9113 if flags & dirty::COMPONENT != 0
9114 && self.nodes[key as usize].kind == Kind::Native
9115 && let Some(component) = self.nodes[key as usize].component.as_ref()
9116 && component.name.is_none()
9117 {
9118 log::warn!(target: "js", "a <native> element without `component`");
9119 }
9120 if flags & dirty::COMPONENT != 0
9121 && let Some(component) = self.nodes[key as usize].component.as_mut()
9122 && !component.changed.is_empty()
9123 {
9124 let changed = std::mem::take(&mut component.changed);
9125 let props: Vec<_> = changed
9126 .into_iter()
9127 .filter(|name| !component.is_bound(name))
9129 .map(|name| {
9130 let value = component
9131 .props
9132 .iter()
9133 .find(|(k, _)| *k == name)
9134 .map(|(_, v)| v.clone());
9135 (name, value)
9136 })
9137 .collect();
9138 if !props.is_empty() {
9139 self.mount.push(MountItem::ComponentProps { id, props });
9140 }
9141 }
9142 if flags & dirty::NATIVE != 0 && !self.web_unchecked.is_empty() {
9143 self.settle_web_urls(key);
9144 }
9145 let node = &self.nodes[key as usize];
9146 if flags & dirty::NATIVE != 0
9147 && let Some(control) = &node.control
9148 {
9149 self.mount.push(MountItem::NativeProps {
9150 id,
9151 props: (**control).clone(),
9152 });
9153 }
9154 if flags & dirty::MODAL != 0
9155 && let Some(root) = &node.root
9156 {
9157 let mut config = root.modal.clone();
9158 config.window = self.window_of(key);
9159 let item = MountItem::ModalConfig { id, config };
9164 match self
9165 .mount
9166 .iter()
9167 .position(|m| matches!(m, MountItem::Insert { child, .. } if *child == id))
9168 {
9169 Some(at) => self.mount.insert(at, item),
9170 None => self.mount.push(item),
9171 }
9172 }
9173 if flags & dirty::NAV_SHADER != 0
9174 && let Some(root) = &node.root
9175 {
9176 let shader = root.nav_shader.clone();
9177 self.mount.push(MountItem::NavShader { id, shader });
9178 }
9179 if let Some(input) = &node.input {
9180 if flags & dirty::INPUT != 0 {
9181 let mut config = input.config.clone();
9182 config.accessory = config
9183 .accessory_id
9184 .as_deref()
9185 .and_then(|name| self.accessories.get(name).copied());
9186 config.placeholder_color = config
9190 .placeholder_color
9191 .or(node.text_style.placeholder_color);
9192 config.selection_color =
9193 config.selection_color.or(node.text_style.selection_color);
9194 let class = node.class_props.as_deref();
9195 if let Some(c) = class {
9196 config.placeholder_color = config.placeholder_color.or(c.placeholder_color);
9197 }
9198 config.selection_color =
9199 config.selection_color.or(self.inherited_text_props(key).2);
9200 config.caret_color = config
9201 .caret_color
9202 .or(node.text_style.caret_color)
9203 .or(class.and_then(|c| c.caret_color));
9204 config.style = scaled(
9205 self.inherited_text_style(key).inherit(&node.text_style),
9206 node.paragraph.font_multiplier(self.font_scale),
9207 );
9208 config.align = directed_align(
9209 node.text_style.text_align.unwrap_or_default(),
9210 node.rtl && !node.text_style.text_align_physical,
9211 );
9212 config.rtl = node.text_style.writing_direction.unwrap_or(node.rtl);
9213 config.scrollbar_visible =
9215 input.scrollbar != crate::ScrollbarSetting::Hidden && input.bar.is_none();
9216 config.report_scroll = input.bar.is_some() || input.watched;
9217 self.mount.push(MountItem::Input {
9218 id,
9219 config: Box::new(config),
9220 });
9221 }
9222 if flags & dirty::INPUT_VALUE != 0 {
9223 self.mount.push(MountItem::InputValue {
9224 id,
9225 text: input.value.clone(),
9226 count: input.count,
9227 });
9228 }
9229 }
9230 if flags & dirty::TEXT_MOUNT != 0 {
9231 self.queue_text(key);
9232 }
9233 }
9234 queue.clear();
9235 if self.queue.is_empty() {
9237 self.queue = queue;
9238 }
9239 }
9240
9241 fn report_content_size(&mut self, key: Key, width: f32) {
9246 let node = &self.nodes[key as usize];
9247 let (Some(input), Some(layout)) = (node.input.as_ref(), node.layout) else {
9248 return;
9249 };
9250 let max = input.config.multiline.then_some(width);
9251 let (placeholder, empty_line) = (input.placeholder_measured, input.empty_line);
9252 let Some(LeafContext::Text(cx)) = self.layout.get_node_context_mut(layout) else {
9253 return;
9254 };
9255 let size = if !placeholder {
9256 measure_text(&self.text_engine, &mut self.measure_cache, cx, max)
9257 } else if let Some((hash, size)) = empty_line
9258 && hash == cx.layout_hash
9259 {
9260 size
9261 } else {
9262 let hash = cx.layout_hash;
9264 let mut empty = TextContext::new(Arc::new(self.input_text(key, "")));
9265 let size = measure_text(&self.text_engine, &mut self.measure_cache, &mut empty, max);
9266 let input = self.nodes[key as usize]
9267 .input
9268 .as_mut()
9269 .expect("input state");
9270 input.empty_line = Some((hash, size));
9271 size
9272 };
9273 let node = &mut self.nodes[key as usize];
9274 let input = node.input.as_mut().expect("input state");
9275 if input.content_size == Some(size) {
9276 return;
9277 }
9278 input.content_size = Some(size);
9279 let id = node.id;
9280 self.events.push(crate::element::JsEvent::Event(
9281 id,
9282 EventKind::ContentSizeChange,
9283 EventPayload::Map(vec![
9284 ("width", PayloadValue::Number(size.width.0 as f64)),
9285 ("height", PayloadValue::Number(size.height.0 as f64)),
9286 ]),
9287 ));
9288 }
9289
9290 fn text_cx(&mut self, layout: LayoutId) -> &mut TextContext<M::Prepared> {
9291 match self.layout.get_node_context_mut(layout) {
9292 Some(LeafContext::Text(cx)) => cx,
9293 _ => unreachable!("text block without text context"),
9294 }
9295 }
9296
9297 fn base_text_style(&self) -> ResolvedTextStyle {
9303 ResolvedTextStyle {
9304 font_family: self.default_font,
9305 ..ResolvedTextStyle::default()
9306 }
9307 }
9308
9309 fn sync_accent(&mut self, key: Key) {
9313 let node = &mut self.nodes[key as usize];
9314 let accent = node.view_style.accent_color;
9315 let Some(component) = node.component.as_mut() else {
9316 return;
9317 };
9318 let value = accent.map(|Color(c)| crate::JsonValue::from(format!("#{c:08X}")));
9319 let at = component
9320 .props
9321 .iter()
9322 .position(|(k, _)| &**k == ACCENT_PROP);
9323 if at.map(|i| &component.props[i].1) == value.as_ref() {
9324 return;
9325 }
9326 let name: Arc<str> = Arc::from(ACCENT_PROP);
9327 match (at, value) {
9328 (Some(i), Some(v)) => component.props[i].1 = v,
9329 (None, Some(v)) => component.props.push((name.clone(), v)),
9330 (Some(i), None) => {
9331 component.props.swap_remove(i);
9332 }
9333 (None, None) => return,
9334 }
9335 if !component.changed.contains(&name) {
9336 component.changed.push(name);
9337 }
9338 self.mark(key, dirty::COMPONENT);
9339 }
9340
9341 fn inherited_text_style(&self, key: Key) -> ResolvedTextStyle {
9347 let mut chain: Vec<Key> = Vec::new();
9348 let mut k = self.nodes[key as usize].parent;
9349 while k != NO_KEY {
9350 let node = &self.nodes[k as usize];
9351 let passes = if node.kind == Kind::Text {
9352 node.text_style.color.is_some()
9353 } else {
9354 node.text_style != TextStyle::default()
9355 };
9356 if passes {
9357 chain.push(k);
9358 }
9359 k = node.parent;
9360 }
9361 chain
9362 .iter()
9363 .rev()
9364 .fold(self.base_text_style(), |style, &k| {
9365 let node = &self.nodes[k as usize];
9366 if node.kind == Kind::Text {
9367 ResolvedTextStyle {
9368 color: node.text_style.color.unwrap_or(style.color),
9369 ..style
9370 }
9371 } else {
9372 style.inherit(&node.text_style)
9373 }
9374 })
9375 }
9376
9377 fn inherited_text_props(&self, key: Key) -> (Option<bool>, Option<bool>, Option<Color>) {
9385 let (no_wrap, selectable, highlight, _) = self.inherited_text_wrap(key);
9386 (no_wrap, selectable, highlight)
9387 }
9388
9389 fn inherited_text_wrap(&self, key: Key) -> (Option<bool>, Option<bool>, Option<Color>, bool) {
9393 let (mut no_wrap, mut selectable, mut highlight) = (None, None, None);
9394 let mut pretty = None;
9395 let mut k = key;
9396 while k != NO_KEY && (no_wrap.is_none() || selectable.is_none() || highlight.is_none()) {
9397 let node = &self.nodes[k as usize];
9398 if !matches!(node.kind, Kind::Text | Kind::Input) {
9399 highlight = highlight.or(node.paragraph.selection_color);
9400 }
9401 if let Some(c) = node.class_props.as_deref() {
9402 if no_wrap.is_none() && c.no_wrap.is_some() {
9403 pretty = Some(c.pretty);
9404 }
9405 no_wrap = no_wrap.or(c.no_wrap);
9406 selectable = selectable.or(c.selectable);
9407 highlight = highlight.or(c.selection_color);
9408 }
9409 k = node.parent;
9410 }
9411 (no_wrap, selectable, highlight, pretty.unwrap_or(false))
9412 }
9413
9414 fn inherited_text_align(&self, key: Key) -> Option<(TextAlign, bool)> {
9416 let mut k = self.nodes[key as usize].parent;
9417 while k != NO_KEY {
9418 let node = &self.nodes[k as usize];
9419 if let Some(a) = node.text_style.text_align {
9420 return Some((a, node.text_style.text_align_physical));
9421 }
9422 k = node.parent;
9423 }
9424 None
9425 }
9426
9427 fn inherited_text_indent(&self, key: Key) -> Option<Points> {
9431 let mut k = key;
9432 while k != NO_KEY {
9433 let style = &self.nodes[k as usize].text_style;
9434 if let Some(em) = style.text_indent_em {
9436 return Some(Points(self.font_size_at(k) * em));
9437 }
9438 if let Some(points) = style.text_indent {
9439 return Some(points);
9440 }
9441 k = self.nodes[k as usize].parent;
9442 }
9443 None
9444 }
9445
9446 fn font_size_at(&self, key: Key) -> f32 {
9449 let mut em = 1.0f32;
9450 let mut k = key;
9451 loop {
9452 let style = &self.nodes[k as usize].text_style;
9453 if let Some(scale) = style.font_size_em {
9454 em *= scale;
9455 } else if let Some(size) = style.font_size {
9456 return size.0 * em;
9457 }
9458 let parent = self.nodes[k as usize].parent;
9459 if parent == NO_KEY {
9460 return self.base_text_style().font_size.0 * em;
9461 }
9462 k = parent;
9463 }
9464 }
9465
9466 fn mark_inheriting_text(&mut self, key: Key) {
9468 self.ch_changed(key);
9469 let mut stack: Vec<Key> = self.nodes[key as usize].children.clone();
9470 while let Some(k) = stack.pop() {
9471 match self.nodes[k as usize].kind {
9472 Kind::Text => {
9474 if !self.nodes[k as usize].inline {
9475 self.mark_text_block(k);
9476 }
9477 stack.extend_from_slice(&self.nodes[k as usize].children);
9478 }
9479 Kind::Input => {
9480 self.measure_input(k);
9481 self.mark(k, dirty::INPUT);
9482 }
9483 Kind::RawText => {}
9484 _ => stack.extend_from_slice(&self.nodes[k as usize].children),
9485 }
9486 }
9487 }
9488
9489 fn rebuild_text(&mut self, key: Key) -> bool {
9494 let deferred = !self.nodes[key as usize].created && self.cull_scope(key).is_some();
9497 let node = &self.nodes[key as usize];
9498 let class = node.class_props.as_deref();
9500 let max_lines = class.and_then(|c| c.number_of_lines).unwrap_or(0);
9501 let ellipsize = class.and_then(|c| c.ellipsize).unwrap_or_default();
9502 let inherited = self.inherited_text_style(key);
9503 let (no_wrap, selectable, highlight, pretty) = self.inherited_text_wrap(key);
9504 let (align, physical) = node
9505 .text_style
9506 .text_align
9507 .map(|align| (align, node.text_style.text_align_physical))
9508 .or_else(|| self.inherited_text_align(key))
9509 .unwrap_or_default();
9510 let base = inherited.inherit(&node.text_style);
9511 let mut text = AttributedText {
9512 paragraph_strut: Some(base),
9513 align: directed_align(align, node.rtl && !physical),
9514 writing_direction: node.text_style.writing_direction,
9515 rtl: node.rtl,
9516 max_lines,
9517 ellipsize,
9518 no_wrap: max_lines == 0 && no_wrap.unwrap_or(false),
9521 shadow: node.text_style.shadow(),
9522 selectable,
9523 selection_color: node
9524 .paragraph
9525 .selection_color
9526 .or(node.text_style.selection_color)
9527 .or(highlight),
9528 ..AttributedText::default()
9529 };
9530 let multiplier = node.paragraph.font_multiplier(self.font_scale);
9531 let options = crate::TextOptions::default().indent(
9532 self.inherited_text_indent(key)
9533 .map(|indent| indent * multiplier),
9534 );
9535 let inserted = self.update_attachments(key);
9536 let baselines = self.attachment_baselines(key);
9537 let mut parts = TextAttachments {
9538 alignments: crate::AttachmentAlignments::default(),
9539 spacers: Vec::new(),
9540 baselines: &baselines,
9541 next_baseline: 0,
9542 };
9543 self.collect_text(key, base, &mut text, &mut parts, false);
9544 let TextAttachments {
9545 alignments,
9546 spacers,
9547 ..
9548 } = parts;
9549 self.hide_attachments(key, false);
9550 if multiplier != 1.0 {
9551 if let Some(strut) = &mut text.paragraph_strut {
9552 *strut = scaled(*strut, multiplier);
9553 }
9554 for span in &mut text.spans {
9555 span.style = scaled(span.style, multiplier);
9556 }
9557 }
9558 let layout = self.nodes[key as usize]
9559 .layout
9560 .expect("text block has layout");
9561 let colors_at_draw = self.text_engine.draws_colors_from_text();
9562 let cx = self.text_cx(layout);
9563 cx.deferred = deferred;
9564 cx.spacers = spacers;
9565 let pretty_changed = cx.pretty.is_some() != pretty;
9566 if pretty_changed {
9567 cx.pretty = pretty.then(|| Box::new((f32::NAN, Points::ZERO)));
9568 cx.laid_out = None;
9569 }
9570 if *cx.text == text && cx.alignments == alignments && cx.options == options {
9571 if inserted {
9572 cx.laid_out = None;
9574 }
9575 return inserted || pretty_changed;
9576 }
9577 if !cx.text.metadata_eq(&text)
9578 && !inserted
9579 && cx.alignments == alignments
9580 && cx.options == options
9581 && cx.text.rendering_eq(&text)
9582 {
9583 cx.text = Arc::new(text);
9584 cx.metadata_changed = true;
9585 return true;
9586 }
9587 if !inserted
9592 && cx.alignments == alignments
9593 && cx.options == options
9594 && colors_at_draw
9595 && cx
9596 .laid_out
9597 .as_ref()
9598 .is_none_or(|l| Arc::ptr_eq(&l.text, &cx.text))
9599 && cx.text.same_but_colors(&text)
9600 {
9601 let text = Arc::new(text);
9602 if let Some(laid) = &mut cx.laid_out {
9603 laid.text = text.clone();
9604 }
9605 cx.text = text;
9606 cx.metadata_changed = true;
9607 return true;
9608 }
9609 cx.metadata_changed = false;
9610 let same_layout =
9611 cx.text.layout_eq(&text) && cx.alignments == alignments && cx.options == options;
9612 cx.alignments = alignments;
9613 cx.options = options;
9614 cx.text = Arc::new(text);
9615 cx.prepared = None;
9618 cx.min_content = None;
9619 cx.laid_out = None;
9620 if let Some(p) = &mut cx.pretty {
9621 p.0 = f32::NAN;
9622 }
9623 if !same_layout {
9624 cx.layout_hash = text_layout_hash(&cx.alignments, &cx.text, &cx.options);
9625 cx.cache = None;
9626 cx.baseline = None;
9627 cx.same_lines = None;
9628 cx.no_ahead = false;
9629 let attachments =
9633 !cx.alignments.is_empty() || !self.nodes[key as usize].attached.is_empty();
9634 let measure = leaf_measure(&self.text_engine, &mut self.measure_cache);
9635 if attachments
9638 || !(self.layout.sized_by_style(layout)
9639 || self.layout.measures_as_before(layout, measure))
9640 {
9641 self.layout.mark_dirty(layout);
9642 self.needs_layout = true;
9643 }
9644 }
9645 true
9646 }
9647
9648 fn collect_text(
9651 &self,
9652 key: Key,
9653 style: ResolvedTextStyle,
9654 out: &mut AttributedText,
9655 parts: &mut TextAttachments<'_>,
9656 in_press: bool,
9657 ) {
9658 if let Some(text) = self.folded_text(key) {
9659 out.push(text, style);
9660 }
9661 for &c in &self.nodes[key as usize].children {
9662 let child = &self.nodes[c as usize];
9663 if child.is_overlay() {
9664 continue;
9665 }
9666 match child.kind {
9667 Kind::RawText => out.push(&child.text, style),
9668 Kind::Text => {
9669 let start = out.len_utf16();
9670 let mut inner = style.inherit(&child.text_style);
9671 if let Some(mut b) = span_background(&child.view_style, child.id) {
9672 (b.top, b.bottom) = span_vertical_padding(child);
9673 inner.background = Some(b);
9674 }
9675 if inner.hidden || child.view_style.hidden {
9678 inner = inner.hide();
9679 }
9680 let press = pressable(child.events);
9681 let hinted = child.overlay_watched & overlay::watch::HINT != 0;
9682 let tracked = child.classes.as_ref().map_or(0, |c| c.tracked_states());
9685 let hovers = tracked & crate::tailwind::state::HOVERED != 0;
9686 let (first, last) = span_padding(child, out.rtl);
9690 let pad = |out: &mut AttributedText, spacers: &mut Vec<u32>, w: f32| {
9691 if w > 0.0 {
9692 spacers.push(out.len_utf16());
9693 out.push_attachment(crate::geometry::size_pt(w, 0.0), inner);
9694 }
9695 };
9696 pad(out, &mut parts.spacers, first);
9697 self.collect_text(c, inner, out, parts, in_press || press);
9698 pad(out, &mut parts.spacers, last);
9699 if !inner.hidden && (press || ((hinted || hovers) && !in_press)) {
9712 let mut events = child.events;
9713 if hinted || hovers {
9714 events.set(EventKind::MouseEnter, true);
9715 events.set(EventKind::MouseLeave, true);
9716 }
9717 if press && tracked & crate::tailwind::state::PRESSED != 0 {
9718 events.set(EventKind::PressDown, true);
9719 events.set(EventKind::PressUp, true);
9720 }
9721 if let Some(href) = child.props.as_ref().and_then(|p| p.href.clone()) {
9724 out.link_hrefs
9725 .push(crate::text::LinkHref::new(out.links.len() as u32, href));
9726 }
9727 out.links.push(crate::text::TextLink {
9728 start,
9729 end: out.len_utf16(),
9730 node: child.id,
9731 events,
9732 focus_stop: press
9733 && child.props.as_ref().is_none_or(|p| p.focus_stop(true)),
9734 });
9735 }
9736 if let Some(test_id) = child.props.as_ref().and_then(|p| p.test_id.clone()) {
9737 out.test_ids.push(crate::text::SpanTestId {
9738 start,
9739 end: out.len_utf16(),
9740 test_id,
9741 });
9742 }
9743 }
9744 Kind::Overlay => {}
9746 _ => {
9748 if let Some(l) = child.layout {
9749 let size = self.rounded_layout(l).size;
9750 if let Some(&(_, baseline)) = parts
9753 .baselines
9754 .get(parts.next_baseline)
9755 .filter(|b| b.0 == c)
9756 {
9757 parts.next_baseline += 1;
9758 parts
9759 .alignments
9760 .set_baseline(out.len_utf16(), Some(baseline));
9761 }
9762 if let Some(copy) = self.attachment_copy_text(c) {
9763 out.copy_texts.push(crate::text::AttachmentCopyText::new(
9764 out.len_utf16(),
9765 copy.clone(),
9766 ));
9767 }
9768 parts.alignments.push(
9769 out,
9770 crate::geometry::size_pt(size.width, size.height),
9771 self.attachment_align(c),
9772 style,
9773 );
9774 }
9775 }
9776 }
9777 }
9778 }
9779
9780 fn attachment_align(&self, key: Key) -> crate::style::VerticalAlign {
9786 use crate::style::VerticalAlign;
9787 let node = &self.nodes[key as usize];
9788 if node.vertical_align != VerticalAlign::Baseline
9789 || !self.components.renders.is_place(node.id)
9790 {
9791 return node.vertical_align;
9792 }
9793 self.render_content(key)
9794 .map_or(VerticalAlign::Baseline, |content| {
9795 self.nodes[content as usize].vertical_align
9796 })
9797 }
9798
9799 fn attachment_copy_text(&self, key: Key) -> Option<&Arc<str>> {
9804 let node = &self.nodes[key as usize];
9805 let copy = match &node.copy_text {
9806 Some(copy) => Some(copy),
9807 None if self.components.renders.is_place(node.id) => self
9808 .render_content(key)
9809 .and_then(|content| self.nodes[content as usize].copy_text.as_ref()),
9810 None => None,
9811 };
9812 copy.filter(|c| !c.is_empty())
9813 }
9814
9815 fn render_content(&self, key: Key) -> Option<Key> {
9818 let mut key = key;
9819 for _ in 0..2 {
9820 let mut children = self.nodes[key as usize]
9821 .children
9822 .iter()
9823 .filter(|&&c| !self.nodes[c as usize].is_overlay());
9824 match (children.next(), children.next()) {
9825 (Some(&only), None) => key = only,
9826 _ => return None,
9827 }
9828 }
9829 Some(key)
9830 }
9831
9832 fn attachment_baselines(&mut self, key: Key) -> Vec<(Key, Points)> {
9840 let mut keys = Vec::new();
9841 self.attachments_of(key, &mut keys);
9842 keys.retain(|&a| self.attachment_align(a) == crate::style::VerticalAlign::Baseline);
9843 keys.into_iter()
9844 .filter_map(|a| Some((a, self.first_text_baseline(a, true)?)))
9845 .collect()
9846 }
9847
9848 fn first_text_baseline(&mut self, key: Key, root: bool) -> Option<Points> {
9852 let node = &self.nodes[key as usize];
9853 if node.is_overlay() {
9854 return None;
9855 }
9856 let layout = node.layout?;
9857 if !root
9861 && (self.layout.displays_none(layout)
9862 || self.layout.style(layout).position == Position::Absolute)
9863 {
9864 return None;
9865 }
9866 let text = node.kind == Kind::Text;
9867 let l = *self.layout.unrounded_layout(layout);
9868 let top = if root { 0.0 } else { l.location.y };
9869 if text {
9870 let width =
9871 l.size.width - l.padding.left - l.padding.right - l.border.left - l.border.right;
9872 let engine = &self.text_engine;
9873 let Some(LeafContext::Text(cx)) = self.layout.get_node_context_mut(layout) else {
9874 return None;
9875 };
9876 let baseline = text_baseline(engine, cx, width.max(0.0))?;
9877 return Some(Points(top + l.border.top + l.padding.top) + baseline);
9878 }
9879 let children = self.nodes[key as usize].children.clone();
9880 children
9881 .into_iter()
9882 .find_map(|c| self.first_text_baseline(c, false))
9883 .map(|inner| Points(top) + inner)
9884 }
9885
9886 fn placed_in_text(&self, key: Key) -> Option<Key> {
9889 let holder = self.nodes[key as usize].parent;
9890 if holder == NO_KEY || !self.is_render_holder(self.nodes[holder as usize].id) {
9891 return None;
9892 }
9893 let place = self.nodes[holder as usize].parent;
9894 (place != NO_KEY && self.nodes[place as usize].inline).then_some(place)
9895 }
9896
9897 fn attachments_of(&self, key: Key, out: &mut Vec<Key>) {
9900 for &c in &self.nodes[key as usize].children {
9901 let child = &self.nodes[c as usize];
9902 if child.is_overlay() {
9903 continue;
9904 }
9905 match child.kind {
9906 Kind::RawText | Kind::Overlay => {}
9907 Kind::Text => self.attachments_of(c, out),
9908 _ if child.layout.is_some() => out.push(c),
9909 _ => {}
9910 }
9911 }
9912 }
9913
9914 fn attachment_block(&self, key: Key) -> Option<Key> {
9916 let node = &self.nodes[key as usize];
9917 if !node.inline || node.layout.is_none() || node.kind == Kind::Text {
9918 return None;
9919 }
9920 let mut k = node.parent;
9921 while k != NO_KEY {
9922 let n = &self.nodes[k as usize];
9923 if !n.inline {
9924 return (n.kind == Kind::Text).then_some(k);
9925 }
9926 k = n.parent;
9927 }
9928 None
9929 }
9930
9931 fn update_attachments(&mut self, key: Key) -> bool {
9935 let mut keys = Vec::new();
9936 self.attachments_of(key, &mut keys);
9937 let block = &self.nodes[key as usize];
9938 if keys.is_empty() && block.attached.is_empty() {
9939 return false;
9940 }
9941 let (block_id, created) = (block.id, block.created);
9942 let old = std::mem::take(&mut self.nodes[key as usize].attached);
9943 let mut inserted = false;
9944 for &a in &keys {
9945 let id = self.nodes[a as usize].id;
9946 let new = !old.contains(&id);
9947 if created && new {
9948 self.ensure_created(a);
9949 self.mount.push(MountItem::Insert {
9950 parent: block_id,
9951 child: id,
9952 before: None,
9953 });
9954 inserted = true;
9955 }
9956 let layout = self.nodes[a as usize].layout.expect("attachment layout");
9957 let dirty = self.layout.dirty(layout);
9958 if dirty {
9959 self.layout_root(
9960 layout,
9961 taffy::Size {
9962 width: AvailableSpace::MaxContent,
9963 height: AvailableSpace::MaxContent,
9964 },
9965 );
9966 }
9967 if created && (dirty || new) {
9968 let children = std::mem::take(&mut self.nodes[a as usize].children);
9970 for &child in &children {
9971 self.emit_frames(child);
9972 }
9973 self.nodes[a as usize].children = children;
9974 }
9975 }
9976 for id in old {
9978 let Ok(k) = self.key(id) else { continue };
9979 let n = &self.nodes[k as usize];
9980 let moved = n.parent != NO_KEY && !n.inline && self.nodes[n.parent as usize].created;
9981 if n.created && !moved && self.attachment_block(k).is_none() {
9982 self.mount.push(MountItem::Remove { id });
9983 }
9984 }
9985 let ids: Vec<NodeId> = keys.iter().map(|&a| self.nodes[a as usize].id).collect();
9986 let has = !ids.is_empty();
9987 self.nodes[key as usize].attached = if created { ids } else { Vec::new() };
9988 match (has, self.attachment_blocks.contains(&key)) {
9989 (true, false) => self.attachment_blocks.push(key),
9990 (false, true) => self.attachment_blocks.retain(|&k| k != key),
9991 _ => {}
9992 }
9993 inserted
9994 }
9995
9996 fn check_attachments(&mut self) {
9998 let mut i = 0;
9999 while i < self.attachment_blocks.len() {
10000 let key = self.attachment_blocks[i];
10001 i += 1;
10002 let Some(node) = self.nodes.get(key as usize) else {
10003 continue;
10004 };
10005 let dirty = node.attached.iter().any(|&id| {
10006 self.key(id).is_ok_and(|k| {
10007 self.nodes[k as usize]
10008 .layout
10009 .is_some_and(|l| self.layout.dirty(l))
10010 })
10011 });
10012 if dirty {
10013 self.mark(key, dirty::TEXT_BUILD);
10014 }
10015 }
10016 }
10017
10018 fn positioning_parent(&self, layout: LayoutId) -> Option<LayoutId> {
10024 let mut parent = self.layout.parent(layout)?;
10025 match self.layout.style(layout).position {
10026 Position::Absolute => {
10027 while !self.layout.style(parent).position.is_positioned() {
10028 let Some(above) = self.layout.parent(parent) else {
10029 break;
10030 };
10031 parent = above;
10032 }
10033 }
10034 Position::Fixed => {
10035 while let Some(above) = self.layout.parent(parent) {
10036 parent = above;
10037 }
10038 }
10039 _ => {}
10040 }
10041 Some(parent)
10042 }
10043
10044 fn layout_origin(&self, layout: LayoutId) -> taffy::Point<f32> {
10045 let mut above = Vec::new();
10046 let mut at = self.positioning_parent(layout);
10047 while let Some(node) = at {
10048 above.push(node);
10049 at = self.positioning_parent(node);
10050 }
10051 above
10052 .iter()
10053 .rev()
10054 .fold(taffy::Point::ZERO, |origin, &node| {
10055 let l = self.layout.unrounded_layout(node);
10056 taffy::Point {
10057 x: origin.x + l.location.x,
10058 y: origin.y + l.location.y,
10059 }
10060 })
10061 }
10062
10063 fn rounded_layout(&self, layout: LayoutId) -> taffy::Layout {
10067 rounded(
10068 self.layout.unrounded_layout(layout),
10069 self.containing_origin(layout),
10070 self.frame_ratio(),
10071 )
10072 }
10073
10074 fn containing_origin(&self, layout: LayoutId) -> Origin {
10077 self.positioning_parent(layout)
10078 .map_or(Origin::default(), |parent| self.box_origin(parent))
10079 }
10080
10081 fn box_origin(&self, layout: LayoutId) -> Origin {
10083 let origin = self.layout_origin(layout);
10084 let l = self.layout.unrounded_layout(layout);
10085 Origin::of(
10086 taffy::Point {
10087 x: origin.x + l.location.x,
10088 y: origin.y + l.location.y,
10089 },
10090 l.size,
10091 self.frame_ratio(),
10092 )
10093 }
10094
10095 fn frame_ratio(&self) -> taffy::Size<f32> {
10099 match self.layout.grid() {
10100 Some(grid) => grid.ratio(),
10101 None => {
10102 let ratio = self.pixel_ratio();
10103 taffy::Size {
10104 width: ratio,
10105 height: ratio,
10106 }
10107 }
10108 }
10109 }
10110
10111 fn cell_changed(&mut self, cell: Option<Size<Points>>, dark: bool) {
10115 let grid = cell
10116 .and_then(terminal_layout::Grid::new)
10117 .map(|g| g.with_page(dark));
10118 let cell = grid.map(|g| Size::new(Points(g.width), Points(g.height)));
10119 if self.measure_cache.set_cell(cell) {
10120 self.fonts_changed();
10121 }
10122 if self.layout.set_grid(grid) {
10123 self.needs_layout = true;
10124 }
10125 }
10126
10127 fn pixel_ratio(&self) -> f32 {
10130 self.measure_cache.pixel_ratio()
10131 }
10132
10133 fn pixel_ratio_changed(&mut self, ratio: f32) {
10137 if !self.measure_cache.set_pixel_ratio(ratio) {
10138 return;
10139 }
10140 self.fonts_changed();
10141 let layouts: Vec<LayoutId> = self
10142 .nodes
10143 .iter()
10144 .filter(|(_, n)| n.created)
10145 .filter_map(|(_, n)| n.layout)
10146 .collect();
10147 for layout in layouts {
10148 self.layout.mark_dirty(layout);
10149 }
10150 self.needs_layout = true;
10151 }
10152
10153 fn layout_main(&mut self) -> bool {
10155 let root = self.nodes[self.root as usize].layout.expect("root layout");
10156 let available = taffy::Size {
10157 width: AvailableSpace::Definite(self.viewport.width.0),
10158 height: AvailableSpace::Definite(self.viewport.height.0),
10159 };
10160 let main = self.layout.dirty(root);
10162 if main {
10163 let (fitting, fitted) = self
10166 .windows
10167 .get(&crate::ROOT_ID)
10168 .map_or(((false, false), false), |r| (r.fits(), r.fitted.is_some()));
10169 let mut available = available;
10170 if fitting != (false, false) || fitted {
10171 let mut style = root_style(self.viewport);
10172 if fitting.0 {
10173 available.width = AvailableSpace::MaxContent;
10174 style.size.width = taffy::Dimension::auto();
10175 }
10176 if fitting.1 {
10177 available.height = AvailableSpace::MaxContent;
10178 style.size.height = taffy::Dimension::auto();
10179 }
10180 self.layout.set_style(root, style);
10181 }
10182 self.layout_root(root, available);
10183 self.fit_window(self.root, root);
10184 }
10185 main
10186 }
10187
10188 fn layout_roots(&mut self) {
10192 if self.roots.is_empty() {
10193 return;
10194 }
10195 let mut order: Vec<(u32, Key)> = self
10196 .roots
10197 .iter()
10198 .filter(|&&k| {
10199 let n = &self.nodes[k as usize];
10200 n.created
10201 && n.parent != NO_KEY
10202 && (!n.is_overlay() || self.overlay(k).is_some_and(|s| s.host.is_some()))
10203 })
10204 .map(|&k| (self.root_depth(k), k))
10205 .collect();
10206 order.sort_unstable();
10207 for (_, key) in order {
10208 self.layout_detached(key);
10209 }
10210 }
10211
10212 fn accessory_attached(&mut self, key: Key, attached: bool) {
10215 let node = &self.nodes[key as usize];
10216 let Some(name) = node.root.as_ref().and_then(|r| r.native_id.clone()) else {
10217 return;
10218 };
10219 let id = node.id;
10220 if attached {
10221 self.accessories.insert(name.clone(), id);
10222 } else if self.accessories.get(&name) == Some(&id) {
10223 self.accessories.remove(&name);
10224 } else {
10225 return;
10226 }
10227 let inputs: Vec<Key> = self
10228 .nodes
10229 .iter()
10230 .filter(|(_, n)| {
10231 n.input
10232 .as_ref()
10233 .is_some_and(|i| i.config.accessory_id.as_deref() == Some(&*name))
10234 })
10235 .map(|(k, _)| k as Key)
10236 .collect();
10237 for k in inputs {
10238 self.mark(k, dirty::INPUT);
10239 }
10240 }
10241
10242 fn root_depth(&self, mut key: Key) -> u32 {
10244 let mut depth = 0;
10245 key = self.nodes[key as usize].parent;
10246 while key != NO_KEY {
10247 let n = &self.nodes[key as usize];
10248 if n.is_layout_root() {
10249 depth += 1;
10250 }
10251 key = n.parent;
10252 }
10253 depth
10254 }
10255
10256 fn top_overlap(&self, key: Key) -> f32 {
10259 let mut y = 0.0;
10260 let mut k = key;
10261 loop {
10262 let n = &self.nodes[k as usize];
10263 if k == self.root {
10264 return (self.safe_area.top.0 - y).max(0.0);
10265 }
10266 if n.is_layout_root() {
10267 let inset = match n.kind {
10268 Kind::Modal => n.root.as_ref().map_or(0.0, |r| r.insets.top.0),
10269 _ => 0.0,
10270 };
10271 return (inset - y).max(0.0);
10272 }
10273 if !n.frame.origin.y.0.is_nan() {
10274 y += n.frame.origin.y.0;
10275 }
10276 if n.parent == NO_KEY {
10277 return 0.0;
10278 }
10279 k = n.parent;
10280 }
10281 }
10282
10283 fn native_header(&self) -> bool {
10287 self.header_heights != crate::NO_NATIVE_HEADER
10288 }
10289
10290 fn screen_size(&self, key: Key) -> Option<Size<Points>> {
10292 let parent = self.nodes[key as usize].parent;
10293 let p = self.nodes.get(parent as usize)?;
10294 let stack_layout = p.layout.filter(|_| p.kind == Kind::Stack)?;
10295 let s = self.rounded_layout(stack_layout).size;
10296 Some(size_pt(s.width, s.height))
10297 }
10298
10299 fn header_slot(&self, key: Key) -> Option<Key> {
10301 self.nodes[key as usize]
10302 .children
10303 .iter()
10304 .copied()
10305 .find(|&c| {
10306 let n = &self.nodes[c as usize];
10307 n.kind == Kind::HeaderItem
10308 && n.created
10309 && n.root
10310 .as_ref()
10311 .is_some_and(|r| r.slot == HeaderSlot::Header)
10312 })
10313 }
10314
10315 fn drawn_header(&mut self, key: Key) -> f32 {
10318 let Some(item) = self.header_slot(key) else {
10319 return 0.0;
10320 };
10321 self.layout_detached(item);
10322 self.nodes[item as usize]
10323 .layout
10324 .map_or(0.0, |l| self.rounded_layout(l).size.height)
10325 }
10326
10327 fn layout_detached(&mut self, key: Key) {
10328 if self.nodes[key as usize].is_overlay() {
10329 self.layout_overlay(key);
10330 return;
10331 }
10332 let native_header = self.native_header();
10333 let drawn_header = if !native_header && self.nodes[key as usize].kind == Kind::Screen {
10334 self.drawn_header(key)
10335 } else {
10336 0.0
10337 };
10338 let title_room = {
10339 let n = &self.nodes[key as usize];
10340 let title = native_header
10341 && n.kind == Kind::HeaderItem
10342 && n.root.as_ref().is_some_and(|r| r.slot == HeaderSlot::Title);
10343 let parent = n.parent;
10344 if title && parent != NO_KEY {
10345 self.title_room(parent).unwrap_or(0.0)
10346 } else {
10347 0.0
10348 }
10349 };
10350 let node = &self.nodes[key as usize];
10351 let (Some(layout), kind, parent) = (node.layout, node.kind, node.parent) else {
10352 return;
10353 };
10354 let root = node.root.as_ref().expect("root state");
10355 let (size, header, available) = match kind {
10356 Kind::Screen => {
10357 let Some(size) = self.screen_size(key) else {
10358 return;
10359 };
10360 let c = &root.screen;
10361 let measured = root
10362 .header
10363 .filter(|_| !c.large_title && !c.header_transparent);
10364 let header = if !native_header {
10365 drawn_header
10366 } else if !c.header_visible {
10367 0.0
10368 } else if let Some(measured) = measured {
10369 measured
10370 } else {
10371 let bar = if c.large_title {
10372 self.header_heights.1
10373 } else {
10374 self.header_heights.0
10375 };
10376 bar.0 + self.top_overlap(parent)
10377 };
10378 (size, header, definite(size))
10379 }
10380 Kind::HeaderItem if !native_header && root.slot == HeaderSlot::Header => {
10383 let Some(screen) = self.screen_size(parent) else {
10384 return;
10385 };
10386 (
10387 size_pt(screen.width.0, 0.0),
10388 0.0,
10389 taffy::Size {
10390 width: AvailableSpace::Definite(screen.width.0),
10391 height: AvailableSpace::MaxContent,
10392 },
10393 )
10394 }
10395 Kind::HeaderItem if native_header && root.slot == HeaderSlot::Title => (
10399 Size::default(),
10400 title_room,
10401 taffy::Size {
10402 width: AvailableSpace::MaxContent,
10403 height: AvailableSpace::MaxContent,
10404 },
10405 ),
10406 Kind::Modal => {
10407 let known = self.root_view_size(key);
10409 let size = known.unwrap_or_default();
10410 let mut available = match known {
10411 Some(size) => definite(size),
10412 None => taffy::Size {
10413 width: AvailableSpace::MaxContent,
10414 height: AvailableSpace::MaxContent,
10415 },
10416 };
10417 let (width, height) = self
10420 .windows
10421 .get(&node.id)
10422 .map_or((false, false), |r| r.fits());
10423 if width {
10424 available.width = AvailableSpace::MaxContent;
10425 }
10426 if height {
10427 available.height = AvailableSpace::MaxContent;
10428 }
10429 (size, 0.0, available)
10430 }
10431 Kind::InputAccessory => (
10433 size_pt(self.viewport.width.0, 0.0),
10434 0.0,
10435 taffy::Size {
10436 width: AvailableSpace::Definite(self.viewport.width.0),
10437 height: AvailableSpace::MaxContent,
10438 },
10439 ),
10440 _ => (
10441 Size::default(),
10442 0.0,
10443 taffy::Size {
10444 width: AvailableSpace::MaxContent,
10445 height: AvailableSpace::MaxContent,
10446 },
10447 ),
10448 };
10449 let changed = root.laid_out != Some((size, header));
10450 if !changed && !self.layout.dirty(layout) {
10451 return;
10452 }
10453 if kind == Kind::HeaderItem && native_header && root.slot == HeaderSlot::Title {
10454 let mut style = self.layout.style(layout).clone();
10455 style.max_size.width = if header > 0.0 {
10456 taffy::LengthPercentageAuto::length(header)
10457 } else {
10458 taffy::LengthPercentageAuto::auto()
10459 };
10460 self.layout.set_style(layout, style);
10461 } else if kind == Kind::InputAccessory
10462 || (kind == Kind::HeaderItem && size.width > Points::ZERO)
10463 {
10464 let mut style = self.layout.style(layout).clone();
10465 style.size.width = taffy::Dimension::length(size.width.0);
10466 self.layout.set_style(layout, style);
10467 } else if kind != Kind::HeaderItem {
10468 let config_padding = match kind {
10469 Kind::Screen
10473 if native_header
10474 && (root.screen.header_transparent || root.screen.large_title) =>
10475 {
10476 0.0
10477 }
10478 _ => header,
10479 };
10480 let mut style = self.nodes[key as usize]
10481 .base_layout
10482 .as_deref()
10483 .cloned()
10484 .unwrap_or_default();
10485 style.size = taffy::Size {
10486 width: taffy::Dimension::length(size.width.0),
10487 height: taffy::Dimension::length(size.height.0),
10488 };
10489 if kind == Kind::Modal {
10490 let id = self.nodes[key as usize].id;
10491 let (mut width, mut height) =
10492 self.windows.get(&id).map_or((false, false), |r| r.fits());
10493 if self.root_view_size(key).is_none() {
10494 (width, height) = (true, true);
10495 }
10496 if width {
10497 style.size.width = taffy::Dimension::auto();
10498 }
10499 if height {
10500 style.size.height = taffy::Dimension::auto();
10501 }
10502 }
10503 if config_padding > 0.0 {
10504 let base = match style.padding.top.into_raw() {
10505 raw if raw.tag() == taffy::CompactLength::LENGTH_TAG => raw.value(),
10506 _ => 0.0,
10507 };
10508 style.padding.top = taffy::LengthPercentage::length(base + config_padding);
10509 }
10510 self.layout.set_style(layout, style);
10511 }
10512 let header_changed = root.laid_out.is_none_or(|(_, h)| h != header);
10513 self.nodes[key as usize]
10514 .root
10515 .as_mut()
10516 .expect("root state")
10517 .laid_out = Some((size, header));
10518 self.layout_root(layout, available);
10519 if kind == Kind::Modal {
10520 self.fit_window(key, layout);
10521 }
10522 self.emit_frames(key);
10523 let screen = match kind {
10524 Kind::Screen if header_changed => Some(key),
10525 Kind::HeaderItem if self.header_item_emptied(key) => Some(parent),
10526 _ => None,
10527 };
10528 if let Some(screen) = screen {
10529 let id = self.nodes[screen as usize].id;
10530 if let Some(config) = self.screen_config(screen) {
10531 self.mount.push(MountItem::ScreenConfig {
10532 id,
10533 config: Box::new(config),
10534 });
10535 }
10536 }
10537 }
10538
10539 fn header_item_emptied(&mut self, key: Key) -> bool {
10544 let width = self.nodes[key as usize]
10545 .layout
10546 .map_or(0.0, |l| self.rounded_layout(l).size.width);
10547 let root = self.nodes[key as usize].root.as_mut().expect("root state");
10548 if root.slot == HeaderSlot::Header {
10549 return false;
10550 }
10551 let empty = width <= 0.0;
10552 std::mem::replace(&mut root.empty, empty) != empty
10553 }
10554
10555 fn title_room(&mut self, key: Key) -> Option<f32> {
10559 const INSET: f32 = 16.0;
10561 const BACK: f32 = 56.0;
10563 const BUTTON: f32 = 48.0;
10565 let width = self.screen_size(key)?.width.0;
10566 let items: Vec<(Key, HeaderSlot)> = self.nodes[key as usize]
10567 .children
10568 .iter()
10569 .filter_map(|&c| {
10570 let n = &self.nodes[c as usize];
10571 let slot = n.root.as_ref()?.slot;
10572 (n.kind == Kind::HeaderItem
10573 && n.created
10574 && matches!(slot, HeaderSlot::Left | HeaderSlot::Right))
10575 .then_some((c, slot))
10576 })
10577 .collect();
10578 let mut room = width - 2.0 * INSET;
10579 let (mut left, mut right) = (false, false);
10580 for (item, slot) in items {
10581 self.layout_detached(item);
10582 let w = self.nodes[item as usize]
10583 .layout
10584 .map_or(0.0, |l| self.rounded_layout(l).size.width);
10585 room -= w + INSET;
10586 match slot {
10587 HeaderSlot::Left => left = true,
10588 _ => right = true,
10589 }
10590 }
10591 let screen = &self.nodes[key as usize];
10592 let config = &screen.root.as_ref()?.screen;
10593 if !right && !config.right_items.is_empty() {
10594 room -= config.right_items.len() as f32 * BUTTON;
10595 }
10596 if !left && !config.left_items.is_empty() {
10597 room -= config.left_items.len() as f32 * BUTTON;
10598 }
10599 let first = self.nodes[screen.parent as usize].children.first() == Some(&key);
10601 if !left && config.back_visible && !first {
10602 room -= BACK;
10603 }
10604 Some(room.max(1.0))
10605 }
10606
10607 fn screen_config(&self, key: Key) -> Option<ScreenConfig> {
10609 let node = &self.nodes[key as usize];
10610 let root = node.root.as_ref().filter(|_| node.kind == Kind::Screen)?;
10611 let mut config = root.screen.clone();
10612 config.header_height = Points(root.laid_out.map_or(0.0, |(_, h)| h));
10613 for &c in &node.children {
10614 let child = &self.nodes[c as usize];
10615 if child.kind != Kind::HeaderItem || !child.created {
10616 continue;
10617 }
10618 let slot = child.root.as_ref().map_or(HeaderSlot::Left, |r| r.slot);
10619 let empty = child.root.as_ref().is_some_and(|r| r.empty);
10623 let system = match slot {
10624 HeaderSlot::Left => {
10625 config.left_system_item.is_some() || config.left_symbol.is_some()
10626 }
10627 HeaderSlot::Right => {
10628 config.right_system_item.is_some() || config.right_symbol.is_some()
10629 }
10630 HeaderSlot::Title => false,
10632 HeaderSlot::Header => true,
10633 };
10634 if empty && !system {
10635 continue;
10636 }
10637 let target = match slot {
10638 HeaderSlot::Left => &mut config.left,
10639 HeaderSlot::Right => &mut config.right,
10640 HeaderSlot::Title => &mut config.title_view,
10641 HeaderSlot::Header => &mut config.header_view,
10642 };
10643 *target = Some(child.id);
10644 }
10645 if let Some(style) = self.part_resolved(key, classes::Part::Header) {
10646 let background = style.view.background_color;
10647 config.background_color = (background.0 & 0xff != 0).then_some(background);
10648 config.title_color = style.text.color;
10649 config.tint_color = style.view.tint_color;
10650 }
10651 Some(config)
10652 }
10653
10654 fn layout_cells(&mut self) {
10657 for i in 0..self.lists.len() {
10658 let key = self.lists[i];
10659 let list = &self.nodes[key as usize];
10660 let Some(list_layout) = list.layout else {
10661 continue;
10662 };
10663 let state = list.list.as_ref().expect("list");
10664 let horizontal = state.horizontal;
10665 let l = self.rounded_layout(list_layout);
10666 let size = l.size;
10667 let cross = if !state.parent {
10668 if horizontal { size.height } else { size.width }
10669 } else if horizontal {
10670 (size.height - l.border.top - l.border.bottom - l.padding.top - l.padding.bottom)
10672 .max(0.0)
10673 } else {
10674 (size.width - l.border.left - l.border.right - l.padding.left - l.padding.right)
10675 .max(0.0)
10676 };
10677 let cross = if state.parent {
10680 cross
10681 } else {
10682 let main = if horizontal {
10683 size.width - l.border.left - l.border.right - l.padding.left - l.padding.right
10684 } else {
10685 size.height - l.border.top - l.border.bottom - l.padding.top - l.padding.bottom
10686 };
10687 let room = self.layout.list_bar_room(list_layout, horizontal);
10688 if room > 0.0 && state.content_len() > main + 0.5 {
10689 (cross - room).max(0.0)
10690 } else {
10691 cross
10692 }
10693 };
10694 let cell = self
10695 .layout
10696 .grid()
10697 .map(|g| if horizontal { g.height } else { g.width });
10698 let item_cross = state.column(cross, 0, cell).1;
10699 let extra_cross = state.full_width(cross).1;
10700 let stretch = state
10701 .content
10702 .align_items
10703 .is_none_or(|a| a == taffy::AlignItems::STRETCH);
10704 let available = |c: f32| {
10705 let cross = if stretch {
10706 AvailableSpace::Definite(c)
10707 } else {
10708 AvailableSpace::MaxContent
10709 };
10710 if horizontal {
10711 taffy::Size {
10712 width: AvailableSpace::MaxContent,
10713 height: cross,
10714 }
10715 } else {
10716 taffy::Size {
10717 width: cross,
10718 height: AvailableSpace::MaxContent,
10719 }
10720 }
10721 };
10722 let list_state = self.nodes[key as usize].list.as_mut().expect("list");
10726 let resized = list_state.cells_cross != cross;
10727 list_state.cells_cross = cross;
10728 let cells = std::mem::take(&mut self.nodes[key as usize].children);
10729 for &cell in &cells {
10730 let node = &self.nodes[cell as usize];
10731 let (Some(cell_layout), false) = (node.layout, node.decoration) else {
10733 continue;
10734 };
10735 let c = match node.slot {
10736 Some(CellSlot::Item(_)) | None => item_cross,
10737 Some(_) => extra_cross,
10738 };
10739 self.layout.set_host(cell_layout, list_layout);
10740 if resized || self.layout.dirty(cell_layout) {
10741 self.layout_root(cell_layout, available(c));
10742 self.nodes[cell as usize].relaid = true;
10743 }
10744 }
10745 self.nodes[key as usize].children = cells;
10746 }
10747 }
10748
10749 fn layout_root(&mut self, root: LayoutId, available: taffy::Size<AvailableSpace>) {
10751 let measure = leaf_measure(&self.text_engine, &mut self.measure_cache);
10752 self.layout
10753 .compute_layout_with_measure(root, available, measure);
10754 }
10755
10756 fn relayout_boundaries(&mut self) -> Vec<Key> {
10760 let measure = leaf_measure(&self.text_engine, &mut self.measure_cache);
10761 self.layout.relayout_boundaries(measure)
10762 }
10763
10764 fn displays_none(&self, key: Key) -> bool {
10767 let mut k = key;
10768 while k != NO_KEY {
10769 let n = &self.nodes[k as usize];
10770 if let Some(layout) = n.layout
10771 && self.layout.displays_none(layout)
10772 {
10773 return true;
10774 }
10775 if n.is_layout_root() {
10776 return false;
10777 }
10778 k = n.parent;
10779 }
10780 false
10781 }
10782
10783 #[inline]
10784 fn queue_text(&mut self, key: Key) {
10785 let node = &mut self.nodes[key as usize];
10786 if !node.text_queued {
10787 node.text_queued = true;
10788 self.pending_text.push(key);
10789 }
10790 }
10791
10792 fn flush_text(&mut self) {
10795 let mut pending = std::mem::take(&mut self.pending_text);
10796 let mut placements: Vec<(Key, TextLayout, Bounds<Points>)> = Vec::new();
10798 for &key in &pending {
10799 let Some(node) = self.nodes.get_mut(key as usize) else {
10800 continue;
10801 };
10802 node.text_queued = false;
10803 let align_vertical = node.text_style.align_vertical.unwrap_or_default();
10804 let report_lines = node.events.contains(EventKind::TextLayout);
10805 let fit = node
10807 .paragraph
10808 .fit
10809 .then_some(node.paragraph.min_font_scale.max(0.1));
10810 let (id, created, Some(layout)) = (node.id, node.created, node.layout) else {
10811 continue;
10812 };
10813 if !created {
10814 continue;
10815 }
10816 if let Some(commit) = self.measure_cache.resizing
10817 && let Some(LeafContext::Text(cx)) = self.layout.get_node_context_mut(layout)
10818 && cx.near_screen != commit
10819 && cx
10820 .laid_out
10821 .as_ref()
10822 .is_some_and(|l| Arc::ptr_eq(&l.text, &cx.text))
10823 {
10824 cx.held = true;
10825 continue;
10826 }
10827 let hidden = self.displays_none(key);
10829 let mut content = if hidden {
10830 Bounds::default()
10831 } else {
10832 content_box(&self.rounded_layout(layout))
10833 };
10834 let measured_width = (!hidden && self.layout.grid().is_none())
10838 .then(|| content_box(self.layout.unrounded_layout(layout)).size.width);
10839 let ratio = self.frame_ratio().width;
10840 let engine = &self.text_engine;
10841 let cache = &mut self.measure_cache;
10842 let Some(LeafContext::Text(cx)) = self.layout.get_node_context_mut(layout) else {
10843 continue;
10844 };
10845 let no_wrap = cx.text.no_wrap;
10846 let typeset = |rounded: Points| match measured_width {
10847 Some(measured) if !no_wrap => typeset_width(rounded, measured, ratio),
10848 _ => rounded,
10849 };
10850 if hidden {
10851 if let Some((text, layout)) = cx.remount_metadata(content) {
10856 self.mount.push(MountItem::Text {
10857 id,
10858 text,
10859 layout,
10860 content,
10861 });
10862 continue;
10863 }
10864 if matches!(&cx.laid_out, Some(l) if l.content == content) {
10865 continue;
10866 }
10867 let layout =
10868 engine.layout(&engine.prepare(&AttributedText::default()), content.size);
10869 cx.laid_out = Some(LaidText {
10870 content,
10871 layout: layout.clone(),
10872 text: cx.text.clone(),
10873 });
10874 cx.metadata_changed = false;
10875 self.mount.push(MountItem::Text {
10876 id,
10877 text: cx.text.clone(),
10878 layout,
10879 content,
10880 });
10881 continue;
10882 }
10883 if cx.text.no_wrap {
10884 content.size.width = content
10886 .size
10887 .width
10888 .max(measure_text(engine, cache, cx, None).width);
10889 }
10890 if align_vertical > Percentage(0.0) {
10891 let height =
10893 measure_text(engine, cache, cx, Some(typeset(content.size.width).0)).height;
10894 if height < content.size.height {
10895 content.origin.y += align_vertical.of(content.size.height - height);
10896 content.size.height = height;
10897 }
10898 }
10899 if cx.pretty.is_some() && fit.is_none() {
10900 let width = pretty_width(engine, cx, content.size.width);
10903 let spare = content.size.width - width;
10904 if spare > Points::ZERO {
10905 content.origin.x += match cx.text.align {
10906 TextAlign::Center => spare * 0.5,
10907 TextAlign::Right => spare,
10908 TextAlign::Auto if cx.text.rtl => spare,
10909 _ => Points::ZERO,
10910 };
10911 content.size.width = width;
10912 }
10913 }
10914 if let Some((text, layout)) = cx.remount_metadata(content) {
10915 self.mount.push(MountItem::Text {
10916 id,
10917 text,
10918 layout,
10919 content,
10920 });
10921 continue;
10922 }
10923 let size = content.size;
10924 if let Some(min) = fit {
10925 if matches!(&cx.laid_out, Some(l) if l.content == content) {
10927 continue;
10928 }
10929 let text = Arc::new(fitted(
10930 engine,
10931 &cx.text,
10932 &cx.alignments,
10933 &cx.options,
10934 size,
10935 min,
10936 ));
10937 let prepared = engine.prepare_with(&text, &cx.alignments, &cx.options);
10938 let text_layout = engine.layout(&prepared, size);
10939 cx.laid_out = Some(LaidText {
10940 content,
10941 layout: text_layout.clone(),
10942 text: text.clone(),
10943 });
10944 cx.metadata_changed = false;
10945 if report_lines {
10946 self.events.push(crate::element::JsEvent::Event(
10947 id,
10948 EventKind::TextLayout,
10949 text_lines(engine, &text, &text_layout),
10950 ));
10951 keep_geometry(
10952 &self.geometry_engine,
10953 &mut self.geometries,
10954 id,
10955 &text_layout,
10956 &text,
10957 &cx.spacers,
10958 );
10959 }
10960 if !text.attachments.is_empty() {
10961 placements.push((key, text_layout.clone(), content));
10962 }
10963 self.mount.push(MountItem::Text {
10964 id,
10965 text,
10966 layout: text_layout,
10967 content,
10968 });
10969 continue;
10970 }
10971 let text_layout = match &cx.laid_out {
10972 Some(l) if l.content == content => continue,
10973 Some(l) if l.content.size == size => l.layout.clone(),
10975 Some(l) if keeps_lines(cx, l, size) => l.layout.clone(),
10978 _ => {
10979 let prepared = cx.prepared.get_or_insert_with(|| {
10980 engine.prepare_with(&cx.text, &cx.alignments, &cx.options)
10981 });
10982 let layout =
10983 engine.layout(prepared, Size::new(typeset(size.width), size.height));
10984 if report_lines {
10985 self.events.push(crate::element::JsEvent::Event(
10986 id,
10987 EventKind::TextLayout,
10988 text_lines(engine, &cx.text, &layout),
10989 ));
10990 keep_geometry(
10991 &self.geometry_engine,
10992 &mut self.geometries,
10993 id,
10994 &layout,
10995 &cx.text,
10996 &cx.spacers,
10997 );
10998 }
10999 layout
11000 }
11001 };
11002 cx.laid_out = Some(LaidText {
11003 content,
11004 layout: text_layout.clone(),
11005 text: cx.text.clone(),
11006 });
11007 cx.metadata_changed = false;
11008 if !cx.text.attachments.is_empty() {
11009 placements.push((key, text_layout.clone(), content));
11010 }
11011 self.mount.push(MountItem::Text {
11012 id,
11013 text: cx.text.clone(),
11014 layout: text_layout,
11015 content,
11016 });
11017 }
11018 pending.clear();
11019 self.pending_text = pending;
11020 for (key, layout, content) in placements {
11021 self.place_attachments(key, &layout, content);
11022 }
11023 }
11024
11025 fn place_attachments(&mut self, key: Key, layout: &TextLayout, content: Bounds<Points>) {
11029 let mut points = self.text_engine.attachments(layout);
11030 if let Some(l) = self.nodes[key as usize].layout {
11031 let cx = self.text_cx(l);
11033 if !cx.spacers.is_empty() {
11034 let mut indices = cx.text.attachments.iter().map(|a| a.index);
11035 points.retain(|_| indices.next().is_none_or(|i| !cx.spacers.contains(&i)));
11036 }
11037 }
11038 let attached = std::mem::take(&mut self.nodes[key as usize].attached);
11039 for (i, &id) in attached.iter().enumerate() {
11040 let Ok(a) = self.key(id) else { continue };
11041 let Some(l) = self.nodes[a as usize].layout else {
11042 continue;
11043 };
11044 let size = self.rounded_layout(l).size;
11045 let (x, y) = match points.get(i).copied().flatten() {
11046 Some(p) => (content.origin.x.0 + p.x.0, content.origin.y.0 + p.y.0),
11047 None => (-100_000.0, 0.0),
11049 };
11050 self.set_frame(a, rect(x, y, size.width, size.height));
11051 }
11052 self.nodes[key as usize].attached = attached;
11053 }
11054
11055 fn emit_frames(&mut self, key: Key) {
11057 let parent = self.nodes[key as usize].parent;
11058 let hidden = parent != NO_KEY && self.displays_none(parent);
11059 let origin = self.nodes[key as usize]
11060 .layout
11061 .and_then(|l| self.layout.parent(l))
11062 .map_or(Origin::default(), |parent| self.box_origin(parent));
11063 self.emit_frames_in(key, hidden, origin);
11064 }
11065
11066 fn emit_frames_in(&mut self, key: Key, hidden: bool, origin: Origin) {
11079 let node = &self.nodes[key as usize];
11080 let Some(layout) = node.layout else { return };
11081 if !node.created {
11082 if node.culled {
11083 self.cull_frames_in(key, hidden, origin);
11084 }
11085 return;
11086 }
11087 let hidden = hidden || self.layout.displays_none(layout);
11088 if hidden {
11089 self.layout.emitted(layout);
11090 self.nodes[key as usize].emitted = None;
11091 if self.nodes[key as usize].follow.is_some() {
11092 self.laid_follower(key, None, false, (0.0, 0.0));
11093 }
11094 self.set_frame(key, Bounds::default());
11095 let node = &mut self.nodes[key as usize];
11099 if let Some(input) = node.input.as_mut()
11100 && input.content.is_some_and(|c| c != Bounds::default())
11101 {
11102 input.content = Some(Bounds::default());
11103 self.mount.push(MountItem::InputContent {
11104 id: node.id,
11105 content: Bounds::default(),
11106 });
11107 }
11108 if self.nodes[key as usize].kind.is_container() {
11109 let children = std::mem::take(&mut self.nodes[key as usize].children);
11110 for &child in &children {
11111 if !self.nodes[child as usize].is_layout_root() {
11112 self.emit_frames_in(child, true, origin);
11113 }
11114 }
11115 self.nodes[key as usize].children = children;
11116 }
11117 return;
11118 }
11119 let node = &self.nodes[key as usize];
11120 let unrounded = *self.layout.unrounded_layout(layout);
11121 let position = self.layout.style(layout).position;
11127 let escaping = position == Position::Fixed
11128 || (position == Position::Absolute
11129 && !self
11130 .layout
11131 .parent(layout)
11132 .is_some_and(|p| self.layout.style(p).position.is_positioned()));
11133 let ratio = self.frame_ratio();
11134 if !self.layout.stale(layout)
11139 && !node.escapes
11140 && !node.is_overlay()
11141 && !node.decoration
11142 && !self.nodes.get(node.parent as usize).is_some_and(|p| p.rtl)
11143 && node.emitted.is_some_and(|(at, r)| {
11144 let moved = |a: f32, b: f32, ratio: f32| {
11145 let d = (a - b) * ratio;
11146 d == d.round()
11147 };
11148 r == ratio
11149 && at.back == origin.back
11150 && moved(origin.at.x, at.at.x, ratio.width)
11151 && moved(origin.at.y, at.at.y, ratio.height)
11152 })
11153 {
11154 self.nodes[key as usize].emitted = Some((origin, ratio));
11155 return;
11156 }
11157 self.layout.emitted(layout);
11158 let containing = if escaping {
11159 self.containing_origin(layout)
11160 } else {
11161 origin
11162 };
11163 let inner = Origin::of(
11164 taffy::Point {
11165 x: containing.at.x + unrounded.location.x,
11166 y: containing.at.y + unrounded.location.y,
11167 },
11168 unrounded.size,
11169 ratio,
11170 );
11171 let l = rounded(&unrounded, containing, ratio);
11172 let offset = origin.to(containing, ratio);
11173 let mut frame = rect(
11174 l.location.x + offset.x,
11175 l.location.y + offset.y,
11176 l.size.width,
11177 l.size.height,
11178 );
11179 if let Some(parent) = self.nodes.get(node.parent as usize)
11182 && !node.decoration
11183 && parent.rtl
11184 && let Some(ScrollState {
11185 horizontal: true,
11186 content: Some(content),
11187 ..
11188 }) = parent.scroll.as_deref()
11189 && parent.kind == Kind::Scroll
11190 {
11191 frame.origin.x = content.width - frame.origin.x - frame.size.width;
11192 }
11193 if node.is_overlay() {
11194 frame.origin = self.overlay_origin(key, frame);
11195 }
11196 let beside = self.nodes[key as usize].beside;
11198 if beside != NO_KEY {
11199 frame.origin = self.nodes[beside as usize].frame.origin;
11200 } else if self.nodes[key as usize].decoration {
11201 let offset = Origin::default().to(origin, ratio);
11205 frame.origin.x.0 += offset.x;
11206 frame.origin.y.0 += offset.y;
11207 }
11208 if self.nodes[key as usize].follow.is_some() {
11209 let column = self.layout.parent(layout).is_some_and(|p| {
11212 let style = self.layout.style(p);
11213 style.display == taffy::Display::Flex
11214 && matches!(
11215 style.flex_direction,
11216 taffy::FlexDirection::Column | taffy::FlexDirection::ColumnReverse
11217 )
11218 });
11219 let m = unrounded.margin;
11220 let margins = if column {
11221 (round(m.top, ratio.height), round(m.bottom, ratio.height))
11222 } else {
11223 (round(m.left, ratio.width), round(m.right, ratio.width))
11224 };
11225 self.laid_follower(key, Some(frame), column, margins);
11226 } else {
11227 self.set_frame(key, frame);
11228 }
11229 self.sync_cell_style(key, layout, &unrounded);
11230 self.sync_focus_ring(key);
11231 let kind = self.nodes[key as usize].kind;
11232 if kind == Kind::Input {
11233 let content = content_box(&l);
11234 let node = &mut self.nodes[key as usize];
11235 let input = node.input.as_mut().expect("input state");
11236 if input.content != Some(content) {
11237 input.content = Some(content);
11238 self.mount.push(MountItem::InputContent {
11239 id: node.id,
11240 content,
11241 });
11242 }
11243 if node.events.contains(EventKind::ContentSizeChange) {
11244 self.report_content_size(key, content.size.width.0);
11245 }
11246 }
11247 if kind == Kind::Scroll {
11248 let horizontal = self.nodes[key as usize]
11249 .scroll
11250 .as_ref()
11251 .is_some_and(|s| s.horizontal);
11252 self.set_scroll_content(key, scroll_extent(&l, horizontal));
11253 }
11254 let mut escapes = escaping;
11257 if kind.is_container() && kind != Kind::List {
11258 let children = std::mem::take(&mut self.nodes[key as usize].children);
11259 for &child in &children {
11260 if !self.nodes[child as usize].is_layout_root() {
11261 self.emit_frames_in(child, false, inner);
11262 escapes |= self.nodes[child as usize].escapes;
11263 }
11264 }
11265 self.nodes[key as usize].children = children;
11266 self.update_overflow(key);
11267 }
11268 let node = &mut self.nodes[key as usize];
11269 node.escapes = escapes;
11270 node.emitted = Some((origin, ratio));
11271 }
11272
11273 fn sync_cell_style(&mut self, key: Key, layout: LayoutId, l: &taffy::Layout) {
11278 let w = self.nodes[key as usize].view_style.borders.widths;
11279 let styled = [w.top, w.right, w.bottom, w.left]
11280 .iter()
11281 .any(|&v| v > Points::ZERO);
11282 let sides = self.layout.grid().filter(|_| styled).map(|_| {
11284 let b = l.border;
11285 [b.top, b.right, b.bottom, b.left]
11286 .iter()
11287 .enumerate()
11288 .fold(0u8, |m, (bit, &v)| m | (u8::from(v > 0.0) << bit))
11289 });
11290 let label = self.layout.labelled(layout);
11291 let node = &mut self.nodes[key as usize];
11292 if node.cell_border == sides && node.cell_label == label {
11293 return;
11294 }
11295 node.cell_border = sides;
11296 node.cell_label = label;
11297 let id = node.id;
11298 let style = self.mounted_view_style(key);
11299 self.mount.push(MountItem::ViewStyle { id, style });
11300 }
11301
11302 fn report_frame(&mut self, key: Key) {
11305 let node = &self.nodes[key as usize];
11306 if !node.frame.origin.x.0.is_nan() {
11307 self.events.push(crate::element::JsEvent::Event(
11308 node.id,
11309 EventKind::Layout,
11310 EventPayload::Layout(node.frame),
11311 ));
11312 }
11313 }
11314
11315 fn set_frame(&mut self, key: Key, frame: Bounds<Points>) {
11316 let node = &mut self.nodes[key as usize];
11317 if node.frame != frame {
11318 let resized = node.frame.size != frame.size;
11319 node.frame = frame;
11320 self.note_resized(key, resized);
11321 self.follow_changed |= !self.followers.is_empty();
11323 let node = &self.nodes[key as usize];
11324 let (id, is_text) = (node.id, node.kind == Kind::Text);
11325 if node.events.contains(EventKind::Layout) {
11326 self.events.push(crate::element::JsEvent::Event(
11327 id,
11328 EventKind::Layout,
11329 EventPayload::Layout(frame),
11330 ));
11331 }
11332 if node.created {
11333 self.mount.push(MountItem::Frame { id, frame });
11334 }
11335 let node = &self.nodes[key as usize];
11336 if self.track_tree_order
11338 && node.parent != NO_KEY
11339 && self.nodes[node.parent as usize].list.is_some()
11340 {
11341 self.tree_order_changed = true;
11342 }
11343 let node = &self.nodes[key as usize];
11344 let parent_perspective = self.perspective_steps(key) > 0;
11347 if node.created && (node.view_style.transform.has_fractions() || parent_perspective) {
11348 let style = self.mounted_view_style(key);
11349 self.mount.push(MountItem::ViewStyle { id, style });
11350 }
11351 if node.child_perspective.is_some() {
11352 let children = node.children.clone();
11354 for c in children {
11355 self.mark(c, dirty::VIEW);
11356 }
11357 }
11358 if is_text {
11359 self.queue_text(key);
11360 }
11361 let node = &self.nodes[key as usize];
11363 if node.kind == Kind::Canvas && node.drawing.as_ref().is_some_and(|d| d.fit().is_some())
11364 {
11365 self.fitted_pending.push(key);
11366 }
11367 }
11368 }
11369
11370 fn set_scroll_content(&mut self, key: Key, size: Size<Points>) {
11371 let node = &mut self.nodes[key as usize];
11372 let (id, rtl, kind, viewport) = (node.id, node.rtl, node.kind, node.frame.size.width.0);
11373 if let Some(scroll) = node.scroll.as_mut()
11374 && scroll.content != Some(size)
11375 {
11376 let old = scroll.content.replace(size);
11377 let batch = self.batches;
11380 let queued = scroll
11381 .content_item
11382 .filter(|&(b, _)| b == batch)
11383 .and_then(|(_, i)| {
11384 let at = self.mount.get(i..)?.iter().position(
11385 |m| matches!(m, MountItem::ScrollContent { id: queued, .. } if *queued == id),
11386 )?;
11387 Some(i + at)
11388 });
11389 let shrunk = old.is_some_and(|old| {
11392 if scroll.horizontal {
11393 size.width < old.width
11394 } else {
11395 size.height < old.height
11396 }
11397 });
11398 let keep_earlier = shrunk
11399 && queued.is_some_and(|j| {
11400 self.mount[j + 1..].iter().any(|item| match item {
11401 MountItem::ScrollBy { id: scrolled, .. } => *scrolled == id,
11402 MountItem::Command {
11403 id: scrolled,
11404 command: Command::ScrollTo { .. },
11405 } => *scrolled == id,
11406 _ => false,
11407 })
11408 });
11409 if let Some(j) = queued
11410 && !keep_earlier
11411 {
11412 self.mount[j] = MountItem::ScrollContent { id, size };
11413 }
11414 if queued.is_none() || keep_earlier {
11415 scroll.content_item = Some((batch, self.mount.len()));
11416 self.mount.push(MountItem::ScrollContent { id, size });
11417 }
11418 if kind == Kind::Scroll && scroll.horizontal && rtl {
11421 match old {
11422 None => self.commands.push((
11423 id,
11424 Command::ScrollTo {
11425 x: (size.width - Points(viewport)).max(Points::ZERO),
11426 y: Points::ZERO,
11427 animated: false,
11428 },
11429 )),
11430 Some(old) if old.width != size.width => {
11431 let dx = size.width - old.width;
11432 self.mount.push(MountItem::ScrollBy {
11433 id,
11434 dx,
11435 dy: Points::ZERO,
11436 });
11437 self.scroll_issued(key, PendingScroll::By(dx.0));
11438 }
11439 Some(_) => {}
11440 }
11441 }
11442 }
11443 }
11444
11445 fn update_lists(&mut self, relayout: bool) {
11448 let mut awaiting = std::mem::take(&mut self.awaiting_renders);
11451 self.cells_awaiting_renders(&mut awaiting);
11452 self.awaiting_renders = awaiting;
11453 for i in 0..self.lists.len() {
11454 let key = self.lists[i];
11455 if self.nodes[key as usize]
11457 .list
11458 .as_ref()
11459 .is_some_and(|l| l.parent)
11460 {
11461 continue;
11462 }
11463 self.update_list(key, relayout, None);
11464 }
11465 if !self.parent_lists.is_empty() {
11466 if self.outer_moved {
11467 self.resolve_outer();
11468 }
11469 for i in 0..self.parent_lists.len() {
11470 let key = self.parent_lists[i];
11471 if !self.nodes[key as usize].created {
11472 continue;
11473 }
11474 let Some(outer) = self.outer_input(key) else {
11476 continue;
11477 };
11478 self.update_list(key, relayout, Some(outer));
11479 }
11480 }
11481 if !self.sticky_nodes.is_empty()
11482 || !self.sticky_scrollers.is_empty()
11483 || !self.decorated.is_empty()
11484 {
11485 self.update_sticky_views(relayout);
11486 }
11487 if !self.sticky_views.is_empty() {
11488 self.send_page_sticky();
11489 }
11490 }
11491
11492 fn hide_attachments(&mut self, key: Key, hidden: bool) {
11496 let count = self.nodes[key as usize].children.len();
11497 for i in 0..count {
11498 let c = self.nodes[key as usize].children[i];
11499 let child = &self.nodes[c as usize];
11500 if child.is_overlay() {
11501 continue;
11502 }
11503 match child.kind {
11504 Kind::RawText | Kind::Overlay => {}
11505 Kind::Text => {
11506 let hidden = hidden || child.view_style.hidden;
11507 self.hide_attachments(c, hidden);
11508 }
11509 _ if child.layout.is_some() => self.set_hidden_in_text(c, hidden),
11510 _ => {}
11511 }
11512 }
11513 }
11514
11515 fn set_hidden_in_text(&mut self, key: Key, hidden: bool) {
11518 let node = &mut self.nodes[key as usize];
11519 if node.hidden_in_text == hidden {
11520 return;
11521 }
11522 node.hidden_in_text = hidden;
11523 if !node.created {
11524 return;
11526 }
11527 let (id, props) = (node.id, node.mounted_props());
11528 let style = self.mounted_view_style(key);
11529 self.mount.push(MountItem::ViewStyle { id, style });
11530 self.mount.push(MountItem::ViewProps { id, props });
11531 }
11532
11533 fn set_spare(&mut self, key: Key, spare: bool) {
11538 let node = &mut self.nodes[key as usize];
11539 if node.spare == spare {
11540 return;
11541 }
11542 node.spare = spare;
11543 self.follow_changed |= !self.followers.is_empty();
11545 let node = &self.nodes[key as usize];
11546 if !node.created {
11547 return;
11549 }
11550 let (id, props) = (node.id, node.mounted_props());
11551 let style = self.mounted_view_style(key);
11552 self.mount.push(MountItem::ViewStyle { id, style });
11553 self.mount.push(MountItem::ViewProps { id, props });
11554 }
11555
11556 fn set_left_behind(&mut self, key: Key, left_behind: bool) {
11561 let node = &mut self.nodes[key as usize];
11562 if node.left_behind == left_behind {
11563 return;
11564 }
11565 node.left_behind = left_behind;
11566 if !node.created || node.spare {
11567 return;
11570 }
11571 let (id, props) = (node.id, node.mounted_props());
11572 self.mount.push(MountItem::ViewProps { id, props });
11573 }
11574
11575 fn update_list(
11578 &mut self,
11579 key: Key,
11580 relayout: bool,
11581 outer: Option<parent_viewport::OuterInput>,
11582 ) {
11583 let moved = match &outer {
11584 Some(o) => self.nodes[key as usize]
11585 .list
11586 .as_mut()
11587 .expect("list")
11588 .set_outer(o.start, o.offset, o.viewport, o.max, o.settled),
11589 None => false,
11590 };
11591 let node = &self.nodes[key as usize];
11592 if !node.created {
11593 return;
11594 }
11595 if self.displays_none(key) {
11599 return;
11600 }
11601 let list = node.list.as_ref().expect("list");
11602 if !(relayout || moved || list.dirty || self.commands.iter().any(|c| c.0 == node.id)) {
11603 return;
11604 }
11605 let (id, events) = (node.id, node.events);
11606 let horizontal = list.horizontal;
11607 let l = self.rounded_layout(node.layout.expect("list layout"));
11608 let (main, cross) = match &outer {
11609 Some(o) => (o.viewport, o.cross),
11611 None if horizontal => (l.size.width, l.size.height),
11612 None => (l.size.height, l.size.width),
11613 };
11614 let main_of = |s: taffy::Size<f32>| if horizontal { s.width } else { s.height };
11615
11616 let mut ready = std::mem::take(&mut self.cells_scratch);
11618 ready.clear();
11619 ready.extend(
11620 list.slots
11621 .iter()
11622 .filter_map(|s| s.ready().map(|i| (i, s.cell))),
11623 );
11624 let extras = list.extras;
11625 self.nodes[key as usize]
11628 .list
11629 .as_mut()
11630 .expect("list")
11631 .loads_at_start = events.contains(EventKind::LoadMoreAtStart);
11632 let mut anchor = 0.0;
11633 for &(index, cell) in &ready {
11634 if self.awaiting_renders.binary_search(&cell).is_ok() {
11639 continue;
11640 }
11641 if let Some(cell_layout) = self.nodes.get(cell as usize).and_then(|c| c.layout) {
11642 let size = main_of(self.rounded_layout(cell_layout).size);
11643 let list = self.nodes[key as usize].list.as_mut().expect("list");
11644 anchor += list.measured(index, size);
11645 }
11646 }
11647 for (kind, extra) in [ExtraKind::Header, ExtraKind::Footer, ExtraKind::Empty]
11648 .into_iter()
11649 .zip(extras)
11650 {
11651 if self.awaiting_renders.binary_search(&extra.cell).is_ok() {
11652 continue;
11653 }
11654 if let Some(cell_layout) = self.nodes.get(extra.cell as usize).and_then(|c| c.layout) {
11655 let size = main_of(self.rounded_layout(cell_layout).size);
11656 let list = self.nodes[key as usize].list.as_mut().expect("list");
11657 anchor += list.measured_extra(kind, size);
11658 }
11659 }
11660
11661 let inset = match (&outer, self.nodes[key as usize].scroll.as_deref()) {
11664 (None, Some(scroll)) => {
11665 let i = scroll.behavior.content_inset;
11666 if horizontal {
11667 (i.left.0, i.right.0)
11668 } else {
11669 (i.top.0, i.bottom.0)
11670 }
11671 }
11672 _ => (0.0, 0.0),
11673 };
11674 let list = self.nodes[key as usize].list.as_mut().expect("list");
11675 let grew = outer.is_none() && list.viewport > 0.0 && main > list.viewport;
11677 list.viewport = main;
11678 list.inset = inset;
11679 list.offset += anchor;
11680 let spliced = list.take_splice_anchor();
11684 anchor += spliced;
11685 let kept = anchor;
11686 let revealing = !self.scoped_layout.is_empty() && {
11690 let scoped = &self.scoped_layout;
11691 scoped.iter().any(|&(scope, ..)| {
11692 self.key(scope)
11693 .is_ok_and(|k| k != key && self.is_within(k, key))
11694 })
11695 };
11696 let list = self.nodes[key as usize].list.as_mut().expect("list");
11697 list.revealing = revealing;
11698 anchor += list.anchor_end(kept);
11701 let mut retarget = None;
11704 match list.follow_pin(anchor) {
11705 Follow::Stay => {}
11706 Follow::By(delta) => anchor += delta,
11707 Follow::To(offset) => retarget = Some(offset),
11708 }
11709 if list.take_animated_end() {
11714 let end = list.target_offset(PinTarget::End);
11715 list.pin(Some(PinTarget::End), end, true);
11716 retarget = Some(end);
11717 }
11718
11719 list.key_ends.clear();
11722 let mut outer_to = None;
11726 let mut scrolls_to = Vec::new();
11732 for (target, command) in &mut self.commands {
11733 if *target != id {
11734 continue;
11735 }
11736 let list = self.nodes[key as usize].list.as_mut().expect("list");
11737 let (pin, animated) = match *command {
11738 Command::ScrollToIndex {
11739 index,
11740 animated,
11741 view_position,
11742 view_offset,
11743 } => (
11744 Some(PinTarget::Index {
11745 index,
11746 view_position: view_position.0,
11747 view_offset: view_offset.0,
11748 }),
11749 animated,
11750 ),
11751 Command::ScrollToEnd { animated } => (Some(PinTarget::End), animated),
11752 Command::ScrollTo { animated, .. } => (None, animated),
11753 _ => continue,
11754 };
11755 let offset = match (pin, &*command) {
11756 (Some(pin), _) => list.target_offset(pin),
11757 (None, &Command::ScrollTo { x, y, .. }) => {
11758 let offset = if horizontal { x.0 } else { y.0 };
11759 if outer.is_some() {
11760 list.clamped(offset)
11761 } else {
11762 offset
11763 }
11764 }
11765 _ => continue,
11766 };
11767 list.pin(pin, offset, animated);
11769 retarget = None;
11771 if !animated {
11772 list.jump(offset);
11773 }
11774 if let Some(o) = &outer {
11775 outer_to = Some((o.start + offset, animated));
11776 continue;
11777 }
11778 scrolls_to.push((offset, animated));
11779 let (x, y) = if horizontal {
11780 (Points(offset), Points::ZERO)
11781 } else {
11782 (Points::ZERO, Points(offset))
11783 };
11784 *command = Command::ScrollTo { x, y, animated };
11785 }
11786 if outer_to.is_some() {
11787 self.commands.retain(|(target, command)| {
11789 *target != id
11790 || !matches!(
11791 command,
11792 Command::ScrollTo { .. }
11793 | Command::ScrollToIndex { .. }
11794 | Command::ScrollToEnd { .. }
11795 )
11796 });
11797 }
11798 if let (Some(offset), Some(o)) = (retarget, &outer) {
11799 outer_to = Some((o.start + offset, true));
11800 } else if let Some(offset) = retarget {
11801 scrolls_to.push((offset, true));
11802 let (x, y) = if horizontal {
11803 (Points(offset), Points::ZERO)
11804 } else {
11805 (Points::ZERO, Points(offset))
11806 };
11807 let command = Command::ScrollTo {
11808 x,
11809 y,
11810 animated: true,
11811 };
11812 self.commands.push((id, command));
11813 }
11814
11815 let paced = !self.components.is_virtual_list(id);
11818 let list = self.nodes[key as usize].list.as_mut().expect("list");
11819 list.paced = paced;
11820 let mut binds = Vec::new();
11821 let edges = list.update_window(&mut binds);
11822 if edges.end {
11823 self.events.push(crate::element::JsEvent::Event(
11824 id,
11825 EventKind::LoadMore,
11826 EventPayload::None,
11827 ));
11828 }
11829 if edges.start && events.contains(EventKind::LoadMoreAtStart) {
11830 self.events.push(crate::element::JsEvent::Event(
11831 id,
11832 EventKind::LoadMoreAtStart,
11833 EventPayload::None,
11834 ));
11835 }
11836 if !binds.is_empty() {
11837 self.list_binds.push(ListBind { list: id, binds });
11838 }
11839 if list.paced && list.has_paced() && !self.paced_lists.contains(&id) {
11840 self.paced_lists.push(id);
11841 }
11842 if events.contains(EventKind::ViewableItemsChange) {
11843 let viewable = list.viewable_items();
11844 if viewable != list.viewable {
11845 list.viewable = viewable;
11846 let (first, last) = viewable.map_or((-1.0, -1.0), |(f, l)| (f as f64, l as f64));
11847 self.events.push(crate::element::JsEvent::Event(
11848 id,
11849 EventKind::ViewableItemsChange,
11850 EventPayload::Map(vec![
11851 ("first", PayloadValue::Number(first)),
11852 ("last", PayloadValue::Number(last)),
11853 ]),
11854 ));
11855 }
11856 }
11857
11858 let list = self.nodes[key as usize].list.as_ref().expect("list");
11862 let sticky = list.sticky_enabled();
11863 ready.clear();
11864 ready.extend(
11865 list.slots
11866 .iter()
11867 .filter_map(|s| s.ready().map(|i| (i, s.cell))),
11868 );
11869 for &(index, cell) in &ready {
11874 if self.awaiting_renders.binary_search(&cell).is_ok() {
11875 continue;
11876 }
11877 if let Some(cell_layout) = self.nodes.get(cell as usize).and_then(|c| c.layout) {
11878 let size = main_of(self.rounded_layout(cell_layout).size);
11879 let list = self.nodes[key as usize].list.as_mut().expect("list");
11880 list.measured_unknown(index, size);
11881 }
11882 }
11883 let list = self.nodes[key as usize].list.as_ref().expect("list");
11884 let content_len = list.content_len();
11885 let blocks = list.blocks();
11886 let (window_start, window_end) = list.render_window();
11897 let motion = outer.is_none() && self.list_motion.active();
11898 if motion {
11899 let cells: Vec<Key> = list
11900 .slots
11901 .iter()
11902 .map(|s| s.cell)
11903 .chain(list.extras.iter().map(|e| e.cell))
11904 .collect();
11905 self.note_cell_starts(cells);
11906 }
11907 let list = self.nodes[key as usize].list.as_ref().expect("list");
11908 let inset = outer.map_or((0.0, 0.0), |o| o.inset);
11911 let unbound: Vec<Key> = list
11912 .slots
11913 .iter()
11914 .filter(|s| s.ready().is_none() && s.cell != u32::MAX)
11915 .map(|s| s.cell)
11916 .collect();
11917 let changed = std::mem::take(
11918 &mut self.nodes[key as usize]
11919 .list
11920 .as_mut()
11921 .expect("list")
11922 .items_changed,
11923 );
11924 for cell in unbound {
11925 let frame = self.nodes[cell as usize].frame;
11926 if frame.size.width.0.is_nan() {
11927 self.set_spare(cell, true);
11929 continue;
11930 }
11931 let (start, size) = if horizontal {
11932 (frame.origin.x.0 - inset.0, frame.size.width.0)
11933 } else {
11934 (frame.origin.y.0 - inset.0, frame.size.height.0)
11935 };
11936 if start + size <= window_start || start >= window_end {
11937 if changed {
11938 self.set_spare(cell, true);
11939 } else {
11940 self.set_left_behind(cell, true);
11941 }
11942 continue;
11943 }
11944 self.set_spare(cell, true);
11945 let away = if horizontal {
11946 Bounds {
11947 origin: Point::new(Points(-HIDDEN), frame.origin.y),
11948 ..frame
11949 }
11950 } else {
11951 Bounds {
11952 origin: Point::new(frame.origin.x, Points(-HIDDEN)),
11953 ..frame
11954 }
11955 };
11956 if frame != away {
11957 self.set_frame(cell, away);
11958 self.nodes[key as usize]
11959 .list
11960 .as_mut()
11961 .expect("list")
11962 .unplace(cell);
11963 }
11964 }
11965 let mut sticky_cells = Vec::new();
11966 let place = |this: &mut Self, cell: Key, at: f32, row: f32, (x, width): (f32, f32)| {
11967 let cell_layout = this.nodes.get(cell as usize).and_then(|c| c.layout)?;
11968 let size = this.rounded_layout(cell_layout).size;
11969 let list = this.nodes[key as usize].list.as_ref().expect("list");
11970 let mut main_at = list.to_content(at, row.max(main_of(size)));
11971 let mut x = x;
11972 if outer.is_some() {
11973 main_at += inset.0;
11974 x += inset.1;
11975 }
11976 let cell_cross = if horizontal { size.height } else { size.width };
11977 x = list.align_cross(x, width, cell_cross);
11978 let frame = if horizontal {
11979 rect(main_at, x, size.width, cell_cross)
11980 } else {
11981 rect(x, main_at, cell_cross, size.height)
11982 };
11983 this.set_frame(cell, frame);
11984 this.set_left_behind(cell, false);
11985 this.set_spare(cell, false);
11986 if std::mem::take(&mut this.nodes[cell as usize].relaid) {
11987 let waits = {
11992 let node = &this.nodes[cell as usize];
11993 !node.created && node.culled
11994 };
11995 let children = std::mem::take(&mut this.nodes[cell as usize].children);
11996 for &child in &children {
11997 if waits {
11998 let node = &mut this.nodes[child as usize];
11999 if !node.created && !node.is_layout_root() {
12000 node.culled = true;
12001 }
12002 }
12003 this.emit_frames(child);
12004 }
12005 this.nodes[cell as usize].children = children;
12006 this.update_overflow(cell);
12007 this.cells_framed = true;
12008 }
12009 Some(main_of(size))
12010 };
12011 let unit = self
12015 .layout
12016 .grid()
12017 .map(|g| if horizontal { g.height } else { g.width });
12018 let columns_cross = {
12019 let laid = self.nodes[key as usize]
12020 .list
12021 .as_ref()
12022 .expect("list")
12023 .cells_cross;
12024 if unit.is_some() && laid.is_finite() {
12025 laid
12026 } else {
12027 cross
12028 }
12029 };
12030 let mut placed = list_motion::Placed::default();
12031 for &(index, cell) in &ready {
12032 let list = self.nodes[key as usize].list.as_ref().expect("list");
12033 let (at, row) = (list.item_at(index), list.row_extent(index));
12034 let column = list.column(columns_cross, list.column_of(index), unit);
12035 let Some(size) = place(self, cell, at, row, column) else {
12036 continue;
12037 };
12038 let list = self.nodes[key as usize].list.as_mut().expect("list");
12039 if list.place(index) {
12040 placed.new.push(cell);
12041 } else {
12042 placed.kept.push(cell);
12043 }
12044 let list = self.nodes[key as usize].list.as_ref().expect("list");
12045 if sticky && list.sticky.binary_search(&index).is_ok() {
12046 let range = list.sticky_range(index, self.nodes[cell as usize].id, size);
12047 sticky_cells.push(range);
12048 }
12049 }
12050 let full = self.nodes[key as usize]
12051 .list
12052 .as_ref()
12053 .expect("list")
12054 .full_width(columns_cross);
12055 for (extra, at) in extras
12056 .iter()
12057 .zip([blocks.header, blocks.footer, blocks.body])
12058 {
12059 if extra.cell != u32::MAX && place(self, extra.cell, at, 0.0, full).is_some() {
12060 placed.kept.push(extra.cell);
12061 }
12062 }
12063 self.cells_scratch = ready;
12064
12065 sticky_cells.sort_by_key(|c| c.cell);
12066 let list = self.nodes[key as usize].list.as_mut().expect("list");
12067 if let Some(o) = &outer {
12068 if sticky_cells != list.sent_sticky {
12070 let old = std::mem::replace(&mut list.sent_sticky, sticky_cells);
12071 self.page_sticky_changed(key, o.view, &old);
12072 }
12073 } else if sticky_cells != list.sent_sticky {
12074 list.sent_sticky = sticky_cells;
12079 self.sticky_views.push(key);
12080 }
12081
12082 if let Some(o) = &outer {
12083 if anchor != 0.0 {
12087 self.ask_outer(o.view, None, anchor);
12088 }
12089 if outer_to.is_some() {
12090 self.ask_outer(o.view, outer_to, 0.0);
12091 }
12092 self.sync_spacer(key, false);
12093 return;
12094 }
12095 let content = if horizontal {
12096 size_pt(content_len, cross)
12097 } else {
12098 size_pt(cross, content_len)
12099 };
12100 let old_len = self.nodes[key as usize]
12103 .scroll
12104 .as_ref()
12105 .and_then(|s| s.content)
12106 .map_or(0.0, |c| if horizontal { c.width.0 } else { c.height.0 });
12107 let list = self.nodes[key as usize].list.as_mut().expect("list");
12108 if anchor != 0.0 {
12109 list.issue_scroll_by(anchor);
12110 }
12111 for (offset, animated) in scrolls_to {
12112 list.issue_scroll_to(offset, animated);
12113 }
12114 let scroll_by = (anchor != 0.0).then(|| {
12115 let (dx, dy) = if horizontal {
12116 (Points(anchor), Points::ZERO)
12117 } else {
12118 (Points::ZERO, Points(anchor))
12119 };
12120 MountItem::ScrollBy { id, dx, dy }
12121 });
12122 let frame_at = grew
12127 .then(|| {
12128 self.mount
12129 .iter()
12130 .position(|m| matches!(m, MountItem::Frame { id: f, .. } if *f == id))
12131 })
12132 .flatten();
12133 match (scroll_by, frame_at) {
12134 (Some(item), Some(at)) if content_len > old_len => {
12139 self.set_scroll_content(key, content);
12140 match self
12141 .mount
12142 .iter()
12143 .rposition(|m| matches!(m, MountItem::ScrollContent { id: c, .. } if *c == id))
12144 {
12145 Some(queued) if queued > at => {
12146 let grown = self.mount.remove(queued);
12147 self.mount.insert(at, grown);
12148 self.mount.insert(at + 1, item);
12149 }
12150 _ => self.mount.insert(at, item),
12151 }
12152 }
12153 (Some(item), Some(at)) => {
12154 self.mount.insert(at, item);
12155 self.set_scroll_content(key, content);
12156 }
12157 (Some(item), None) if content_len < old_len => {
12158 self.mount.push(item);
12159 self.set_scroll_content(key, content);
12160 }
12161 (item, _) => {
12162 self.set_scroll_content(key, content);
12163 self.mount.extend(item);
12164 }
12165 }
12166 if motion {
12167 self.move_list_cells(key, id, horizontal, anchor, placed);
12168 }
12169 }
12170}
12171
12172const HIDDEN: f32 = 1.0e6;
12174
12175fn position_from_ends<T: PartialEq>(items: &[T], x: &T) -> Option<(usize, usize)> {
12178 let (mut front, mut back) = (0, items.len());
12179 while front < back {
12180 if items[front] == *x {
12181 return Some((front, 2 * front + 1));
12182 }
12183 back -= 1;
12184 if items[back] == *x {
12185 return Some((back, 2 * (items.len() - back)));
12186 }
12187 front += 1;
12188 }
12189 None
12190}
12191
12192fn position_near<T: PartialEq>(items: &[T], x: &T, near: usize) -> Option<(usize, usize)> {
12196 let near = near.min(items.len().checked_sub(1)?);
12197 let mut looked = 0;
12198 for distance in 0..items.len() {
12200 let below = near.checked_sub(distance);
12201 let above = (distance > 0)
12202 .then_some(near + distance)
12203 .filter(|&i| i < items.len());
12204 for i in [below, above].into_iter().flatten() {
12205 looked += 1;
12206 if items[i] == *x {
12207 return Some((i, looked));
12208 }
12209 }
12210 }
12211 None
12212}
12213
12214fn round(value: f32, ratio: f32) -> f32 {
12222 (pixel(value, ratio) / f64::from(ratio)) as f32
12223}
12224
12225fn pixel(value: f32, ratio: f32) -> f64 {
12232 (snapped(value, ratio) + 0.5).floor()
12233}
12234
12235fn snapped(value: f32, ratio: f32) -> f64 {
12237 let p = f64::from(value) * f64::from(ratio);
12238 (p * 64.0).round() / 64.0
12239}
12240
12241fn edges(start: f32, len: f32, ratio: f32) -> (f64, f64) {
12250 let end = start + len;
12251 let (from, to) = (pixel(start, ratio), pixel(end, ratio));
12252 let (a, b) = (snapped(start, ratio), snapped(end, ratio));
12253 if from != to || b <= a {
12254 (from, to)
12255 } else if a + b < 2.0 * from {
12256 (from - 1.0, from)
12257 } else {
12258 (from, from + 1.0)
12259 }
12260}
12261
12262#[derive(Clone, Copy, Debug, Default, PartialEq)]
12269struct Origin {
12270 at: taffy::Point<f32>,
12271 back: taffy::Point<bool>,
12272}
12273
12274impl Origin {
12275 fn of(at: taffy::Point<f32>, size: taffy::Size<f32>, ratio: taffy::Size<f32>) -> Origin {
12277 let back =
12278 |start: f32, len: f32, ratio: f32| edges(start, len, ratio).0 < pixel(start, ratio);
12279 Origin {
12280 at,
12281 back: taffy::Point {
12282 x: back(at.x, size.width, ratio.width),
12283 y: back(at.y, size.height, ratio.height),
12284 },
12285 }
12286 }
12287
12288 fn lead(self, ratio: taffy::Size<f32>) -> taffy::Point<f64> {
12290 taffy::Point {
12291 x: pixel(self.at.x, ratio.width) - f64::from(u8::from(self.back.x)),
12292 y: pixel(self.at.y, ratio.height) - f64::from(u8::from(self.back.y)),
12293 }
12294 }
12295
12296 fn to(self, to: Origin, ratio: taffy::Size<f32>) -> taffy::Point<f32> {
12299 let (from, to) = (self.lead(ratio), to.lead(ratio));
12300 taffy::Point {
12301 x: ((to.x - from.x) / f64::from(ratio.width)) as f32,
12302 y: ((to.y - from.y) / f64::from(ratio.height)) as f32,
12303 }
12304 }
12305}
12306
12307fn span(from: f32, to: f32, ratio: f32) -> f32 {
12314 ((pixel(to, ratio) - pixel(from, ratio)) / f64::from(ratio)) as f32
12315}
12316
12317fn typeset_width(rounded: Points, measured: Points, ratio: f32) -> Points {
12328 if measured.0.is_finite() && ((measured.0 - rounded.0) * ratio).abs() < 1.0 {
12329 measured
12330 } else {
12331 rounded
12332 }
12333}
12334
12335fn ceil_to_pixel(value: Points, ratio: f32) -> Points {
12342 let up = (value.0 * ratio - 1.0e-3).ceil().max(0.0) / ratio;
12343 Points(if up < value.0 { up + 1.0 / ratio } else { up })
12344}
12345
12346fn scroll_extent(l: &taffy::Layout, horizontal: bool) -> Size<Points> {
12357 let o = l.scrollable_overflow_rect;
12358 let (width, height) = (l.border.left + o.right(), l.border.top + o.bottom());
12359 if horizontal {
12360 size_pt(width, height.max(l.size.height))
12361 } else {
12362 size_pt(width.max(l.size.width), height)
12363 }
12364}
12365
12366fn rounded(layout: &taffy::Layout, origin: Origin, ratio: taffy::Size<f32>) -> taffy::Layout {
12379 let mut out = *layout;
12380 let (x, y) = (
12381 origin.at.x + layout.location.x,
12382 origin.at.y + layout.location.y,
12383 );
12384 let (rx, ry) = (ratio.width, ratio.height);
12385 let (x0, x1) = edges(x, layout.size.width, rx);
12386 let (y0, y1) = edges(y, layout.size.height, ry);
12387 let lead = origin.lead(ratio);
12388 let points = |pixels: f64, ratio: f32| (pixels / f64::from(ratio)) as f32;
12389 out.location.x = points(x0 - lead.x, rx);
12390 out.location.y = points(y0 - lead.y, ry);
12391 out.size.width = points(x1 - x0, rx);
12392 out.size.height = points(y1 - y0, ry);
12393 out.scrollbar_size.width = round(layout.scrollbar_size.width, rx);
12394 out.scrollbar_size.height = round(layout.scrollbar_size.height, ry);
12395 out.border.left = span(x, x + layout.border.left, rx);
12396 out.border.right = span(
12397 x + layout.size.width - layout.border.right,
12398 x + layout.size.width,
12399 rx,
12400 );
12401 out.border.top = span(y, y + layout.border.top, ry);
12402 out.border.bottom = span(
12403 y + layout.size.height - layout.border.bottom,
12404 y + layout.size.height,
12405 ry,
12406 );
12407 let (left, right) = (
12415 x + layout.border.left,
12416 x + layout.size.width - layout.border.right,
12417 );
12418 let (top, bottom) = (
12419 y + layout.border.top,
12420 y + layout.size.height - layout.border.bottom,
12421 );
12422 out.padding.left = span(left, left + layout.padding.left, rx);
12423 out.padding.right = span(right - layout.padding.right, right, rx);
12424 out.padding.top = span(top, top + layout.padding.top, ry);
12425 out.padding.bottom = span(bottom - layout.padding.bottom, bottom, ry);
12426 let o = layout.scrollable_overflow_rect;
12427 out.scrollable_overflow_rect = taffy::ScrollableOverflow::new(
12430 taffy::Rect {
12431 left: points(pixel(x + o.left(), rx) - x0, rx).min(0.0),
12432 right: points(pixel(x + o.right(), rx) - x0, rx).max(0.0),
12433 top: points(pixel(y + o.top(), ry) - y0, ry).min(0.0),
12434 bottom: points(pixel(y + o.bottom(), ry) - y0, ry).max(0.0),
12435 },
12436 o.is_reversed(),
12437 );
12438 out
12439}
12440
12441fn content_box(l: &taffy::Layout) -> Bounds<Points> {
12442 rect(
12443 l.padding.left + l.border.left,
12444 l.padding.top + l.border.top,
12445 (l.size.width - l.padding.left - l.padding.right - l.border.left - l.border.right).max(0.0),
12446 (l.size.height - l.padding.top - l.padding.bottom - l.border.top - l.border.bottom)
12447 .max(0.0),
12448 )
12449}
12450
12451#[derive(Default)]
12453struct ImageLimits {
12454 min: taffy::Size<Option<f32>>,
12455 max: taffy::Size<Option<f32>>,
12456}
12457
12458impl ImageLimits {
12459 fn width(&self, w: f32) -> f32 {
12460 clamp_side(w, self.min.width, self.max.width)
12461 }
12462
12463 fn height(&self, h: f32) -> f32 {
12464 clamp_side(h, self.min.height, self.max.height)
12465 }
12466}
12467
12468fn clamp_side(v: f32, min: Option<f32>, max: Option<f32>) -> f32 {
12469 let v = max.map_or(v, |max| v.min(max));
12470 min.map_or(v, |min| v.max(min))
12471}
12472
12473fn image_size(
12476 natural: Size<Points>,
12477 w: Option<f32>,
12478 h: Option<f32>,
12479 limits: &ImageLimits,
12480) -> taffy::Size<f32> {
12481 let ratio = if natural.height > Points::ZERO {
12482 natural.width / natural.height
12483 } else {
12484 1.0
12485 };
12486 let (width, height) = match (w, h) {
12487 (Some(w), None) => (w, limits.height(w / ratio)),
12488 (None, Some(h)) => (limits.width(h * ratio), h),
12489 (Some(w), Some(h)) => (w, h),
12490 (None, None) => {
12491 let width = limits.width(natural.width.0);
12492 let height = width / ratio;
12493 let clamped = limits.height(height);
12494 if clamped == height {
12495 (width, height)
12496 } else {
12497 (limits.width(clamped * ratio), clamped)
12498 }
12499 }
12500 };
12501 taffy::Size { width, height }
12502}
12503
12504fn keep_geometry(
12511 engine: &Option<Rc<dyn crate::text::GeometryEngine>>,
12512 geometries: &mut rustc_hash::FxHashMap<NodeId, crate::text::TextGeometry>,
12513 id: NodeId,
12514 layout: &TextLayout,
12515 text: &Arc<AttributedText>,
12516 spacers: &[u32],
12517) {
12518 if let Some(engine) = engine.as_ref().filter(|_| id % 2 == 1) {
12519 geometries.insert(
12520 id,
12521 crate::text::TextGeometry::new(engine.clone(), layout.clone(), text.clone(), spacers),
12522 );
12523 }
12524}
12525
12526fn text_lines<M: TextEngine>(
12528 engine: &M,
12529 text: &AttributedText,
12530 layout: &TextLayout,
12531) -> EventPayload {
12532 let units: Vec<u16> = text.text.encode_utf16().collect();
12533 let mut lines = engine.lines(layout);
12534 for line in &mut lines {
12535 let (start, end) = (line.start as usize, (line.end as usize).min(units.len()));
12536 if start < end {
12537 line.text = String::from_utf16_lossy(&units[start..end]);
12538 }
12539 }
12540 EventPayload::TextLayout(lines)
12541}
12542
12543fn fitted<M: TextEngine>(
12547 engine: &M,
12548 text: &AttributedText,
12549 alignments: &crate::AttachmentAlignments,
12550 options: &crate::TextOptions,
12551 size: Size<Points>,
12552 min: f32,
12553) -> AttributedText {
12554 let scaled = |scale: f32| {
12555 let mut t = text.clone();
12556 if let Some(strut) = &mut t.paragraph_strut {
12557 strut.font_size *= scale;
12558 strut.line_height *= scale;
12559 }
12560 for span in &mut t.spans {
12561 span.style.font_size *= scale;
12562 span.style.line_height *= scale;
12563 span.style.letter_spacing *= scale;
12564 }
12565 t
12566 };
12567 let fits = |t: &AttributedText| {
12568 let all = AttributedText {
12571 max_lines: 0,
12572 ..t.clone()
12573 };
12574 let full = engine.measure(
12575 &engine.prepare_with(&all, alignments, options),
12576 Some(size.width),
12577 );
12578 let limited = if t.max_lines > 0 {
12579 engine
12580 .measure(
12581 &engine.prepare_with(t, alignments, options),
12582 Some(size.width),
12583 )
12584 .height
12585 } else {
12586 Points(f32::INFINITY)
12587 };
12588 full.height <= size.height.min(limited) + Points(0.5)
12589 && full.width <= size.width + Points(0.5)
12590 };
12591 if fits(text) {
12592 return text.clone();
12593 }
12594 let (mut lo, mut hi) = (min, 1.0f32);
12595 if !fits(&scaled(lo)) {
12596 return scaled(lo);
12597 }
12598 for _ in 0..7 {
12599 let mid = (lo + hi) / 2.0;
12600 if fits(&scaled(mid)) {
12601 lo = mid;
12602 } else {
12603 hi = mid;
12604 }
12605 }
12606 scaled(lo)
12607}
12608
12609fn estimate_text(text: &AttributedText, max_width: Option<f32>) -> Size<Points> {
12616 let (_, line) = text_metrics(text);
12617 let mut width = 0.0f32;
12618 let mut lines = 0u32;
12619 for paragraph in text.text.split('\n') {
12620 let w = estimate_line(text, paragraph).0;
12621 width = width.max(match max_width {
12622 Some(max) => w.min(max),
12623 None => w,
12624 });
12625 lines += match max_width {
12626 Some(max) if max > 0.0 && !text.no_wrap => (w / max).ceil().max(1.0) as u32,
12627 _ => 1,
12628 };
12629 }
12630 if text.max_lines > 0 {
12631 lines = lines.min(text.max_lines);
12632 }
12633 Size::new(Points(width.ceil()), Points((lines as f32 * line).ceil()))
12634}
12635
12636fn estimate_line(text: &AttributedText, run: &str) -> Points {
12639 let (size, _) = text_metrics(text);
12640 Points(
12641 run.chars()
12642 .map(|c| {
12643 if c as u32 >= 0x2e80 {
12644 size
12645 } else {
12646 size * 0.55
12647 }
12648 })
12649 .sum(),
12650 )
12651}
12652
12653fn text_metrics(text: &AttributedText) -> (f32, f32) {
12656 let (font, line) = text.approx_metrics();
12657 (font.0, line.0)
12658}
12659
12660fn min_content_width<M: TextEngine>(
12661 engine: &M,
12662 cache: &mut MeasureCache,
12663 cx: &mut TextContext<M::Prepared>,
12664) -> Points {
12665 if let Some(width) = cx.min_content {
12666 return width;
12667 }
12668 if cx.deferred {
12669 return cx
12671 .text
12672 .text
12673 .split_whitespace()
12674 .map(|word| estimate_line(&cx.text, word))
12675 .fold(Points::ZERO, Points::max);
12676 }
12677 let text = &cx.text;
12678 let mut offsets = Vec::with_capacity(text.text.chars().count() + 1);
12679 let mut utf16 = 0u32;
12680 for (byte, ch) in text.text.char_indices() {
12681 offsets.push((utf16, byte));
12682 utf16 += ch.len_utf16() as u32;
12683 }
12684 offsets.push((utf16, text.text.len()));
12685 let byte_at = |offset: u32| {
12686 offsets[offsets
12687 .binary_search_by_key(&offset, |&(at, _)| at)
12688 .unwrap()]
12689 .1
12690 };
12691 let mut start = 0usize;
12692 let mut width = Points::ZERO;
12693 for (end, _) in unicode_linebreak::linebreaks(&text.text) {
12694 let word = text.text[start..end].trim_end_matches([' ', '\t', '\n', '\r', '\u{000c}']);
12695 let from = offsets[offsets
12696 .binary_search_by_key(&start, |&(_, byte)| byte)
12697 .unwrap()]
12698 .0;
12699 let to = from + word.encode_utf16().count() as u32;
12700 if from < to {
12701 let mut part = AttributedText {
12702 no_wrap: true,
12703 rtl: text.rtl,
12704 writing_direction: text.writing_direction,
12705 ..Default::default()
12706 };
12707 for span in &text.spans {
12708 let (lo, hi) = (from.max(span.start), to.min(span.end));
12709 if lo < hi {
12710 part.push(&text.text[byte_at(lo)..byte_at(hi)], span.style);
12711 }
12712 }
12713 for attachment in &text.attachments {
12714 if (from..to).contains(&attachment.index) {
12715 let mut attachment = *attachment;
12716 attachment.index -= from;
12717 part.attachments.push(attachment);
12718 }
12719 }
12720 let hash = part.layout_hash();
12721 let measured = cache.get(hash, None).unwrap_or_else(|| {
12722 let measured = engine.measure(&engine.prepare(&part), None);
12723 cache.insert(hash, None, measured);
12724 measured
12725 });
12726 width = width.max(measured.width);
12727 }
12728 start = end;
12729 }
12730 cx.min_content = Some(width);
12731 width
12732}
12733
12734fn leaf_measure<'a, M: TextEngine>(
12738 engine: &'a M,
12739 cache: &'a mut MeasureCache,
12740) -> impl FnMut(
12741 taffy::LayoutInput,
12742 LayoutId,
12743 Option<&mut LeafContext<M::Prepared>>,
12744 &taffy::Style,
12745 layout_tree::Aligned,
12746) -> taffy::LayoutOutput
12747+ 'a {
12748 move |input, _, cx, style, aligned| measure_leaf(engine, cache, input, cx, style, aligned)
12749}
12750
12751fn measure_leaf<M: TextEngine>(
12759 engine: &M,
12760 cache: &mut MeasureCache,
12761 input: taffy::LayoutInput,
12762 mut cx: Option<&mut LeafContext<M::Prepared>>,
12763 style: &taffy::Style,
12764 aligned: layout_tree::Aligned,
12765) -> taffy::LayoutOutput {
12766 let mut output = measure_leaf_size(engine, cache, input, cx.as_deref_mut(), style);
12767 if aligned == layout_tree::Aligned::Baseline
12770 && input.run_mode == taffy::RunMode::PerformLayout
12771 && let Some(LeafContext::Text(cx)) = cx
12772 {
12773 use taffy::util::ResolveOrZero;
12774 let resolve = |_: taffy::CalcHandle, _: f32| 0.0;
12775 let padding = style
12776 .padding
12777 .resolve_or_zero(input.parent_size.width, resolve);
12778 let border = style
12779 .border
12780 .resolve_or_zero(input.parent_size.width, resolve);
12781 let width = output.size.width - padding.left - padding.right - border.left - border.right;
12782 if let Some(baseline) = text_baseline(engine, cx, width.max(0.0)) {
12783 output.baselines.first = Some(padding.top + border.top + baseline.0);
12784 }
12785 }
12786 output
12787}
12788
12789fn text_baseline<M: TextEngine>(
12793 engine: &M,
12794 cx: &mut TextContext<M::Prepared>,
12795 width: f32,
12796) -> Option<Points> {
12797 if cx.deferred {
12798 return None;
12799 }
12800 if let Some((w, baseline)) = cx.baseline
12801 && w == width
12802 {
12803 return baseline;
12804 }
12805 let prepared = cx
12806 .prepared
12807 .get_or_insert_with(|| engine.prepare_with(&cx.text, &cx.alignments, &cx.options));
12808 let baseline = engine.first_baseline(prepared, Points(width));
12809 cx.baseline = Some((width, baseline));
12810 baseline
12811}
12812
12813fn measure_leaf_size<M: TextEngine>(
12815 engine: &M,
12816 cache: &mut MeasureCache,
12817 input: taffy::LayoutInput,
12818 cx: Option<&mut LeafContext<M::Prepared>>,
12819 style: &taffy::Style,
12820) -> taffy::LayoutOutput {
12821 use taffy::{MaybeResolve as _, ResolveOrZero as _};
12822 let input_max_height = match &cx {
12828 Some(LeafContext::Text(cx)) if cx.field.is_some() => {
12829 let parent = input.parent_size;
12830 let max: Option<f32> = style
12831 .max_size
12832 .height
12833 .maybe_resolve(parent.height, |_, _| 0.0);
12834 max.map(|max| {
12835 let inset = (style.padding.resolve_or_zero(parent.width, |_, _| 0.0)
12836 + style.border.resolve_or_zero(parent.width, |_, _| 0.0))
12837 .vertical_axis_sum();
12838 match style.box_sizing {
12839 taffy::BoxSizing::BorderBox => (max - inset).max(0.0),
12840 taffy::BoxSizing::ContentBox => max,
12841 }
12842 })
12843 }
12844 _ => None,
12845 };
12846 let inset = {
12852 let parent = input.parent_size.width;
12853 let mut inset = (style.padding.resolve_or_zero(parent, |_, _| 0.0)
12854 + style.border.resolve_or_zero(parent, |_, _| 0.0))
12855 .sum_axes();
12856 if style.overflow.y == taffy::Overflow::Scroll {
12858 inset.width += style.scrollbar_width;
12859 }
12860 if style.overflow.x == taffy::Overflow::Scroll {
12861 inset.height += style.scrollbar_width;
12862 }
12863 inset
12864 };
12865 let image = matches!(cx, Some(LeafContext::Image(_)));
12866 let image_limits = match &cx {
12871 Some(LeafContext::Image(Some(_))) => {
12872 let parent = input.parent_size;
12873 let content = |v: Option<f32>, inset: f32| {
12874 v.map(|v| match style.box_sizing {
12875 taffy::BoxSizing::BorderBox => (v - inset).max(0.0),
12876 taffy::BoxSizing::ContentBox => v,
12877 })
12878 };
12879 let inset = (style.padding.resolve_or_zero(parent.width, |_, _| 0.0)
12880 + style.border.resolve_or_zero(parent.width, |_, _| 0.0))
12881 .sum_axes();
12882 let min: taffy::Size<Option<f32>> = style.min_size.maybe_resolve(parent, |_, _| 0.0);
12883 let max: taffy::Size<Option<f32>> = style.max_size.maybe_resolve(parent, |_, _| 0.0);
12884 ImageLimits {
12885 min: taffy::Size {
12886 width: content(min.width, inset.width),
12887 height: content(min.height, inset.height),
12888 },
12889 max: taffy::Size {
12890 width: content(max.width, inset.width),
12891 height: content(max.height, inset.height),
12892 },
12893 }
12894 }
12895 _ => ImageLimits::default(),
12896 };
12897 let mut output = taffy::compute_leaf_layout(
12898 input,
12899 style,
12900 |_, _| 0.0,
12901 |known, available| {
12902 let known = taffy::Size {
12903 width: known.width.map(|w| (w - inset.width).max(0.0)),
12904 height: known.height.map(|h| (h - inset.height).max(0.0)),
12905 };
12906 let available = taffy::Size {
12913 width: available.width.map_definite_value(|w| w.max(0.0)),
12914 height: available.height.map_definite_value(|h| h.max(0.0)),
12915 };
12916 if let Some(LeafContext::Image(Some(natural))) = cx {
12917 return image_size(*natural, known.width, known.height, &image_limits);
12918 }
12919 measure_content(engine, cache, cx, known, available, input_max_height)
12920 },
12921 );
12922 if image {
12928 let o = output.scrollable_overflow_rect;
12929 let mut rect = o.rect();
12930 rect.right = rect.right.min(output.size.width);
12931 rect.bottom = rect.bottom.min(output.size.height);
12932 output.scrollable_overflow_rect = taffy::ScrollableOverflow::new(rect, o.is_reversed());
12933 }
12934 output
12935}
12936
12937fn measure_content<M: TextEngine>(
12940 engine: &M,
12941 cache: &mut MeasureCache,
12942 cx: Option<&mut LeafContext<M::Prepared>>,
12943 known: taffy::Size<Option<f32>>,
12944 available: taffy::Size<AvailableSpace>,
12945 input_max_height: Option<f32>,
12946) -> taffy::Size<f32> {
12947 match cx {
12948 Some(LeafContext::Text(cx)) => {
12949 let field = cx
12952 .field
12953 .as_deref_mut()
12954 .map(|field| measure_text(engine, cache, field, None));
12955 let field_width = field.map(|size| size.width.0);
12956 let max_width = if cx.text.no_wrap {
12957 None
12958 } else {
12959 known.width.or(match (available.width, field_width) {
12960 (AvailableSpace::Definite(w), Some(field)) => Some(field.min(w)),
12961 (AvailableSpace::Definite(w), None) => Some(w),
12962 (_, Some(field)) => Some(field),
12963 (AvailableSpace::MinContent, None) => {
12964 Some(min_content_width(engine, cache, cx).0)
12965 }
12966 (AvailableSpace::MaxContent, None) => None,
12967 })
12968 };
12969 let width = known.width.or(field_width.and(max_width));
12970 let measured = match field {
12974 Some(sample)
12975 if width.is_some()
12976 && cx.text.max_lines == 1
12977 && engine.uniform_input_line_height() =>
12978 {
12979 sample
12980 }
12981 _ => measure_text(engine, cache, cx, max_width),
12982 };
12983 taffy::Size {
12984 width: width.unwrap_or(measured.width.0),
12985 height: known.height.unwrap_or(match input_max_height {
12986 Some(max) => measured.height.0.min(max),
12987 None => measured.height.0,
12988 }),
12989 }
12990 }
12991 Some(LeafContext::Image(Some(natural))) => {
12992 image_size(*natural, known.width, known.height, &ImageLimits::default())
12993 }
12994 Some(LeafContext::Native(Some(own))) => taffy::Size {
12995 width: known.width.unwrap_or(own.width.0),
12996 height: known.height.unwrap_or(own.height.0),
12997 },
12998 _ => taffy::Size::ZERO,
12999 }
13000}
13001
13002fn measure_text<M: TextEngine>(
13003 engine: &M,
13004 cache: &mut MeasureCache,
13005 cx: &mut TextContext<M::Prepared>,
13006 max_width: Option<f32>,
13007) -> Size<Points> {
13008 if let Some((w, size)) = cx.cache
13009 && w == max_width
13010 {
13011 return size;
13012 }
13013 let typed = max_width.map(Points);
13014 if cx.deferred {
13017 let size = cache.get(cx.layout_hash, typed).unwrap_or_else(|| {
13018 cx.estimated = true;
13019 estimate_text(&cx.text, max_width)
13020 });
13021 cx.cache = Some((max_width, size));
13022 return size;
13023 }
13024 if let (Some(width), Some(same)) = (max_width, cx.same_lines)
13025 && (same.narrowest..=same.widest).contains(&width)
13026 {
13027 cx.cache = Some((max_width, same.size));
13028 return same.size;
13029 }
13030 let greedy = engine.breaks_lines_greedily() && cx.text.max_lines == 0;
13032 let size = match cache.get(cx.layout_hash, typed) {
13033 Some(size) => size,
13034 None => {
13035 if let (Some(commit), Some((_, last))) = (cache.resizing, cx.cache)
13038 && cx.near_screen != commit
13039 {
13040 cx.held = true;
13041 return Size::new(
13042 max_width.map_or(last.width, |w| last.width.min(Points(w))),
13043 last.height,
13044 );
13045 }
13046 let prepared = cx
13047 .prepared
13048 .get_or_insert_with(|| engine.prepare_with(&cx.text, &cx.alignments, &cx.options));
13049 let ratio = cache.pixel_ratio();
13053 let on_pixels = |size: Size<Points>| {
13054 cache
13055 .on_cells(size)
13056 .unwrap_or_else(|| size.map(|v| ceil_to_pixel(v, ratio)))
13057 };
13058 let ahead = max_width.filter(|width| {
13061 greedy && !cx.no_ahead && cx.same_lines.is_some_and(|same| *width > same.widest)
13062 });
13063 let ahead = ahead.and_then(|width| {
13064 let wider = Points(width + SAME_LINES_AHEAD);
13065 let size = on_pixels(engine.measure(prepared, Some(wider)));
13066 cx.no_ahead = size.width.0 > width;
13067 (size.width.0 <= width).then_some((wider.0, size))
13068 });
13069 let (measured, size) = match ahead {
13070 Some(found) => found,
13071 None => (
13072 max_width.unwrap_or(f32::INFINITY),
13073 on_pixels(engine.measure(prepared, typed)),
13074 ),
13075 };
13076 cache.insert(cx.layout_hash, typed, size);
13077 if greedy && size.width.0 <= measured {
13078 cx.same_lines = Some(SameLines {
13079 narrowest: size.width.0,
13080 widest: measured,
13081 size,
13082 });
13083 }
13084 size
13085 }
13086 };
13087 cx.cache = Some((max_width, size));
13088 size
13089}
13090
13091fn pretty_width<M: TextEngine>(
13101 engine: &M,
13102 cx: &mut TextContext<M::Prepared>,
13103 width: Points,
13104) -> Points {
13105 if let Some(&(w, out)) = cx.pretty.as_deref()
13106 && w == width.0
13107 {
13108 return out;
13109 }
13110 let out = narrower_lines(engine, cx, width).unwrap_or(width);
13111 if let Some(p) = &mut cx.pretty {
13112 **p = (width.0, out);
13113 }
13114 out
13115}
13116
13117const PRETTY_LAST_LINE: f32 = 0.25;
13119
13120fn narrower_lines<M: TextEngine>(
13121 engine: &M,
13122 cx: &mut TextContext<M::Prepared>,
13123 width: Points,
13124) -> Option<Points> {
13125 let text = &cx.text;
13126 if text.no_wrap || text.max_lines > 0 || width <= Points::ZERO || text.text.contains('\n') {
13127 return None;
13128 }
13129 let prepared = cx
13130 .prepared
13131 .get_or_insert_with(|| engine.prepare_with(&cx.text, &cx.alignments, &cx.options));
13132 let height = engine.measure(prepared, Some(width)).height;
13133 let short = |w: Points| -> Option<bool> {
13135 let size = engine.measure(prepared, Some(w));
13136 if size.height > height {
13137 return None;
13138 }
13139 let lines = engine.lines(&engine.layout(prepared, Size { width: w, height }));
13140 let last = lines.last()?;
13141 Some(lines.len() > 1 && last.width < w * PRETTY_LAST_LINE)
13142 };
13143 if short(width) != Some(true) {
13144 return None;
13145 }
13146 let lines = engine
13150 .lines(&engine.layout(prepared, Size { width, height }))
13151 .len();
13152 let (mut lo, mut hi) = (width * ((lines - 1) as f32 / lines as f32), width);
13153 let mut found = None;
13154 for _ in 0..8 {
13155 let mid = (lo + hi) * 0.5;
13156 match short(mid) {
13157 Some(false) => {
13158 found = Some(mid);
13159 lo = mid;
13160 }
13161 Some(true) => hi = mid,
13162 None => lo = mid,
13163 }
13164 if hi - lo < Points(1.0) {
13165 break;
13166 }
13167 }
13168 found
13169}
13170
13171fn keeps_lines<P>(cx: &TextContext<P>, laid: &LaidText, size: Size<Points>) -> bool {
13172 let Some(same) = cx.same_lines else {
13173 return false;
13174 };
13175 let widths = same.narrowest..=same.widest;
13176 laid.content.size.height == size.height
13177 && widths.contains(&laid.content.size.width.0)
13178 && widths.contains(&size.width.0)
13179 && Arc::ptr_eq(&laid.text, &cx.text)
13180 && lines_start_left(&cx.text)
13181}
13182
13183fn lines_start_left(text: &AttributedText) -> bool {
13187 match text.align {
13188 TextAlign::Left => !text.text.chars().any(is_right_to_left),
13189 TextAlign::Auto => {
13190 !text.rtl
13191 && text.writing_direction != Some(true)
13192 && !text.text.chars().any(is_right_to_left)
13193 }
13194 TextAlign::Center | TextAlign::Right | TextAlign::Justify => false,
13195 }
13196}
13197
13198fn is_right_to_left(c: char) -> bool {
13200 matches!(
13201 c as u32,
13202 0x0590..=0x08FF | 0xFB1D..=0xFDFF | 0xFE70..=0xFEFF | 0x10800..=0x10FFF | 0x1E800..=0x1EFFF
13203 )
13204}
13205
13206fn definite(size: Size<Points>) -> taffy::Size<AvailableSpace> {
13207 taffy::Size {
13208 width: AvailableSpace::Definite(size.width.0),
13209 height: AvailableSpace::Definite(size.height.0),
13210 }
13211}
13212
13213fn web_url(prop: &Prop) -> Option<&str> {
13216 match prop {
13217 Prop::Native(
13218 NativeProp::Src(Some(url))
13219 | NativeProp::BaseUrl(Some(url))
13220 | NativeProp::Source(
13221 crate::WebSource::Uri(url)
13222 | crate::WebSource::Html {
13223 base_url: Some(url),
13224 ..
13225 },
13226 ),
13227 ) => Some(url),
13228 _ => None,
13229 }
13230}
13231
13232fn not_granted(what: &str, uri: &str, capability: &str) -> String {
13233 let advice = crate::access::grant_advice(uri, capability);
13234 format!("{what} {uri} is not granted: {advice}")
13235}
13236
13237fn media_not_granted(what: &str, uri: &str, base: Option<&str>) -> String {
13240 let advice = crate::access::media_grant_advice(uri, base);
13241 format!("{what} {uri} is not granted: {advice}")
13242}
13243
13244fn apply_native(control: &mut NativeProps, prop: NativeProp) {
13247 use NativeProp as P;
13248 match (control, prop) {
13249 (NativeProps::WebView(p), P::Source(v)) => p.source = v,
13250 (NativeProps::WebView(p), P::Src(Some(url))) => {
13253 if !matches!(p.source, crate::WebSource::Html { .. }) {
13254 p.source = crate::WebSource::Uri(url.clone());
13255 }
13256 p.src = Some(url);
13257 }
13258 (NativeProps::WebView(p), P::Src(None)) => {
13259 p.src = None;
13260 if matches!(p.source, crate::WebSource::Uri(_)) {
13261 p.source = crate::WebSource::None;
13262 }
13263 }
13264 (NativeProps::WebView(p), P::Html(Some(html))) => {
13265 p.source = crate::WebSource::Html {
13266 html,
13267 base_url: p.base_url.clone(),
13268 };
13269 }
13270 (NativeProps::WebView(p), P::Html(None)) => {
13271 if matches!(p.source, crate::WebSource::Html { .. }) {
13272 p.source = match &p.src {
13273 Some(url) => crate::WebSource::Uri(url.clone()),
13274 None => crate::WebSource::None,
13275 };
13276 }
13277 }
13278 (NativeProps::WebView(p), P::BaseUrl(url)) => {
13279 if let crate::WebSource::Html { base_url, .. } = &mut p.source {
13280 base_url.clone_from(&url);
13281 }
13282 p.base_url = url;
13283 }
13284 (NativeProps::WebView(p), P::AllowOrigin(v)) => {
13285 p.allow_origin = v.and_then(|o| crate::access::WebOrigin::parse(&o).ok());
13286 }
13287 (NativeProps::WebView(p), P::AllowNavigation(v)) => {
13288 p.allow_navigation = v.and_then(|h| crate::access::WebHosts::parse(&h).ok());
13289 }
13290 (NativeProps::WebView(p), P::InjectedJavaScript(v)) => p.injected_js = v,
13291 (NativeProps::WebView(p), P::InjectedJavaScriptBefore(v)) => p.injected_js_before = v,
13292 (NativeProps::WebView(p), P::UserAgent(v)) => p.user_agent = v,
13293 (NativeProps::WebView(p), P::Scrollable(v)) => p.scrollable = v,
13294 (NativeProps::WebView(p), P::JavaScriptEnabled(v)) => p.javascript_enabled = v,
13295 (NativeProps::WebView(p), P::BackForwardGestures(v)) => p.back_forward_gestures = v,
13296 (NativeProps::WebView(p), P::Incognito(v)) => p.incognito = v,
13297 (NativeProps::WebView(p), P::Zoomable(v)) => p.zoomable = v,
13298 (NativeProps::WebView(p), P::UrlSchemes(v)) => p.url_schemes = v,
13299 (NativeProps::WebView(p), P::DeferDownloads(v)) => p.defer_downloads = v,
13300 (NativeProps::Video(p), P::Source(v)) => {
13301 p.source = match v {
13302 crate::WebSource::Uri(uri) => Some(uri),
13303 _ => None,
13304 }
13305 }
13306 (NativeProps::Video(p), P::Src(v)) => p.source = v,
13307 (NativeProps::Video(p), P::Poster(v)) => p.poster = v,
13308 (NativeProps::Video(p), P::Paused(v)) => p.paused = v,
13309 (NativeProps::Video(p), P::Muted(v)) => p.muted = v,
13310 (NativeProps::Video(p), P::Volume(v)) => p.volume = v.clamp(0.0, 1.0),
13311 (NativeProps::Video(p), P::Rate(v)) => p.rate = v.max(0.0),
13312 (NativeProps::Video(p), P::Repeat(v)) => p.repeat = v,
13313 (NativeProps::Video(p), P::VideoResizeMode(v)) => p.resize_mode = v,
13314 (NativeProps::Video(p), P::Controls(v)) => p.controls = v,
13315 (NativeProps::Video(p), P::ProgressInterval(v)) => p.progress_interval_ms = v.max(16.0),
13316 (NativeProps::Video(p), P::AudioSession(v)) => p.audio_session = v,
13317 _ => {}
13318 }
13319}
13320
13321fn scaled(mut style: ResolvedTextStyle, multiplier: f32) -> ResolvedTextStyle {
13323 if multiplier != 1.0 {
13324 style.font_size *= multiplier;
13325 style.line_height *= multiplier;
13326 }
13327 style
13328}
13329
13330fn root_style(viewport: Size<Points>) -> taffy::Style {
13331 let mut style = taffy::Style {
13332 size: taffy::Size {
13333 width: taffy::Dimension::length(viewport.width.0),
13334 height: taffy::Dimension::length(viewport.height.0),
13335 },
13336 ..Style::default().layout
13337 };
13338 crate::style::resolve_normal_alignment(&mut style);
13339 style
13340}
13341
13342fn text_layout_hash(
13345 alignments: &crate::AttachmentAlignments,
13346 text: &crate::AttributedText,
13347 options: &crate::TextOptions,
13348) -> u64 {
13349 use std::hash::{Hash as _, Hasher as _};
13350 let mut h = std::collections::hash_map::DefaultHasher::new();
13351 alignments.layout_hash(text).hash(&mut h);
13352 options.indent.map(|indent| indent.0.to_bits()).hash(&mut h);
13353 h.finish()
13354}
13355
13356fn directed_align(align: TextAlign, rtl: bool) -> TextAlign {
13359 match (align, rtl) {
13360 (TextAlign::Left, true) => TextAlign::Right,
13361 (TextAlign::Right, true) => TextAlign::Left,
13362 (align, _) => align,
13363 }
13364}
13365
13366const HANDLED: [EventKind; 7] = [
13371 EventKind::PanStart,
13372 EventKind::PanEnd,
13373 EventKind::PinchStart,
13374 EventKind::PinchEnd,
13375 EventKind::RotationStart,
13376 EventKind::RotationEnd,
13377 EventKind::Touch,
13378];
13379
13380const PRESSES: [EventKind; 4] = [
13381 EventKind::Press,
13382 EventKind::LongPress,
13383 EventKind::PressDown,
13384 EventKind::PressUp,
13385];
13386
13387const DISABLED_OFF: [EventKind; 8] = [
13389 EventKind::Press,
13390 EventKind::LongPress,
13391 EventKind::PressDown,
13392 EventKind::PressUp,
13393 EventKind::ContextMenu,
13394 EventKind::FileDragEnter,
13395 EventKind::FileDragLeave,
13396 EventKind::FileDrop,
13397];
13398
13399fn disabling_changes(events: EventMask) -> bool {
13401 DISABLED_OFF.iter().any(|&e| events.contains(e))
13402}
13403
13404fn span_padding(node: &Node, rtl: bool) -> (f32, f32) {
13408 let Some(style) = node.base_layout.as_deref() else {
13409 return (0.0, 0.0);
13410 };
13411 let len = |p: taffy::LengthPercentage| match p.into_raw().tag() {
13412 taffy::CompactLength::LENGTH_TAG => p.into_raw().value().max(0.0),
13413 _ => 0.0,
13414 };
13415 let (left, right) = (len(style.padding.left), len(style.padding.right));
13416 if rtl { (right, left) } else { (left, right) }
13417}
13418
13419fn span_vertical_padding(node: &Node) -> (Points, Points) {
13423 let Some(style) = node.base_layout.as_deref() else {
13424 return (Points::ZERO, Points::ZERO);
13425 };
13426 let len = |p: taffy::LengthPercentage| match p.into_raw().tag() {
13427 taffy::CompactLength::LENGTH_TAG => Points(p.into_raw().value().max(0.0)),
13428 _ => Points::ZERO,
13429 };
13430 (len(style.padding.top), len(style.padding.bottom))
13431}
13432
13433fn span_background(style: &ViewStyle, node: NodeId) -> Option<crate::text::TextBackground> {
13435 (style.background_color.0 & 0xff != 0).then_some(crate::text::TextBackground {
13436 color: style.background_color,
13437 radius: style.border_radius.max(Points::ZERO),
13438 node,
13439 top: Points::ZERO,
13440 bottom: Points::ZERO,
13441 })
13442}
13443
13444fn pressable(events: EventMask) -> bool {
13446 PRESSES.iter().any(|&e| events.contains(e))
13447}
13448
13449fn broken_runs(content: &str) -> std::borrow::Cow<'_, str> {
13460 let mut broken: Option<String> = None;
13461 let (mut start, mut from) = (0, 0);
13462 for (end, _) in unicode_linebreak::linebreaks(content) {
13463 let mut run = 0;
13464 for (offset, c) in content[start..end].char_indices() {
13465 let i = start + offset;
13466 if run == MEASURED_RUN && i + c.len_utf8() < end {
13469 let broken = broken.get_or_insert_with(|| {
13470 String::with_capacity(content.len() + content.len() / MEASURED_RUN)
13471 });
13472 broken.push_str(&content[from..i]);
13473 broken.push('\n');
13474 (run, from) = (0, i);
13475 }
13476 run += 1;
13477 }
13478 start = end;
13479 }
13480 match broken {
13481 Some(mut broken) => {
13482 broken.push_str(&content[from..]);
13483 broken.into()
13484 }
13485 None => content.into(),
13486 }
13487}
13488
13489trait StyleSlot<T: SharedDefault>: Sized {
13495 fn get(&self) -> &T;
13496 fn same(&self, held: &Sparse<T>) -> bool;
13498 fn install(self, held: &mut Sparse<T>);
13499}
13500
13501impl<T: SharedDefault + Clone> StyleSlot<T> for T {
13502 fn get(&self) -> &T {
13503 self
13504 }
13505
13506 fn same(&self, held: &Sparse<T>) -> bool {
13507 **held == *self
13508 }
13509
13510 fn install(self, held: &mut Sparse<T>) {
13511 held.set(self);
13512 }
13513}
13514
13515impl<T: SharedDefault + Clone> StyleSlot<T> for Option<Rc<T>> {
13516 fn get(&self) -> &T {
13517 self.as_deref().unwrap_or_else(|| T::shared_default())
13518 }
13519
13520 fn same(&self, held: &Sparse<T>) -> bool {
13521 match (&held.0, self) {
13522 (None, None) => true,
13523 (Some(a), Some(b)) => Rc::ptr_eq(a, b) || **a == **b,
13524 (Some(a), None) => **a == *T::shared_default(),
13525 (None, Some(b)) => *T::shared_default() == **b,
13526 }
13527 }
13528
13529 fn install(self, held: &mut Sparse<T>) {
13530 held.0 = self;
13531 }
13532}
13533
13534trait LayoutSlot: Sized {
13537 fn get(&self) -> &taffy::Style;
13538 fn to_mut(&mut self) -> &mut taffy::Style;
13540 fn into_owned(self) -> taffy::Style;
13541 fn set_on<C>(self, tree: &mut LayoutTree<C>, node: LayoutId) -> bool;
13543}
13544
13545impl LayoutSlot for taffy::Style {
13546 fn get(&self) -> &taffy::Style {
13547 self
13548 }
13549
13550 fn to_mut(&mut self) -> &mut taffy::Style {
13551 self
13552 }
13553
13554 fn into_owned(self) -> taffy::Style {
13555 self
13556 }
13557
13558 fn set_on<C>(self, tree: &mut LayoutTree<C>, node: LayoutId) -> bool {
13559 tree.set_style(node, self)
13560 }
13561}
13562
13563impl LayoutSlot for Rc<taffy::Style> {
13564 fn get(&self) -> &taffy::Style {
13565 self
13566 }
13567
13568 fn to_mut(&mut self) -> &mut taffy::Style {
13569 Rc::make_mut(self)
13570 }
13571
13572 fn into_owned(self) -> taffy::Style {
13573 Rc::unwrap_or_clone(self)
13574 }
13575
13576 fn set_on<C>(self, tree: &mut LayoutTree<C>, node: LayoutId) -> bool {
13577 tree.set_style_shared(node, self)
13578 }
13579}
13580
13581struct StyleRecord<L, V, X> {
13584 layout: L,
13585 view: V,
13586 text: X,
13587 paint: Option<Rc<PaintStyle>>,
13588 animated: Vec<(AnimationProp, crate::animation::NodeId)>,
13589 sticky: Option<taffy::Rect<taffy::LengthPercentageAuto>>,
13591 perspective: Option<Points>,
13592 object_fit: Option<ResizeMode>,
13593 wants_fixed: bool,
13594 env: crate::style::EnvEdges,
13595 z_index: i32,
13596 vertical_align: crate::style::VerticalAlign,
13597 has_logical: bool,
13598 rtl: bool,
13599}
13600
13601fn prepare_layout(
13607 layout: &mut taffy::Style,
13608 view: &mut ViewStyle,
13609 logical: &crate::style::Logical,
13610 rtl: bool,
13611 sticky: bool,
13612) -> Option<taffy::Rect<taffy::LengthPercentageAuto>> {
13613 crate::style::resolve_normal_alignment(layout);
13614 crate::style::apply_direction(layout, view, logical, rtl);
13615 sticky.then(|| {
13616 let auto = taffy::LengthPercentageAuto::auto();
13617 std::mem::replace(
13618 &mut layout.inset,
13619 taffy::Rect {
13620 left: auto,
13621 right: auto,
13622 top: auto,
13623 bottom: auto,
13624 },
13625 )
13626 })
13627}
13628
13629fn clip_overflow(layout: &mut taffy::Style, clip: bool) {
13639 let clip = if clip {
13640 taffy::Overflow::Clip
13641 } else {
13642 taffy::Overflow::Visible
13643 };
13644 layout.overflow = taffy::Point { x: clip, y: clip };
13645}
13646
13647fn opt_rc_eq<T: PartialEq>(a: Option<&Rc<T>>, b: Option<&Rc<T>>) -> bool {
13649 match (a, b) {
13650 (None, None) => true,
13651 (Some(a), Some(b)) => Rc::ptr_eq(a, b) || **a == **b,
13652 _ => false,
13653 }
13654}
13655
13656fn leaf_context<P>(kind: Kind) -> Option<LeafContext<P>> {
13660 match kind {
13661 Kind::Text | Kind::Input => Some(LeafContext::Text(Box::new(TextContext::new(
13662 Arc::default(),
13663 )))),
13664 Kind::Image => Some(LeafContext::Image(None)),
13665 Kind::Native => Some(LeafContext::Native(None)),
13666 _ => None,
13667 }
13668}
13669
13670enum Shown {
13673 Nothing,
13678 View(NodeId),
13680 Everywhere,
13683}
13684
13685fn shown_by(item: &MountItem) -> Shown {
13686 use MountItem as M;
13687 match item {
13688 M::Events { .. }
13689 | M::Keymap(_)
13690 | M::Gestures { .. }
13691 | M::AccessibilityLabel { .. }
13692 | M::ShaderInput { .. }
13693 | M::LayoutAnimation(_)
13694 | M::Animation(_)
13695 | M::ComponentPropSlots { .. }
13696 | M::TrackStates { .. }
13697 | M::InputContent { .. }
13698 | M::Remove { .. }
13699 | M::Delete { .. } => Shown::Nothing,
13700 M::Insert { child, .. } => Shown::View(*child),
13701 M::ProjectStates { id, .. }
13702 | M::ScrollConfig { id, .. }
13703 | M::ScrollBy { id, .. }
13704 | M::StickyCells { id, .. }
13705 | M::ScrollBehavior { id, .. }
13706 | M::Refreshing { id, .. }
13707 | M::AnimationBindings { id, .. }
13708 | M::ScreenConfig { id, .. }
13709 | M::ModalConfig { id, .. } => Shown::View(*id),
13710 M::Command { id, command } => {
13711 use crate::ops::Command as C;
13712 match command {
13713 C::ExitApp
13716 | C::PostMessage { .. }
13717 | C::SendInput { .. }
13718 | C::SetJsResponder { .. }
13719 | C::ClearJsResponder
13720 | C::Announce { .. }
13721 | C::ImageInfo { .. }
13722 | C::AccessibilityFocus
13723 | C::Measure { .. }
13724 | C::MeasureScrollPosition { .. }
13725 | C::SetClipboard { .. }
13726 | C::SetClipboardItem(_)
13727 | C::ReadClipboard { .. }
13728 | C::SetClipboardImage { .. }
13729 | C::ReadClipboardImage { .. }
13730 | C::ReadClipboardFiles { .. }
13731 | C::PickImages { .. }
13732 | C::PickFiles { .. }
13733 | C::OpenUrl { .. }
13734 | C::OpenAppSettings { .. }
13735 | C::PickScreenColor { .. }
13736 | C::RenderCanvas { .. }
13737 | C::FileRequest { .. }
13738 | C::Audio { .. }
13739 | C::Notification { .. }
13740 | C::Desktop { .. }
13741 | C::HostCall { .. }
13742 | C::HostPost { .. } => Shown::Nothing,
13743 C::Tokens { .. } => Shown::Everywhere,
13745 _ => Shown::View(*id),
13746 }
13747 }
13748 item => item.view().map_or(Shown::Everywhere, Shown::View),
13749 }
13750}
13751
13752struct TextAttachments<'a> {
13755 alignments: crate::AttachmentAlignments,
13757 spacers: Vec<u32>,
13759 baselines: &'a [(Key, Points)],
13762 next_baseline: usize,
13765}