1#![allow(non_snake_case)]
9
10use std::{
11 fmt,
12 hash::{Hash, Hasher},
13 rc::Rc,
14};
15
16use cranpose_core::hash::default;
17
18mod alignment;
19mod background;
20mod blur;
21mod chain;
22mod clickable;
23mod draw_cache;
24mod fill;
25mod focus;
26mod graphics_layer;
27mod local;
28mod offset;
29mod padding;
30pub(crate) mod pointer_input;
31mod rotary_input;
32mod scroll;
33mod selectable;
34mod semantics;
35mod shadow;
36mod size;
37mod slices;
38mod toggleable;
39mod weight;
40
41#[allow(unused_imports)]
42pub use chain::{ModifierChainHandle, ModifierChainInspectorNode, ModifierLocalsHandle};
43pub use cranpose_foundation::{
44 AnyModifierElement, DynModifierElement, FocusState, PointerEvent, PointerEventKind,
45 PointerSource, RotaryScrollEvent, SemanticsConfiguration, modifier_element,
46};
47use cranpose_foundation::{ModifierNodeElement, NodeCapabilities, ProgressBarRangeInfo};
48#[allow(unused_imports)]
49pub use cranpose_ui_graphics::{
50 BlendMode, BlurredEdgeTreatment, Brush, Color, ColorFilter, CompositingStrategy, CornerRadii,
51 CutDirection, Dp, DpOffset, EdgeInsets, GradientCutMaskSpec, GradientFadeMaskSpec,
52 GraphicsLayer, LayerShape, Point, Rect, RenderEffect, RoundedCornerShape, RuntimeShader,
53 Shadow, ShadowScope, Size, TransformOrigin,
54};
55use cranpose_ui_layout::{Alignment, HorizontalAlignment, IntrinsicSize, VerticalAlignment};
56use focus::FocusTargetElement;
57#[allow(unused_imports)]
58pub use focus::{FocusDirection, FocusRequestError, FocusRequester, FocusRequesterElement};
59pub use graphics_layer::GlassMaterial;
60pub(crate) use local::{
61 ModifierLocalAncestorResolver, ModifierLocalSource, ModifierLocalToken, ResolvedModifierLocal,
62};
63use local::{ModifierLocalConsumerElement, ModifierLocalProviderElement};
64#[allow(unused_imports)]
65pub use local::{ModifierLocalKey, ModifierLocalReadScope};
66#[allow(unused_imports)]
67pub use pointer_input::{AwaitPointerEventScope, PointerInputScope};
68pub use rotary_input::RotaryInputModifierNode;
69#[cfg(test)]
70pub(crate) use scroll::lazy_scroll_semantics;
71#[cfg(feature = "test-helpers")]
72pub use scroll::{last_fling_velocity, reset_last_fling_velocity};
73use semantics::SemanticsElement;
74pub use semantics::{
75 SemanticsRequester, SemanticsRequesterElement, collect_semantics_from_chain,
76 collect_semantics_from_modifier,
77};
78pub use slices::{
79 ModifierNodeSlices, ModifierNodeSlicesDebugStats, collect_modifier_slices,
80 collect_modifier_slices_into, collect_slices_from_modifier,
81};
82
83pub use crate::draw::{DrawCacheBuilder, DrawCommand};
84use crate::modifier_nodes::ClipToBoundsElement;
85
86#[derive(Clone, Debug, Default)]
87pub struct InspectorInfo {
88 properties: Vec<InspectorProperty>,
89}
90
91impl InspectorInfo {
92 pub fn new() -> Self {
93 Self::default()
94 }
95
96 pub fn add_property<V: Into<String>>(&mut self, name: &'static str, value: V) {
97 self.properties.push(InspectorProperty {
98 name,
99 value: value.into(),
100 });
101 }
102
103 pub fn properties(&self) -> &[InspectorProperty] {
104 &self.properties
105 }
106
107 pub fn is_empty(&self) -> bool {
108 self.properties.is_empty()
109 }
110
111 pub fn add_dimension(&mut self, name: &'static str, constraint: DimensionConstraint) {
112 self.add_property(name, describe_dimension(constraint));
113 }
114
115 pub fn add_offset_components(
116 &mut self,
117 x_name: &'static str,
118 y_name: &'static str,
119 offset: Point,
120 ) {
121 self.add_property(x_name, offset.x.to_string());
122 self.add_property(y_name, offset.y.to_string());
123 }
124
125 pub fn add_alignment<A>(&mut self, name: &'static str, alignment: A)
126 where
127 A: fmt::Debug,
128 {
129 self.add_property(name, format!("{alignment:?}"));
130 }
131}
132
133#[derive(Clone, Debug, PartialEq)]
134pub struct InspectorProperty {
135 pub name: &'static str,
136 pub value: String,
137}
138
139#[derive(Clone, Debug, PartialEq)]
140pub struct ModifierInspectorRecord {
141 pub name: &'static str,
142 pub properties: Vec<InspectorProperty>,
143}
144
145#[derive(Clone, Debug)]
146pub(crate) struct InspectorMetadata {
147 name: &'static str,
148 info: InspectorInfo,
149}
150
151impl InspectorMetadata {
152 pub(crate) fn new<F>(name: &'static str, recorder: F) -> Self
153 where
154 F: FnOnce(&mut InspectorInfo),
155 {
156 let mut info = InspectorInfo::new();
157 recorder(&mut info);
158 Self { name, info }
159 }
160
161 fn is_empty(&self) -> bool {
162 self.info.is_empty()
163 }
164
165 fn to_record(&self) -> ModifierInspectorRecord {
166 ModifierInspectorRecord {
167 name: self.name,
168 properties: self.info.properties().to_vec(),
169 }
170 }
171}
172
173fn describe_dimension(constraint: DimensionConstraint) -> String {
174 match constraint {
175 DimensionConstraint::Unspecified => "unspecified".to_string(),
176 DimensionConstraint::Points(value) => value.to_string(),
177 DimensionConstraint::Fraction(value) => format!("fraction({value})"),
178 DimensionConstraint::Intrinsic(size) => format!("intrinsic({size:?})"),
179 }
180}
181
182pub(crate) fn inspector_metadata<F>(name: &'static str, recorder: F) -> InspectorMetadata
183where
184 F: FnOnce(&mut InspectorInfo),
185{
186 if !inspector_metadata_enabled() {
187 return InspectorMetadata::new(name, |_| {});
188 }
189 InspectorMetadata::new(name, recorder)
190}
191
192pub(crate) fn modifier_debug_enabled() -> bool {
193 #[cfg(not(target_arch = "wasm32"))]
194 {
195 cranpose_core::env_flag!("COMPOSE_DEBUG_MODIFIERS")
196 }
197 #[cfg(target_arch = "wasm32")]
198 {
199 false
200 }
201}
202
203fn inspector_metadata_enabled() -> bool {
204 cfg!(test) || modifier_debug_enabled()
205}
206
207#[derive(Clone)]
208enum ModifierKind {
209 Empty,
210 Single {
211 elements: Rc<Vec<DynModifierElement>>,
212 inspector: Rc<Vec<InspectorMetadata>>,
213 },
214}
215
216const FINGERPRINT_KIND_EMPTY: u8 = 0;
217const FINGERPRINT_KIND_SINGLE: u8 = 1;
218
219const FINGERPRINT_EMPTY_STRICT_SEED: u64 = 0x243f_6a88_85a3_08d3;
220const FINGERPRINT_EMPTY_STRUCTURAL_SEED: u64 = 0x1319_8a2e_0370_7344;
221const FINGERPRINT_SINGLE_STRICT_SEED: u64 = 0xa409_3822_299f_31d0;
222const FINGERPRINT_SINGLE_STRUCTURAL_SEED: u64 = 0x082e_fa98_ec4e_6c89;
223const FINGERPRINT_SEQUENCE_MUL: u64 = 0x9e37_79b1_85eb_ca87;
224const FINGERPRINT_STRICT_UPDATE_TAG: u64 = 0xdbe6_d5d5_fe4c_ce2f;
225const FINGERPRINT_STRUCTURAL_DRAW_ONLY_TAG: u64 = 0x94d0_49bb_1331_11eb;
226
227#[derive(Clone, Copy, Debug, PartialEq, Eq)]
228struct ModifierFingerprints {
229 strict: u64,
230 structural: u64,
231}
232
233#[inline]
234fn mix_fingerprint_bits(mut value: u64) -> u64 {
235 value ^= value >> 33;
236 value = value.wrapping_mul(0xff51_afd7_ed55_8ccd);
237 value ^= value >> 33;
238 value = value.wrapping_mul(0xc4ce_b9fe_1a85_ec53);
239 value ^ (value >> 33)
240}
241
242#[inline]
243fn fold_fingerprint(state: u64, value: u64) -> u64 {
244 mix_fingerprint_bits(state ^ value.wrapping_add(FINGERPRINT_SEQUENCE_MUL))
245 .wrapping_mul(FINGERPRINT_SEQUENCE_MUL)
246}
247
248#[inline]
249fn empty_fingerprints() -> ModifierFingerprints {
250 ModifierFingerprints {
251 strict: fold_fingerprint(FINGERPRINT_EMPTY_STRICT_SEED, FINGERPRINT_KIND_EMPTY as u64),
252 structural: fold_fingerprint(
253 FINGERPRINT_EMPTY_STRUCTURAL_SEED,
254 FINGERPRINT_KIND_EMPTY as u64,
255 ),
256 }
257}
258
259#[inline]
260fn single_fingerprint_seed() -> ModifierFingerprints {
261 let strict = fold_fingerprint(
262 FINGERPRINT_SINGLE_STRICT_SEED,
263 FINGERPRINT_KIND_SINGLE as u64,
264 );
265 let structural = fold_fingerprint(
266 FINGERPRINT_SINGLE_STRUCTURAL_SEED,
267 FINGERPRINT_KIND_SINGLE as u64,
268 );
269 ModifierFingerprints { strict, structural }
270}
271
272#[inline]
273fn element_common_fingerprint(element: &DynModifierElement) -> u64 {
274 let mut hasher = default::new();
275 element.element_type().hash(&mut hasher);
276 element.capabilities().bits().hash(&mut hasher);
277 hasher.finish()
278}
279
280#[inline]
281fn element_fingerprints(element: &DynModifierElement) -> ModifierFingerprints {
282 let common = element_common_fingerprint(element);
283 let requires_update = element.requires_update();
284 let strict_payload = if requires_update {
285 let element_ptr = Rc::as_ptr(element) as *const () as usize as u64;
286 element_ptr ^ FINGERPRINT_STRICT_UPDATE_TAG
287 } else {
288 element.hash_code()
289 };
290 let strict = mix_fingerprint_bits(common ^ strict_payload);
291
292 let is_draw_only = element.capabilities() == NodeCapabilities::DRAW;
293 let structural_payload = if is_draw_only {
294 FINGERPRINT_STRUCTURAL_DRAW_ONLY_TAG
295 } else {
296 element.hash_code()
297 };
298 let structural = mix_fingerprint_bits(common ^ structural_payload);
299
300 ModifierFingerprints { strict, structural }
301}
302
303#[inline]
304fn append_fingerprints(
305 mut fingerprints: ModifierFingerprints,
306 elements: &[DynModifierElement],
307) -> ModifierFingerprints {
308 for element in elements {
309 let element_fingerprints = element_fingerprints(element);
310 fingerprints.strict = fold_fingerprint(fingerprints.strict, element_fingerprints.strict);
311 fingerprints.structural =
312 fold_fingerprint(fingerprints.structural, element_fingerprints.structural);
313 }
314 fingerprints
315}
316
317fn single_fingerprints(elements: &[DynModifierElement]) -> ModifierFingerprints {
318 append_fingerprints(single_fingerprint_seed(), elements)
319}
320
321pub struct ModifierElementIterator<'a> {
322 inner: std::slice::Iter<'a, DynModifierElement>,
323}
324
325impl<'a> Iterator for ModifierElementIterator<'a> {
326 type Item = &'a DynModifierElement;
327
328 #[inline]
329 fn next(&mut self) -> Option<Self::Item> {
330 self.inner.next()
331 }
332
333 #[inline]
334 fn size_hint(&self) -> (usize, Option<usize>) {
335 self.inner.size_hint()
336 }
337}
338
339impl ExactSizeIterator for ModifierElementIterator<'_> {}
340
341pub(crate) struct ModifierInspectorIterator<'a> {
342 inner: std::slice::Iter<'a, InspectorMetadata>,
343}
344
345impl<'a> Iterator for ModifierInspectorIterator<'a> {
346 type Item = &'a InspectorMetadata;
347
348 #[inline]
349 fn next(&mut self) -> Option<Self::Item> {
350 self.inner.next()
351 }
352
353 #[inline]
354 fn size_hint(&self) -> (usize, Option<usize>) {
355 self.inner.size_hint()
356 }
357}
358
359impl ExactSizeIterator for ModifierInspectorIterator<'_> {}
360
361#[derive(Clone)]
379pub struct Modifier {
380 kind: ModifierKind,
381 strict_fingerprint: u64,
382 structural_fingerprint: u64,
383 element_count: usize,
384}
385
386impl Default for Modifier {
387 fn default() -> Self {
388 let fingerprints = empty_fingerprints();
389 Self {
390 kind: ModifierKind::Empty,
391 strict_fingerprint: fingerprints.strict,
392 structural_fingerprint: fingerprints.structural,
393 element_count: 0,
394 }
395 }
396}
397
398impl Modifier {
399 pub fn empty() -> Self {
400 Self::default()
401 }
402
403 pub fn from_element<E>(element: E) -> Self
405 where
406 E: ModifierNodeElement,
407 {
408 Self::with_element(element)
409 }
410
411 pub fn clip_to_bounds(self) -> Self {
415 let modifier = Self::with_element(ClipToBoundsElement::new()).with_inspector_metadata(
416 inspector_metadata("clipToBounds", |info| {
417 info.add_property("clipToBounds", "true");
418 }),
419 );
420 self.then(modifier)
421 }
422
423 pub fn modifier_local_provider<T, F>(self, key: ModifierLocalKey<T>, value: F) -> Self
424 where
425 T: 'static,
426 F: Fn() -> T + 'static,
427 {
428 let element = ModifierLocalProviderElement::new(key, value);
429 let modifier = Modifier::from_parts(vec![modifier_element(element)]);
430 self.then(modifier)
431 }
432
433 pub fn modifier_local_consumer<F>(self, consumer: F) -> Self
434 where
435 F: for<'scope> Fn(&mut ModifierLocalReadScope<'scope>) + 'static,
436 {
437 let element = ModifierLocalConsumerElement::new(consumer);
438 let modifier = Modifier::from_parts(vec![modifier_element(element)]);
439 self.then(modifier)
440 }
441
442 pub fn semantics<F>(self, recorder: F) -> Self
443 where
444 F: Fn(&mut SemanticsConfiguration) + 'static,
445 {
446 let recorder: std::rc::Rc<dyn Fn(&mut SemanticsConfiguration)> = std::rc::Rc::new(recorder);
447 let metadata = if inspector_metadata_enabled() {
448 let mut preview = SemanticsConfiguration::default();
449 recorder(&mut preview);
450 let description = preview.content_description.clone();
451 let state_description = preview.state_description.clone();
452 let role = preview.role;
453 let is_clickable = preview.is_activatable();
454 let canvas_children = preview.canvas_children.len();
455 inspector_metadata("semantics", move |info| {
456 if let Some(desc) = &description {
457 info.add_property("contentDescription", desc.clone());
458 }
459 if let Some(state) = &state_description {
460 info.add_property("stateDescription", state.clone());
461 }
462 if let Some(role) = role {
463 info.add_property("role", format!("{role:?}"));
464 }
465 if is_clickable {
466 info.add_property("isClickable", "true");
467 }
468 if canvas_children > 0 {
469 info.add_property("canvasSemanticsChildren", canvas_children.to_string());
470 }
471 })
472 } else {
473 inspector_metadata("semantics", |_| {})
474 };
475 let element = SemanticsElement::new(recorder);
476 let modifier =
477 Modifier::from_parts(vec![modifier_element(element)]).with_inspector_metadata(metadata);
478 self.then(modifier)
479 }
480
481 pub fn progress_semantics(self, current: f32, start: f32, end: f32, steps: u32) -> Self {
490 let info = ProgressBarRangeInfo::new(current, start, end, steps);
491 self.semantics(move |config| config.progress = Some(info))
492 }
493
494 pub fn pane_title(self, title: impl Into<String>) -> Self {
498 let title = title.into();
499 self.semantics(move |config| config.pane_title = Some(title.clone()))
500 }
501
502 pub fn selectable_group(self) -> Self {
507 self.semantics(|config| config.selectable_group = true)
508 }
509
510 pub fn merge_descendants(self) -> Self {
515 self.semantics(|config| config.merge_descendants = true)
516 }
517
518 pub fn hide_from_accessibility(self) -> Self {
523 self.semantics(|config| config.hidden = true)
524 }
525
526 pub fn heading(self) -> Self {
531 self.role(cranpose_foundation::SemanticsWidgetRole::Header)
532 }
533
534 pub fn role(self, role: cranpose_foundation::SemanticsWidgetRole) -> Self {
539 self.semantics(move |config| config.role = Some(role))
540 }
541
542 pub fn live_region(self, mode: cranpose_foundation::LiveRegionMode) -> Self {
548 self.semantics(move |config| config.live_region = Some(mode))
549 }
550
551 pub fn content_description(self, description: impl Into<String>) -> Self {
556 let description = description.into();
557 self.semantics(move |config| config.content_description = Some(description.clone()))
558 }
559
560 pub fn focus_target(self) -> Self {
566 let element = FocusTargetElement::new();
567 let modifier = Modifier::from_parts(vec![modifier_element(element)]);
568 self.then(modifier)
569 }
570
571 pub fn on_focus_changed<F>(self, callback: F) -> Self
576 where
577 F: Fn(FocusState) + 'static,
578 {
579 let element = FocusTargetElement::with_callback(callback);
580 let modifier = Modifier::from_parts(vec![modifier_element(element)]);
581 self.then(modifier)
582 }
583
584 pub fn focus_requester(self, requester: &FocusRequester) -> Self {
591 let element = FocusRequesterElement::new(requester.clone());
592 let modifier = Modifier::from_parts(vec![modifier_element(element)]);
593 self.then(modifier)
594 }
595
596 pub fn focusable(self) -> Self {
605 self.focus_target()
606 }
607
608 pub fn semantics_requester(self, requester: &SemanticsRequester) -> Self {
616 let element = SemanticsRequesterElement::new(requester.clone());
617 let modifier = Modifier::from_parts(vec![modifier_element(element)]);
618 self.then(modifier)
619 }
620
621 pub fn debug_chain(self, tag: &'static str) -> Self {
639 use cranpose_foundation::{ModifierNode, ModifierNodeContext, NodeCapabilities, NodeState};
640
641 #[derive(Clone)]
642 struct DebugChainElement {
643 tag: &'static str,
644 }
645
646 impl fmt::Debug for DebugChainElement {
647 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
648 f.debug_struct("DebugChainElement")
649 .field("tag", &self.tag)
650 .finish()
651 }
652 }
653
654 impl PartialEq for DebugChainElement {
655 fn eq(&self, other: &Self) -> bool {
656 self.tag == other.tag
657 }
658 }
659
660 impl Eq for DebugChainElement {}
661
662 impl std::hash::Hash for DebugChainElement {
663 fn hash<H: std::hash::Hasher>(&self, state: &mut H) {
664 self.tag.hash(state);
665 }
666 }
667
668 impl ModifierNodeElement for DebugChainElement {
669 type Node = DebugChainNode;
670
671 fn create(&self) -> Self::Node {
672 DebugChainNode::new(self.tag)
673 }
674
675 fn update(&self, node: &mut Self::Node) {
676 node.tag = self.tag;
677 }
678
679 fn capabilities(&self) -> NodeCapabilities {
680 NodeCapabilities::empty()
681 }
682 }
683
684 struct DebugChainNode {
685 tag: &'static str,
686 state: NodeState,
687 }
688
689 impl DebugChainNode {
690 fn new(tag: &'static str) -> Self {
691 Self {
692 tag,
693 state: NodeState::new(),
694 }
695 }
696 }
697
698 impl ModifierNode for DebugChainNode {
699 fn on_attach(&mut self, _context: &mut dyn ModifierNodeContext) {
700 eprintln!("[debug_chain:{}] Modifier chain attached", self.tag);
701 }
702
703 fn on_detach(&mut self) {
704 eprintln!("[debug_chain:{}] Modifier chain detached", self.tag);
705 }
706
707 fn on_reset(&mut self) {
708 eprintln!("[debug_chain:{}] Modifier chain reset", self.tag);
709 }
710 }
711
712 impl cranpose_foundation::DelegatableNode for DebugChainNode {
713 fn node_state(&self) -> &NodeState {
714 &self.state
715 }
716 }
717
718 let element = DebugChainElement { tag };
719 let modifier = Modifier::from_parts(vec![modifier_element(element)]);
720 self.then(modifier)
721 .with_inspector_metadata(inspector_metadata("debugChain", move |info| {
722 info.add_property("tag", tag);
723 }))
724 }
725
726 pub fn then(&self, next: Modifier) -> Modifier {
731 if self.is_trivially_empty() {
732 return next;
733 }
734 if next.is_trivially_empty() {
735 return self.clone();
736 }
737
738 let Some((self_elements, self_inspector)) = self.single_parts() else {
739 return next;
740 };
741 let Some((next_elements, next_inspector)) = next.single_parts() else {
742 return self.clone();
743 };
744
745 let mut merged_elements = Vec::with_capacity(self_elements.len() + next_elements.len());
746 merged_elements.extend_from_slice(self_elements);
747 merged_elements.extend_from_slice(next_elements);
748
749 let mut merged_inspector = Vec::with_capacity(self_inspector.len() + next_inspector.len());
750 merged_inspector.extend_from_slice(self_inspector);
751 merged_inspector.extend_from_slice(next_inspector);
752
753 let fingerprints = append_fingerprints(
754 ModifierFingerprints {
755 strict: self.strict_fingerprint,
756 structural: self.structural_fingerprint,
757 },
758 next_elements,
759 );
760 Modifier {
761 kind: ModifierKind::Single {
762 elements: Rc::new(merged_elements),
763 inspector: Rc::new(merged_inspector),
764 },
765 strict_fingerprint: fingerprints.strict,
766 structural_fingerprint: fingerprints.structural,
767 element_count: self.element_count + next.element_count,
768 }
769 }
770
771 pub(crate) fn iter_elements(&self) -> ModifierElementIterator<'_> {
772 match &self.kind {
773 ModifierKind::Empty => ModifierElementIterator { inner: [].iter() },
774 ModifierKind::Single { elements, .. } => ModifierElementIterator {
775 inner: elements.iter(),
776 },
777 }
778 }
779
780 pub(crate) fn iter_inspector_metadata(&self) -> ModifierInspectorIterator<'_> {
781 match &self.kind {
782 ModifierKind::Empty => ModifierInspectorIterator { inner: [].iter() },
783 ModifierKind::Single { inspector, .. } => ModifierInspectorIterator {
784 inner: inspector.iter(),
785 },
786 }
787 }
788
789 #[cfg(test)]
790 pub(crate) fn elements(&self) -> Vec<DynModifierElement> {
791 match &self.kind {
792 ModifierKind::Empty => Vec::new(),
793 ModifierKind::Single { elements, .. } => elements.as_ref().clone(),
794 }
795 }
796
797 pub(crate) fn inspector_metadata(&self) -> Vec<InspectorMetadata> {
798 match &self.kind {
799 ModifierKind::Empty => Vec::new(),
800 ModifierKind::Single { inspector, .. } => inspector.as_ref().clone(),
801 }
802 }
803
804 pub(crate) fn rehouse_for_live_compaction(&self) -> Self {
805 match &self.kind {
806 ModifierKind::Empty => Self::default(),
807 ModifierKind::Single {
808 elements,
809 inspector,
810 } => Self {
811 kind: ModifierKind::Single {
812 elements: Rc::new(elements.iter().cloned().collect()),
813 inspector: Rc::new(inspector.as_ref().clone()),
814 },
815 strict_fingerprint: self.strict_fingerprint,
816 structural_fingerprint: self.structural_fingerprint,
817 element_count: self.element_count,
818 },
819 }
820 }
821
822 pub fn total_padding(&self) -> f32 {
823 let padding = self.padding_values();
824 padding
825 .left
826 .max(padding.right)
827 .max(padding.top)
828 .max(padding.bottom)
829 }
830
831 pub fn explicit_size(&self) -> Option<Size> {
832 let props = self.layout_properties();
833 match (props.width, props.height) {
834 (DimensionConstraint::Points(width), DimensionConstraint::Points(height)) => {
835 Some(Size { width, height })
836 }
837 _ => None,
838 }
839 }
840
841 pub fn padding_values(&self) -> EdgeInsets {
842 self.resolved_modifiers().padding()
843 }
844
845 pub(crate) fn layout_properties(&self) -> LayoutProperties {
846 self.resolved_modifiers().layout_properties()
847 }
848
849 pub fn box_alignment(&self) -> Option<Alignment> {
850 self.layout_properties().box_alignment()
851 }
852
853 pub fn column_alignment(&self) -> Option<HorizontalAlignment> {
854 self.layout_properties().column_alignment()
855 }
856
857 pub fn row_alignment(&self) -> Option<VerticalAlignment> {
858 self.layout_properties().row_alignment()
859 }
860
861 pub fn draw_commands(&self) -> Vec<DrawCommand> {
862 collect_slices_from_modifier(self).draw_commands().to_vec()
863 }
864
865 pub fn clips_to_bounds(&self) -> bool {
866 collect_slices_from_modifier(self).clip_to_bounds()
867 }
868
869 pub fn collect_inspector_records(&self) -> Vec<ModifierInspectorRecord> {
871 self.inspector_metadata()
872 .iter()
873 .map(|metadata| metadata.to_record())
874 .collect()
875 }
876
877 pub fn resolved_modifiers(&self) -> ResolvedModifiers {
878 let mut handle = ModifierChainHandle::new();
879 let _ = handle.update(self);
880 handle.resolved_modifiers()
881 }
882
883 pub(crate) fn with_element<E>(element: E) -> Self
884 where
885 E: ModifierNodeElement,
886 {
887 let dyn_element = modifier_element(element);
888 Self::from_parts(vec![dyn_element])
889 }
890
891 pub(crate) fn from_parts(elements: Vec<DynModifierElement>) -> Self {
892 if elements.is_empty() {
893 Self::default()
894 } else {
895 let element_count = elements.len();
896 let fingerprints = single_fingerprints(elements.as_slice());
897 Self {
898 kind: ModifierKind::Single {
899 elements: Rc::new(elements),
900 inspector: Rc::new(Vec::new()),
901 },
902 strict_fingerprint: fingerprints.strict,
903 structural_fingerprint: fingerprints.structural,
904 element_count,
905 }
906 }
907 }
908
909 fn is_trivially_empty(&self) -> bool {
910 matches!(self.kind, ModifierKind::Empty)
911 }
912
913 fn single_parts(&self) -> Option<(&[DynModifierElement], &[InspectorMetadata])> {
914 match &self.kind {
915 ModifierKind::Empty => None,
916 ModifierKind::Single {
917 elements,
918 inspector,
919 } => Some((elements.as_slice(), inspector.as_slice())),
920 }
921 }
922
923 pub(crate) fn with_inspector_metadata(self, metadata: InspectorMetadata) -> Self {
924 if metadata.is_empty() {
925 return self;
926 }
927 match self.kind {
928 ModifierKind::Empty => self,
929 ModifierKind::Single {
930 elements,
931 inspector,
932 } => {
933 let mut new_inspector = inspector.as_ref().clone();
934 new_inspector.push(metadata);
935 Self {
936 kind: ModifierKind::Single {
937 elements,
938 inspector: Rc::new(new_inspector),
939 },
940 strict_fingerprint: self.strict_fingerprint,
941 structural_fingerprint: self.structural_fingerprint,
942 element_count: self.element_count,
943 }
944 }
945 }
946 }
947
948 pub fn structural_eq(&self, other: &Self) -> bool {
953 self.eq_internal(other, false)
954 }
955
956 fn eq_internal(&self, other: &Self, consider_always_update: bool) -> bool {
957 if self.element_count != other.element_count {
958 return false;
959 }
960 if consider_always_update {
961 if self.strict_fingerprint != other.strict_fingerprint {
962 return false;
963 }
964 } else if self.structural_fingerprint != other.structural_fingerprint {
965 return false;
966 }
967
968 match (&self.kind, &other.kind) {
969 (ModifierKind::Empty, ModifierKind::Empty) => true,
970 (
971 ModifierKind::Single {
972 elements: e1,
973 inspector: _,
974 },
975 ModifierKind::Single {
976 elements: e2,
977 inspector: _,
978 },
979 ) => {
980 if Rc::ptr_eq(e1, e2) {
981 return true;
982 }
983
984 if e1.len() != e2.len() {
985 return false;
986 }
987
988 for (a, b) in e1.iter().zip(e2.iter()) {
989 if !consider_always_update
990 && a.element_type() == b.element_type()
991 && a.capabilities() == NodeCapabilities::DRAW
992 && b.capabilities() == NodeCapabilities::DRAW
993 {
994 continue;
995 }
996
997 if consider_always_update && (a.requires_update() || b.requires_update()) {
998 if !Rc::ptr_eq(a, b) {
999 return false;
1000 }
1001 continue;
1002 }
1003
1004 if !a.equals_element(&**b) {
1005 return false;
1006 }
1007 }
1008
1009 true
1010 }
1011 _ => false,
1012 }
1013 }
1014}
1015
1016impl PartialEq for Modifier {
1017 fn eq(&self, other: &Self) -> bool {
1018 self.eq_internal(other, true)
1019 }
1020}
1021
1022impl Eq for Modifier {}
1023
1024impl fmt::Display for Modifier {
1025 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1026 match &self.kind {
1027 ModifierKind::Empty => write!(f, "Modifier.empty"),
1028 ModifierKind::Single { elements, .. } => {
1029 if elements.is_empty() {
1030 return write!(f, "Modifier.empty");
1031 }
1032 write!(f, "Modifier[")?;
1033 for (index, element) in elements.iter().enumerate() {
1034 if index > 0 {
1035 write!(f, ", ")?;
1036 }
1037 let name = element.inspector_name();
1038 let mut properties = Vec::new();
1039 element.record_inspector_properties(&mut |prop, value| {
1040 properties.push(format!("{prop}={value}"));
1041 });
1042 if properties.is_empty() {
1043 write!(f, "{name}")?;
1044 } else {
1045 write!(f, "{name}({})", properties.join(", "))?;
1046 }
1047 }
1048 write!(f, "]")
1049 }
1050 }
1051 }
1052}
1053
1054impl fmt::Debug for Modifier {
1055 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1056 fmt::Display::fmt(self, f)
1057 }
1058}
1059
1060#[derive(Clone, Copy, Debug, PartialEq)]
1061pub struct ResolvedBackground {
1062 color: Color,
1063 shape: Option<RoundedCornerShape>,
1064}
1065
1066impl ResolvedBackground {
1067 pub fn new(color: Color, shape: Option<RoundedCornerShape>) -> Self {
1068 Self { color, shape }
1069 }
1070
1071 pub fn color(&self) -> Color {
1072 self.color
1073 }
1074
1075 pub fn shape(&self) -> Option<RoundedCornerShape> {
1076 self.shape
1077 }
1078
1079 pub fn set_shape(&mut self, shape: Option<RoundedCornerShape>) {
1080 self.shape = shape;
1081 }
1082}
1083
1084#[derive(Clone, Copy, Debug, PartialEq, Default)]
1085pub struct ResolvedModifiers {
1086 padding: EdgeInsets,
1087 layout: LayoutProperties,
1088 offset: Point,
1089}
1090
1091impl ResolvedModifiers {
1092 pub fn padding(&self) -> EdgeInsets {
1093 self.padding
1094 }
1095
1096 pub fn layout_properties(&self) -> LayoutProperties {
1097 self.layout
1098 }
1099
1100 pub fn offset(&self) -> Point {
1101 self.offset
1102 }
1103
1104 pub(crate) fn set_padding(&mut self, padding: EdgeInsets) {
1105 self.padding = padding;
1106 }
1107
1108 pub(crate) fn set_layout_properties(&mut self, layout: LayoutProperties) {
1109 self.layout = layout;
1110 }
1111
1112 pub(crate) fn set_offset(&mut self, offset: Point) {
1113 self.offset = offset;
1114 }
1115}
1116
1117#[derive(Clone, Copy, Debug, Default, PartialEq)]
1118pub enum DimensionConstraint {
1119 #[default]
1120 Unspecified,
1121 Points(f32),
1122 Fraction(f32),
1123 Intrinsic(IntrinsicSize),
1124}
1125
1126#[derive(Clone, Copy, Debug, Default, PartialEq)]
1127pub struct LayoutWeight {
1128 pub weight: f32,
1129 pub fill: bool,
1130}
1131
1132#[derive(Clone, Copy, Debug, Default, PartialEq)]
1133pub struct LayoutProperties {
1134 padding: EdgeInsets,
1135 width: DimensionConstraint,
1136 height: DimensionConstraint,
1137 min_width: Option<f32>,
1138 min_height: Option<f32>,
1139 max_width: Option<f32>,
1140 max_height: Option<f32>,
1141 weight: Option<LayoutWeight>,
1142 box_alignment: Option<Alignment>,
1143 column_alignment: Option<HorizontalAlignment>,
1144 row_alignment: Option<VerticalAlignment>,
1145}
1146
1147impl LayoutProperties {
1148 pub fn padding(&self) -> EdgeInsets {
1149 self.padding
1150 }
1151
1152 pub fn width(&self) -> DimensionConstraint {
1153 self.width
1154 }
1155
1156 pub fn height(&self) -> DimensionConstraint {
1157 self.height
1158 }
1159
1160 pub fn min_width(&self) -> Option<f32> {
1161 self.min_width
1162 }
1163
1164 pub fn min_height(&self) -> Option<f32> {
1165 self.min_height
1166 }
1167
1168 pub fn max_width(&self) -> Option<f32> {
1169 self.max_width
1170 }
1171
1172 pub fn max_height(&self) -> Option<f32> {
1173 self.max_height
1174 }
1175
1176 pub fn weight(&self) -> Option<LayoutWeight> {
1177 self.weight
1178 }
1179
1180 pub fn box_alignment(&self) -> Option<Alignment> {
1181 self.box_alignment
1182 }
1183
1184 pub fn column_alignment(&self) -> Option<HorizontalAlignment> {
1185 self.column_alignment
1186 }
1187
1188 pub fn row_alignment(&self) -> Option<VerticalAlignment> {
1189 self.row_alignment
1190 }
1191}
1192
1193#[cfg(test)]
1194#[path = "tests/modifier_tests.rs"]
1195mod tests;