1use std::{
2 hash::{Hash, Hasher},
3 iter, mem,
4 ops::Range,
5 sync::Arc,
6};
7
8use crate::{
9 AbsoluteLength, App, Background, BackgroundTag, BorderStyle, Bounds, ContentMask, CornerShape,
10 CornerShapes, Corners,
11 CornersRefinement, CursorStyle, DefiniteLength, DevicePixels, Edges, EdgesRefinement,
12 EffectCrossFade, EffectSpec, Font,
13 FontFallbacks, FontFeatures, FontStyle, FontWeight, GridLocation, Hsla, Length, Pixels, Point,
14 PointRefinement, Rgba, SharedString, Size, SizeRefinement, Styled, TextRun, Window, black, phi,
15 TransformSpec, TransformationMatrix, VnClipOutline, VnFillRule, VnPathVerb, point, px, quad,
16 rems, size,
17};
18use collections::HashSet;
19use refineable::Refineable;
20#[cfg(feature = "schemars")]
21use schemars::JsonSchema;
22use serde::{Deserialize, Serialize};
23
24#[cfg(debug_assertions)]
28pub struct DebugBelow;
29
30#[cfg(debug_assertions)]
31impl crate::Global for DebugBelow {}
32
33pub enum ObjectFit {
35 Fill,
37 Contain,
39 Cover,
41 ScaleDown,
43 None,
45}
46
47impl ObjectFit {
48 pub fn get_bounds(
50 &self,
51 bounds: Bounds<Pixels>,
52 image_size: Size<DevicePixels>,
53 ) -> Bounds<Pixels> {
54 let fitted = self.get_bounds_at(bounds, image_size, ObjectPosition::default());
55 match self {
56 ObjectFit::None => Bounds {
57 origin: bounds.origin,
58 size: fitted.size,
59 },
60 _ => fitted,
61 }
62 }
63
64 pub fn get_bounds_at(
67 &self,
68 bounds: Bounds<Pixels>,
69 image_size: Size<DevicePixels>,
70 position: ObjectPosition,
71 ) -> Bounds<Pixels> {
72 let image_size = image_size.map(|dimension| Pixels::from(u32::from(dimension)));
73 let image_ratio = image_size.width / image_size.height;
74 let bounds_ratio = bounds.size.width / bounds.size.height;
75 let contain = || {
76 if bounds_ratio > image_ratio {
77 size(
78 image_size.width * (bounds.size.height / image_size.height),
79 bounds.size.height,
80 )
81 } else {
82 size(
83 bounds.size.width,
84 image_size.height * (bounds.size.width / image_size.width),
85 )
86 }
87 };
88
89 let new_size = match self {
90 ObjectFit::Fill => bounds.size,
91 ObjectFit::Contain => contain(),
92 ObjectFit::ScaleDown => {
93 if image_size.width > bounds.size.width || image_size.height > bounds.size.height {
94 contain()
95 } else {
96 image_size
97 }
98 }
99 ObjectFit::Cover => {
100 if bounds_ratio > image_ratio {
101 size(
102 bounds.size.width,
103 image_size.height * (bounds.size.width / image_size.width),
104 )
105 } else {
106 size(
107 image_size.width * (bounds.size.height / image_size.height),
108 bounds.size.height,
109 )
110 }
111 }
112 ObjectFit::None => image_size,
113 };
114 Bounds {
115 origin: point(
116 bounds.origin.x
117 + (bounds.size.width - new_size.width) * position.x_fraction
118 + position.x_offset,
119 bounds.origin.y
120 + (bounds.size.height - new_size.height) * position.y_fraction
121 + position.y_offset,
122 ),
123 size: new_size,
124 }
125 }
126}
127
128#[derive(Clone, Copy, Debug, PartialEq, Serialize, Deserialize)]
131#[cfg_attr(feature = "schemars", derive(JsonSchema))]
132pub struct ObjectPosition {
133 pub x_fraction: f32,
135 pub x_offset: Pixels,
137 pub y_fraction: f32,
139 pub y_offset: Pixels,
141}
142
143impl Default for ObjectPosition {
144 fn default() -> Self {
145 Self {
146 x_fraction: 0.5,
147 x_offset: Pixels::ZERO,
148 y_fraction: 0.5,
149 y_offset: Pixels::ZERO,
150 }
151 }
152}
153
154#[derive(Copy, Clone, PartialEq, Eq, PartialOrd, Ord, Debug, Default, Serialize, Deserialize)]
156#[cfg_attr(feature = "schemars", derive(JsonSchema))]
157pub enum GridTemplateMinSize {
158 #[default]
160 Zero,
161 MinContent,
163 MaxContent,
165}
166
167#[derive(
169 Copy, Clone, Refineable, PartialEq, Eq, PartialOrd, Ord, Debug, Default, Serialize, Deserialize,
170)]
171#[cfg_attr(feature = "schemars", derive(JsonSchema))]
172pub struct GridTemplate {
173 pub repeat: u16,
175 pub min_size: GridTemplateMinSize,
177}
178
179#[derive(Copy, Clone, PartialEq, Debug, Default, Serialize, Deserialize)]
186#[cfg_attr(feature = "schemars", derive(JsonSchema))]
187pub enum GridTrackSize {
188 #[default]
190 Auto,
191 MinContent,
193 MaxContent,
195 Px(f32),
197 Percent(f32),
200 Fr(f32),
203}
204
205#[derive(Copy, Clone, PartialEq, Debug, Default, Serialize, Deserialize)]
211#[cfg_attr(feature = "schemars", derive(JsonSchema))]
212pub struct GridTrack {
213 pub min: GridTrackSize,
215 pub max: GridTrackSize,
217}
218
219impl GridTrack {
220 pub fn fixed(size: GridTrackSize) -> Self {
222 Self {
223 min: size,
224 max: size,
225 }
226 }
227
228 pub fn fr(flex: f32) -> Self {
230 Self {
231 min: GridTrackSize::Auto,
232 max: GridTrackSize::Fr(flex),
233 }
234 }
235}
236
237#[derive(Copy, Clone, PartialEq, Eq, Debug, Serialize, Deserialize)]
244#[cfg_attr(feature = "schemars", derive(JsonSchema))]
245pub struct GridAutoRepeat {
246 pub fit: bool,
249 pub start: u16,
251 pub len: u16,
253}
254
255#[derive(Copy, Clone, PartialEq, Eq, Debug, Default, Serialize, Deserialize)]
258#[cfg_attr(feature = "schemars", derive(JsonSchema))]
259pub enum GridAutoFlow {
260 #[default]
262 Row,
263 Column,
265 RowDense,
267 ColumnDense,
269}
270
271#[derive(Copy, Clone, PartialEq, Debug, Serialize, Deserialize)]
274#[cfg_attr(feature = "schemars", derive(JsonSchema))]
275pub struct Outline {
276 pub width: Pixels,
278 pub offset: Pixels,
281 pub color: Hsla,
283 pub style: BorderStyle,
285}
286
287#[derive(Copy, Clone, PartialEq, Debug, Serialize, Deserialize)]
291#[cfg_attr(feature = "schemars", derive(JsonSchema))]
292pub struct VnCornerRadius {
293 pub x: DefiniteLength,
295 pub y: DefiniteLength,
297}
298
299static VN_ELLIPSE_DRAWN_AS_CIRCLE: std::sync::atomic::AtomicBool =
300 std::sync::atomic::AtomicBool::new(false);
301
302pub fn vn_take_ellipse_drawn_as_circle() -> bool {
306 VN_ELLIPSE_DRAWN_AS_CIRCLE.swap(false, std::sync::atomic::Ordering::Relaxed)
307}
308
309pub fn vn_resolve_corner_radii(
326 lengths: &Corners<AbsoluteLength>,
327 relative: &Corners<Option<VnCornerRadius>>,
328 size: Size<Pixels>,
329 rem_size: Pixels,
330) -> Corners<Pixels> {
331 let (width, height) = (f32::from(size.width).max(0.), f32::from(size.height).max(0.));
332 let pair = |length: &AbsoluteLength, relative: &Option<VnCornerRadius>| -> (f32, f32) {
333 match relative {
334 Some(radius) => (
335 f32::from(radius.x.to_pixels(px(width).into(), rem_size)).max(0.),
336 f32::from(radius.y.to_pixels(px(height).into(), rem_size)).max(0.),
337 ),
338 None => {
339 let radius = f32::from(length.to_pixels(rem_size)).max(0.);
340 (radius, radius)
341 }
342 }
343 };
344 let top_left = pair(&lengths.top_left, &relative.top_left);
345 let top_right = pair(&lengths.top_right, &relative.top_right);
346 let bottom_right = pair(&lengths.bottom_right, &relative.bottom_right);
347 let bottom_left = pair(&lengths.bottom_left, &relative.bottom_left);
348
349 let ratio = |side: f32, a: f32, b: f32| if a + b > side { side / (a + b) } else { 1. };
350 let factor = ratio(width, top_left.0, top_right.0)
351 .min(ratio(width, bottom_left.0, bottom_right.0))
352 .min(ratio(height, top_left.1, bottom_left.1))
353 .min(ratio(height, top_right.1, bottom_right.1));
354
355 let circle = |(x, y): (f32, f32)| {
356 let (x, y) = (x * factor, y * factor);
357 let radius = x.min(y);
358 if radius > 0. && (x - y).abs() > 0.5 {
359 VN_ELLIPSE_DRAWN_AS_CIRCLE.store(true, std::sync::atomic::Ordering::Relaxed);
360 }
361 px(radius)
362 };
363 Corners {
364 top_left: circle(top_left),
365 top_right: circle(top_right),
366 bottom_right: circle(bottom_right),
367 bottom_left: circle(bottom_left),
368 }
369 .clamp_radii_for_quad_size(size)
370}
371
372#[derive(Copy, Clone, Default, PartialEq, Debug, Serialize, Deserialize)]
376#[cfg_attr(feature = "schemars", derive(JsonSchema))]
377pub enum VnClipBox {
378 Margin,
380 #[default]
382 Border,
383 Padding,
385 Content,
387}
388
389#[derive(Copy, Clone, PartialEq, Debug, Serialize, Deserialize)]
391#[cfg_attr(feature = "schemars", derive(JsonSchema))]
392pub enum VnShapeRadius {
393 Length(DefiniteLength),
397 ClosestSide,
400 FarthestSide,
402}
403
404#[derive(Clone, Default, PartialEq, Debug, Serialize, Deserialize)]
409#[cfg_attr(feature = "schemars", derive(JsonSchema))]
410pub enum VnClipPath {
411 #[default]
413 None,
414 Box(VnClipBox),
417 Inset {
422 reference: VnClipBox,
424 insets: [DefiniteLength; 4],
426 radii: [VnCornerRadius; 4],
429 },
430 Ellipse {
434 reference: VnClipBox,
436 center: [DefiniteLength; 2],
438 radius: [VnShapeRadius; 2],
440 circle: bool,
443 },
444 Polygon {
447 reference: VnClipBox,
449 fill_rule: VnFillRule,
451 points: Arc<[[DefiniteLength; 2]]>,
453 },
454 Path {
457 reference: VnClipBox,
459 fill_rule: VnFillRule,
461 verbs: Arc<[VnPathVerb]>,
463 },
464}
465
466fn vn_clip_ellipse(
469 rect: Bounds<Pixels>,
470 center: &[DefiniteLength; 2],
471 radius: &[VnShapeRadius; 2],
472 circle: bool,
473 rem_size: Pixels,
474) -> (Point<Pixels>, Pixels, Pixels) {
475 let (w, h) = (rect.size.width, rect.size.height);
476 let resolve = |length: &DefiniteLength, base: Pixels| length.to_pixels(AbsoluteLength::Pixels(base), rem_size);
477 let cx = rect.left() + resolve(¢er[0], w);
478 let cy = rect.top() + resolve(¢er[1], h);
479 let (near_x, far_x) = ((cx - rect.left()).abs(), (rect.right() - cx).abs());
480 let (near_y, far_y) = ((cy - rect.top()).abs(), (rect.bottom() - cy).abs());
481 let diagonal = px((f32::from(w).powi(2) + f32::from(h).powi(2)).sqrt() / 2f32.sqrt());
484 let one = |r: &VnShapeRadius, horizontal: bool| -> Pixels {
485 let (a, b) = if circle {
486 (near_x.min(far_x).min(near_y.min(far_y)), near_x.max(far_x).max(near_y.max(far_y)))
487 } else if horizontal {
488 (near_x.min(far_x), near_x.max(far_x))
489 } else {
490 (near_y.min(far_y), near_y.max(far_y))
491 };
492 match r {
493 VnShapeRadius::ClosestSide => a,
494 VnShapeRadius::FarthestSide => b,
495 VnShapeRadius::Length(l) => resolve(l, if circle { diagonal } else if horizontal { w } else { h }).max(px(0.)),
496 }
497 };
498 (point(cx, cy), one(&radius[0], true), one(&radius[1], false))
499}
500
501#[derive(Clone, Refineable, Debug)]
503#[refineable(Debug, PartialEq, Serialize, Deserialize)]
504#[cfg_attr(feature = "schemars", refineable(JsonSchema))]
505pub struct Style {
506 pub display: Display,
508
509 pub visibility: Visibility,
511
512 #[refineable]
515 pub overflow: Point<Overflow>,
516 pub scrollbar_width: AbsoluteLength,
518 pub allow_concurrent_scroll: bool,
520 pub restrict_scroll_to_axis: bool,
546
547 pub position: Position,
550 #[refineable]
552 pub inset: Edges<Length>,
553
554 #[refineable]
557 pub size: Size<Length>,
558 #[refineable]
560 pub min_size: Size<Length>,
561 #[refineable]
563 pub max_size: Size<Length>,
564 pub aspect_ratio: Option<f32>,
567
568 #[refineable]
571 pub margin: Edges<Length>,
572 #[refineable]
574 pub padding: Edges<DefiniteLength>,
575 #[refineable]
577 pub border_widths: Edges<AbsoluteLength>,
578
579 pub align_items: Option<AlignItems>,
582 pub align_self: Option<AlignSelf>,
584 pub align_content: Option<AlignContent>,
586 pub justify_content: Option<JustifyContent>,
588 #[refineable]
590 pub gap: Size<DefiniteLength>,
591
592 pub flex_direction: FlexDirection,
595 pub flex_wrap: FlexWrap,
597 pub flex_basis: Length,
599 pub flex_grow: f32,
601 pub flex_shrink: f32,
603 pub vn_order: i32,
606 pub vn_object_position: Option<ObjectPosition>,
609
610 pub background: Option<Fill>,
612
613 pub background_layers: Vec<Background>,
626
627 pub border_color: Option<Hsla>,
629
630 #[refineable]
632 pub vn_border_colors: Edges<Option<Hsla>>,
633
634 pub border_style: BorderStyle,
636
637 #[refineable]
639 pub corner_radii: Corners<AbsoluteLength>,
640
641 #[refineable]
648 pub vn_corner_radii: Corners<Option<VnCornerRadius>>,
649
650 #[refineable]
652 pub vn_corner_shapes: Corners<CornerShape>,
653
654 pub box_shadow: Vec<BoxShadow>,
656
657 pub vn_shadow_under_box: bool,
667
668 pub backdrop_blur: Option<Pixels>,
675
676 pub vn_effect: Option<EffectSpec>,
691
692 pub vn_effect_fade: Option<EffectCrossFade>,
695
696 pub vn_transform: Option<TransformSpec>,
716
717 #[refineable]
719 pub text: TextStyleRefinement,
720
721 pub mouse_cursor: Option<CursorStyle>,
723
724 pub opacity: Option<f32>,
726
727 pub grid_cols: Option<GridTemplate>,
730
731 pub grid_rows: Option<GridTemplate>,
734
735 pub grid_location: Option<GridLocation>,
737
738 pub vn_grid_cols: Option<Vec<GridTrack>>,
745
746 pub vn_grid_rows: Option<Vec<GridTrack>>,
749
750 pub vn_grid_cols_auto: Option<GridAutoRepeat>,
753
754 pub vn_grid_rows_auto: Option<GridAutoRepeat>,
756
757 pub vn_grid_auto_cols: Option<Vec<GridTrack>>,
759
760 pub vn_grid_auto_rows: Option<Vec<GridTrack>>,
762
763 pub vn_grid_auto_flow: Option<GridAutoFlow>,
766
767 pub vn_justify_items: Option<AlignItems>,
771
772 pub vn_justify_self: Option<AlignSelf>,
775
776 pub vn_outline: Option<Outline>,
784
785 pub vn_mask_ring: bool,
803
804 pub vn_clip_path: VnClipPath,
809
810 pub vn_color_matrix: Option<crate::VnColorMatrix>,
812
813 pub vn_capture: Option<u64>,
816
817 pub vn_isolate: bool,
820
821 pub vn_contain_size: u8,
824
825 pub vn_text_fill: Option<VnTextFill>,
827
828 pub vn_mask: Option<VnMask>,
830
831 #[cfg(debug_assertions)]
833 pub debug: bool,
834
835 #[cfg(debug_assertions)]
837 pub debug_below: bool,
838}
839
840impl Styled for StyleRefinement {
841 fn style(&mut self) -> &mut StyleRefinement {
842 self
843 }
844}
845
846impl StyleRefinement {
847 pub fn grid_location_mut(&mut self) -> &mut GridLocation {
849 self.grid_location.get_or_insert_default()
850 }
851}
852
853#[derive(Default, Clone, Copy, Debug, Eq, PartialEq, Serialize, Deserialize)]
855#[cfg_attr(feature = "schemars", derive(JsonSchema))]
856pub enum Visibility {
857 #[default]
859 Visible,
860 Hidden,
862}
863
864#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
866#[cfg_attr(feature = "schemars", derive(JsonSchema))]
867pub struct BoxShadow {
868 pub color: Hsla,
870 pub offset: Point<Pixels>,
872 pub blur_radius: Pixels,
874 pub spread_radius: Pixels,
876 pub inset: bool,
878}
879
880#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Serialize, Deserialize)]
882#[cfg_attr(feature = "schemars", derive(JsonSchema))]
883pub struct TextShadow {
884 pub color: Option<Hsla>,
886 pub offset: Point<Pixels>,
888 pub blur_radius: Pixels,
890}
891
892impl BoxShadow {
893 pub fn new(offset_x: Pixels, offset_y: Pixels, color: Hsla) -> Self {
897 Self {
898 color,
899 offset: point(offset_x, offset_y),
900 blur_radius: px(0.),
901 spread_radius: px(0.),
902 inset: false,
903 }
904 }
905
906 pub fn blur_radius(mut self, blur_radius: Pixels) -> Self {
908 self.blur_radius = blur_radius;
909 self
910 }
911
912 pub fn spread_radius(mut self, spread_radius: Pixels) -> Self {
914 self.spread_radius = spread_radius;
915 self
916 }
917
918 pub fn inset(mut self) -> Self {
920 self.inset = true;
921 self
922 }
923}
924
925#[derive(Copy, Clone, Debug, Default, PartialEq, Eq, Serialize, Deserialize)]
927#[cfg_attr(feature = "schemars", derive(JsonSchema))]
928pub enum WhiteSpace {
929 #[default]
931 Normal,
932 Nowrap,
934}
935
936#[derive(Copy, Clone, Debug, Default, PartialEq, Eq, Hash, Serialize, Deserialize)]
939#[cfg_attr(feature = "schemars", derive(JsonSchema))]
940pub enum OverflowWrap {
941 #[default]
944 Normal,
945 BreakWord,
948 Anywhere,
951}
952
953#[derive(Copy, Clone, Debug, Default, PartialEq, Eq, Hash, Serialize, Deserialize)]
955#[cfg_attr(feature = "schemars", derive(JsonSchema))]
956pub enum WordBreak {
957 #[default]
959 Normal,
960 BreakAll,
963 KeepAll,
966 BreakWord,
969}
970
971#[derive(Copy, Clone, Debug, Default, PartialEq, Eq, Hash, Serialize, Deserialize)]
974#[cfg_attr(feature = "schemars", derive(JsonSchema))]
975pub enum Hyphens {
976 None,
978 #[default]
980 Manual,
981}
982
983#[derive(Copy, Clone, Debug, Default, PartialEq, Eq, Hash)]
986pub struct TextWrap {
987 pub overflow_wrap: OverflowWrap,
989 pub word_break: WordBreak,
991 pub hyphens: Hyphens,
993}
994
995impl TextWrap {
996 pub const BREAK_WORD: Self = Self {
1001 overflow_wrap: OverflowWrap::BreakWord,
1002 word_break: WordBreak::Normal,
1003 hyphens: Hyphens::Manual,
1004 };
1005
1006 pub(crate) fn breaks_words(&self) -> bool {
1008 self.overflow_wrap != OverflowWrap::Normal || self.word_break == WordBreak::BreakWord
1009 }
1010
1011 pub(crate) fn min_content_breaks_words(&self) -> bool {
1013 self.overflow_wrap == OverflowWrap::Anywhere || self.word_break == WordBreak::BreakWord
1014 }
1015}
1016
1017#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
1019#[cfg_attr(feature = "schemars", derive(JsonSchema))]
1020pub enum TextOverflow {
1021 Truncate(SharedString),
1024 TruncateStart(SharedString),
1028 TruncateMiddle(SharedString),
1032}
1033
1034#[derive(Copy, Clone, Debug, Default, PartialEq, Eq, Serialize, Deserialize)]
1036#[cfg_attr(feature = "schemars", derive(JsonSchema))]
1037pub enum TextAlign {
1038 #[default]
1040 Left,
1041
1042 Center,
1044
1045 Right,
1047}
1048
1049pub type VnMaskPainter = std::rc::Rc<dyn Fn(Bounds<Pixels>, Option<Hsla>, &mut Window, &mut App)>;
1053
1054#[derive(Clone, Default, Serialize, Deserialize)]
1057#[cfg_attr(feature = "schemars", derive(JsonSchema))]
1058pub struct VnMask {
1059 pub luminance: bool,
1061 pub tint_leaf: bool,
1065 pub key: u64,
1067 #[serde(skip)]
1069 #[cfg_attr(feature = "schemars", schemars(skip))]
1070 pub paint: Option<VnMaskPainter>,
1071}
1072
1073impl std::fmt::Debug for VnMask {
1074 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
1075 f.debug_struct("VnMask")
1076 .field("luminance", &self.luminance)
1077 .field("tint_leaf", &self.tint_leaf)
1078 .field("key", &self.key)
1079 .finish_non_exhaustive()
1080 }
1081}
1082
1083impl PartialEq for VnMask {
1084 fn eq(&self, other: &Self) -> bool {
1085 (self.luminance, self.tint_leaf, self.key) == (other.luminance, other.tint_leaf, other.key)
1086 }
1087}
1088
1089#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
1091#[cfg_attr(feature = "schemars", derive(JsonSchema))]
1092pub struct VnTextFill {
1093 pub group_id: u64,
1095 pub backgrounds: Vec<Background>,
1097}
1098
1099#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
1102#[cfg_attr(feature = "schemars", derive(JsonSchema))]
1103pub struct VnTextPaint {
1104 pub fill: VnTextFill,
1106 pub bounds: [f32; 4],
1108 pub inverse: [f32; 6],
1110 pub scale_factor: f32,
1112 #[serde(skip)]
1114 #[cfg_attr(feature = "schemars", schemars(skip))]
1115 pub geometry: Arc<crate::VnClipGeometry>,
1116 #[serde(skip)]
1118 #[cfg_attr(feature = "schemars", schemars(skip))]
1119 pub content_mask: ContentMask<crate::ScaledPixels>,
1120}
1121
1122#[derive(Refineable, Clone, Debug, PartialEq)]
1124#[refineable(Debug, PartialEq, Serialize, Deserialize)]
1125#[cfg_attr(feature = "schemars", refineable(JsonSchema))]
1126pub struct TextStyle {
1127 pub color: Hsla,
1129
1130 pub vn_text_paint: Option<Arc<VnTextPaint>>,
1132
1133 pub font_family: SharedString,
1135
1136 pub font_features: FontFeatures,
1138
1139 pub font_fallbacks: Option<FontFallbacks>,
1141
1142 pub font_size: AbsoluteLength,
1144
1145 pub line_height: DefiniteLength,
1147
1148 pub font_weight: FontWeight,
1150
1151 pub font_style: FontStyle,
1153
1154 pub background_color: Option<Hsla>,
1156
1157 pub underline: Option<UnderlineStyle>,
1159
1160 pub strikethrough: Option<StrikethroughStyle>,
1162
1163 pub white_space: WhiteSpace,
1165
1166 pub text_overflow: Option<TextOverflow>,
1168
1169 pub text_align: TextAlign,
1171
1172 pub line_clamp: Option<usize>,
1174
1175 pub letter_spacing: Pixels,
1179
1180 pub word_spacing: Pixels,
1182
1183 pub overflow_wrap: OverflowWrap,
1185
1186 pub word_break: WordBreak,
1188
1189 pub hyphens: Hyphens,
1191
1192 pub text_shadow: Vec<TextShadow>,
1194}
1195
1196impl Default for TextStyle {
1197 fn default() -> Self {
1198 TextStyle {
1199 color: black(),
1200 vn_text_paint: None,
1201 font_family: ".SystemUIFont".into(),
1203 font_features: FontFeatures::default(),
1204 font_fallbacks: None,
1205 font_size: rems(1.).into(),
1206 line_height: phi(),
1207 font_weight: FontWeight::default(),
1208 font_style: FontStyle::default(),
1209 background_color: None,
1210 underline: None,
1211 strikethrough: None,
1212 white_space: WhiteSpace::Normal,
1213 text_overflow: None,
1214 text_align: TextAlign::default(),
1215 line_clamp: None,
1216 letter_spacing: px(0.),
1217 word_spacing: px(0.),
1218 overflow_wrap: OverflowWrap::default(),
1219 word_break: WordBreak::default(),
1220 hyphens: Hyphens::default(),
1221 text_shadow: Vec::new(),
1222 }
1223 }
1224}
1225
1226impl TextStyle {
1227 pub fn wrap(&self) -> TextWrap {
1229 TextWrap {
1230 overflow_wrap: self.overflow_wrap,
1231 word_break: self.word_break,
1232 hyphens: self.hyphens,
1233 }
1234 }
1235
1236 pub fn highlight(mut self, style: impl Into<HighlightStyle>) -> Self {
1238 let style = style.into();
1239 if let Some(weight) = style.font_weight {
1240 self.font_weight = weight;
1241 }
1242 if let Some(style) = style.font_style {
1243 self.font_style = style;
1244 }
1245
1246 if let Some(color) = style.color {
1247 self.color = self.color.blend(color);
1248 }
1249
1250 if let Some(factor) = style.fade_out {
1251 self.color.fade_out(factor);
1252 }
1253
1254 if let Some(background_color) = style.background_color {
1255 self.background_color = Some(background_color);
1256 }
1257
1258 if let Some(underline) = style.underline {
1259 self.underline = Some(underline);
1260 }
1261
1262 if let Some(strikethrough) = style.strikethrough {
1263 self.strikethrough = Some(strikethrough);
1264 }
1265
1266 self
1267 }
1268
1269 pub fn font(&self) -> Font {
1271 Font {
1272 family: self.font_family.clone(),
1273 features: self.font_features.clone(),
1274 fallbacks: self.font_fallbacks.clone(),
1275 weight: self.font_weight,
1276 style: self.font_style,
1277 }
1278 }
1279
1280 pub fn line_height_in_pixels(&self, rem_size: Pixels) -> Pixels {
1282 self.line_height.to_pixels(self.font_size, rem_size).round()
1283 }
1284
1285 pub fn to_run(&self, len: usize) -> TextRun {
1287 TextRun {
1288 len,
1289 font: Font {
1290 family: self.font_family.clone(),
1291 features: self.font_features.clone(),
1292 fallbacks: self.font_fallbacks.clone(),
1293 weight: self.font_weight,
1294 style: self.font_style,
1295 },
1296 color: self.color,
1297 background_color: self.background_color,
1298 underline: self.underline,
1299 strikethrough: self.strikethrough,
1300 tracking: self.letter_spacing,
1301 word_spacing: self.word_spacing,
1302 text_shadow: self.text_shadow.clone(),
1303 }
1304 }
1305}
1306
1307#[derive(Copy, Clone, Debug, Default, PartialEq)]
1310pub struct HighlightStyle {
1311 pub color: Option<Hsla>,
1313
1314 pub font_weight: Option<FontWeight>,
1316
1317 pub font_style: Option<FontStyle>,
1319
1320 pub background_color: Option<Hsla>,
1322
1323 pub underline: Option<UnderlineStyle>,
1325
1326 pub strikethrough: Option<StrikethroughStyle>,
1328
1329 pub fade_out: Option<f32>,
1331}
1332
1333impl Eq for HighlightStyle {}
1334
1335impl Hash for HighlightStyle {
1336 fn hash<H: Hasher>(&self, state: &mut H) {
1337 self.color.hash(state);
1338 self.font_weight.hash(state);
1339 self.font_style.hash(state);
1340 self.background_color.hash(state);
1341 self.underline.hash(state);
1342 self.strikethrough.hash(state);
1343 state.write_u32(u32::from_be_bytes(
1344 self.fade_out.map(|f| f.to_be_bytes()).unwrap_or_default(),
1345 ));
1346 }
1347}
1348
1349fn representative_color(background: &Background) -> Hsla {
1353 match background.tag {
1354 BackgroundTag::Solid | BackgroundTag::PatternSlash | BackgroundTag::Checkerboard => {
1355 background.solid
1356 }
1357 BackgroundTag::LinearGradient
1358 | BackgroundTag::RadialGradient
1359 | BackgroundTag::ConicGradient => background
1360 .live_stops()
1361 .first()
1362 .map(|stop| stop.color)
1363 .unwrap_or_default(),
1364 }
1365}
1366
1367impl Style {
1368 pub const CONTAIN_INLINE_SIZE: u8 = 1;
1370 pub const CONTAIN_BLOCK_SIZE: u8 = 2;
1372
1373 pub fn has_opaque_background(&self) -> bool {
1375 self.background
1376 .as_ref()
1377 .is_some_and(|fill| fill.color().is_some_and(|color| !color.is_transparent()))
1378 }
1379
1380 pub fn text_style(&self) -> Option<&TextStyleRefinement> {
1382 if self.text.is_some() {
1383 Some(&self.text)
1384 } else {
1385 None
1386 }
1387 }
1388
1389 pub fn text_style_for_bounds(&self, bounds: Bounds<Pixels>, window: &Window) -> Option<TextStyleRefinement> {
1392 let mut text = self.text.clone();
1393 if let Some(fill) = &self.vn_text_fill {
1394 text.vn_text_paint = Some(window.vn_text_paint(fill.clone(), bounds));
1395 }
1396 text.is_some().then_some(text)
1397 }
1398
1399 pub fn corner_radii_for(&self, size: Size<Pixels>, rem_size: Pixels) -> Corners<Pixels> {
1402 vn_resolve_corner_radii(&self.corner_radii, &self.vn_corner_radii, size, rem_size)
1403 }
1404
1405 pub fn overflow_mask(
1408 &self,
1409 bounds: Bounds<Pixels>,
1410 rem_size: Pixels,
1411 ) -> Option<ContentMask<Pixels>> {
1412 match self.overflow {
1413 Point {
1414 x: Overflow::Visible,
1415 y: Overflow::Visible,
1416 } => None,
1417 _ => {
1418 let mut min = bounds.origin;
1419 let mut max = bounds.bottom_right();
1420 let border_box = bounds;
1421
1422 let painted = self
1427 .vn_resolved_border_colors()
1428 .map(|color| !color.is_transparent());
1429 if painted.left {
1430 min.x += self.border_widths.left.to_pixels(rem_size);
1431 }
1432 if painted.right {
1433 max.x -= self.border_widths.right.to_pixels(rem_size);
1434 }
1435 if painted.top {
1436 min.y += self.border_widths.top.to_pixels(rem_size);
1437 }
1438 if painted.bottom {
1439 max.y -= self.border_widths.bottom.to_pixels(rem_size);
1440 }
1441
1442 let bounds = match (
1443 self.overflow.x == Overflow::Visible,
1444 self.overflow.y == Overflow::Visible,
1445 ) {
1446 (true, true) => return None,
1448 (true, false) => Bounds::from_corners(
1450 point(min.x, bounds.origin.y),
1451 point(max.x, bounds.bottom_right().y),
1452 ),
1453 (false, true) => Bounds::from_corners(
1455 point(bounds.origin.x, min.y),
1456 point(bounds.bottom_right().x, max.y),
1457 ),
1458 (false, false) => Bounds::from_corners(min, max),
1460 };
1461
1462 let insets = Edges {
1470 top: bounds.top() - border_box.top(),
1471 right: border_box.right() - bounds.right(),
1472 bottom: border_box.bottom() - bounds.bottom(),
1473 left: bounds.left() - border_box.left(),
1474 };
1475 let outer = self.corner_radii_for(border_box.size, rem_size);
1476 let inner = |radius: Pixels, a: Pixels, b: Pixels| (radius - a.max(b)).max(px(0.));
1477 let corner_radii = Corners {
1478 top_left: inner(outer.top_left, insets.top, insets.left),
1479 top_right: inner(outer.top_right, insets.top, insets.right),
1480 bottom_right: inner(outer.bottom_right, insets.bottom, insets.right),
1481 bottom_left: inner(outer.bottom_left, insets.bottom, insets.left),
1482 }
1483 .clamp_radii_for_quad_size(bounds.size);
1484
1485 Some(self.vn_shaped_mask(border_box, bounds, corner_radii, rem_size))
1486 }
1487 }
1488 }
1489
1490 fn vn_shaped_mask(
1494 &self,
1495 border_box: Bounds<Pixels>,
1496 rect: Bounds<Pixels>,
1497 round_radii: Corners<Pixels>,
1498 rem_size: Pixels,
1499 ) -> ContentMask<Pixels> {
1500 let shapes = &self.vn_corner_shapes;
1501 if *shapes == Corners::default() {
1502 return ContentMask { bounds: rect, corner_radii: round_radii, corner_shapes: CornerShapes::default() };
1503 }
1504 let outer = self.corner_radii_for(border_box.size, rem_size);
1505 let pick = |round: Pixels, outer: Pixels, shape: CornerShape| if shape.is_round() { round } else { outer };
1506 let corner_radii = Corners {
1507 top_left: pick(round_radii.top_left, outer.top_left, shapes.top_left),
1508 top_right: pick(round_radii.top_right, outer.top_right, shapes.top_right),
1509 bottom_right: pick(round_radii.bottom_right, outer.bottom_right, shapes.bottom_right),
1510 bottom_left: pick(round_radii.bottom_left, outer.bottom_left, shapes.bottom_left),
1511 };
1512 let inset = |a: Pixels, b: Pixels| f32::from(a - b).max(0.);
1513 let (left, top) = (inset(rect.left(), border_box.left()), inset(rect.top(), border_box.top()));
1514 let (right, bottom) =
1515 (inset(border_box.right(), rect.right()), inset(border_box.bottom(), rect.bottom()));
1516 let insets = Corners {
1517 top_left: (left, top),
1518 top_right: (right, top),
1519 bottom_right: (right, bottom),
1520 bottom_left: (left, bottom),
1521 };
1522 ContentMask {
1523 bounds: rect,
1524 corner_radii,
1525 corner_shapes: CornerShapes::new(shapes).with_insets(insets),
1526 }
1527 }
1528
1529 pub fn vn_clip_mask(&self, bounds: Bounds<Pixels>, rem_size: Pixels) -> Option<ContentMask<Pixels>> {
1537 let clip = &self.vn_clip_path;
1538 let reference = match clip {
1539 VnClipPath::None => return None,
1540 VnClipPath::Polygon { .. } | VnClipPath::Path { .. } => {
1541 let outline = self.vn_clip_outline(bounds, rem_size)?;
1542 let rect = outline.control_bounds().unwrap_or(Bounds { origin: bounds.origin, size: Size::default() });
1543 return Some(ContentMask::rect(rect));
1544 }
1545 VnClipPath::Box(reference)
1546 | VnClipPath::Inset { reference, .. }
1547 | VnClipPath::Ellipse { reference, .. } => *reference,
1548 };
1549 let (rect, rounded) = self.vn_clip_box(reference, bounds, rem_size);
1550 let (w, h) = (rect.size.width, rect.size.height);
1551 let resolve = |length: &DefiniteLength, base: Pixels| length.to_pixels(AbsoluteLength::Pixels(base), rem_size);
1552 Some(match clip {
1553 VnClipPath::None | VnClipPath::Polygon { .. } | VnClipPath::Path { .. } => return None,
1554 VnClipPath::Box(VnClipBox::Margin) => ContentMask { bounds: rect, corner_radii: rounded, ..Default::default() },
1555 VnClipPath::Box(_) => self.vn_shaped_mask(bounds, rect, rounded, rem_size),
1556 VnClipPath::Inset { insets, radii, .. } => {
1557 let [top, right, bottom, left] = insets;
1562 let (top, right) = (resolve(top, h), resolve(right, w));
1563 let (bottom, left) = (resolve(bottom, h), resolve(left, w));
1564 let shape = Bounds {
1565 origin: point(rect.left() + left, rect.top() + top),
1566 size: size((w - left - right).max(px(0.)), (h - top - bottom).max(px(0.))),
1567 };
1568 let pairs = radii.map(|r| {
1569 let x = f32::from(resolve(&r.x, w)).max(0.);
1570 let y = f32::from(resolve(&r.y, h)).max(0.);
1571 (x, y)
1572 });
1573 let [tl, tr, br, bl] = pairs;
1574 let (sw, sh) = (f32::from(shape.size.width), f32::from(shape.size.height));
1575 let ratio = |side: f32, a: f32, b: f32| if a + b > side { side / (a + b) } else { 1. };
1576 let factor = ratio(sw, tl.0, tr.0)
1577 .min(ratio(sw, bl.0, br.0))
1578 .min(ratio(sh, tl.1, bl.1))
1579 .min(ratio(sh, tr.1, br.1));
1580 let circle = |(x, y): (f32, f32)| px(x.min(y) * factor);
1581 let corner_radii = Corners {
1582 top_left: circle(tl),
1583 top_right: circle(tr),
1584 bottom_right: circle(br),
1585 bottom_left: circle(bl),
1586 }
1587 .clamp_radii_for_quad_size(shape.size);
1588 ContentMask { bounds: shape, corner_radii, ..Default::default() }
1589 }
1590 VnClipPath::Ellipse { center, radius, circle, .. } => {
1591 let (c, rx, ry) = vn_clip_ellipse(rect, center, radius, *circle, rem_size);
1592 let shape = Bounds { origin: point(c.x - rx, c.y - ry), size: size(rx * 2., ry * 2.) };
1593 let corner_radii = if rx == ry { Corners::all(rx) } else { Corners::default() };
1596 ContentMask { bounds: shape, corner_radii, ..Default::default() }
1597 }
1598 })
1599 }
1600
1601 pub fn vn_clip_outline(&self, bounds: Bounds<Pixels>, rem_size: Pixels) -> Option<VnClipOutline> {
1608 let resolve = |length: &DefiniteLength, base: Pixels| {
1609 f32::from(length.to_pixels(AbsoluteLength::Pixels(base), rem_size))
1610 };
1611 match &self.vn_clip_path {
1612 VnClipPath::Polygon { reference, fill_rule, points } => {
1613 let (rect, _) = self.vn_clip_box(*reference, bounds, rem_size);
1614 let (x0, y0) = (f32::from(rect.left()), f32::from(rect.top()));
1615 let (w, h) = (rect.size.width, rect.size.height);
1616 let mut verbs = Vec::with_capacity(points.len() + 1);
1617 for (i, [x, y]) in points.iter().enumerate() {
1618 let p = [x0 + resolve(x, w), y0 + resolve(y, h)];
1619 verbs.push(if i == 0 { VnPathVerb::MoveTo(p) } else { VnPathVerb::LineTo(p) });
1620 }
1621 if !verbs.is_empty() {
1622 verbs.push(VnPathVerb::Close);
1623 }
1624 Some(VnClipOutline { fill_rule: *fill_rule, verbs })
1625 }
1626 VnClipPath::Path { reference, fill_rule, verbs } => {
1627 let (rect, _) = self.vn_clip_box(*reference, bounds, rem_size);
1628 let (x0, y0) = (f32::from(rect.left()), f32::from(rect.top()));
1629 let at = |p: [f32; 2]| [p[0] + x0, p[1] + y0];
1630 let verbs = verbs
1631 .iter()
1632 .map(|v| match *v {
1633 VnPathVerb::MoveTo(p) => VnPathVerb::MoveTo(at(p)),
1634 VnPathVerb::LineTo(p) => VnPathVerb::LineTo(at(p)),
1635 VnPathVerb::QuadTo(c, p) => VnPathVerb::QuadTo(at(c), at(p)),
1636 VnPathVerb::CubicTo(c1, c2, p) => VnPathVerb::CubicTo(at(c1), at(c2), at(p)),
1637 VnPathVerb::Close => VnPathVerb::Close,
1638 })
1639 .collect();
1640 Some(VnClipOutline { fill_rule: *fill_rule, verbs })
1641 }
1642 VnClipPath::Ellipse { reference, center, radius, circle } => {
1643 let (rect, _) = self.vn_clip_box(*reference, bounds, rem_size);
1644 let (c, rx, ry) = vn_clip_ellipse(rect, center, radius, *circle, rem_size);
1645 if rx == ry {
1646 return None;
1647 }
1648 let (cx, cy, rx, ry) = (f32::from(c.x), f32::from(c.y), f32::from(rx), f32::from(ry));
1650 let (kx, ky) = (0.552_284_8 * rx, 0.552_284_8 * ry);
1651 use VnPathVerb::*;
1652 Some(VnClipOutline {
1653 fill_rule: VnFillRule::NonZero,
1654 verbs: vec![
1655 MoveTo([cx + rx, cy]),
1656 CubicTo([cx + rx, cy + ky], [cx + kx, cy + ry], [cx, cy + ry]),
1657 CubicTo([cx - kx, cy + ry], [cx - rx, cy + ky], [cx - rx, cy]),
1658 CubicTo([cx - rx, cy - ky], [cx - kx, cy - ry], [cx, cy - ry]),
1659 CubicTo([cx + kx, cy - ry], [cx + rx, cy - ky], [cx + rx, cy]),
1660 Close,
1661 ],
1662 })
1663 }
1664 VnClipPath::None | VnClipPath::Box(_) | VnClipPath::Inset { .. } => None,
1665 }
1666 }
1667
1668 fn vn_clip_box(&self, reference: VnClipBox, bounds: Bounds<Pixels>, rem_size: Pixels) -> (Bounds<Pixels>, Corners<Pixels>) {
1675 let outer = self.corner_radii_for(bounds.size, rem_size);
1676 let width = AbsoluteLength::Pixels(bounds.size.width);
1677 let edges = match reference {
1678 VnClipBox::Border => return (bounds, outer),
1679 VnClipBox::Margin => {
1680 let margin = |l: &Length| match l {
1681 Length::Definite(l) => -l.to_pixels(width, rem_size),
1682 Length::Auto | Length::VnCalcSize(_) => px(0.),
1683 };
1684 Edges {
1685 top: margin(&self.margin.top),
1686 right: margin(&self.margin.right),
1687 bottom: margin(&self.margin.bottom),
1688 left: margin(&self.margin.left),
1689 }
1690 }
1691 VnClipBox::Padding | VnClipBox::Content => {
1692 let border = self.border_widths.to_pixels(rem_size);
1693 if reference == VnClipBox::Padding {
1694 border
1695 } else {
1696 let padding = self.padding.to_pixels(size(width, width), rem_size);
1697 Edges {
1698 top: border.top + padding.top,
1699 right: border.right + padding.right,
1700 bottom: border.bottom + padding.bottom,
1701 left: border.left + padding.left,
1702 }
1703 }
1704 }
1705 };
1706 let rect = Bounds::from_corners(
1707 point(bounds.left() + edges.left, bounds.top() + edges.top),
1708 point(
1709 (bounds.right() - edges.right).max(bounds.left() + edges.left),
1710 (bounds.bottom() - edges.bottom).max(bounds.top() + edges.top),
1711 ),
1712 );
1713 let corner = |radius: Pixels, a: Pixels, b: Pixels| {
1715 if a < px(0.) || b < px(0.) {
1716 if radius > px(0.) { radius - a.min(b) } else { px(0.) }
1717 } else {
1718 (radius - a.max(b)).max(px(0.))
1719 }
1720 };
1721 let corner_radii = Corners {
1722 top_left: corner(outer.top_left, edges.top, edges.left),
1723 top_right: corner(outer.top_right, edges.top, edges.right),
1724 bottom_right: corner(outer.bottom_right, edges.bottom, edges.right),
1725 bottom_left: corner(outer.bottom_left, edges.bottom, edges.left),
1726 }
1727 .clamp_radii_for_quad_size(rect.size);
1728 (rect, corner_radii)
1729 }
1730
1731 pub fn transform_matrix(&self, bounds: Bounds<Pixels>, scale_factor: f32) -> TransformationMatrix
1738 {
1739 self.vn_transform
1740 .filter(|t| !t.is_identity())
1741 .map(|t| t.to_matrix(bounds, scale_factor))
1742 .unwrap_or_else(TransformationMatrix::unit)
1743 }
1744
1745 pub fn paint(
1747 &self,
1748 bounds: Bounds<Pixels>,
1749 window: &mut Window,
1750 cx: &mut App,
1751 continuation: impl FnOnce(&mut Window, &mut App),
1752 ) {
1753 let transformation = if self.vn_capture.is_some() {
1768 TransformationMatrix::unit()
1769 } else {
1770 self.transform_matrix(bounds, window.scale_factor())
1771 };
1772 let clip = self.vn_clip_mask(bounds, window.rem_size());
1773 let outline = self.vn_clip_outline(bounds, window.rem_size());
1774 let element = window.vn_take_effect_element();
1775 let paint = |window: &mut Window| {
1776 window.with_content_mask(clip, |window| {
1777 window.vn_with_clip_shape(outline.as_ref(), |window| {
1778 if let Some(tint) = self.vn_mask_tint()
1779 && let Some(paint) = self.vn_mask.as_ref().and_then(|mask| mask.paint.clone())
1780 {
1781 if !tint.is_transparent() {
1782 window.with_element_opacity(Some(tint.a), |window| {
1783 paint(bounds, Some(Hsla { a: 1., ..tint }), window, cx)
1784 });
1785 }
1786 return continuation(window, cx);
1787 }
1788 window.vn_with_mask(self.vn_mask.as_ref(), bounds, cx, |window, cx| {
1789 window.vn_with_color_matrix(self.vn_color_matrix, |window| {
1790 window.vn_with_isolation(self.vn_isolate, |window| {
1791 self.paint_shaded(bounds, element, window, cx, continuation)
1792 })
1793 })
1794 })
1795 })
1796 })
1797 };
1798 if !transformation.is_unit() {
1799 return window.with_element_transform(transformation, paint);
1800 }
1801 paint(window)
1802 }
1803
1804 fn vn_mask_tint(&self) -> Option<Hsla> {
1807 let mask = self.vn_mask.as_ref()?;
1808 if !mask.tint_leaf
1809 || mask.luminance
1810 || self.vn_color_matrix.is_some()
1811 || !self.background_layers.is_empty()
1812 || !self.box_shadow.is_empty()
1813 || self.is_border_visible()
1814 || self.backdrop_blur.is_some_and(|radius| radius > px(0.))
1815 || self.vn_effect.is_some()
1816 || self.vn_effect_fade.is_some()
1817 || self.vn_mask_ring
1818 || self.vn_outline.is_some_and(|o| o.width > px(0.) && !o.color.is_transparent())
1819 {
1820 return None;
1821 }
1822 match self.background.as_ref().and_then(Fill::color) {
1823 None => Some(Hsla::transparent_black()),
1824 Some(background) => background.as_solid(),
1825 }
1826 }
1827
1828 fn vn_effects(&self, cx: &App) -> [Option<(EffectSpec, f32)>; 2] {
1831 let reduce_motion = cx.reduce_motion();
1837 let layer = |mut spec: EffectSpec, weight: f32| {
1838 (spec.is_some() && !self.vn_mask_ring && weight > 0.).then(|| {
1839 spec.animated &= !reduce_motion;
1840 if reduce_motion {
1841 spec.clock_mask = 0;
1842 }
1843 (spec, weight)
1844 })
1845 };
1846 let progress = self
1847 .vn_effect_fade
1848 .map_or(1., |fade| fade.progress.clamp(0., 1.));
1849 [
1850 self.vn_effect_fade
1851 .and_then(|fade| layer(fade.from, 1. - progress)),
1852 self.vn_effect.and_then(|spec| layer(spec, progress)),
1853 ]
1854 }
1855
1856 fn paint_shaded(
1861 &self,
1862 bounds: Bounds<Pixels>,
1863 element: u64,
1864 window: &mut Window,
1865 cx: &mut App,
1866 continuation: impl FnOnce(&mut Window, &mut App),
1867 ) {
1868 let effects = self.vn_effects(cx);
1869 let content = effects
1870 .iter()
1871 .flatten()
1872 .any(|(spec, _)| spec.flags & crate::EFFECT_FLAG_NEEDS_CONTENT != 0);
1873 if !content {
1874 return self.paint_untransformed(
1875 bounds,
1876 window,
1877 cx,
1878 continuation,
1879 &effects,
1880 element,
1881 false,
1882 );
1883 }
1884 let corner_radii = self.corner_radii_for(bounds.size, window.rem_size());
1885 self.paint_backdrop(bounds, corner_radii, window, cx, &effects, element);
1886 let shaded: Vec<_> = effects
1887 .iter()
1888 .flatten()
1889 .map(|(spec, weight)| {
1890 let textures = crate::resolve_effect_textures(spec, window, cx);
1891 (*spec, *weight, textures)
1892 })
1893 .collect();
1894 let shapes = self.vn_corner_shapes;
1895 window.vn_with_effect_content(bounds, corner_radii, shapes, &shaded, element, cx, |window, cx| {
1896 self.paint_untransformed(bounds, window, cx, continuation, &effects, element, true)
1897 })
1898 }
1899
1900 pub fn vn_reads_content(&self) -> bool {
1903 [self.vn_effect, self.vn_effect_fade.map(|fade| fade.from)]
1904 .into_iter()
1905 .flatten()
1906 .any(|spec| spec.is_some() && spec.flags & crate::EFFECT_FLAG_NEEDS_CONTENT != 0)
1907 }
1908
1909 fn paint_backdrop(
1919 &self,
1920 bounds: Bounds<Pixels>,
1921 corner_radii: Corners<Pixels>,
1922 window: &mut Window,
1923 cx: &mut App,
1924 effects: &[Option<(EffectSpec, f32)>; 2],
1925 element: u64,
1926 ) {
1927 if let Some(radius) = self.backdrop_blur
1928 && radius > crate::px(0.)
1929 && !self.vn_mask_ring
1930 {
1931 window.vn_paint_backdrop_blur_rect(
1932 bounds,
1933 corner_radii,
1934 self.vn_corner_shapes,
1935 crate::BackdropBlurEffect::new(radius),
1936 );
1937 }
1938 self.paint_effects(bounds, corner_radii, window, cx, effects, element, true);
1939 }
1940
1941 #[allow(clippy::too_many_arguments)]
1947 fn paint_effects(
1948 &self,
1949 bounds: Bounds<Pixels>,
1950 corner_radii: Corners<Pixels>,
1951 window: &mut Window,
1952 cx: &mut App,
1953 effects: &[Option<(EffectSpec, f32)>; 2],
1954 element: u64,
1955 backdrop: bool,
1956 ) {
1957 for (spec, weight) in effects.iter().flatten() {
1958 if spec.flags & crate::EFFECT_FLAG_NEEDS_CONTENT == 0
1959 && (spec.flags & crate::EFFECT_FLAG_NEEDS_BACKDROP != 0) == backdrop
1960 {
1961 window.with_element_opacity((*weight < 1.).then_some(*weight), |window| {
1962 window.vn_paint_textured_effect(
1963 bounds,
1964 corner_radii,
1965 self.vn_corner_shapes,
1966 *spec,
1967 element,
1968 cx,
1969 )
1970 });
1971 }
1972 }
1973 }
1974
1975 #[allow(clippy::too_many_arguments)]
1976 fn paint_untransformed(
1977 &self,
1978 bounds: Bounds<Pixels>,
1979 window: &mut Window,
1980 cx: &mut App,
1981 continuation: impl FnOnce(&mut Window, &mut App),
1982 effects: &[Option<(EffectSpec, f32)>; 2],
1983 element: u64,
1984 in_content: bool,
1985 ) {
1986 #[cfg(debug_assertions)]
1987 if self.debug_below {
1988 cx.set_global(DebugBelow)
1989 }
1990
1991 #[cfg(debug_assertions)]
1992 if self.debug || cx.has_global::<DebugBelow>() {
1993 window.paint_quad(crate::outline(bounds, crate::red(), BorderStyle::default()));
1994 }
1995
1996 let rem_size = window.rem_size();
1997 let corner_radii = self.corner_radii_for(bounds.size, rem_size);
1998
1999 let ring_widths = self.vn_mask_ring.then(|| {
2004 let border = self.border_widths.to_pixels(rem_size);
2005 let width = AbsoluteLength::Pixels(bounds.size.width);
2006 let padding = self.padding.to_pixels(size(width, width), rem_size);
2007 Edges {
2008 top: border.top + padding.top,
2009 right: border.right + padding.right,
2010 bottom: border.bottom + padding.bottom,
2011 left: border.left + padding.left,
2012 }
2013 });
2014 let ring = ring_widths.is_some();
2015
2016 if !ring {
2017 window.vn_paint_drop_shadows(
2018 bounds,
2019 corner_radii,
2020 self.vn_corner_shapes,
2021 &self.box_shadow,
2022 self.vn_shadow_under_box,
2023 );
2024 }
2025
2026 if !in_content {
2027 self.paint_backdrop(bounds, corner_radii, window, cx, effects, element);
2028 }
2029 let fill = |background: Background| match ring_widths {
2031 Some(widths) => (background.ring(), widths),
2032 None => (background, Edges::default()),
2033 };
2034
2035 let background_color = self.background.as_ref().and_then(Fill::color);
2036 if background_color.is_some_and(|color| !color.is_transparent()) {
2037 let color = background_color.unwrap_or_default();
2038 let mut border_color = representative_color(&color);
2039 border_color.a = 0.;
2040 let (color, widths) = fill(color);
2041 window.paint_quad(quad(
2042 bounds,
2043 corner_radii,
2044 color,
2045 widths,
2046 border_color,
2047 self.border_style,
2048 ).corner_shapes(self.vn_corner_shapes));
2049 }
2050
2051 for layer in &self.background_layers {
2057 if layer.is_transparent() {
2058 continue;
2059 }
2060 let mut border_color = representative_color(layer);
2061 border_color.a = 0.;
2062 let (layer, widths) = fill(*layer);
2063 window.paint_quad(quad(
2064 bounds,
2065 corner_radii,
2066 layer,
2067 widths,
2068 border_color,
2069 self.border_style,
2070 ).corner_shapes(self.vn_corner_shapes));
2071 }
2072
2073 if !ring {
2074 window.vn_paint_inset_shadows(bounds, corner_radii, self.vn_corner_shapes, &self.box_shadow);
2075 }
2076
2077 self.paint_effects(bounds, corner_radii, window, cx, effects, element, false);
2078
2079 continuation(window, cx);
2080
2081 if self.is_border_visible() {
2082 let border_widths = self.border_widths.to_pixels(rem_size);
2083 let colors = self.vn_resolved_border_colors();
2084 if colors.top == colors.right && colors.top == colors.bottom && colors.top == colors.left {
2085 window.paint_quad(quad(
2086 bounds, corner_radii, Hsla::transparent_black(), border_widths,
2087 colors.top, self.border_style,
2088 ).corner_shapes(self.vn_corner_shapes));
2089 } else {
2090 let clips = Self::vn_border_side_clips(bounds, border_widths);
2094 for (points, (color, width)) in clips.into_iter().zip([
2095 (colors.top, border_widths.top), (colors.right, border_widths.right),
2096 (colors.bottom, border_widths.bottom), (colors.left, border_widths.left),
2097 ]) {
2098 if width <= px(0.) || color.is_transparent() || points.len() < 3 { continue; }
2099 let mut verbs: Vec<_> = points.into_iter().enumerate().map(|(index, point)| {
2100 if index == 0 { VnPathVerb::MoveTo(point) } else { VnPathVerb::LineTo(point) }
2101 }).collect();
2102 verbs.push(VnPathVerb::Close);
2103 let outline = VnClipOutline { fill_rule: VnFillRule::NonZero, verbs };
2104 window.vn_with_clip_shape(Some(&outline), |window| {
2105 window.paint_quad(quad(bounds, corner_radii, Hsla::transparent_black(),
2106 border_widths, color, self.border_style).corner_shapes(self.vn_corner_shapes));
2107 });
2108 }
2109 }
2110 }
2111
2112 if let Some(outline) = self
2122 .vn_outline
2123 .filter(|o| o.width > px(0.) && !o.color.is_transparent() && !ring)
2124 {
2125 let grow = outline.offset + outline.width;
2126 let ring = bounds.dilate(grow);
2127 let radii = corner_radii.map(|r| {
2130 if r.0 <= 0.0 {
2131 px(0.)
2132 } else {
2133 px((r.0 + grow.0).max(0.0))
2134 }
2135 });
2136 window.paint_quad(quad(
2137 ring,
2138 radii,
2139 Hsla::transparent_black(),
2140 Edges::all(outline.width),
2141 outline.color,
2142 outline.style,
2143 ).corner_shapes(self.vn_corner_shapes));
2144 }
2145
2146 #[cfg(debug_assertions)]
2147 if self.debug_below {
2148 cx.remove_global::<DebugBelow>();
2149 }
2150 }
2151
2152 fn vn_resolved_border_colors(&self) -> Edges<Hsla> {
2153 let shared = self.border_color.unwrap_or_default();
2154 self.vn_border_colors.map(|color| color.unwrap_or(shared))
2155 }
2156
2157 fn vn_border_side_clips(bounds: Bounds<Pixels>, widths: Edges<Pixels>) -> [Vec<[f32; 2]>; 4] {
2158 let (left, top, right, bottom) = (f32::from(bounds.left()), f32::from(bounds.top()),
2159 f32::from(bounds.right()), f32::from(bounds.bottom()));
2160 let widths = [widths.top, widths.right, widths.bottom, widths.left].map(|width| f32::from(width).max(0.));
2161 let distances = [[0., 1., -top], [-1., 0., right], [0., -1., bottom], [1., 0., -left]];
2162 std::array::from_fn(|side| {
2163 if widths[side] <= 0. { return Vec::new(); }
2164 let mut polygon = vec![[left, top], [right, top], [right, bottom], [left, bottom]];
2165 for other in 0..4 {
2170 if other == side || widths[other] <= 0. { continue; }
2171 let plane: [f32; 3] = std::array::from_fn(|index|
2172 distances[side][index] * widths[other] - distances[other][index] * widths[side]);
2173 let distance = |point: [f32; 2]| plane[0] * point[0] + plane[1] * point[1] + plane[2];
2174 let Some(mut previous) = polygon.last().copied() else { break };
2175 let mut previous_distance = distance(previous);
2176 let mut clipped = Vec::with_capacity(polygon.len() + 1);
2177 for current in polygon {
2178 let current_distance = distance(current);
2179 if (previous_distance <= 0.) != (current_distance <= 0.) {
2180 let fraction = previous_distance / (previous_distance - current_distance);
2181 clipped.push([previous[0] + fraction * (current[0] - previous[0]),
2182 previous[1] + fraction * (current[1] - previous[1])]);
2183 }
2184 if current_distance <= 0. { clipped.push(current); }
2185 previous = current;
2186 previous_distance = current_distance;
2187 }
2188 polygon = clipped;
2189 }
2190 polygon
2191 })
2192 }
2193
2194 fn is_border_visible(&self) -> bool {
2195 self.vn_resolved_border_colors().any(|color| !color.is_transparent())
2196 && self.border_widths.any(|length| !length.is_zero())
2197 }
2198}
2199
2200impl Default for Style {
2201 fn default() -> Self {
2202 Style {
2203 display: Display::Block,
2204 visibility: Visibility::Visible,
2205 overflow: Point {
2206 x: Overflow::Visible,
2207 y: Overflow::Visible,
2208 },
2209 allow_concurrent_scroll: false,
2210 restrict_scroll_to_axis: false,
2211 scrollbar_width: AbsoluteLength::default(),
2212 position: Position::Relative,
2213 inset: Edges::auto(),
2214 margin: Edges::<Length>::zero(),
2215 padding: Edges::<DefiniteLength>::zero(),
2216 border_widths: Edges::<AbsoluteLength>::zero(),
2217 size: Size::auto(),
2218 min_size: Size::auto(),
2219 max_size: Size::auto(),
2220 aspect_ratio: None,
2221 gap: Size::default(),
2222 align_items: None,
2224 align_self: None,
2225 align_content: None,
2226 justify_content: None,
2227 flex_direction: FlexDirection::Row,
2229 flex_wrap: FlexWrap::NoWrap,
2230 flex_grow: 0.0,
2231 flex_shrink: 1.0,
2232 vn_order: 0,
2233 vn_object_position: None,
2234 flex_basis: Length::Auto,
2235 background: None,
2236 background_layers: Vec::new(),
2237 border_color: None,
2238 vn_border_colors: Edges::default(),
2239 border_style: BorderStyle::default(),
2240 corner_radii: Corners::default(),
2241 box_shadow: Default::default(),
2242 vn_shadow_under_box: false,
2243 backdrop_blur: None,
2244 vn_effect: None,
2245 vn_effect_fade: None,
2246 vn_transform: None,
2247 text: TextStyleRefinement::default(),
2248 mouse_cursor: None,
2249 opacity: None,
2250 grid_rows: None,
2251 grid_cols: None,
2252 grid_location: None,
2253 vn_grid_cols: None,
2254 vn_grid_rows: None,
2255 vn_grid_cols_auto: None,
2256 vn_grid_rows_auto: None,
2257 vn_grid_auto_cols: None,
2258 vn_grid_auto_rows: None,
2259 vn_grid_auto_flow: None,
2260 vn_justify_items: None,
2261 vn_justify_self: None,
2262 vn_outline: None,
2263 vn_mask_ring: false,
2264 vn_clip_path: VnClipPath::None,
2265 vn_color_matrix: None,
2266 vn_capture: None,
2267 vn_isolate: false,
2268 vn_contain_size: 0,
2269 vn_text_fill: None,
2270 vn_mask: None,
2271 vn_corner_radii: Corners::default(),
2272 vn_corner_shapes: Corners::default(),
2273
2274 #[cfg(debug_assertions)]
2275 debug: false,
2276 #[cfg(debug_assertions)]
2277 debug_below: false,
2278 }
2279 }
2280}
2281
2282#[derive(Refineable, Copy, Clone, Default, Debug, PartialEq, Eq, Hash, Serialize, Deserialize)]
2284#[cfg_attr(feature = "schemars", derive(JsonSchema))]
2285pub struct UnderlineStyle {
2286 pub thickness: Pixels,
2288
2289 pub color: Option<Hsla>,
2291
2292 pub wavy: bool,
2294
2295 pub offset: Pixels,
2299}
2300
2301#[derive(Refineable, Copy, Clone, Default, Debug, PartialEq, Eq, Hash, Serialize, Deserialize)]
2303#[cfg_attr(feature = "schemars", derive(JsonSchema))]
2304pub struct StrikethroughStyle {
2305 pub thickness: Pixels,
2307
2308 pub color: Option<Hsla>,
2310}
2311
2312#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
2314#[cfg_attr(feature = "schemars", derive(JsonSchema))]
2315pub enum Fill {
2316 Color(Background),
2318}
2319
2320impl Fill {
2321 pub fn color(&self) -> Option<Background> {
2325 match self {
2326 Fill::Color(color) => Some(*color),
2327 }
2328 }
2329}
2330
2331impl Default for Fill {
2332 fn default() -> Self {
2333 Self::Color(Background::default())
2334 }
2335}
2336
2337impl From<Hsla> for Fill {
2338 fn from(color: Hsla) -> Self {
2339 Self::Color(color.into())
2340 }
2341}
2342
2343impl From<Rgba> for Fill {
2344 fn from(color: Rgba) -> Self {
2345 Self::Color(color.into())
2346 }
2347}
2348
2349impl From<Background> for Fill {
2350 fn from(background: Background) -> Self {
2351 Self::Color(background)
2352 }
2353}
2354
2355impl From<TextStyle> for HighlightStyle {
2356 fn from(other: TextStyle) -> Self {
2357 Self::from(&other)
2358 }
2359}
2360
2361impl From<&TextStyle> for HighlightStyle {
2362 fn from(other: &TextStyle) -> Self {
2363 Self {
2364 color: Some(other.color),
2365 font_weight: Some(other.font_weight),
2366 font_style: Some(other.font_style),
2367 background_color: other.background_color,
2368 underline: other.underline,
2369 strikethrough: other.strikethrough,
2370 fade_out: None,
2371 }
2372 }
2373}
2374
2375impl HighlightStyle {
2376 pub fn color(color: Hsla) -> Self {
2378 Self {
2379 color: Some(color),
2380 ..Default::default()
2381 }
2382 }
2383 #[must_use]
2386 pub fn highlight(self, other: HighlightStyle) -> Self {
2387 Self {
2388 color: other
2389 .color
2390 .map(|other_color| {
2391 if let Some(color) = self.color {
2392 color.blend(other_color)
2393 } else {
2394 other_color
2395 }
2396 })
2397 .or(self.color),
2398 font_weight: other.font_weight.or(self.font_weight),
2399 font_style: other.font_style.or(self.font_style),
2400 background_color: other.background_color.or(self.background_color),
2401 underline: other.underline.or(self.underline),
2402 strikethrough: other.strikethrough.or(self.strikethrough),
2403 fade_out: other
2404 .fade_out
2405 .map(|source_fade| {
2406 self.fade_out
2407 .map(|dest_fade| (dest_fade * (1. + source_fade)).clamp(0., 1.))
2408 .unwrap_or(source_fade)
2409 })
2410 .or(self.fade_out),
2411 }
2412 }
2413}
2414
2415impl From<Hsla> for HighlightStyle {
2416 fn from(color: Hsla) -> Self {
2417 Self {
2418 color: Some(color),
2419 ..Default::default()
2420 }
2421 }
2422}
2423
2424impl From<FontWeight> for HighlightStyle {
2425 fn from(font_weight: FontWeight) -> Self {
2426 Self {
2427 font_weight: Some(font_weight),
2428 ..Default::default()
2429 }
2430 }
2431}
2432
2433impl From<FontStyle> for HighlightStyle {
2434 fn from(font_style: FontStyle) -> Self {
2435 Self {
2436 font_style: Some(font_style),
2437 ..Default::default()
2438 }
2439 }
2440}
2441
2442impl From<Rgba> for HighlightStyle {
2443 fn from(color: Rgba) -> Self {
2444 Self {
2445 color: Some(color.into()),
2446 ..Default::default()
2447 }
2448 }
2449}
2450
2451pub fn combine_highlights(
2453 a: impl IntoIterator<Item = (Range<usize>, HighlightStyle)>,
2454 b: impl IntoIterator<Item = (Range<usize>, HighlightStyle)>,
2455) -> impl Iterator<Item = (Range<usize>, HighlightStyle)> {
2456 let mut endpoints = Vec::new();
2457 let mut highlights = Vec::new();
2458 for (range, highlight) in a.into_iter().chain(b) {
2459 if !range.is_empty() {
2460 let highlight_id = highlights.len();
2461 endpoints.push((range.start, highlight_id, true));
2462 endpoints.push((range.end, highlight_id, false));
2463 highlights.push(highlight);
2464 }
2465 }
2466 endpoints.sort_unstable_by_key(|(position, _, _)| *position);
2467 let mut endpoints = endpoints.into_iter().peekable();
2468
2469 let mut active_styles = HashSet::default();
2470 let mut ix = 0;
2471 iter::from_fn(move || {
2472 while let Some((endpoint_ix, highlight_id, is_start)) = endpoints.peek() {
2473 let prev_index = mem::replace(&mut ix, *endpoint_ix);
2474 if ix > prev_index && !active_styles.is_empty() {
2475 let current_style = active_styles
2476 .iter()
2477 .fold(HighlightStyle::default(), |acc, highlight_id| {
2478 acc.highlight(highlights[*highlight_id])
2479 });
2480 return Some((prev_index..ix, current_style));
2481 }
2482
2483 if *is_start {
2484 active_styles.insert(*highlight_id);
2485 } else {
2486 active_styles.remove(highlight_id);
2487 }
2488 endpoints.next();
2489 }
2490 None
2491 })
2492}
2493
2494#[derive(Copy, Clone, PartialEq, Eq, Debug, Serialize, Deserialize)]
2500#[cfg_attr(feature = "schemars", derive(JsonSchema))]
2501pub enum AlignItems {
2503 Start,
2505 End,
2507 FlexStart,
2512 FlexEnd,
2517 Center,
2519 Baseline,
2521 Stretch,
2523}
2524pub type JustifyItems = AlignItems;
2530pub type AlignSelf = AlignItems;
2537pub type JustifySelf = AlignItems;
2544
2545#[derive(Copy, Clone, PartialEq, Eq, Debug, Serialize, Deserialize)]
2551#[cfg_attr(feature = "schemars", derive(JsonSchema))]
2552pub enum AlignContent {
2554 Start,
2556 End,
2558 FlexStart,
2563 FlexEnd,
2568 Center,
2570 Stretch,
2572 SpaceBetween,
2575 SpaceEvenly,
2578 SpaceAround,
2581 SafeCenter,
2585}
2586
2587pub type JustifyContent = AlignContent;
2593
2594#[derive(Copy, Clone, PartialEq, Eq, Debug, Default, Serialize, Deserialize)]
2598#[cfg_attr(feature = "schemars", derive(JsonSchema))]
2599pub enum Display {
2601 Block,
2603 #[default]
2605 Flex,
2606 Grid,
2608 None,
2610}
2611
2612#[derive(Copy, Clone, PartialEq, Eq, Debug, Default, Serialize, Deserialize)]
2618#[cfg_attr(feature = "schemars", derive(JsonSchema))]
2619pub enum FlexWrap {
2621 #[default]
2623 NoWrap,
2624 Wrap,
2626 WrapReverse,
2628}
2629
2630#[derive(Copy, Clone, PartialEq, Eq, Debug, Default, Serialize, Deserialize)]
2642#[cfg_attr(feature = "schemars", derive(JsonSchema))]
2643pub enum FlexDirection {
2645 #[default]
2649 Row,
2650 Column,
2654 RowReverse,
2658 ColumnReverse,
2662}
2663
2664#[derive(Copy, Clone, PartialEq, Eq, Debug, Default, Serialize, Deserialize)]
2678#[cfg_attr(feature = "schemars", derive(JsonSchema))]
2679pub enum Overflow {
2681 #[default]
2684 Visible,
2685 Clip,
2688 Hidden,
2691 Scroll,
2695}
2696
2697#[derive(Copy, Clone, PartialEq, Eq, Debug, Default, Serialize, Deserialize)]
2707#[cfg_attr(feature = "schemars", derive(JsonSchema))]
2708pub enum Position {
2710 #[default]
2713 Relative,
2714 Absolute,
2720}
2721
2722impl From<AlignItems> for taffy::style::AlignItems {
2723 fn from(value: AlignItems) -> Self {
2724 match value {
2725 AlignItems::Start => Self::START,
2726 AlignItems::End => Self::END,
2727 AlignItems::FlexStart => Self::FLEX_START,
2728 AlignItems::FlexEnd => Self::FLEX_END,
2729 AlignItems::Center => Self::CENTER,
2730 AlignItems::Baseline => Self::BASELINE,
2731 AlignItems::Stretch => Self::STRETCH,
2732 }
2733 }
2734}
2735
2736impl From<AlignContent> for taffy::style::AlignContent {
2737 fn from(value: AlignContent) -> Self {
2738 match value {
2739 AlignContent::Start => Self::START,
2740 AlignContent::End => Self::END,
2741 AlignContent::FlexStart => Self::FLEX_START,
2742 AlignContent::FlexEnd => Self::FLEX_END,
2743 AlignContent::Center => Self::CENTER,
2744 AlignContent::Stretch => Self::STRETCH,
2745 AlignContent::SpaceBetween => Self::SPACE_BETWEEN,
2746 AlignContent::SpaceEvenly => Self::SPACE_EVENLY,
2747 AlignContent::SpaceAround => Self::SPACE_AROUND,
2748 AlignContent::SafeCenter => Self::SAFE_CENTER,
2749 }
2750 }
2751}
2752
2753impl From<Display> for taffy::style::Display {
2754 fn from(value: Display) -> Self {
2755 match value {
2756 Display::Block => Self::Block,
2757 Display::Flex => Self::Flex,
2758 Display::Grid => Self::Grid,
2759 Display::None => Self::None,
2760 }
2761 }
2762}
2763
2764impl From<FlexWrap> for taffy::style::FlexWrap {
2765 fn from(value: FlexWrap) -> Self {
2766 match value {
2767 FlexWrap::NoWrap => Self::NoWrap,
2768 FlexWrap::Wrap => Self::Wrap,
2769 FlexWrap::WrapReverse => Self::WrapReverse,
2770 }
2771 }
2772}
2773
2774impl From<FlexDirection> for taffy::style::FlexDirection {
2775 fn from(value: FlexDirection) -> Self {
2776 match value {
2777 FlexDirection::Row => Self::Row,
2778 FlexDirection::Column => Self::Column,
2779 FlexDirection::RowReverse => Self::RowReverse,
2780 FlexDirection::ColumnReverse => Self::ColumnReverse,
2781 }
2782 }
2783}
2784
2785impl From<Overflow> for taffy::style::Overflow {
2786 fn from(value: Overflow) -> Self {
2787 match value {
2788 Overflow::Visible => Self::Visible,
2789 Overflow::Clip => Self::Clip,
2790 Overflow::Hidden => Self::Hidden,
2791 Overflow::Scroll => Self::Scroll,
2792 }
2793 }
2794}
2795
2796impl From<Position> for taffy::style::Position {
2797 fn from(value: Position) -> Self {
2798 match value {
2799 Position::Relative => Self::Relative,
2800 Position::Absolute => Self::Absolute,
2801 }
2802 }
2803}
2804
2805#[cfg(test)]
2806mod tests {
2807 use crate::{blue, green, px, red, yellow};
2808
2809 use super::*;
2810
2811 use util_macros::perf;
2812
2813 #[perf]
2814 fn test_basic_highlight_style_combination() {
2815 let style_a = HighlightStyle::default();
2816 let style_b = HighlightStyle::default();
2817 let style_a = style_a.highlight(style_b);
2818 assert_eq!(
2819 style_a,
2820 HighlightStyle::default(),
2821 "Combining empty styles should not produce a non-empty style."
2822 );
2823
2824 let style_b = HighlightStyle {
2825 color: Some(red()),
2826 strikethrough: Some(StrikethroughStyle {
2827 thickness: px(2.),
2828 color: Some(blue()),
2829 }),
2830 fade_out: Some(0.),
2831 font_style: Some(FontStyle::Italic),
2832 font_weight: Some(FontWeight(300.)),
2833 background_color: Some(yellow()),
2834 underline: Some(UnderlineStyle {
2835 thickness: px(2.),
2836 color: Some(red()),
2837 wavy: true,
2838 offset: px(0.),
2839 }),
2840 };
2841 let expected_style = style_b;
2842
2843 let style_a = style_a.highlight(style_b);
2844 assert_eq!(
2845 style_a, expected_style,
2846 "Blending an empty style with another style should return the other style"
2847 );
2848
2849 let style_b = style_b.highlight(Default::default());
2850 assert_eq!(
2851 style_b, expected_style,
2852 "Blending a style with an empty style should not change the style."
2853 );
2854
2855 let style_c = expected_style;
2856
2857 let style_d = HighlightStyle {
2858 color: Some(blue().alpha(0.7)),
2859 strikethrough: Some(StrikethroughStyle {
2860 thickness: px(4.),
2861 color: Some(crate::red()),
2862 }),
2863 fade_out: Some(0.),
2864 font_style: Some(FontStyle::Oblique),
2865 font_weight: Some(FontWeight(800.)),
2866 background_color: Some(green()),
2867 underline: Some(UnderlineStyle {
2868 thickness: px(4.),
2869 color: None,
2870 wavy: false,
2871 offset: px(0.),
2872 }),
2873 };
2874
2875 let expected_style = HighlightStyle {
2876 color: Some(red().blend(blue().alpha(0.7))),
2877 strikethrough: Some(StrikethroughStyle {
2878 thickness: px(4.),
2879 color: Some(red()),
2880 }),
2881 fade_out: Some(0.),
2883 font_style: Some(FontStyle::Oblique),
2884 font_weight: Some(FontWeight(800.)),
2885 background_color: Some(green()),
2886 underline: Some(UnderlineStyle {
2887 thickness: px(4.),
2888 color: None,
2889 wavy: false,
2890 offset: px(0.),
2891 }),
2892 };
2893
2894 let style_c = style_c.highlight(style_d);
2895 assert_eq!(
2896 style_c, expected_style,
2897 "Blending styles should blend properties where possible and override all others"
2898 );
2899 }
2900
2901 #[perf]
2902 fn test_combine_highlights() {
2903 assert_eq!(
2904 combine_highlights(
2905 [
2906 (0..5, green().into()),
2907 (4..10, FontWeight::BOLD.into()),
2908 (15..20, yellow().into()),
2909 ],
2910 [
2911 (2..6, FontStyle::Italic.into()),
2912 (1..3, blue().into()),
2913 (21..23, red().into()),
2914 ]
2915 )
2916 .collect::<Vec<_>>(),
2917 [
2918 (
2919 0..1,
2920 HighlightStyle {
2921 color: Some(green()),
2922 ..Default::default()
2923 }
2924 ),
2925 (
2926 1..2,
2927 HighlightStyle {
2928 color: Some(blue()),
2929 ..Default::default()
2930 }
2931 ),
2932 (
2933 2..3,
2934 HighlightStyle {
2935 color: Some(blue()),
2936 font_style: Some(FontStyle::Italic),
2937 ..Default::default()
2938 }
2939 ),
2940 (
2941 3..4,
2942 HighlightStyle {
2943 color: Some(green()),
2944 font_style: Some(FontStyle::Italic),
2945 ..Default::default()
2946 }
2947 ),
2948 (
2949 4..5,
2950 HighlightStyle {
2951 color: Some(green()),
2952 font_weight: Some(FontWeight::BOLD),
2953 font_style: Some(FontStyle::Italic),
2954 ..Default::default()
2955 }
2956 ),
2957 (
2958 5..6,
2959 HighlightStyle {
2960 font_weight: Some(FontWeight::BOLD),
2961 font_style: Some(FontStyle::Italic),
2962 ..Default::default()
2963 }
2964 ),
2965 (
2966 6..10,
2967 HighlightStyle {
2968 font_weight: Some(FontWeight::BOLD),
2969 ..Default::default()
2970 }
2971 ),
2972 (
2973 15..20,
2974 HighlightStyle {
2975 color: Some(yellow()),
2976 ..Default::default()
2977 }
2978 ),
2979 (
2980 21..23,
2981 HighlightStyle {
2982 color: Some(red()),
2983 ..Default::default()
2984 }
2985 )
2986 ]
2987 );
2988 }
2989
2990 #[perf]
2991 fn test_text_style_refinement() {
2992 let mut style = Style::default();
2993 style.refine(&StyleRefinement::default().text_size(px(20.0)));
2994 style.refine(&StyleRefinement::default().font_weight(FontWeight::SEMIBOLD));
2995
2996 assert_eq!(
2997 Some(AbsoluteLength::from(px(20.0))),
2998 style.text_style().unwrap().font_size
2999 );
3000
3001 assert_eq!(
3002 Some(FontWeight::SEMIBOLD),
3003 style.text_style().unwrap().font_weight
3004 );
3005 }
3006}
3007
3008#[cfg(test)]
3012mod vn_object_position_tests {
3013 use super::*;
3014 use crate::{px, size};
3015
3016 #[test]
3017 fn the_position_places_the_fitted_image_in_the_free_space() {
3018 let bounds = Bounds::new(point(px(10.), px(20.)), size(px(100.), px(50.)));
3019 let square = size(DevicePixels(40), DevicePixels(40));
3020 let at = |fit: ObjectFit, x: (f32, f32), y: (f32, f32)| {
3021 let position = ObjectPosition {
3022 x_fraction: x.0,
3023 x_offset: px(x.1),
3024 y_fraction: y.0,
3025 y_offset: px(y.1),
3026 };
3027 let b = fit.get_bounds_at(bounds, square, position);
3028 (f32::from(b.origin.x), f32::from(b.origin.y), f32::from(b.size.width), f32::from(b.size.height))
3029 };
3030 assert_eq!(at(ObjectFit::Contain, (0., 0.), (0., 0.)), (10., 20., 50., 50.));
3031 assert_eq!(at(ObjectFit::Contain, (1., -5.), (0.5, 0.)), (55., 20., 50., 50.));
3032 assert_eq!(at(ObjectFit::Cover, (0., 0.), (1., 0.)), (10., -30., 100., 100.));
3033 assert_eq!(at(ObjectFit::None, (0.25, 0.), (0., 3.)), (25., 23., 40., 40.));
3034 assert_eq!(at(ObjectFit::Fill, (0.5, 7.), (0.5, 0.)), (17., 20., 100., 50.));
3035 let legacy = ObjectFit::None.get_bounds(bounds, square);
3036 assert_eq!(legacy.origin, bounds.origin);
3037 }
3038}
3039
3040#[cfg(test)]
3041mod vn_safe_center_tests {
3042 use crate::{AlignContent, Context, TestAppContext, Window, div, prelude::*, px, size};
3043
3044 struct Boxes;
3045
3046 impl Render for Boxes {
3047 fn render(&mut self, _window: &mut Window, _cx: &mut Context<Self>) -> impl IntoElement {
3048 let block = |name: &'static str, child_h: f32| {
3049 let mut d = div().w(px(100.)).h(px(100.));
3050 d.style().align_content = Some(AlignContent::SafeCenter);
3051 d.child(div().debug_selector(move || name.into()).w(px(10.)).h(px(child_h)))
3052 };
3053 div().child(block("FITS", 20.)).child(block("OVERFLOWS", 200.))
3054 }
3055 }
3056
3057 #[gpui::test]
3058 fn safe_center_centres_what_fits_and_starts_what_overflows(cx: &mut TestAppContext) {
3059 let window = cx.open_window(size(px(400.), px(600.)), |_, _| Boxes);
3060 cx.run_until_parked();
3061 window
3062 .update(cx, |_, window, _| {
3063 let at = |name: &str| window.rendered_frame.debug_bounds.get(name).copied().unwrap();
3064 assert_eq!(at("FITS").origin.y, px(40.), "(100 - 20) / 2");
3065 assert_eq!(at("OVERFLOWS").origin.y, px(100.), "at the start of the second box");
3066 })
3067 .unwrap();
3068 }
3069}
3070
3071#[cfg(test)]
3073mod vn_mask_ring_tests {
3074 use crate::{
3075 BoxShadow, Context, Hsla, TestAppContext, Window, color::BG_RING, div, point,
3076 prelude::*, px, size,
3077 };
3078
3079 struct Card {
3080 ring: bool,
3081 }
3082
3083 impl Render for Card {
3084 fn render(&mut self, _window: &mut Window, _cx: &mut Context<Self>) -> impl IntoElement {
3085 let mut d = div()
3086 .w(px(100.))
3087 .h(px(60.))
3088 .p(px(2.))
3089 .border_1()
3090 .border_color(Hsla::white())
3091 .bg(Hsla::red())
3092 .shadow(vec![BoxShadow {
3093 color: Hsla::black(),
3094 offset: point(px(0.), px(4.)),
3095 blur_radius: px(8.),
3096 spread_radius: px(0.),
3097 inset: false,
3098 }]);
3099 d.style().vn_mask_ring = Some(self.ring);
3100 d
3101 }
3102 }
3103
3104 fn paint(ring: bool, cx: &mut TestAppContext) -> (Vec<crate::Quad>, usize, f32) {
3106 let window = cx.open_window(size(px(300.), px(300.)), move |_, _| Card { ring });
3107 cx.run_until_parked();
3108 window
3109 .update(cx, |_, window, _| {
3110 let shadows = window.rendered_frame.scene.shadows.len();
3111 (window.painted_quads(), shadows, window.scale_factor())
3112 })
3113 .unwrap()
3114 }
3115
3116 #[gpui::test]
3117 fn a_ring_mask_paints_the_background_in_the_padding_and_border_only(
3118 cx: &mut TestAppContext,
3119 ) {
3120 let (quads, shadows, scale) = paint(false, cx);
3121 let background = quads.iter().find(|q| q.background.as_solid() == Some(Hsla::red()));
3122 let background = background.expect("the background quad");
3123 assert_eq!(background.background.flags & BG_RING, 0);
3124 assert_eq!(background.border_widths.top.0, 0.0, "a plain background fills the box");
3125 assert_eq!(shadows, 1);
3126
3127 let (quads, shadows, _) = paint(true, cx);
3128 let background = quads
3129 .iter()
3130 .find(|q| q.background.flags & BG_RING != 0)
3131 .expect("the background quad, flagged");
3132 assert_eq!(background.background.as_solid(), Some(Hsla::red()));
3133 for width in [
3134 background.border_widths.top,
3135 background.border_widths.right,
3136 background.border_widths.bottom,
3137 background.border_widths.left,
3138 ] {
3139 assert_eq!(width.0, 3.0 * scale, "1px border + 2px padding");
3140 }
3141 let border = quads
3142 .iter()
3143 .find(|q| q.border_color == Hsla::white())
3144 .expect("the border still paints");
3145 assert_eq!(border.border_widths.top.0, 1.0 * scale);
3146 assert_eq!(shadows, 0, "the mask cuts the outer shadow");
3147 }
3148}
3149
3150#[cfg(test)]
3153mod vn_rounded_clip_tests {
3154 use crate::{
3155 Bounds, Context, Corners, DefiniteLength, Edges, Hsla, Overflow, Style, TestAppContext,
3156 VnCornerRadius, Window, div, point, prelude::*, px, size, vn_resolve_corner_radii,
3157 vn_take_ellipse_drawn_as_circle,
3158 };
3159
3160 fn clipping(radius: f32, border: f32, border_color: Option<Hsla>) -> Style {
3161 Style {
3162 overflow: point(Overflow::Hidden, Overflow::Hidden),
3163 corner_radii: Corners::all(px(radius)).map(|radius| (*radius).into()),
3164 border_widths: Edges::all(px(border).into()),
3165 border_color,
3166 ..Style::default()
3167 }
3168 }
3169
3170 #[test]
3171 fn an_overflow_clip_takes_the_padding_box_curve() {
3172 let rem = px(16.);
3173 let bounds = Bounds::new(point(px(10.), px(20.)), size(px(200.), px(160.)));
3174
3175 let mask = clipping(24., 4., Some(Hsla::black())).overflow_mask(bounds, rem).unwrap();
3176 assert_eq!(mask.bounds, Bounds::new(point(px(14.), px(24.)), size(px(192.), px(152.))));
3177 assert_eq!(mask.corner_radii, Corners::all(px(20.)), "the radius less the border");
3178
3179 let mask = clipping(24., 4., None).overflow_mask(bounds, rem).unwrap();
3180 assert_eq!(mask.bounds, bounds, "a transparent border is not inset");
3181 assert_eq!(mask.corner_radii, Corners::all(px(24.)), "so it takes nothing off");
3182
3183 let mask = clipping(3., 4., Some(Hsla::black())).overflow_mask(bounds, rem).unwrap();
3184 assert_eq!(mask.corner_radii, Corners::all(px(0.)), "a border wider than the radius");
3185
3186 let avatar = Bounds::new(point(px(0.), px(0.)), size(px(64.), px(64.)));
3187 let mask = clipping(9999., 0., None).overflow_mask(avatar, rem).unwrap();
3188 assert_eq!(mask.corner_radii, Corners::all(px(32.)), "a pill is a circle");
3189
3190 let mask = clipping(0., 0., None).overflow_mask(bounds, rem).unwrap();
3191 assert!(!mask.is_rounded(), "no radius, the plain rect");
3192 }
3193
3194 fn resolve(lengths: [f32; 4], relative: [Option<(DefiniteLength, DefiniteLength)>; 4], w: f32, h: f32) -> [f32; 4] {
3195 let corner = |r: Option<(DefiniteLength, DefiniteLength)>| r.map(|(x, y)| VnCornerRadius { x, y });
3196 let radii = vn_resolve_corner_radii(
3197 &Corners {
3198 top_left: px(lengths[0]).into(),
3199 top_right: px(lengths[1]).into(),
3200 bottom_right: px(lengths[2]).into(),
3201 bottom_left: px(lengths[3]).into(),
3202 },
3203 &Corners {
3204 top_left: corner(relative[0]),
3205 top_right: corner(relative[1]),
3206 bottom_right: corner(relative[2]),
3207 bottom_left: corner(relative[3]),
3208 },
3209 size(px(w), px(h)),
3210 px(16.),
3211 );
3212 [radii.top_left, radii.top_right, radii.bottom_right, radii.bottom_left].map(f32::from)
3213 }
3214
3215 #[test]
3216 fn percentages_resolve_against_the_box_and_overlaps_scale() {
3217 let half = Some((DefiniteLength::Fraction(0.5), DefiniteLength::Fraction(0.5)));
3218 let _ = vn_take_ellipse_drawn_as_circle();
3219
3220 assert_eq!(resolve([0.; 4], [half; 4], 64., 64.), [32.; 4], "50% of a square: a circle");
3221 assert!(!vn_take_ellipse_drawn_as_circle());
3222
3223 assert_eq!(resolve([0.; 4], [half; 4], 120., 48.), [24.; 4]);
3226 assert!(vn_take_ellipse_drawn_as_circle());
3227
3228 assert_eq!(resolve([9999.; 4], [None; 4], 100., 40.), [20.; 4]);
3230 assert_eq!(resolve([9999., 0., 0., 9999.], [None; 4], 100., 40.), [20., 0., 0., 20.]);
3233 assert_eq!(resolve([8., 4., 0., 12.], [None; 4], 100., 40.), [8., 4., 0., 12.]);
3235 assert_eq!(resolve([40., 40., 0., 0.], [None; 4], 60., 200.), [30., 30., 0., 0.]);
3237
3238 let calc = DefiniteLength::Calc { fraction: 0.5, pixels: px(-4.) };
3240 assert_eq!(resolve([0.; 4], [Some((calc, calc)); 4], 64., 64.), [28.; 4]);
3241 let ellipse = Some((DefiniteLength::Absolute(px(10.).into()), DefiniteLength::Absolute(px(20.).into())));
3242 assert_eq!(resolve([0.; 4], [ellipse; 4], 100., 100.), [10.; 4]);
3243 assert!(vn_take_ellipse_drawn_as_circle());
3244 }
3245
3246 #[test]
3247 fn a_percentage_radius_clips_overflow_too() {
3248 let mut avatar = clipping(0., 0., None);
3249 let half = Some(VnCornerRadius {
3250 x: DefiniteLength::Fraction(0.5),
3251 y: DefiniteLength::Fraction(0.5),
3252 });
3253 avatar.vn_corner_radii = Corners {
3254 top_left: half,
3255 top_right: half,
3256 bottom_right: half,
3257 bottom_left: half,
3258 };
3259 let bounds = Bounds::new(point(px(0.), px(0.)), size(px(40.), px(40.)));
3260 let mask = avatar.overflow_mask(bounds, px(16.)).unwrap();
3261 assert_eq!(mask.corner_radii, Corners::all(px(20.)));
3262 }
3263
3264 struct Clips;
3267
3268 impl Render for Clips {
3269 fn render(&mut self, _window: &mut Window, _cx: &mut Context<Self>) -> impl IntoElement {
3270 div()
3271 .child(
3272 div()
3273 .size(px(64.))
3274 .rounded_full()
3275 .overflow_hidden()
3276 .child(div().size_full().bg(Hsla::red())),
3277 )
3278 .child(
3279 div()
3280 .w(px(200.))
3281 .h(px(160.))
3282 .rounded(px(24.))
3283 .overflow_hidden()
3284 .child(
3285 div()
3286 .id("list")
3287 .size_full()
3288 .overflow_y_scroll()
3289 .child(div().w_full().h(px(400.)).bg(Hsla::green())),
3290 ),
3291 )
3292 }
3293 }
3294
3295 #[gpui::test]
3296 fn what_paints_inside_carries_the_rounded_mask(cx: &mut TestAppContext) {
3297 let window = cx.open_window(size(px(400.), px(400.)), |_, _| Clips);
3298 cx.run_until_parked();
3299 let (quads, scale) = window
3300 .update(cx, |_, window, _| (window.painted_quads(), window.scale_factor()))
3301 .unwrap();
3302 let quad = |color: Hsla| {
3303 quads
3304 .iter()
3305 .find(|q| q.background.as_solid() == Some(color))
3306 .copied()
3307 .expect("the quad")
3308 };
3309
3310 let avatar = quad(Hsla::red());
3311 assert_eq!(avatar.content_mask.corner_radii, Corners::all(px(32.)).scale(scale));
3312 assert_eq!(avatar.corner_radii, Corners::default(), "the image itself is square");
3313
3314 let rows = quad(Hsla::green());
3317 assert_eq!(rows.content_mask.corner_radii, Corners::all(px(24.)).scale(scale));
3318 assert_eq!(rows.content_mask.bounds.size, size(px(200.), px(160.)).scale(scale));
3319 }
3320}
3321
3322#[cfg(test)]
3325mod vn_clip_path_tests {
3326 use crate::{
3327 Bounds, BoxShadow, Context, Corners, DefiniteLength, Edges, Hsla, Length, Pixels, Style,
3328 TestAppContext, VnClipBox, VnClipPath, VnCornerRadius, VnShapeRadius, Window, div, point,
3329 prelude::*, px, relative, size,
3330 };
3331
3332 const BOX: VnClipBox = VnClipBox::Border;
3333
3334 fn len(v: f32) -> DefiniteLength {
3335 px(v).into()
3336 }
3337
3338 fn round(x: DefiniteLength, y: DefiniteLength) -> [VnCornerRadius; 4] {
3339 [VnCornerRadius { x, y }; 4]
3340 }
3341
3342 fn mask(clip: VnClipPath, style: Style, bounds: [f32; 4]) -> ([f32; 4], [f32; 4]) {
3344 let bounds = Bounds::new(point(px(bounds[0]), px(bounds[1])), size(px(bounds[2]), px(bounds[3])));
3345 let m = Style { vn_clip_path: clip, ..style }.vn_clip_mask(bounds, px(16.)).expect("a mask");
3346 let (b, r) = (m.bounds, m.corner_radii);
3347 let at = |v: Pixels| (f32::from(v) * 100.).round() / 100.;
3348 (
3349 [b.origin.x, b.origin.y, b.size.width, b.size.height].map(at),
3350 [r.top_left, r.top_right, r.bottom_right, r.bottom_left].map(at),
3351 )
3352 }
3353
3354 fn inset(insets: [DefiniteLength; 4], radii: [VnCornerRadius; 4]) -> VnClipPath {
3355 VnClipPath::Inset { reference: BOX, insets, radii }
3356 }
3357
3358 fn ellipse(center: [DefiniteLength; 2], radius: [VnShapeRadius; 2], circle: bool) -> VnClipPath {
3359 VnClipPath::Ellipse { reference: BOX, center, radius, circle }
3360 }
3361
3362 #[test]
3363 fn inset_takes_its_insets_off_the_box_and_fits_its_radii() {
3364 let none = Style::default;
3365 let square = round(len(0.), len(0.));
3366 assert_eq!(Style::default().vn_clip_mask(Bounds::default(), px(16.)), None, "none is no mask");
3367 let insets = [len(10.), relative(0.2), len(10.), relative(0.2)];
3369 assert_eq!(
3370 mask(inset(insets, round(len(8.), len(8.))), none(), [10., 20., 200., 100.]),
3371 ([50., 30., 120., 80.], [8.; 4])
3372 );
3373 let half = relative(0.5);
3375 assert_eq!(mask(inset([half; 4], square), none(), [0., 0., 30., 10.]).0, [15., 5., 0., 0.]);
3376 assert_eq!(mask(inset([len(80.); 4], square), none(), [0., 0., 100., 100.]).0, [80., 80., 0., 0.]);
3378 let strip = [len(40.), len(0.), len(40.), len(0.)];
3382 assert_eq!(mask(inset(strip, round(len(30.), len(30.))), none(), [0., 0., 200., 100.]).1, [10.; 4]);
3383 let ten = relative(0.1);
3384 assert_eq!(mask(inset([len(0.); 4], round(ten, ten)), none(), [0., 0., 200., 100.]).1, [10.; 4]);
3385 }
3386
3387 #[test]
3388 fn circle_and_ellipse_resolve_against_the_box() {
3389 let none = Style::default;
3390 let mid = [relative(0.5), relative(0.5)];
3391 let circle = ellipse(mid, [VnShapeRadius::Length(relative(0.5)); 2], true);
3393 assert_eq!(mask(circle.clone(), none(), [0., 0., 60., 60.]), ([0., 0., 60., 60.], [30.; 4]));
3394 assert_eq!(mask(circle, none(), [0., 0., 200., 100.]).1, [79.06; 4]);
3396 let at = [relative(0.25), relative(0.5)];
3398 assert_eq!(
3399 mask(ellipse(at, [VnShapeRadius::ClosestSide; 2], true), none(), [0., 0., 200., 100.]),
3400 ([0., 0., 100., 100.], [50.; 4])
3401 );
3402 let far = ellipse(at, [VnShapeRadius::FarthestSide; 2], true);
3403 assert_eq!(mask(far, none(), [0., 0., 200., 100.]).1, [150.; 4]);
3404 let e = ellipse(mid, [VnShapeRadius::ClosestSide, VnShapeRadius::FarthestSide], false);
3408 assert_eq!(mask(e.clone(), none(), [0., 0., 200., 100.]), ([0., 0., 200., 100.], [0.; 4]));
3409 let bounds = Bounds::new(point(px(0.), px(0.)), size(px(200.), px(100.)));
3410 let outline = Style { vn_clip_path: e, ..none() }.vn_clip_outline(bounds, px(16.)).expect("an outline");
3411 let g = crate::VnClipGeometry::new(&outline, 1., crate::TransformationMatrix::unit());
3412 assert!(g.contains([100., 50.]) && g.contains([2., 50.]) && g.contains([100., 2.]));
3413 assert!(!g.contains([20., 10.]), "the corner a capsule would keep");
3414 let right = [DefiniteLength::Calc { fraction: 1., pixels: px(-10.) }, relative(0.5)];
3416 let e = ellipse(right, [VnShapeRadius::Length(len(10.)), VnShapeRadius::Length(relative(0.2))], false);
3417 assert_eq!(mask(e, none(), [0., 0., 200., 100.]), ([180., 30., 20., 40.], [0.; 4]));
3418 let c = Style { vn_clip_path: ellipse(mid, [VnShapeRadius::ClosestSide; 2], true), ..none() };
3420 assert_eq!(c.vn_clip_outline(bounds, px(16.)), None);
3421 }
3422
3423 #[test]
3424 fn a_box_alone_is_rounded_as_the_border_radius_rounds_it() {
3425 let style = || Style {
3426 corner_radii: Corners::all(px(24.)).map(|r| (*r).into()),
3427 border_widths: Edges::all(px(4.).into()),
3428 padding: Edges::all(px(6.).into()),
3429 margin: Edges { top: Length::Auto, ..Edges::all(len(8.).into()) },
3430 ..Style::default()
3431 };
3432 let at = [0., 0., 100., 80.];
3433 assert_eq!(mask(VnClipPath::Box(VnClipBox::Border), style(), at), ([0., 0., 100., 80.], [24.; 4]));
3434 assert_eq!(mask(VnClipPath::Box(VnClipBox::Padding), style(), at), ([4., 4., 92., 72.], [20.; 4]));
3435 assert_eq!(mask(VnClipPath::Box(VnClipBox::Content), style(), at), ([10., 10., 80., 60.], [14.; 4]));
3436 assert_eq!(mask(VnClipPath::Box(VnClipBox::Margin), style(), at), ([-8., 0., 116., 88.], [32.; 4]));
3438 let clip = VnClipPath::Inset { reference: VnClipBox::Content, insets: [len(5.); 4], radii: round(len(0.), len(0.)) };
3440 assert_eq!(mask(clip, style(), at), ([15., 15., 70., 50.], [0.; 4]));
3441 }
3442
3443 struct Clipped;
3446
3447 impl Render for Clipped {
3448 fn render(&mut self, _window: &mut Window, _cx: &mut Context<Self>) -> impl IntoElement {
3449 let mut d = div()
3450 .size(px(60.))
3451 .bg(Hsla::red())
3452 .border_2()
3453 .border_color(Hsla::white())
3454 .shadow(vec![BoxShadow {
3455 color: Hsla::black(),
3456 offset: point(px(0.), px(4.)),
3457 blur_radius: px(8.),
3458 spread_radius: px(0.),
3459 inset: false,
3460 }])
3461 .child(div().size(px(100.)).bg(Hsla::green()));
3462 d.style().vn_clip_path = Some(VnClipPath::Ellipse {
3463 reference: VnClipBox::Border,
3464 center: [relative(0.5), relative(0.5)],
3465 radius: [VnShapeRadius::Length(relative(0.5)); 2],
3466 circle: true,
3467 });
3468 div().child(d)
3469 }
3470 }
3471
3472 #[gpui::test]
3473 fn everything_the_element_paints_carries_the_mask(cx: &mut TestAppContext) {
3474 let window = cx.open_window(size(px(200.), px(200.)), |_, _| Clipped);
3475 cx.run_until_parked();
3476 let (quads, shadows, scale) = window
3477 .update(cx, |_, window, _| {
3478 (window.painted_quads(), window.rendered_frame.scene.shadows.clone(), window.scale_factor())
3479 })
3480 .unwrap();
3481 let disc = Bounds::new(point(px(0.), px(0.)), size(px(60.), px(60.))).scale(scale);
3482 let radius = Corners::all(px(30.)).scale(scale);
3483 for color in [Hsla::red(), Hsla::green()] {
3484 let q = quads.iter().find(|q| q.background.as_solid() == Some(color)).expect("the quad");
3485 assert_eq!((q.content_mask.bounds, q.content_mask.corner_radii), (disc, radius), "{color:?}");
3486 }
3487 let border = quads.iter().find(|q| q.border_color == Hsla::white()).expect("the border");
3488 assert_eq!(border.content_mask.bounds, disc);
3489 assert_eq!(shadows.len(), 1);
3490 assert_eq!((shadows[0].content_mask.bounds, shadows[0].content_mask.corner_radii), (disc, radius));
3491 }
3492
3493 fn polygon(reference: VnClipBox, fill_rule: crate::VnFillRule, points: &[[DefiniteLength; 2]]) -> VnClipPath {
3494 VnClipPath::Polygon { reference, fill_rule, points: points.to_vec().into() }
3495 }
3496
3497 fn outline(clip: VnClipPath, style: Style, at: [f32; 4]) -> crate::VnClipOutline {
3498 let bounds = Bounds::new(point(px(at[0]), px(at[1])), size(px(at[2]), px(at[3])));
3499 Style { vn_clip_path: clip, ..style }.vn_clip_outline(bounds, px(16.)).expect("an outline")
3500 }
3501
3502 #[test]
3503 fn a_polygon_resolves_its_percentages_against_the_reference_box() {
3504 use crate::{VnFillRule, VnPathVerb::*};
3505 let triangle = [[relative(0.5), len(0.)], [relative(1.), relative(1.)], [len(0.), relative(1.)]];
3507 let o = outline(polygon(BOX, VnFillRule::NonZero, &triangle), Style::default(), [10., 20., 200., 100.]);
3508 assert_eq!(o.verbs, vec![MoveTo([110., 20.]), LineTo([210., 120.]), LineTo([10., 120.]), Close]);
3509 assert_eq!(
3511 mask(polygon(BOX, VnFillRule::NonZero, &triangle), Style::default(), [10., 20., 200., 100.]),
3512 ([10., 20., 200., 100.], [0.; 4])
3513 );
3514 let style = || Style {
3516 border_widths: Edges::all(px(4.).into()),
3517 padding: Edges::all(px(6.).into()),
3518 ..Style::default()
3519 };
3520 let o = outline(polygon(VnClipBox::Content, VnFillRule::EvenOdd, &triangle), style(), [0., 0., 100., 100.]);
3521 assert_eq!(o.fill_rule, VnFillRule::EvenOdd);
3522 assert_eq!(o.verbs[0], MoveTo([50., 10.]));
3523 assert_eq!(o.verbs[1], LineTo([90., 90.]));
3524 let past = [[DefiniteLength::Calc { fraction: 1., pixels: px(-10.) }, relative(1.5)]];
3526 assert_eq!(
3527 outline(polygon(BOX, VnFillRule::NonZero, &past), Style::default(), [0., 0., 100., 40.]).verbs[0],
3528 MoveTo([90., 60.])
3529 );
3530 }
3531
3532 #[test]
3533 fn a_path_is_laid_from_the_reference_box_corner() {
3534 use crate::{VnFillRule, VnPathVerb::*};
3535 let verbs = vec![MoveTo([0., 0.]), QuadTo([10., 20.], [20., 0.]), Close];
3536 let path = |reference| VnClipPath::Path { reference, fill_rule: VnFillRule::NonZero, verbs: verbs.clone().into() };
3537 let o = outline(path(BOX), Style::default(), [5., 7., 50., 50.]);
3538 assert_eq!(o.verbs, vec![MoveTo([5., 7.]), QuadTo([15., 27.], [25., 7.]), Close]);
3539 let style = Style { padding: Edges::all(px(3.).into()), ..Style::default() };
3540 let o = outline(path(VnClipBox::Content), style, [0., 0., 50., 50.]);
3541 assert_eq!(o.verbs[0], MoveTo([3., 3.]));
3542 assert_eq!(mask(path(BOX), Style::default(), [5., 7., 50., 50.]).0, [5., 7., 20., 20.]);
3544 }
3545
3546 struct Triangle;
3548
3549 impl Render for Triangle {
3550 fn render(&mut self, _window: &mut Window, _cx: &mut Context<Self>) -> impl IntoElement {
3551 let mut d = div()
3552 .size(px(100.))
3553 .bg(Hsla::red())
3554 .cursor_pointer()
3555 .child(div().size(px(100.)).bg(Hsla::green()))
3556 .child(crate::deferred(div().absolute().top_0().left_0().size(px(50.)).bg(Hsla::blue())).clip_to_ancestors(true));
3557 d.style().vn_clip_path = Some(polygon(
3558 BOX,
3559 crate::VnFillRule::NonZero,
3560 &[[len(0.), len(0.)], [len(100.), len(0.)], [len(0.), len(100.)]],
3561 ));
3562 div().child(d)
3563 }
3564 }
3565
3566 #[gpui::test]
3567 fn a_polygon_paints_into_an_isolated_layer_and_cuts_the_hit_test(cx: &mut TestAppContext) {
3568 let window = cx.open_window(size(px(200.), px(200.)), |_, _| Triangle);
3569 cx.run_until_parked();
3570 window
3571 .update(cx, |_, window, _| {
3572 let scale = window.scale_factor();
3573 let scene = &window.rendered_frame.scene;
3574 assert_eq!(scene.vn_layers.len(), 2, "{:?}", scene.vn_layers);
3577 assert_eq!(scene.vn_group_count(), 3);
3578 let root: Vec<_> = scene.vn_batches(0).collect();
3579 assert!(root.iter().all(|b| matches!(b, crate::VnBatch::Layers(_))), "{root:?}");
3580 let colors = |group: usize| -> Vec<Hsla> {
3581 scene
3582 .vn_batches(group)
3583 .filter_map(|b| match b {
3584 crate::VnBatch::Primitives(crate::PrimitiveBatch::Quads(r)) => Some(r),
3585 _ => None,
3586 })
3587 .flat_map(|r| scene.quads[r].iter().filter_map(|q| q.background.as_solid()).collect::<Vec<_>>())
3588 .collect()
3589 };
3590 let mut groups: Vec<Vec<Hsla>> = scene.vn_layers.iter().map(|l| colors(l.group as usize)).collect();
3591 groups.sort_by_key(|g| g.len());
3592 assert_eq!(groups, vec![vec![Hsla::blue()], vec![Hsla::red(), Hsla::green()]]);
3593 for layer in &scene.vn_layers {
3596 assert_eq!(layer.segment_count, 3);
3597 assert_eq!(layer.fill_rule, 0);
3598 assert!(layer.bounds.size.width.0 >= 100. * scale);
3599 }
3600 assert_eq!(scene.vn_clip_segments.len(), 6);
3601 let flat = scene.batches().count();
3603 assert!(flat >= 2, "{flat}");
3604
3605 let frame = &window.rendered_frame;
3607 let clipped: Vec<_> = frame.hitboxes.iter().filter(|h| h.vn_clip.is_some()).collect();
3608 assert_eq!(clipped.len(), 1);
3609 let id = clipped[0].id;
3610 let hits = |x: f32, y: f32| frame.hit_test(point(px(x), px(y)), scale).ids.contains(&id);
3611 assert!(hits(10., 10.));
3612 assert!(hits(40., 40.));
3613 assert!(!hits(60., 60.), "inside the box, outside the triangle");
3614 assert!(!hits(150., 10.));
3615 })
3616 .unwrap();
3617 }
3618
3619 fn quad_mask(tint_leaf: bool) -> crate::VnMask {
3620 crate::VnMask {
3621 luminance: false,
3622 tint_leaf,
3623 key: 1,
3624 paint: Some(std::rc::Rc::new(|bounds, tint, window: &mut Window, _: &mut crate::App| {
3625 let half = Bounds::new(bounds.origin, size(bounds.size.width / 2., bounds.size.height));
3626 window.paint_quad(crate::fill(half, tint.unwrap_or_else(Hsla::white)));
3627 })),
3628 }
3629 }
3630
3631 struct Masked;
3633
3634 impl Render for Masked {
3635 fn render(&mut self, _window: &mut Window, _cx: &mut Context<Self>) -> impl IntoElement {
3636 let deferred = crate::deferred(div().absolute().top_0().left_0().size(px(20.)).bg(Hsla::black()));
3637 let mut boxed = div()
3638 .size(px(40.))
3639 .bg(Hsla::red())
3640 .opacity(0.5)
3641 .child(div().size(px(10.)).bg(Hsla::green()))
3642 .child(deferred.clip_to_ancestors(true));
3643 boxed.style().vn_mask = Some(quad_mask(false));
3644 let mut icon = div().size(px(20.)).bg(Hsla::blue());
3645 icon.style().vn_mask = Some(quad_mask(true));
3646 div().child(boxed).child(icon)
3647 }
3648 }
3649
3650 #[gpui::test]
3651 fn a_mask_composites_its_group_through_the_mask_group_and_a_leaf_is_tinted(cx: &mut TestAppContext) {
3652 let window = cx.open_window(size(px(200.), px(200.)), |_, _| Masked);
3653 cx.run_until_parked();
3654 window
3655 .update(cx, |_, window, _| {
3656 let scene = &window.rendered_frame.scene;
3657 assert_eq!(scene.vn_layers.len(), 2, "the box, the deferred child, and no layer for the leaf");
3658 let colors = |group: usize| -> Vec<Hsla> {
3659 scene
3660 .vn_batches(group)
3661 .filter_map(|b| match b {
3662 crate::VnBatch::Primitives(crate::PrimitiveBatch::Quads(r)) => Some(r),
3663 _ => None,
3664 })
3665 .flat_map(|r| scene.quads[r].iter().filter_map(|q| q.background.as_solid()).collect::<Vec<_>>())
3666 .collect()
3667 };
3668 let mut groups = Vec::new();
3669 for layer in &scene.vn_layers {
3670 assert_eq!(layer.fill_rule, 1 << 1, "an alpha mask over a nonzero box");
3671 let content = colors(layer.group as usize);
3672 assert!(content.iter().all(|c| (c.a - 0.5).abs() < 1e-3), "{content:?}");
3673 assert_eq!(colors(layer.group as usize + 1), vec![Hsla::white()], "the mask is not faded");
3674 groups.push(content.len());
3675 }
3676 groups.sort();
3677 assert_eq!(groups, vec![1, 2], "the deferred child paints through the mask again");
3678 let root = colors(0);
3679 assert_eq!(root, vec![Hsla::blue()], "the leaf paints the mask in its colour");
3680 let leaf = scene.quads.iter().find(|q| q.background.as_solid() == Some(Hsla::blue())).unwrap();
3681 assert_eq!(leaf.bounds.size.width.0, 10. * window.scale_factor());
3682 })
3683 .unwrap();
3684 }
3685}
3686
3687#[cfg(test)]
3688mod vn_border_color_tests {
3689 use super::*;
3690
3691 #[test]
3692 fn independent_border_colors_keep_shared_fallback_and_transparent_sides() {
3693 let mut style = Style { border_color: Some(Hsla::red()), ..Default::default() };
3694 style.vn_border_colors.left = Some(Hsla::transparent_black());
3695 style.vn_border_colors.top = Some(Hsla::blue());
3696 let colors = style.vn_resolved_border_colors();
3697 assert_eq!(colors.top, Hsla::blue());
3698 assert_eq!(colors.right, Hsla::red());
3699 assert!(colors.left.is_transparent());
3700 }
3701
3702 #[test]
3705 fn overflow_is_clipped_inside_borders_coloured_per_side() {
3706 let mut style = Style::default();
3707 style.overflow = Point { x: Overflow::Hidden, y: Overflow::Hidden };
3708 style.border_widths = Edges::all(px(4.).into());
3709 style.vn_border_colors.top = Some(Hsla::blue());
3710 style.vn_border_colors.left = Some(Hsla::red());
3711 let bounds = Bounds::new(point(px(0.), px(0.)), size(px(100.), px(100.)));
3712 let mask = style.overflow_mask(bounds, px(16.)).unwrap();
3713 assert_eq!(mask.bounds, Bounds::from_corners(point(px(4.), px(4.)), point(px(100.), px(100.))));
3714 }
3715
3716 #[test]
3717 fn colored_border_partitions_cover_rounded_arcs_with_width_weighted_joins() {
3718 let clips = Style::vn_border_side_clips(
3719 Bounds::new(point(px(0.), px(0.)), size(px(80.), px(80.))), Edges::all(px(8.)),
3720 );
3721 let contains = |polygon: &Vec<[f32; 2]>, point: [f32; 2]| {
3722 let mut sign = 0.;
3723 for (a, b) in polygon.iter().zip(polygon.iter().cycle().skip(1)) {
3724 let cross = (b[0] - a[0]) * (point[1] - a[1]) - (b[1] - a[1]) * (point[0] - a[0]);
3725 if cross.abs() < 0.0001 { continue; }
3726 if sign != 0. && cross.signum() != sign { return false; }
3727 sign = cross.signum();
3728 }
3729 polygon.len() >= 3
3730 };
3731 assert!(contains(&clips[0], [15., 13.]), "top rounded arc extends below the rectangular inner top");
3732 assert!(contains(&clips[3], [13., 15.]), "left rounded arc extends beyond the rectangular inner left");
3733 for y in 0..80 {
3734 for x in 0..80 {
3735 assert!(clips.iter().any(|polygon| contains(polygon, [x as f32 + 0.25, y as f32 + 0.25])),
3736 "coloured side clips must cover the entire quad, including rounded corners");
3737 }
3738 }
3739 let clips = Style::vn_border_side_clips(
3740 Bounds::new(point(px(0.), px(0.)), size(px(100.), px(60.))),
3741 Edges { top: px(4.), right: px(8.), bottom: px(6.), left: px(2.) },
3742 );
3743 assert!(contains(&clips[0], [2., 3.]));
3744 assert!(contains(&clips[3], [2., 5.]), "top/left join uses their2:4width ratio");
3745 }
3746}