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, Corners,
10 CornersRefinement, CursorStyle, DefiniteLength, DevicePixels, Edges, EdgesRefinement,
11 EffectCrossFade, EffectSpec, Font,
12 FontFallbacks, FontFeatures, FontStyle, FontWeight, GridLocation, Hsla, Length, Pixels, Point,
13 PointRefinement, Rgba, SharedString, Size, SizeRefinement, Styled, TextRun, Window, black, phi,
14 TransformSpec, TransformationMatrix, VnClipOutline, VnFillRule, VnPathVerb, point, px, quad,
15 rems, size,
16};
17use collections::HashSet;
18use refineable::Refineable;
19#[cfg(feature = "schemars")]
20use schemars::JsonSchema;
21use serde::{Deserialize, Serialize};
22
23#[cfg(debug_assertions)]
27pub struct DebugBelow;
28
29#[cfg(debug_assertions)]
30impl crate::Global for DebugBelow {}
31
32pub enum ObjectFit {
34 Fill,
36 Contain,
38 Cover,
40 ScaleDown,
42 None,
44}
45
46impl ObjectFit {
47 pub fn get_bounds(
49 &self,
50 bounds: Bounds<Pixels>,
51 image_size: Size<DevicePixels>,
52 ) -> Bounds<Pixels> {
53 let fitted = self.get_bounds_at(bounds, image_size, ObjectPosition::default());
54 match self {
55 ObjectFit::None => Bounds {
56 origin: bounds.origin,
57 size: fitted.size,
58 },
59 _ => fitted,
60 }
61 }
62
63 pub fn get_bounds_at(
66 &self,
67 bounds: Bounds<Pixels>,
68 image_size: Size<DevicePixels>,
69 position: ObjectPosition,
70 ) -> Bounds<Pixels> {
71 let image_size = image_size.map(|dimension| Pixels::from(u32::from(dimension)));
72 let image_ratio = image_size.width / image_size.height;
73 let bounds_ratio = bounds.size.width / bounds.size.height;
74 let contain = || {
75 if bounds_ratio > image_ratio {
76 size(
77 image_size.width * (bounds.size.height / image_size.height),
78 bounds.size.height,
79 )
80 } else {
81 size(
82 bounds.size.width,
83 image_size.height * (bounds.size.width / image_size.width),
84 )
85 }
86 };
87
88 let new_size = match self {
89 ObjectFit::Fill => bounds.size,
90 ObjectFit::Contain => contain(),
91 ObjectFit::ScaleDown => {
92 if image_size.width > bounds.size.width || image_size.height > bounds.size.height {
93 contain()
94 } else {
95 image_size
96 }
97 }
98 ObjectFit::Cover => {
99 if bounds_ratio > image_ratio {
100 size(
101 bounds.size.width,
102 image_size.height * (bounds.size.width / image_size.width),
103 )
104 } else {
105 size(
106 image_size.width * (bounds.size.height / image_size.height),
107 bounds.size.height,
108 )
109 }
110 }
111 ObjectFit::None => image_size,
112 };
113 Bounds {
114 origin: point(
115 bounds.origin.x
116 + (bounds.size.width - new_size.width) * position.x_fraction
117 + position.x_offset,
118 bounds.origin.y
119 + (bounds.size.height - new_size.height) * position.y_fraction
120 + position.y_offset,
121 ),
122 size: new_size,
123 }
124 }
125}
126
127#[derive(Clone, Copy, Debug, PartialEq, Serialize, Deserialize)]
130#[cfg_attr(feature = "schemars", derive(JsonSchema))]
131pub struct ObjectPosition {
132 pub x_fraction: f32,
134 pub x_offset: Pixels,
136 pub y_fraction: f32,
138 pub y_offset: Pixels,
140}
141
142impl Default for ObjectPosition {
143 fn default() -> Self {
144 Self {
145 x_fraction: 0.5,
146 x_offset: Pixels::ZERO,
147 y_fraction: 0.5,
148 y_offset: Pixels::ZERO,
149 }
150 }
151}
152
153#[derive(Copy, Clone, PartialEq, Eq, PartialOrd, Ord, Debug, Default, Serialize, Deserialize)]
155#[cfg_attr(feature = "schemars", derive(JsonSchema))]
156pub enum GridTemplateMinSize {
157 #[default]
159 Zero,
160 MinContent,
162 MaxContent,
164}
165
166#[derive(
168 Copy, Clone, Refineable, PartialEq, Eq, PartialOrd, Ord, Debug, Default, Serialize, Deserialize,
169)]
170#[cfg_attr(feature = "schemars", derive(JsonSchema))]
171pub struct GridTemplate {
172 pub repeat: u16,
174 pub min_size: GridTemplateMinSize,
176}
177
178#[derive(Copy, Clone, PartialEq, Debug, Default, Serialize, Deserialize)]
185#[cfg_attr(feature = "schemars", derive(JsonSchema))]
186pub enum GridTrackSize {
187 #[default]
189 Auto,
190 MinContent,
192 MaxContent,
194 Px(f32),
196 Percent(f32),
199 Fr(f32),
202}
203
204#[derive(Copy, Clone, PartialEq, Debug, Default, Serialize, Deserialize)]
210#[cfg_attr(feature = "schemars", derive(JsonSchema))]
211pub struct GridTrack {
212 pub min: GridTrackSize,
214 pub max: GridTrackSize,
216}
217
218impl GridTrack {
219 pub fn fixed(size: GridTrackSize) -> Self {
221 Self {
222 min: size,
223 max: size,
224 }
225 }
226
227 pub fn fr(flex: f32) -> Self {
229 Self {
230 min: GridTrackSize::Auto,
231 max: GridTrackSize::Fr(flex),
232 }
233 }
234}
235
236#[derive(Copy, Clone, PartialEq, Eq, Debug, Serialize, Deserialize)]
243#[cfg_attr(feature = "schemars", derive(JsonSchema))]
244pub struct GridAutoRepeat {
245 pub fit: bool,
248 pub start: u16,
250 pub len: u16,
252}
253
254#[derive(Copy, Clone, PartialEq, Eq, Debug, Default, Serialize, Deserialize)]
257#[cfg_attr(feature = "schemars", derive(JsonSchema))]
258pub enum GridAutoFlow {
259 #[default]
261 Row,
262 Column,
264 RowDense,
266 ColumnDense,
268}
269
270#[derive(Copy, Clone, PartialEq, Debug, Serialize, Deserialize)]
273#[cfg_attr(feature = "schemars", derive(JsonSchema))]
274pub struct Outline {
275 pub width: Pixels,
277 pub offset: Pixels,
280 pub color: Hsla,
282 pub style: BorderStyle,
284}
285
286#[derive(Copy, Clone, PartialEq, Debug, Serialize, Deserialize)]
290#[cfg_attr(feature = "schemars", derive(JsonSchema))]
291pub struct VnCornerRadius {
292 pub x: DefiniteLength,
294 pub y: DefiniteLength,
296}
297
298static VN_ELLIPSE_DRAWN_AS_CIRCLE: std::sync::atomic::AtomicBool =
299 std::sync::atomic::AtomicBool::new(false);
300
301pub fn vn_take_ellipse_drawn_as_circle() -> bool {
305 VN_ELLIPSE_DRAWN_AS_CIRCLE.swap(false, std::sync::atomic::Ordering::Relaxed)
306}
307
308pub fn vn_resolve_corner_radii(
325 lengths: &Corners<AbsoluteLength>,
326 relative: &Corners<Option<VnCornerRadius>>,
327 size: Size<Pixels>,
328 rem_size: Pixels,
329) -> Corners<Pixels> {
330 let (width, height) = (f32::from(size.width).max(0.), f32::from(size.height).max(0.));
331 let pair = |length: &AbsoluteLength, relative: &Option<VnCornerRadius>| -> (f32, f32) {
332 match relative {
333 Some(radius) => (
334 f32::from(radius.x.to_pixels(px(width).into(), rem_size)).max(0.),
335 f32::from(radius.y.to_pixels(px(height).into(), rem_size)).max(0.),
336 ),
337 None => {
338 let radius = f32::from(length.to_pixels(rem_size)).max(0.);
339 (radius, radius)
340 }
341 }
342 };
343 let top_left = pair(&lengths.top_left, &relative.top_left);
344 let top_right = pair(&lengths.top_right, &relative.top_right);
345 let bottom_right = pair(&lengths.bottom_right, &relative.bottom_right);
346 let bottom_left = pair(&lengths.bottom_left, &relative.bottom_left);
347
348 let ratio = |side: f32, a: f32, b: f32| if a + b > side { side / (a + b) } else { 1. };
349 let factor = ratio(width, top_left.0, top_right.0)
350 .min(ratio(width, bottom_left.0, bottom_right.0))
351 .min(ratio(height, top_left.1, bottom_left.1))
352 .min(ratio(height, top_right.1, bottom_right.1));
353
354 let circle = |(x, y): (f32, f32)| {
355 let (x, y) = (x * factor, y * factor);
356 let radius = x.min(y);
357 if radius > 0. && (x - y).abs() > 0.5 {
358 VN_ELLIPSE_DRAWN_AS_CIRCLE.store(true, std::sync::atomic::Ordering::Relaxed);
359 }
360 px(radius)
361 };
362 Corners {
363 top_left: circle(top_left),
364 top_right: circle(top_right),
365 bottom_right: circle(bottom_right),
366 bottom_left: circle(bottom_left),
367 }
368 .clamp_radii_for_quad_size(size)
369}
370
371#[derive(Copy, Clone, Default, PartialEq, Debug, Serialize, Deserialize)]
375#[cfg_attr(feature = "schemars", derive(JsonSchema))]
376pub enum VnClipBox {
377 Margin,
379 #[default]
381 Border,
382 Padding,
384 Content,
386}
387
388#[derive(Copy, Clone, PartialEq, Debug, Serialize, Deserialize)]
390#[cfg_attr(feature = "schemars", derive(JsonSchema))]
391pub enum VnShapeRadius {
392 Length(DefiniteLength),
396 ClosestSide,
399 FarthestSide,
401}
402
403#[derive(Clone, Default, PartialEq, Debug, Serialize, Deserialize)]
408#[cfg_attr(feature = "schemars", derive(JsonSchema))]
409pub enum VnClipPath {
410 #[default]
412 None,
413 Box(VnClipBox),
416 Inset {
421 reference: VnClipBox,
423 insets: [DefiniteLength; 4],
425 radii: [VnCornerRadius; 4],
428 },
429 Ellipse {
433 reference: VnClipBox,
435 center: [DefiniteLength; 2],
437 radius: [VnShapeRadius; 2],
439 circle: bool,
442 },
443 Polygon {
446 reference: VnClipBox,
448 fill_rule: VnFillRule,
450 points: Arc<[[DefiniteLength; 2]]>,
452 },
453 Path {
456 reference: VnClipBox,
458 fill_rule: VnFillRule,
460 verbs: Arc<[VnPathVerb]>,
462 },
463}
464
465fn vn_clip_ellipse(
468 rect: Bounds<Pixels>,
469 center: &[DefiniteLength; 2],
470 radius: &[VnShapeRadius; 2],
471 circle: bool,
472 rem_size: Pixels,
473) -> (Point<Pixels>, Pixels, Pixels) {
474 let (w, h) = (rect.size.width, rect.size.height);
475 let resolve = |length: &DefiniteLength, base: Pixels| length.to_pixels(AbsoluteLength::Pixels(base), rem_size);
476 let cx = rect.left() + resolve(¢er[0], w);
477 let cy = rect.top() + resolve(¢er[1], h);
478 let (near_x, far_x) = ((cx - rect.left()).abs(), (rect.right() - cx).abs());
479 let (near_y, far_y) = ((cy - rect.top()).abs(), (rect.bottom() - cy).abs());
480 let diagonal = px((f32::from(w).powi(2) + f32::from(h).powi(2)).sqrt() / 2f32.sqrt());
483 let one = |r: &VnShapeRadius, horizontal: bool| -> Pixels {
484 let (a, b) = if circle {
485 (near_x.min(far_x).min(near_y.min(far_y)), near_x.max(far_x).max(near_y.max(far_y)))
486 } else if horizontal {
487 (near_x.min(far_x), near_x.max(far_x))
488 } else {
489 (near_y.min(far_y), near_y.max(far_y))
490 };
491 match r {
492 VnShapeRadius::ClosestSide => a,
493 VnShapeRadius::FarthestSide => b,
494 VnShapeRadius::Length(l) => resolve(l, if circle { diagonal } else if horizontal { w } else { h }).max(px(0.)),
495 }
496 };
497 (point(cx, cy), one(&radius[0], true), one(&radius[1], false))
498}
499
500#[derive(Clone, Refineable, Debug)]
502#[refineable(Debug, PartialEq, Serialize, Deserialize)]
503#[cfg_attr(feature = "schemars", refineable(JsonSchema))]
504pub struct Style {
505 pub display: Display,
507
508 pub visibility: Visibility,
510
511 #[refineable]
514 pub overflow: Point<Overflow>,
515 pub scrollbar_width: AbsoluteLength,
517 pub allow_concurrent_scroll: bool,
519 pub restrict_scroll_to_axis: bool,
545
546 pub position: Position,
549 #[refineable]
551 pub inset: Edges<Length>,
552
553 #[refineable]
556 pub size: Size<Length>,
557 #[refineable]
559 pub min_size: Size<Length>,
560 #[refineable]
562 pub max_size: Size<Length>,
563 pub aspect_ratio: Option<f32>,
565
566 #[refineable]
569 pub margin: Edges<Length>,
570 #[refineable]
572 pub padding: Edges<DefiniteLength>,
573 #[refineable]
575 pub border_widths: Edges<AbsoluteLength>,
576
577 pub align_items: Option<AlignItems>,
580 pub align_self: Option<AlignSelf>,
582 pub align_content: Option<AlignContent>,
584 pub justify_content: Option<JustifyContent>,
586 #[refineable]
588 pub gap: Size<DefiniteLength>,
589
590 pub flex_direction: FlexDirection,
593 pub flex_wrap: FlexWrap,
595 pub flex_basis: Length,
597 pub flex_grow: f32,
599 pub flex_shrink: f32,
601 pub vn_order: i32,
604 pub vn_object_position: Option<ObjectPosition>,
607
608 pub background: Option<Fill>,
610
611 pub background_layers: Vec<Background>,
624
625 pub border_color: Option<Hsla>,
627
628 #[refineable]
630 pub vn_border_colors: Edges<Option<Hsla>>,
631
632 pub border_style: BorderStyle,
634
635 #[refineable]
637 pub corner_radii: Corners<AbsoluteLength>,
638
639 #[refineable]
646 pub vn_corner_radii: Corners<Option<VnCornerRadius>>,
647
648 pub box_shadow: Vec<BoxShadow>,
650
651 pub vn_shadow_under_box: bool,
661
662 pub backdrop_blur: Option<Pixels>,
669
670 pub vn_effect: Option<EffectSpec>,
685
686 pub vn_effect_fade: Option<EffectCrossFade>,
689
690 pub vn_transform: Option<TransformSpec>,
710
711 #[refineable]
713 pub text: TextStyleRefinement,
714
715 pub mouse_cursor: Option<CursorStyle>,
717
718 pub opacity: Option<f32>,
720
721 pub grid_cols: Option<GridTemplate>,
724
725 pub grid_rows: Option<GridTemplate>,
728
729 pub grid_location: Option<GridLocation>,
731
732 pub vn_grid_cols: Option<Vec<GridTrack>>,
739
740 pub vn_grid_rows: Option<Vec<GridTrack>>,
743
744 pub vn_grid_cols_auto: Option<GridAutoRepeat>,
747
748 pub vn_grid_rows_auto: Option<GridAutoRepeat>,
750
751 pub vn_grid_auto_cols: Option<Vec<GridTrack>>,
753
754 pub vn_grid_auto_rows: Option<Vec<GridTrack>>,
756
757 pub vn_grid_auto_flow: Option<GridAutoFlow>,
760
761 pub vn_justify_items: Option<AlignItems>,
765
766 pub vn_justify_self: Option<AlignSelf>,
769
770 pub vn_outline: Option<Outline>,
778
779 pub vn_mask_ring: bool,
797
798 pub vn_clip_path: VnClipPath,
803
804 pub vn_color_matrix: Option<crate::VnColorMatrix>,
806
807 pub vn_capture: Option<u64>,
810
811 pub vn_isolate: bool,
814
815 pub vn_text_fill: Option<VnTextFill>,
817
818 pub vn_mask: Option<VnMask>,
820
821 #[cfg(debug_assertions)]
823 pub debug: bool,
824
825 #[cfg(debug_assertions)]
827 pub debug_below: bool,
828}
829
830impl Styled for StyleRefinement {
831 fn style(&mut self) -> &mut StyleRefinement {
832 self
833 }
834}
835
836impl StyleRefinement {
837 pub fn grid_location_mut(&mut self) -> &mut GridLocation {
839 self.grid_location.get_or_insert_default()
840 }
841}
842
843#[derive(Default, Clone, Copy, Debug, Eq, PartialEq, Serialize, Deserialize)]
845#[cfg_attr(feature = "schemars", derive(JsonSchema))]
846pub enum Visibility {
847 #[default]
849 Visible,
850 Hidden,
852}
853
854#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
856#[cfg_attr(feature = "schemars", derive(JsonSchema))]
857pub struct BoxShadow {
858 pub color: Hsla,
860 pub offset: Point<Pixels>,
862 pub blur_radius: Pixels,
864 pub spread_radius: Pixels,
866 pub inset: bool,
868}
869
870#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Serialize, Deserialize)]
872#[cfg_attr(feature = "schemars", derive(JsonSchema))]
873pub struct TextShadow {
874 pub color: Option<Hsla>,
876 pub offset: Point<Pixels>,
878 pub blur_radius: Pixels,
880}
881
882impl BoxShadow {
883 pub fn new(offset_x: Pixels, offset_y: Pixels, color: Hsla) -> Self {
887 Self {
888 color,
889 offset: point(offset_x, offset_y),
890 blur_radius: px(0.),
891 spread_radius: px(0.),
892 inset: false,
893 }
894 }
895
896 pub fn blur_radius(mut self, blur_radius: Pixels) -> Self {
898 self.blur_radius = blur_radius;
899 self
900 }
901
902 pub fn spread_radius(mut self, spread_radius: Pixels) -> Self {
904 self.spread_radius = spread_radius;
905 self
906 }
907
908 pub fn inset(mut self) -> Self {
910 self.inset = true;
911 self
912 }
913}
914
915#[derive(Copy, Clone, Debug, Default, PartialEq, Eq, Serialize, Deserialize)]
917#[cfg_attr(feature = "schemars", derive(JsonSchema))]
918pub enum WhiteSpace {
919 #[default]
921 Normal,
922 Nowrap,
924}
925
926#[derive(Copy, Clone, Debug, Default, PartialEq, Eq, Hash, Serialize, Deserialize)]
929#[cfg_attr(feature = "schemars", derive(JsonSchema))]
930pub enum OverflowWrap {
931 #[default]
934 Normal,
935 BreakWord,
938 Anywhere,
941}
942
943#[derive(Copy, Clone, Debug, Default, PartialEq, Eq, Hash, Serialize, Deserialize)]
945#[cfg_attr(feature = "schemars", derive(JsonSchema))]
946pub enum WordBreak {
947 #[default]
949 Normal,
950 BreakAll,
953 KeepAll,
956 BreakWord,
959}
960
961#[derive(Copy, Clone, Debug, Default, PartialEq, Eq, Hash, Serialize, Deserialize)]
964#[cfg_attr(feature = "schemars", derive(JsonSchema))]
965pub enum Hyphens {
966 None,
968 #[default]
970 Manual,
971}
972
973#[derive(Copy, Clone, Debug, Default, PartialEq, Eq, Hash)]
976pub struct TextWrap {
977 pub overflow_wrap: OverflowWrap,
979 pub word_break: WordBreak,
981 pub hyphens: Hyphens,
983}
984
985impl TextWrap {
986 pub const BREAK_WORD: Self = Self {
991 overflow_wrap: OverflowWrap::BreakWord,
992 word_break: WordBreak::Normal,
993 hyphens: Hyphens::Manual,
994 };
995
996 pub(crate) fn breaks_words(&self) -> bool {
998 self.overflow_wrap != OverflowWrap::Normal || self.word_break == WordBreak::BreakWord
999 }
1000
1001 pub(crate) fn min_content_breaks_words(&self) -> bool {
1003 self.overflow_wrap == OverflowWrap::Anywhere || self.word_break == WordBreak::BreakWord
1004 }
1005}
1006
1007#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
1009#[cfg_attr(feature = "schemars", derive(JsonSchema))]
1010pub enum TextOverflow {
1011 Truncate(SharedString),
1014 TruncateStart(SharedString),
1018 TruncateMiddle(SharedString),
1022}
1023
1024#[derive(Copy, Clone, Debug, Default, PartialEq, Eq, Serialize, Deserialize)]
1026#[cfg_attr(feature = "schemars", derive(JsonSchema))]
1027pub enum TextAlign {
1028 #[default]
1030 Left,
1031
1032 Center,
1034
1035 Right,
1037}
1038
1039pub type VnMaskPainter = std::rc::Rc<dyn Fn(Bounds<Pixels>, Option<Hsla>, &mut Window, &mut App)>;
1043
1044#[derive(Clone, Default, Serialize, Deserialize)]
1047#[cfg_attr(feature = "schemars", derive(JsonSchema))]
1048pub struct VnMask {
1049 pub luminance: bool,
1051 pub tint_leaf: bool,
1055 pub key: u64,
1057 #[serde(skip)]
1059 #[cfg_attr(feature = "schemars", schemars(skip))]
1060 pub paint: Option<VnMaskPainter>,
1061}
1062
1063impl std::fmt::Debug for VnMask {
1064 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
1065 f.debug_struct("VnMask")
1066 .field("luminance", &self.luminance)
1067 .field("tint_leaf", &self.tint_leaf)
1068 .field("key", &self.key)
1069 .finish_non_exhaustive()
1070 }
1071}
1072
1073impl PartialEq for VnMask {
1074 fn eq(&self, other: &Self) -> bool {
1075 (self.luminance, self.tint_leaf, self.key) == (other.luminance, other.tint_leaf, other.key)
1076 }
1077}
1078
1079#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
1081#[cfg_attr(feature = "schemars", derive(JsonSchema))]
1082pub struct VnTextFill {
1083 pub group_id: u64,
1085 pub backgrounds: Vec<Background>,
1087}
1088
1089#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
1092#[cfg_attr(feature = "schemars", derive(JsonSchema))]
1093pub struct VnTextPaint {
1094 pub fill: VnTextFill,
1096 pub bounds: [f32; 4],
1098 pub inverse: [f32; 6],
1100 pub scale_factor: f32,
1102 #[serde(skip)]
1104 #[cfg_attr(feature = "schemars", schemars(skip))]
1105 pub geometry: Arc<crate::VnClipGeometry>,
1106 #[serde(skip)]
1108 #[cfg_attr(feature = "schemars", schemars(skip))]
1109 pub content_mask: ContentMask<crate::ScaledPixels>,
1110}
1111
1112#[derive(Refineable, Clone, Debug, PartialEq)]
1114#[refineable(Debug, PartialEq, Serialize, Deserialize)]
1115#[cfg_attr(feature = "schemars", refineable(JsonSchema))]
1116pub struct TextStyle {
1117 pub color: Hsla,
1119
1120 pub vn_text_paint: Option<Arc<VnTextPaint>>,
1122
1123 pub font_family: SharedString,
1125
1126 pub font_features: FontFeatures,
1128
1129 pub font_fallbacks: Option<FontFallbacks>,
1131
1132 pub font_size: AbsoluteLength,
1134
1135 pub line_height: DefiniteLength,
1137
1138 pub font_weight: FontWeight,
1140
1141 pub font_style: FontStyle,
1143
1144 pub background_color: Option<Hsla>,
1146
1147 pub underline: Option<UnderlineStyle>,
1149
1150 pub strikethrough: Option<StrikethroughStyle>,
1152
1153 pub white_space: WhiteSpace,
1155
1156 pub text_overflow: Option<TextOverflow>,
1158
1159 pub text_align: TextAlign,
1161
1162 pub line_clamp: Option<usize>,
1164
1165 pub letter_spacing: Pixels,
1169
1170 pub word_spacing: Pixels,
1172
1173 pub overflow_wrap: OverflowWrap,
1175
1176 pub word_break: WordBreak,
1178
1179 pub hyphens: Hyphens,
1181
1182 pub text_shadow: Vec<TextShadow>,
1184}
1185
1186impl Default for TextStyle {
1187 fn default() -> Self {
1188 TextStyle {
1189 color: black(),
1190 vn_text_paint: None,
1191 font_family: ".SystemUIFont".into(),
1193 font_features: FontFeatures::default(),
1194 font_fallbacks: None,
1195 font_size: rems(1.).into(),
1196 line_height: phi(),
1197 font_weight: FontWeight::default(),
1198 font_style: FontStyle::default(),
1199 background_color: None,
1200 underline: None,
1201 strikethrough: None,
1202 white_space: WhiteSpace::Normal,
1203 text_overflow: None,
1204 text_align: TextAlign::default(),
1205 line_clamp: None,
1206 letter_spacing: px(0.),
1207 word_spacing: px(0.),
1208 overflow_wrap: OverflowWrap::default(),
1209 word_break: WordBreak::default(),
1210 hyphens: Hyphens::default(),
1211 text_shadow: Vec::new(),
1212 }
1213 }
1214}
1215
1216impl TextStyle {
1217 pub fn wrap(&self) -> TextWrap {
1219 TextWrap {
1220 overflow_wrap: self.overflow_wrap,
1221 word_break: self.word_break,
1222 hyphens: self.hyphens,
1223 }
1224 }
1225
1226 pub fn highlight(mut self, style: impl Into<HighlightStyle>) -> Self {
1228 let style = style.into();
1229 if let Some(weight) = style.font_weight {
1230 self.font_weight = weight;
1231 }
1232 if let Some(style) = style.font_style {
1233 self.font_style = style;
1234 }
1235
1236 if let Some(color) = style.color {
1237 self.color = self.color.blend(color);
1238 }
1239
1240 if let Some(factor) = style.fade_out {
1241 self.color.fade_out(factor);
1242 }
1243
1244 if let Some(background_color) = style.background_color {
1245 self.background_color = Some(background_color);
1246 }
1247
1248 if let Some(underline) = style.underline {
1249 self.underline = Some(underline);
1250 }
1251
1252 if let Some(strikethrough) = style.strikethrough {
1253 self.strikethrough = Some(strikethrough);
1254 }
1255
1256 self
1257 }
1258
1259 pub fn font(&self) -> Font {
1261 Font {
1262 family: self.font_family.clone(),
1263 features: self.font_features.clone(),
1264 fallbacks: self.font_fallbacks.clone(),
1265 weight: self.font_weight,
1266 style: self.font_style,
1267 }
1268 }
1269
1270 pub fn line_height_in_pixels(&self, rem_size: Pixels) -> Pixels {
1272 self.line_height.to_pixels(self.font_size, rem_size).round()
1273 }
1274
1275 pub fn to_run(&self, len: usize) -> TextRun {
1277 TextRun {
1278 len,
1279 font: Font {
1280 family: self.font_family.clone(),
1281 features: self.font_features.clone(),
1282 fallbacks: self.font_fallbacks.clone(),
1283 weight: self.font_weight,
1284 style: self.font_style,
1285 },
1286 color: self.color,
1287 background_color: self.background_color,
1288 underline: self.underline,
1289 strikethrough: self.strikethrough,
1290 tracking: self.letter_spacing,
1291 word_spacing: self.word_spacing,
1292 text_shadow: self.text_shadow.clone(),
1293 }
1294 }
1295}
1296
1297#[derive(Copy, Clone, Debug, Default, PartialEq)]
1300pub struct HighlightStyle {
1301 pub color: Option<Hsla>,
1303
1304 pub font_weight: Option<FontWeight>,
1306
1307 pub font_style: Option<FontStyle>,
1309
1310 pub background_color: Option<Hsla>,
1312
1313 pub underline: Option<UnderlineStyle>,
1315
1316 pub strikethrough: Option<StrikethroughStyle>,
1318
1319 pub fade_out: Option<f32>,
1321}
1322
1323impl Eq for HighlightStyle {}
1324
1325impl Hash for HighlightStyle {
1326 fn hash<H: Hasher>(&self, state: &mut H) {
1327 self.color.hash(state);
1328 self.font_weight.hash(state);
1329 self.font_style.hash(state);
1330 self.background_color.hash(state);
1331 self.underline.hash(state);
1332 self.strikethrough.hash(state);
1333 state.write_u32(u32::from_be_bytes(
1334 self.fade_out.map(|f| f.to_be_bytes()).unwrap_or_default(),
1335 ));
1336 }
1337}
1338
1339fn representative_color(background: &Background) -> Hsla {
1343 match background.tag {
1344 BackgroundTag::Solid | BackgroundTag::PatternSlash | BackgroundTag::Checkerboard => {
1345 background.solid
1346 }
1347 BackgroundTag::LinearGradient
1348 | BackgroundTag::RadialGradient
1349 | BackgroundTag::ConicGradient => background
1350 .live_stops()
1351 .first()
1352 .map(|stop| stop.color)
1353 .unwrap_or_default(),
1354 }
1355}
1356
1357impl Style {
1358 pub fn has_opaque_background(&self) -> bool {
1360 self.background
1361 .as_ref()
1362 .is_some_and(|fill| fill.color().is_some_and(|color| !color.is_transparent()))
1363 }
1364
1365 pub fn text_style(&self) -> Option<&TextStyleRefinement> {
1367 if self.text.is_some() {
1368 Some(&self.text)
1369 } else {
1370 None
1371 }
1372 }
1373
1374 pub fn text_style_for_bounds(&self, bounds: Bounds<Pixels>, window: &Window) -> Option<TextStyleRefinement> {
1377 let mut text = self.text.clone();
1378 if let Some(fill) = &self.vn_text_fill {
1379 text.vn_text_paint = Some(window.vn_text_paint(fill.clone(), bounds));
1380 }
1381 text.is_some().then_some(text)
1382 }
1383
1384 pub fn corner_radii_for(&self, size: Size<Pixels>, rem_size: Pixels) -> Corners<Pixels> {
1387 vn_resolve_corner_radii(&self.corner_radii, &self.vn_corner_radii, size, rem_size)
1388 }
1389
1390 pub fn overflow_mask(
1393 &self,
1394 bounds: Bounds<Pixels>,
1395 rem_size: Pixels,
1396 ) -> Option<ContentMask<Pixels>> {
1397 match self.overflow {
1398 Point {
1399 x: Overflow::Visible,
1400 y: Overflow::Visible,
1401 } => None,
1402 _ => {
1403 let mut min = bounds.origin;
1404 let mut max = bounds.bottom_right();
1405 let border_box = bounds;
1406
1407 let painted = self
1412 .vn_resolved_border_colors()
1413 .map(|color| !color.is_transparent());
1414 if painted.left {
1415 min.x += self.border_widths.left.to_pixels(rem_size);
1416 }
1417 if painted.right {
1418 max.x -= self.border_widths.right.to_pixels(rem_size);
1419 }
1420 if painted.top {
1421 min.y += self.border_widths.top.to_pixels(rem_size);
1422 }
1423 if painted.bottom {
1424 max.y -= self.border_widths.bottom.to_pixels(rem_size);
1425 }
1426
1427 let bounds = match (
1428 self.overflow.x == Overflow::Visible,
1429 self.overflow.y == Overflow::Visible,
1430 ) {
1431 (true, true) => return None,
1433 (true, false) => Bounds::from_corners(
1435 point(min.x, bounds.origin.y),
1436 point(max.x, bounds.bottom_right().y),
1437 ),
1438 (false, true) => Bounds::from_corners(
1440 point(bounds.origin.x, min.y),
1441 point(bounds.bottom_right().x, max.y),
1442 ),
1443 (false, false) => Bounds::from_corners(min, max),
1445 };
1446
1447 let insets = Edges {
1455 top: bounds.top() - border_box.top(),
1456 right: border_box.right() - bounds.right(),
1457 bottom: border_box.bottom() - bounds.bottom(),
1458 left: bounds.left() - border_box.left(),
1459 };
1460 let outer = self.corner_radii_for(border_box.size, rem_size);
1461 let inner = |radius: Pixels, a: Pixels, b: Pixels| (radius - a.max(b)).max(px(0.));
1462 let corner_radii = Corners {
1463 top_left: inner(outer.top_left, insets.top, insets.left),
1464 top_right: inner(outer.top_right, insets.top, insets.right),
1465 bottom_right: inner(outer.bottom_right, insets.bottom, insets.right),
1466 bottom_left: inner(outer.bottom_left, insets.bottom, insets.left),
1467 }
1468 .clamp_radii_for_quad_size(bounds.size);
1469
1470 Some(ContentMask {
1471 bounds,
1472 corner_radii,
1473 })
1474 }
1475 }
1476 }
1477
1478 pub fn vn_clip_mask(&self, bounds: Bounds<Pixels>, rem_size: Pixels) -> Option<ContentMask<Pixels>> {
1486 let clip = &self.vn_clip_path;
1487 let reference = match clip {
1488 VnClipPath::None => return None,
1489 VnClipPath::Polygon { .. } | VnClipPath::Path { .. } => {
1490 let outline = self.vn_clip_outline(bounds, rem_size)?;
1491 let rect = outline.control_bounds().unwrap_or(Bounds { origin: bounds.origin, size: Size::default() });
1492 return Some(ContentMask::rect(rect));
1493 }
1494 VnClipPath::Box(reference)
1495 | VnClipPath::Inset { reference, .. }
1496 | VnClipPath::Ellipse { reference, .. } => *reference,
1497 };
1498 let (rect, rounded) = self.vn_clip_box(reference, bounds, rem_size);
1499 let (w, h) = (rect.size.width, rect.size.height);
1500 let resolve = |length: &DefiniteLength, base: Pixels| length.to_pixels(AbsoluteLength::Pixels(base), rem_size);
1501 Some(match clip {
1502 VnClipPath::None | VnClipPath::Polygon { .. } | VnClipPath::Path { .. } => return None,
1503 VnClipPath::Box(_) => ContentMask { bounds: rect, corner_radii: rounded },
1504 VnClipPath::Inset { insets, radii, .. } => {
1505 let [top, right, bottom, left] = insets;
1510 let (top, right) = (resolve(top, h), resolve(right, w));
1511 let (bottom, left) = (resolve(bottom, h), resolve(left, w));
1512 let shape = Bounds {
1513 origin: point(rect.left() + left, rect.top() + top),
1514 size: size((w - left - right).max(px(0.)), (h - top - bottom).max(px(0.))),
1515 };
1516 let pairs = radii.map(|r| {
1517 let x = f32::from(resolve(&r.x, w)).max(0.);
1518 let y = f32::from(resolve(&r.y, h)).max(0.);
1519 (x, y)
1520 });
1521 let [tl, tr, br, bl] = pairs;
1522 let (sw, sh) = (f32::from(shape.size.width), f32::from(shape.size.height));
1523 let ratio = |side: f32, a: f32, b: f32| if a + b > side { side / (a + b) } else { 1. };
1524 let factor = ratio(sw, tl.0, tr.0)
1525 .min(ratio(sw, bl.0, br.0))
1526 .min(ratio(sh, tl.1, bl.1))
1527 .min(ratio(sh, tr.1, br.1));
1528 let circle = |(x, y): (f32, f32)| px(x.min(y) * factor);
1529 let corner_radii = Corners {
1530 top_left: circle(tl),
1531 top_right: circle(tr),
1532 bottom_right: circle(br),
1533 bottom_left: circle(bl),
1534 }
1535 .clamp_radii_for_quad_size(shape.size);
1536 ContentMask { bounds: shape, corner_radii }
1537 }
1538 VnClipPath::Ellipse { center, radius, circle, .. } => {
1539 let (c, rx, ry) = vn_clip_ellipse(rect, center, radius, *circle, rem_size);
1540 let shape = Bounds { origin: point(c.x - rx, c.y - ry), size: size(rx * 2., ry * 2.) };
1541 let corner_radii = if rx == ry { Corners::all(rx) } else { Corners::default() };
1544 ContentMask { bounds: shape, corner_radii }
1545 }
1546 })
1547 }
1548
1549 pub fn vn_clip_outline(&self, bounds: Bounds<Pixels>, rem_size: Pixels) -> Option<VnClipOutline> {
1556 let resolve = |length: &DefiniteLength, base: Pixels| {
1557 f32::from(length.to_pixels(AbsoluteLength::Pixels(base), rem_size))
1558 };
1559 match &self.vn_clip_path {
1560 VnClipPath::Polygon { reference, fill_rule, points } => {
1561 let (rect, _) = self.vn_clip_box(*reference, bounds, rem_size);
1562 let (x0, y0) = (f32::from(rect.left()), f32::from(rect.top()));
1563 let (w, h) = (rect.size.width, rect.size.height);
1564 let mut verbs = Vec::with_capacity(points.len() + 1);
1565 for (i, [x, y]) in points.iter().enumerate() {
1566 let p = [x0 + resolve(x, w), y0 + resolve(y, h)];
1567 verbs.push(if i == 0 { VnPathVerb::MoveTo(p) } else { VnPathVerb::LineTo(p) });
1568 }
1569 if !verbs.is_empty() {
1570 verbs.push(VnPathVerb::Close);
1571 }
1572 Some(VnClipOutline { fill_rule: *fill_rule, verbs })
1573 }
1574 VnClipPath::Path { reference, fill_rule, verbs } => {
1575 let (rect, _) = self.vn_clip_box(*reference, bounds, rem_size);
1576 let (x0, y0) = (f32::from(rect.left()), f32::from(rect.top()));
1577 let at = |p: [f32; 2]| [p[0] + x0, p[1] + y0];
1578 let verbs = verbs
1579 .iter()
1580 .map(|v| match *v {
1581 VnPathVerb::MoveTo(p) => VnPathVerb::MoveTo(at(p)),
1582 VnPathVerb::LineTo(p) => VnPathVerb::LineTo(at(p)),
1583 VnPathVerb::QuadTo(c, p) => VnPathVerb::QuadTo(at(c), at(p)),
1584 VnPathVerb::CubicTo(c1, c2, p) => VnPathVerb::CubicTo(at(c1), at(c2), at(p)),
1585 VnPathVerb::Close => VnPathVerb::Close,
1586 })
1587 .collect();
1588 Some(VnClipOutline { fill_rule: *fill_rule, verbs })
1589 }
1590 VnClipPath::Ellipse { reference, center, radius, circle } => {
1591 let (rect, _) = self.vn_clip_box(*reference, bounds, rem_size);
1592 let (c, rx, ry) = vn_clip_ellipse(rect, center, radius, *circle, rem_size);
1593 if rx == ry {
1594 return None;
1595 }
1596 let (cx, cy, rx, ry) = (f32::from(c.x), f32::from(c.y), f32::from(rx), f32::from(ry));
1598 let (kx, ky) = (0.552_284_8 * rx, 0.552_284_8 * ry);
1599 use VnPathVerb::*;
1600 Some(VnClipOutline {
1601 fill_rule: VnFillRule::NonZero,
1602 verbs: vec![
1603 MoveTo([cx + rx, cy]),
1604 CubicTo([cx + rx, cy + ky], [cx + kx, cy + ry], [cx, cy + ry]),
1605 CubicTo([cx - kx, cy + ry], [cx - rx, cy + ky], [cx - rx, cy]),
1606 CubicTo([cx - rx, cy - ky], [cx - kx, cy - ry], [cx, cy - ry]),
1607 CubicTo([cx + kx, cy - ry], [cx + rx, cy - ky], [cx + rx, cy]),
1608 Close,
1609 ],
1610 })
1611 }
1612 VnClipPath::None | VnClipPath::Box(_) | VnClipPath::Inset { .. } => None,
1613 }
1614 }
1615
1616 fn vn_clip_box(&self, reference: VnClipBox, bounds: Bounds<Pixels>, rem_size: Pixels) -> (Bounds<Pixels>, Corners<Pixels>) {
1623 let outer = self.corner_radii_for(bounds.size, rem_size);
1624 let width = AbsoluteLength::Pixels(bounds.size.width);
1625 let edges = match reference {
1626 VnClipBox::Border => return (bounds, outer),
1627 VnClipBox::Margin => {
1628 let margin = |l: &Length| match l {
1629 Length::Definite(l) => -l.to_pixels(width, rem_size),
1630 Length::Auto => px(0.),
1631 };
1632 Edges {
1633 top: margin(&self.margin.top),
1634 right: margin(&self.margin.right),
1635 bottom: margin(&self.margin.bottom),
1636 left: margin(&self.margin.left),
1637 }
1638 }
1639 VnClipBox::Padding | VnClipBox::Content => {
1640 let border = self.border_widths.to_pixels(rem_size);
1641 if reference == VnClipBox::Padding {
1642 border
1643 } else {
1644 let padding = self.padding.to_pixels(size(width, width), rem_size);
1645 Edges {
1646 top: border.top + padding.top,
1647 right: border.right + padding.right,
1648 bottom: border.bottom + padding.bottom,
1649 left: border.left + padding.left,
1650 }
1651 }
1652 }
1653 };
1654 let rect = Bounds::from_corners(
1655 point(bounds.left() + edges.left, bounds.top() + edges.top),
1656 point(
1657 (bounds.right() - edges.right).max(bounds.left() + edges.left),
1658 (bounds.bottom() - edges.bottom).max(bounds.top() + edges.top),
1659 ),
1660 );
1661 let corner = |radius: Pixels, a: Pixels, b: Pixels| {
1663 if a < px(0.) || b < px(0.) {
1664 if radius > px(0.) { radius - a.min(b) } else { px(0.) }
1665 } else {
1666 (radius - a.max(b)).max(px(0.))
1667 }
1668 };
1669 let corner_radii = Corners {
1670 top_left: corner(outer.top_left, edges.top, edges.left),
1671 top_right: corner(outer.top_right, edges.top, edges.right),
1672 bottom_right: corner(outer.bottom_right, edges.bottom, edges.right),
1673 bottom_left: corner(outer.bottom_left, edges.bottom, edges.left),
1674 }
1675 .clamp_radii_for_quad_size(rect.size);
1676 (rect, corner_radii)
1677 }
1678
1679 pub fn transform_matrix(&self, bounds: Bounds<Pixels>, scale_factor: f32) -> TransformationMatrix
1686 {
1687 self.vn_transform
1688 .filter(|t| !t.is_identity())
1689 .map(|t| t.to_matrix(bounds, scale_factor))
1690 .unwrap_or_else(TransformationMatrix::unit)
1691 }
1692
1693 pub fn paint(
1695 &self,
1696 bounds: Bounds<Pixels>,
1697 window: &mut Window,
1698 cx: &mut App,
1699 continuation: impl FnOnce(&mut Window, &mut App),
1700 ) {
1701 let transformation = if self.vn_capture.is_some() {
1716 TransformationMatrix::unit()
1717 } else {
1718 self.transform_matrix(bounds, window.scale_factor())
1719 };
1720 let clip = self.vn_clip_mask(bounds, window.rem_size());
1721 let outline = self.vn_clip_outline(bounds, window.rem_size());
1722 let element = window.vn_take_effect_element();
1723 let paint = |window: &mut Window| {
1724 window.with_content_mask(clip, |window| {
1725 window.vn_with_clip_shape(outline.as_ref(), |window| {
1726 if let Some(tint) = self.vn_mask_tint()
1727 && let Some(paint) = self.vn_mask.as_ref().and_then(|mask| mask.paint.clone())
1728 {
1729 if !tint.is_transparent() {
1730 window.with_element_opacity(Some(tint.a), |window| {
1731 paint(bounds, Some(Hsla { a: 1., ..tint }), window, cx)
1732 });
1733 }
1734 return continuation(window, cx);
1735 }
1736 window.vn_with_mask(self.vn_mask.as_ref(), bounds, cx, |window, cx| {
1737 window.vn_with_color_matrix(self.vn_color_matrix, |window| {
1738 window.vn_with_isolation(self.vn_isolate, |window| {
1739 self.paint_shaded(bounds, element, window, cx, continuation)
1740 })
1741 })
1742 })
1743 })
1744 })
1745 };
1746 if !transformation.is_unit() {
1747 return window.with_element_transform(transformation, paint);
1748 }
1749 paint(window)
1750 }
1751
1752 fn vn_mask_tint(&self) -> Option<Hsla> {
1755 let mask = self.vn_mask.as_ref()?;
1756 if !mask.tint_leaf
1757 || mask.luminance
1758 || self.vn_color_matrix.is_some()
1759 || !self.background_layers.is_empty()
1760 || !self.box_shadow.is_empty()
1761 || self.is_border_visible()
1762 || self.backdrop_blur.is_some_and(|radius| radius > px(0.))
1763 || self.vn_effect.is_some()
1764 || self.vn_effect_fade.is_some()
1765 || self.vn_mask_ring
1766 || self.vn_outline.is_some_and(|o| o.width > px(0.) && !o.color.is_transparent())
1767 {
1768 return None;
1769 }
1770 match self.background.as_ref().and_then(Fill::color) {
1771 None => Some(Hsla::transparent_black()),
1772 Some(background) => background.as_solid(),
1773 }
1774 }
1775
1776 fn vn_effects(&self, cx: &App) -> [Option<(EffectSpec, f32)>; 2] {
1779 let reduce_motion = cx.reduce_motion();
1785 let layer = |mut spec: EffectSpec, weight: f32| {
1786 (spec.is_some() && !self.vn_mask_ring && weight > 0.).then(|| {
1787 spec.animated &= !reduce_motion;
1788 if reduce_motion {
1789 spec.clock_mask = 0;
1790 }
1791 (spec, weight)
1792 })
1793 };
1794 let progress = self
1795 .vn_effect_fade
1796 .map_or(1., |fade| fade.progress.clamp(0., 1.));
1797 [
1798 self.vn_effect_fade
1799 .and_then(|fade| layer(fade.from, 1. - progress)),
1800 self.vn_effect.and_then(|spec| layer(spec, progress)),
1801 ]
1802 }
1803
1804 fn paint_shaded(
1809 &self,
1810 bounds: Bounds<Pixels>,
1811 element: u64,
1812 window: &mut Window,
1813 cx: &mut App,
1814 continuation: impl FnOnce(&mut Window, &mut App),
1815 ) {
1816 let effects = self.vn_effects(cx);
1817 let content = effects
1818 .iter()
1819 .flatten()
1820 .any(|(spec, _)| spec.flags & crate::EFFECT_FLAG_NEEDS_CONTENT != 0);
1821 if !content {
1822 return self.paint_untransformed(
1823 bounds,
1824 window,
1825 cx,
1826 continuation,
1827 &effects,
1828 element,
1829 false,
1830 );
1831 }
1832 let corner_radii = self.corner_radii_for(bounds.size, window.rem_size());
1833 self.paint_backdrop(bounds, corner_radii, window, cx, &effects, element);
1834 let shaded: Vec<_> = effects
1835 .iter()
1836 .flatten()
1837 .map(|(spec, weight)| {
1838 let textures = crate::resolve_effect_textures(spec, window, cx);
1839 (*spec, *weight, textures)
1840 })
1841 .collect();
1842 window.vn_with_effect_content(bounds, corner_radii, &shaded, element, cx, |window, cx| {
1843 self.paint_untransformed(bounds, window, cx, continuation, &effects, element, true)
1844 })
1845 }
1846
1847 pub fn vn_reads_content(&self) -> bool {
1850 [self.vn_effect, self.vn_effect_fade.map(|fade| fade.from)]
1851 .into_iter()
1852 .flatten()
1853 .any(|spec| spec.is_some() && spec.flags & crate::EFFECT_FLAG_NEEDS_CONTENT != 0)
1854 }
1855
1856 fn paint_backdrop(
1866 &self,
1867 bounds: Bounds<Pixels>,
1868 corner_radii: Corners<Pixels>,
1869 window: &mut Window,
1870 cx: &mut App,
1871 effects: &[Option<(EffectSpec, f32)>; 2],
1872 element: u64,
1873 ) {
1874 if let Some(radius) = self.backdrop_blur
1875 && radius > crate::px(0.)
1876 && !self.vn_mask_ring
1877 {
1878 window.paint_backdrop_blur_rect(
1879 bounds,
1880 corner_radii,
1881 crate::BackdropBlurEffect::new(radius),
1882 );
1883 }
1884 Self::paint_effects(bounds, corner_radii, window, cx, effects, element, true);
1885 }
1886
1887 fn paint_effects(
1893 bounds: Bounds<Pixels>,
1894 corner_radii: Corners<Pixels>,
1895 window: &mut Window,
1896 cx: &mut App,
1897 effects: &[Option<(EffectSpec, f32)>; 2],
1898 element: u64,
1899 backdrop: bool,
1900 ) {
1901 for (spec, weight) in effects.iter().flatten() {
1902 if spec.flags & crate::EFFECT_FLAG_NEEDS_CONTENT == 0
1903 && (spec.flags & crate::EFFECT_FLAG_NEEDS_BACKDROP != 0) == backdrop
1904 {
1905 window.with_element_opacity((*weight < 1.).then_some(*weight), |window| {
1906 window.vn_paint_textured_effect(bounds, corner_radii, *spec, element, cx)
1907 });
1908 }
1909 }
1910 }
1911
1912 #[allow(clippy::too_many_arguments)]
1913 fn paint_untransformed(
1914 &self,
1915 bounds: Bounds<Pixels>,
1916 window: &mut Window,
1917 cx: &mut App,
1918 continuation: impl FnOnce(&mut Window, &mut App),
1919 effects: &[Option<(EffectSpec, f32)>; 2],
1920 element: u64,
1921 in_content: bool,
1922 ) {
1923 #[cfg(debug_assertions)]
1924 if self.debug_below {
1925 cx.set_global(DebugBelow)
1926 }
1927
1928 #[cfg(debug_assertions)]
1929 if self.debug || cx.has_global::<DebugBelow>() {
1930 window.paint_quad(crate::outline(bounds, crate::red(), BorderStyle::default()));
1931 }
1932
1933 let rem_size = window.rem_size();
1934 let corner_radii = self.corner_radii_for(bounds.size, rem_size);
1935
1936 let ring_widths = self.vn_mask_ring.then(|| {
1941 let border = self.border_widths.to_pixels(rem_size);
1942 let width = AbsoluteLength::Pixels(bounds.size.width);
1943 let padding = self.padding.to_pixels(size(width, width), rem_size);
1944 Edges {
1945 top: border.top + padding.top,
1946 right: border.right + padding.right,
1947 bottom: border.bottom + padding.bottom,
1948 left: border.left + padding.left,
1949 }
1950 });
1951 let ring = ring_widths.is_some();
1952
1953 if !ring {
1954 if self.vn_shadow_under_box {
1955 window.paint_drop_shadows_under_box(bounds, corner_radii, &self.box_shadow);
1956 } else {
1957 window.paint_drop_shadows(bounds, corner_radii, &self.box_shadow);
1958 }
1959 }
1960
1961 if !in_content {
1962 self.paint_backdrop(bounds, corner_radii, window, cx, effects, element);
1963 }
1964 let fill = |background: Background| match ring_widths {
1966 Some(widths) => (background.ring(), widths),
1967 None => (background, Edges::default()),
1968 };
1969
1970 let background_color = self.background.as_ref().and_then(Fill::color);
1971 if background_color.is_some_and(|color| !color.is_transparent()) {
1972 let color = background_color.unwrap_or_default();
1973 let mut border_color = representative_color(&color);
1974 border_color.a = 0.;
1975 let (color, widths) = fill(color);
1976 window.paint_quad(quad(
1977 bounds,
1978 corner_radii,
1979 color,
1980 widths,
1981 border_color,
1982 self.border_style,
1983 ));
1984 }
1985
1986 for layer in &self.background_layers {
1992 if layer.is_transparent() {
1993 continue;
1994 }
1995 let mut border_color = representative_color(layer);
1996 border_color.a = 0.;
1997 let (layer, widths) = fill(*layer);
1998 window.paint_quad(quad(
1999 bounds,
2000 corner_radii,
2001 layer,
2002 widths,
2003 border_color,
2004 self.border_style,
2005 ));
2006 }
2007
2008 if !ring {
2009 window.paint_inset_shadows(bounds, corner_radii, &self.box_shadow);
2010 }
2011
2012 Self::paint_effects(bounds, corner_radii, window, cx, effects, element, false);
2013
2014 continuation(window, cx);
2015
2016 if self.is_border_visible() {
2017 let border_widths = self.border_widths.to_pixels(rem_size);
2018 let colors = self.vn_resolved_border_colors();
2019 if colors.top == colors.right && colors.top == colors.bottom && colors.top == colors.left {
2020 window.paint_quad(quad(
2021 bounds, corner_radii, Hsla::transparent_black(), border_widths,
2022 colors.top, self.border_style,
2023 ));
2024 } else {
2025 let clips = Self::vn_border_side_clips(bounds, border_widths);
2029 for (points, (color, width)) in clips.into_iter().zip([
2030 (colors.top, border_widths.top), (colors.right, border_widths.right),
2031 (colors.bottom, border_widths.bottom), (colors.left, border_widths.left),
2032 ]) {
2033 if width <= px(0.) || color.is_transparent() || points.len() < 3 { continue; }
2034 let mut verbs: Vec<_> = points.into_iter().enumerate().map(|(index, point)| {
2035 if index == 0 { VnPathVerb::MoveTo(point) } else { VnPathVerb::LineTo(point) }
2036 }).collect();
2037 verbs.push(VnPathVerb::Close);
2038 let outline = VnClipOutline { fill_rule: VnFillRule::NonZero, verbs };
2039 window.vn_with_clip_shape(Some(&outline), |window| {
2040 window.paint_quad(quad(bounds, corner_radii, Hsla::transparent_black(),
2041 border_widths, color, self.border_style));
2042 });
2043 }
2044 }
2045 }
2046
2047 if let Some(outline) = self
2057 .vn_outline
2058 .filter(|o| o.width > px(0.) && !o.color.is_transparent() && !ring)
2059 {
2060 let grow = outline.offset + outline.width;
2061 let ring = bounds.dilate(grow);
2062 let radii = corner_radii.map(|r| {
2065 if r.0 <= 0.0 {
2066 px(0.)
2067 } else {
2068 px((r.0 + grow.0).max(0.0))
2069 }
2070 });
2071 window.paint_quad(quad(
2072 ring,
2073 radii,
2074 Hsla::transparent_black(),
2075 Edges::all(outline.width),
2076 outline.color,
2077 outline.style,
2078 ));
2079 }
2080
2081 #[cfg(debug_assertions)]
2082 if self.debug_below {
2083 cx.remove_global::<DebugBelow>();
2084 }
2085 }
2086
2087 fn vn_resolved_border_colors(&self) -> Edges<Hsla> {
2088 let shared = self.border_color.unwrap_or_default();
2089 self.vn_border_colors.map(|color| color.unwrap_or(shared))
2090 }
2091
2092 fn vn_border_side_clips(bounds: Bounds<Pixels>, widths: Edges<Pixels>) -> [Vec<[f32; 2]>; 4] {
2093 let (left, top, right, bottom) = (f32::from(bounds.left()), f32::from(bounds.top()),
2094 f32::from(bounds.right()), f32::from(bounds.bottom()));
2095 let widths = [widths.top, widths.right, widths.bottom, widths.left].map(|width| f32::from(width).max(0.));
2096 let distances = [[0., 1., -top], [-1., 0., right], [0., -1., bottom], [1., 0., -left]];
2097 std::array::from_fn(|side| {
2098 if widths[side] <= 0. { return Vec::new(); }
2099 let mut polygon = vec![[left, top], [right, top], [right, bottom], [left, bottom]];
2100 for other in 0..4 {
2105 if other == side || widths[other] <= 0. { continue; }
2106 let plane: [f32; 3] = std::array::from_fn(|index|
2107 distances[side][index] * widths[other] - distances[other][index] * widths[side]);
2108 let distance = |point: [f32; 2]| plane[0] * point[0] + plane[1] * point[1] + plane[2];
2109 let Some(mut previous) = polygon.last().copied() else { break };
2110 let mut previous_distance = distance(previous);
2111 let mut clipped = Vec::with_capacity(polygon.len() + 1);
2112 for current in polygon {
2113 let current_distance = distance(current);
2114 if (previous_distance <= 0.) != (current_distance <= 0.) {
2115 let fraction = previous_distance / (previous_distance - current_distance);
2116 clipped.push([previous[0] + fraction * (current[0] - previous[0]),
2117 previous[1] + fraction * (current[1] - previous[1])]);
2118 }
2119 if current_distance <= 0. { clipped.push(current); }
2120 previous = current;
2121 previous_distance = current_distance;
2122 }
2123 polygon = clipped;
2124 }
2125 polygon
2126 })
2127 }
2128
2129 fn is_border_visible(&self) -> bool {
2130 self.vn_resolved_border_colors().any(|color| !color.is_transparent())
2131 && self.border_widths.any(|length| !length.is_zero())
2132 }
2133}
2134
2135impl Default for Style {
2136 fn default() -> Self {
2137 Style {
2138 display: Display::Block,
2139 visibility: Visibility::Visible,
2140 overflow: Point {
2141 x: Overflow::Visible,
2142 y: Overflow::Visible,
2143 },
2144 allow_concurrent_scroll: false,
2145 restrict_scroll_to_axis: false,
2146 scrollbar_width: AbsoluteLength::default(),
2147 position: Position::Relative,
2148 inset: Edges::auto(),
2149 margin: Edges::<Length>::zero(),
2150 padding: Edges::<DefiniteLength>::zero(),
2151 border_widths: Edges::<AbsoluteLength>::zero(),
2152 size: Size::auto(),
2153 min_size: Size::auto(),
2154 max_size: Size::auto(),
2155 aspect_ratio: None,
2156 gap: Size::default(),
2157 align_items: None,
2159 align_self: None,
2160 align_content: None,
2161 justify_content: None,
2162 flex_direction: FlexDirection::Row,
2164 flex_wrap: FlexWrap::NoWrap,
2165 flex_grow: 0.0,
2166 flex_shrink: 1.0,
2167 vn_order: 0,
2168 vn_object_position: None,
2169 flex_basis: Length::Auto,
2170 background: None,
2171 background_layers: Vec::new(),
2172 border_color: None,
2173 vn_border_colors: Edges::default(),
2174 border_style: BorderStyle::default(),
2175 corner_radii: Corners::default(),
2176 box_shadow: Default::default(),
2177 vn_shadow_under_box: false,
2178 backdrop_blur: None,
2179 vn_effect: None,
2180 vn_effect_fade: None,
2181 vn_transform: None,
2182 text: TextStyleRefinement::default(),
2183 mouse_cursor: None,
2184 opacity: None,
2185 grid_rows: None,
2186 grid_cols: None,
2187 grid_location: None,
2188 vn_grid_cols: None,
2189 vn_grid_rows: None,
2190 vn_grid_cols_auto: None,
2191 vn_grid_rows_auto: None,
2192 vn_grid_auto_cols: None,
2193 vn_grid_auto_rows: None,
2194 vn_grid_auto_flow: None,
2195 vn_justify_items: None,
2196 vn_justify_self: None,
2197 vn_outline: None,
2198 vn_mask_ring: false,
2199 vn_clip_path: VnClipPath::None,
2200 vn_color_matrix: None,
2201 vn_capture: None,
2202 vn_isolate: false,
2203 vn_text_fill: None,
2204 vn_mask: None,
2205 vn_corner_radii: Corners::default(),
2206
2207 #[cfg(debug_assertions)]
2208 debug: false,
2209 #[cfg(debug_assertions)]
2210 debug_below: false,
2211 }
2212 }
2213}
2214
2215#[derive(Refineable, Copy, Clone, Default, Debug, PartialEq, Eq, Hash, Serialize, Deserialize)]
2217#[cfg_attr(feature = "schemars", derive(JsonSchema))]
2218pub struct UnderlineStyle {
2219 pub thickness: Pixels,
2221
2222 pub color: Option<Hsla>,
2224
2225 pub wavy: bool,
2227
2228 pub offset: Pixels,
2232}
2233
2234#[derive(Refineable, Copy, Clone, Default, Debug, PartialEq, Eq, Hash, Serialize, Deserialize)]
2236#[cfg_attr(feature = "schemars", derive(JsonSchema))]
2237pub struct StrikethroughStyle {
2238 pub thickness: Pixels,
2240
2241 pub color: Option<Hsla>,
2243}
2244
2245#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
2247#[cfg_attr(feature = "schemars", derive(JsonSchema))]
2248pub enum Fill {
2249 Color(Background),
2251}
2252
2253impl Fill {
2254 pub fn color(&self) -> Option<Background> {
2258 match self {
2259 Fill::Color(color) => Some(*color),
2260 }
2261 }
2262}
2263
2264impl Default for Fill {
2265 fn default() -> Self {
2266 Self::Color(Background::default())
2267 }
2268}
2269
2270impl From<Hsla> for Fill {
2271 fn from(color: Hsla) -> Self {
2272 Self::Color(color.into())
2273 }
2274}
2275
2276impl From<Rgba> for Fill {
2277 fn from(color: Rgba) -> Self {
2278 Self::Color(color.into())
2279 }
2280}
2281
2282impl From<Background> for Fill {
2283 fn from(background: Background) -> Self {
2284 Self::Color(background)
2285 }
2286}
2287
2288impl From<TextStyle> for HighlightStyle {
2289 fn from(other: TextStyle) -> Self {
2290 Self::from(&other)
2291 }
2292}
2293
2294impl From<&TextStyle> for HighlightStyle {
2295 fn from(other: &TextStyle) -> Self {
2296 Self {
2297 color: Some(other.color),
2298 font_weight: Some(other.font_weight),
2299 font_style: Some(other.font_style),
2300 background_color: other.background_color,
2301 underline: other.underline,
2302 strikethrough: other.strikethrough,
2303 fade_out: None,
2304 }
2305 }
2306}
2307
2308impl HighlightStyle {
2309 pub fn color(color: Hsla) -> Self {
2311 Self {
2312 color: Some(color),
2313 ..Default::default()
2314 }
2315 }
2316 #[must_use]
2319 pub fn highlight(self, other: HighlightStyle) -> Self {
2320 Self {
2321 color: other
2322 .color
2323 .map(|other_color| {
2324 if let Some(color) = self.color {
2325 color.blend(other_color)
2326 } else {
2327 other_color
2328 }
2329 })
2330 .or(self.color),
2331 font_weight: other.font_weight.or(self.font_weight),
2332 font_style: other.font_style.or(self.font_style),
2333 background_color: other.background_color.or(self.background_color),
2334 underline: other.underline.or(self.underline),
2335 strikethrough: other.strikethrough.or(self.strikethrough),
2336 fade_out: other
2337 .fade_out
2338 .map(|source_fade| {
2339 self.fade_out
2340 .map(|dest_fade| (dest_fade * (1. + source_fade)).clamp(0., 1.))
2341 .unwrap_or(source_fade)
2342 })
2343 .or(self.fade_out),
2344 }
2345 }
2346}
2347
2348impl From<Hsla> for HighlightStyle {
2349 fn from(color: Hsla) -> Self {
2350 Self {
2351 color: Some(color),
2352 ..Default::default()
2353 }
2354 }
2355}
2356
2357impl From<FontWeight> for HighlightStyle {
2358 fn from(font_weight: FontWeight) -> Self {
2359 Self {
2360 font_weight: Some(font_weight),
2361 ..Default::default()
2362 }
2363 }
2364}
2365
2366impl From<FontStyle> for HighlightStyle {
2367 fn from(font_style: FontStyle) -> Self {
2368 Self {
2369 font_style: Some(font_style),
2370 ..Default::default()
2371 }
2372 }
2373}
2374
2375impl From<Rgba> for HighlightStyle {
2376 fn from(color: Rgba) -> Self {
2377 Self {
2378 color: Some(color.into()),
2379 ..Default::default()
2380 }
2381 }
2382}
2383
2384pub fn combine_highlights(
2386 a: impl IntoIterator<Item = (Range<usize>, HighlightStyle)>,
2387 b: impl IntoIterator<Item = (Range<usize>, HighlightStyle)>,
2388) -> impl Iterator<Item = (Range<usize>, HighlightStyle)> {
2389 let mut endpoints = Vec::new();
2390 let mut highlights = Vec::new();
2391 for (range, highlight) in a.into_iter().chain(b) {
2392 if !range.is_empty() {
2393 let highlight_id = highlights.len();
2394 endpoints.push((range.start, highlight_id, true));
2395 endpoints.push((range.end, highlight_id, false));
2396 highlights.push(highlight);
2397 }
2398 }
2399 endpoints.sort_unstable_by_key(|(position, _, _)| *position);
2400 let mut endpoints = endpoints.into_iter().peekable();
2401
2402 let mut active_styles = HashSet::default();
2403 let mut ix = 0;
2404 iter::from_fn(move || {
2405 while let Some((endpoint_ix, highlight_id, is_start)) = endpoints.peek() {
2406 let prev_index = mem::replace(&mut ix, *endpoint_ix);
2407 if ix > prev_index && !active_styles.is_empty() {
2408 let current_style = active_styles
2409 .iter()
2410 .fold(HighlightStyle::default(), |acc, highlight_id| {
2411 acc.highlight(highlights[*highlight_id])
2412 });
2413 return Some((prev_index..ix, current_style));
2414 }
2415
2416 if *is_start {
2417 active_styles.insert(*highlight_id);
2418 } else {
2419 active_styles.remove(highlight_id);
2420 }
2421 endpoints.next();
2422 }
2423 None
2424 })
2425}
2426
2427#[derive(Copy, Clone, PartialEq, Eq, Debug, Serialize, Deserialize)]
2433#[cfg_attr(feature = "schemars", derive(JsonSchema))]
2434pub enum AlignItems {
2436 Start,
2438 End,
2440 FlexStart,
2445 FlexEnd,
2450 Center,
2452 Baseline,
2454 Stretch,
2456}
2457pub type JustifyItems = AlignItems;
2463pub type AlignSelf = AlignItems;
2470pub type JustifySelf = AlignItems;
2477
2478#[derive(Copy, Clone, PartialEq, Eq, Debug, Serialize, Deserialize)]
2484#[cfg_attr(feature = "schemars", derive(JsonSchema))]
2485pub enum AlignContent {
2487 Start,
2489 End,
2491 FlexStart,
2496 FlexEnd,
2501 Center,
2503 Stretch,
2505 SpaceBetween,
2508 SpaceEvenly,
2511 SpaceAround,
2514 SafeCenter,
2518}
2519
2520pub type JustifyContent = AlignContent;
2526
2527#[derive(Copy, Clone, PartialEq, Eq, Debug, Default, Serialize, Deserialize)]
2531#[cfg_attr(feature = "schemars", derive(JsonSchema))]
2532pub enum Display {
2534 Block,
2536 #[default]
2538 Flex,
2539 Grid,
2541 None,
2543}
2544
2545#[derive(Copy, Clone, PartialEq, Eq, Debug, Default, Serialize, Deserialize)]
2551#[cfg_attr(feature = "schemars", derive(JsonSchema))]
2552pub enum FlexWrap {
2554 #[default]
2556 NoWrap,
2557 Wrap,
2559 WrapReverse,
2561}
2562
2563#[derive(Copy, Clone, PartialEq, Eq, Debug, Default, Serialize, Deserialize)]
2575#[cfg_attr(feature = "schemars", derive(JsonSchema))]
2576pub enum FlexDirection {
2578 #[default]
2582 Row,
2583 Column,
2587 RowReverse,
2591 ColumnReverse,
2595}
2596
2597#[derive(Copy, Clone, PartialEq, Eq, Debug, Default, Serialize, Deserialize)]
2611#[cfg_attr(feature = "schemars", derive(JsonSchema))]
2612pub enum Overflow {
2614 #[default]
2617 Visible,
2618 Clip,
2621 Hidden,
2624 Scroll,
2628}
2629
2630#[derive(Copy, Clone, PartialEq, Eq, Debug, Default, Serialize, Deserialize)]
2640#[cfg_attr(feature = "schemars", derive(JsonSchema))]
2641pub enum Position {
2643 #[default]
2646 Relative,
2647 Absolute,
2653}
2654
2655impl From<AlignItems> for taffy::style::AlignItems {
2656 fn from(value: AlignItems) -> Self {
2657 match value {
2658 AlignItems::Start => Self::START,
2659 AlignItems::End => Self::END,
2660 AlignItems::FlexStart => Self::FLEX_START,
2661 AlignItems::FlexEnd => Self::FLEX_END,
2662 AlignItems::Center => Self::CENTER,
2663 AlignItems::Baseline => Self::BASELINE,
2664 AlignItems::Stretch => Self::STRETCH,
2665 }
2666 }
2667}
2668
2669impl From<AlignContent> for taffy::style::AlignContent {
2670 fn from(value: AlignContent) -> Self {
2671 match value {
2672 AlignContent::Start => Self::START,
2673 AlignContent::End => Self::END,
2674 AlignContent::FlexStart => Self::FLEX_START,
2675 AlignContent::FlexEnd => Self::FLEX_END,
2676 AlignContent::Center => Self::CENTER,
2677 AlignContent::Stretch => Self::STRETCH,
2678 AlignContent::SpaceBetween => Self::SPACE_BETWEEN,
2679 AlignContent::SpaceEvenly => Self::SPACE_EVENLY,
2680 AlignContent::SpaceAround => Self::SPACE_AROUND,
2681 AlignContent::SafeCenter => Self::SAFE_CENTER,
2682 }
2683 }
2684}
2685
2686impl From<Display> for taffy::style::Display {
2687 fn from(value: Display) -> Self {
2688 match value {
2689 Display::Block => Self::Block,
2690 Display::Flex => Self::Flex,
2691 Display::Grid => Self::Grid,
2692 Display::None => Self::None,
2693 }
2694 }
2695}
2696
2697impl From<FlexWrap> for taffy::style::FlexWrap {
2698 fn from(value: FlexWrap) -> Self {
2699 match value {
2700 FlexWrap::NoWrap => Self::NoWrap,
2701 FlexWrap::Wrap => Self::Wrap,
2702 FlexWrap::WrapReverse => Self::WrapReverse,
2703 }
2704 }
2705}
2706
2707impl From<FlexDirection> for taffy::style::FlexDirection {
2708 fn from(value: FlexDirection) -> Self {
2709 match value {
2710 FlexDirection::Row => Self::Row,
2711 FlexDirection::Column => Self::Column,
2712 FlexDirection::RowReverse => Self::RowReverse,
2713 FlexDirection::ColumnReverse => Self::ColumnReverse,
2714 }
2715 }
2716}
2717
2718impl From<Overflow> for taffy::style::Overflow {
2719 fn from(value: Overflow) -> Self {
2720 match value {
2721 Overflow::Visible => Self::Visible,
2722 Overflow::Clip => Self::Clip,
2723 Overflow::Hidden => Self::Hidden,
2724 Overflow::Scroll => Self::Scroll,
2725 }
2726 }
2727}
2728
2729impl From<Position> for taffy::style::Position {
2730 fn from(value: Position) -> Self {
2731 match value {
2732 Position::Relative => Self::Relative,
2733 Position::Absolute => Self::Absolute,
2734 }
2735 }
2736}
2737
2738#[cfg(test)]
2739mod tests {
2740 use crate::{blue, green, px, red, yellow};
2741
2742 use super::*;
2743
2744 use util_macros::perf;
2745
2746 #[perf]
2747 fn test_basic_highlight_style_combination() {
2748 let style_a = HighlightStyle::default();
2749 let style_b = HighlightStyle::default();
2750 let style_a = style_a.highlight(style_b);
2751 assert_eq!(
2752 style_a,
2753 HighlightStyle::default(),
2754 "Combining empty styles should not produce a non-empty style."
2755 );
2756
2757 let style_b = HighlightStyle {
2758 color: Some(red()),
2759 strikethrough: Some(StrikethroughStyle {
2760 thickness: px(2.),
2761 color: Some(blue()),
2762 }),
2763 fade_out: Some(0.),
2764 font_style: Some(FontStyle::Italic),
2765 font_weight: Some(FontWeight(300.)),
2766 background_color: Some(yellow()),
2767 underline: Some(UnderlineStyle {
2768 thickness: px(2.),
2769 color: Some(red()),
2770 wavy: true,
2771 offset: px(0.),
2772 }),
2773 };
2774 let expected_style = style_b;
2775
2776 let style_a = style_a.highlight(style_b);
2777 assert_eq!(
2778 style_a, expected_style,
2779 "Blending an empty style with another style should return the other style"
2780 );
2781
2782 let style_b = style_b.highlight(Default::default());
2783 assert_eq!(
2784 style_b, expected_style,
2785 "Blending a style with an empty style should not change the style."
2786 );
2787
2788 let style_c = expected_style;
2789
2790 let style_d = HighlightStyle {
2791 color: Some(blue().alpha(0.7)),
2792 strikethrough: Some(StrikethroughStyle {
2793 thickness: px(4.),
2794 color: Some(crate::red()),
2795 }),
2796 fade_out: Some(0.),
2797 font_style: Some(FontStyle::Oblique),
2798 font_weight: Some(FontWeight(800.)),
2799 background_color: Some(green()),
2800 underline: Some(UnderlineStyle {
2801 thickness: px(4.),
2802 color: None,
2803 wavy: false,
2804 offset: px(0.),
2805 }),
2806 };
2807
2808 let expected_style = HighlightStyle {
2809 color: Some(red().blend(blue().alpha(0.7))),
2810 strikethrough: Some(StrikethroughStyle {
2811 thickness: px(4.),
2812 color: Some(red()),
2813 }),
2814 fade_out: Some(0.),
2816 font_style: Some(FontStyle::Oblique),
2817 font_weight: Some(FontWeight(800.)),
2818 background_color: Some(green()),
2819 underline: Some(UnderlineStyle {
2820 thickness: px(4.),
2821 color: None,
2822 wavy: false,
2823 offset: px(0.),
2824 }),
2825 };
2826
2827 let style_c = style_c.highlight(style_d);
2828 assert_eq!(
2829 style_c, expected_style,
2830 "Blending styles should blend properties where possible and override all others"
2831 );
2832 }
2833
2834 #[perf]
2835 fn test_combine_highlights() {
2836 assert_eq!(
2837 combine_highlights(
2838 [
2839 (0..5, green().into()),
2840 (4..10, FontWeight::BOLD.into()),
2841 (15..20, yellow().into()),
2842 ],
2843 [
2844 (2..6, FontStyle::Italic.into()),
2845 (1..3, blue().into()),
2846 (21..23, red().into()),
2847 ]
2848 )
2849 .collect::<Vec<_>>(),
2850 [
2851 (
2852 0..1,
2853 HighlightStyle {
2854 color: Some(green()),
2855 ..Default::default()
2856 }
2857 ),
2858 (
2859 1..2,
2860 HighlightStyle {
2861 color: Some(blue()),
2862 ..Default::default()
2863 }
2864 ),
2865 (
2866 2..3,
2867 HighlightStyle {
2868 color: Some(blue()),
2869 font_style: Some(FontStyle::Italic),
2870 ..Default::default()
2871 }
2872 ),
2873 (
2874 3..4,
2875 HighlightStyle {
2876 color: Some(green()),
2877 font_style: Some(FontStyle::Italic),
2878 ..Default::default()
2879 }
2880 ),
2881 (
2882 4..5,
2883 HighlightStyle {
2884 color: Some(green()),
2885 font_weight: Some(FontWeight::BOLD),
2886 font_style: Some(FontStyle::Italic),
2887 ..Default::default()
2888 }
2889 ),
2890 (
2891 5..6,
2892 HighlightStyle {
2893 font_weight: Some(FontWeight::BOLD),
2894 font_style: Some(FontStyle::Italic),
2895 ..Default::default()
2896 }
2897 ),
2898 (
2899 6..10,
2900 HighlightStyle {
2901 font_weight: Some(FontWeight::BOLD),
2902 ..Default::default()
2903 }
2904 ),
2905 (
2906 15..20,
2907 HighlightStyle {
2908 color: Some(yellow()),
2909 ..Default::default()
2910 }
2911 ),
2912 (
2913 21..23,
2914 HighlightStyle {
2915 color: Some(red()),
2916 ..Default::default()
2917 }
2918 )
2919 ]
2920 );
2921 }
2922
2923 #[perf]
2924 fn test_text_style_refinement() {
2925 let mut style = Style::default();
2926 style.refine(&StyleRefinement::default().text_size(px(20.0)));
2927 style.refine(&StyleRefinement::default().font_weight(FontWeight::SEMIBOLD));
2928
2929 assert_eq!(
2930 Some(AbsoluteLength::from(px(20.0))),
2931 style.text_style().unwrap().font_size
2932 );
2933
2934 assert_eq!(
2935 Some(FontWeight::SEMIBOLD),
2936 style.text_style().unwrap().font_weight
2937 );
2938 }
2939}
2940
2941#[cfg(test)]
2945mod vn_object_position_tests {
2946 use super::*;
2947 use crate::{px, size};
2948
2949 #[test]
2950 fn the_position_places_the_fitted_image_in_the_free_space() {
2951 let bounds = Bounds::new(point(px(10.), px(20.)), size(px(100.), px(50.)));
2952 let square = size(DevicePixels(40), DevicePixels(40));
2953 let at = |fit: ObjectFit, x: (f32, f32), y: (f32, f32)| {
2954 let position = ObjectPosition {
2955 x_fraction: x.0,
2956 x_offset: px(x.1),
2957 y_fraction: y.0,
2958 y_offset: px(y.1),
2959 };
2960 let b = fit.get_bounds_at(bounds, square, position);
2961 (f32::from(b.origin.x), f32::from(b.origin.y), f32::from(b.size.width), f32::from(b.size.height))
2962 };
2963 assert_eq!(at(ObjectFit::Contain, (0., 0.), (0., 0.)), (10., 20., 50., 50.));
2964 assert_eq!(at(ObjectFit::Contain, (1., -5.), (0.5, 0.)), (55., 20., 50., 50.));
2965 assert_eq!(at(ObjectFit::Cover, (0., 0.), (1., 0.)), (10., -30., 100., 100.));
2966 assert_eq!(at(ObjectFit::None, (0.25, 0.), (0., 3.)), (25., 23., 40., 40.));
2967 assert_eq!(at(ObjectFit::Fill, (0.5, 7.), (0.5, 0.)), (17., 20., 100., 50.));
2968 let legacy = ObjectFit::None.get_bounds(bounds, square);
2969 assert_eq!(legacy.origin, bounds.origin);
2970 }
2971}
2972
2973#[cfg(test)]
2974mod vn_safe_center_tests {
2975 use crate::{AlignContent, Context, TestAppContext, Window, div, prelude::*, px, size};
2976
2977 struct Boxes;
2978
2979 impl Render for Boxes {
2980 fn render(&mut self, _window: &mut Window, _cx: &mut Context<Self>) -> impl IntoElement {
2981 let block = |name: &'static str, child_h: f32| {
2982 let mut d = div().w(px(100.)).h(px(100.));
2983 d.style().align_content = Some(AlignContent::SafeCenter);
2984 d.child(div().debug_selector(move || name.into()).w(px(10.)).h(px(child_h)))
2985 };
2986 div().child(block("FITS", 20.)).child(block("OVERFLOWS", 200.))
2987 }
2988 }
2989
2990 #[gpui::test]
2991 fn safe_center_centres_what_fits_and_starts_what_overflows(cx: &mut TestAppContext) {
2992 let window = cx.open_window(size(px(400.), px(600.)), |_, _| Boxes);
2993 cx.run_until_parked();
2994 window
2995 .update(cx, |_, window, _| {
2996 let at = |name: &str| window.rendered_frame.debug_bounds.get(name).copied().unwrap();
2997 assert_eq!(at("FITS").origin.y, px(40.), "(100 - 20) / 2");
2998 assert_eq!(at("OVERFLOWS").origin.y, px(100.), "at the start of the second box");
2999 })
3000 .unwrap();
3001 }
3002}
3003
3004#[cfg(test)]
3006mod vn_mask_ring_tests {
3007 use crate::{
3008 BoxShadow, Context, Hsla, TestAppContext, Window, color::BG_RING, div, point,
3009 prelude::*, px, size,
3010 };
3011
3012 struct Card {
3013 ring: bool,
3014 }
3015
3016 impl Render for Card {
3017 fn render(&mut self, _window: &mut Window, _cx: &mut Context<Self>) -> impl IntoElement {
3018 let mut d = div()
3019 .w(px(100.))
3020 .h(px(60.))
3021 .p(px(2.))
3022 .border_1()
3023 .border_color(Hsla::white())
3024 .bg(Hsla::red())
3025 .shadow(vec![BoxShadow {
3026 color: Hsla::black(),
3027 offset: point(px(0.), px(4.)),
3028 blur_radius: px(8.),
3029 spread_radius: px(0.),
3030 inset: false,
3031 }]);
3032 d.style().vn_mask_ring = Some(self.ring);
3033 d
3034 }
3035 }
3036
3037 fn paint(ring: bool, cx: &mut TestAppContext) -> (Vec<crate::Quad>, usize, f32) {
3039 let window = cx.open_window(size(px(300.), px(300.)), move |_, _| Card { ring });
3040 cx.run_until_parked();
3041 window
3042 .update(cx, |_, window, _| {
3043 let shadows = window.rendered_frame.scene.shadows.len();
3044 (window.painted_quads(), shadows, window.scale_factor())
3045 })
3046 .unwrap()
3047 }
3048
3049 #[gpui::test]
3050 fn a_ring_mask_paints_the_background_in_the_padding_and_border_only(
3051 cx: &mut TestAppContext,
3052 ) {
3053 let (quads, shadows, scale) = paint(false, cx);
3054 let background = quads.iter().find(|q| q.background.as_solid() == Some(Hsla::red()));
3055 let background = background.expect("the background quad");
3056 assert_eq!(background.background.flags & BG_RING, 0);
3057 assert_eq!(background.border_widths.top.0, 0.0, "a plain background fills the box");
3058 assert_eq!(shadows, 1);
3059
3060 let (quads, shadows, _) = paint(true, cx);
3061 let background = quads
3062 .iter()
3063 .find(|q| q.background.flags & BG_RING != 0)
3064 .expect("the background quad, flagged");
3065 assert_eq!(background.background.as_solid(), Some(Hsla::red()));
3066 for width in [
3067 background.border_widths.top,
3068 background.border_widths.right,
3069 background.border_widths.bottom,
3070 background.border_widths.left,
3071 ] {
3072 assert_eq!(width.0, 3.0 * scale, "1px border + 2px padding");
3073 }
3074 let border = quads
3075 .iter()
3076 .find(|q| q.border_color == Hsla::white())
3077 .expect("the border still paints");
3078 assert_eq!(border.border_widths.top.0, 1.0 * scale);
3079 assert_eq!(shadows, 0, "the mask cuts the outer shadow");
3080 }
3081}
3082
3083#[cfg(test)]
3086mod vn_rounded_clip_tests {
3087 use crate::{
3088 Bounds, Context, Corners, DefiniteLength, Edges, Hsla, Overflow, Style, TestAppContext,
3089 VnCornerRadius, Window, div, point, prelude::*, px, size, vn_resolve_corner_radii,
3090 vn_take_ellipse_drawn_as_circle,
3091 };
3092
3093 fn clipping(radius: f32, border: f32, border_color: Option<Hsla>) -> Style {
3094 Style {
3095 overflow: point(Overflow::Hidden, Overflow::Hidden),
3096 corner_radii: Corners::all(px(radius)).map(|radius| (*radius).into()),
3097 border_widths: Edges::all(px(border).into()),
3098 border_color,
3099 ..Style::default()
3100 }
3101 }
3102
3103 #[test]
3104 fn an_overflow_clip_takes_the_padding_box_curve() {
3105 let rem = px(16.);
3106 let bounds = Bounds::new(point(px(10.), px(20.)), size(px(200.), px(160.)));
3107
3108 let mask = clipping(24., 4., Some(Hsla::black())).overflow_mask(bounds, rem).unwrap();
3109 assert_eq!(mask.bounds, Bounds::new(point(px(14.), px(24.)), size(px(192.), px(152.))));
3110 assert_eq!(mask.corner_radii, Corners::all(px(20.)), "the radius less the border");
3111
3112 let mask = clipping(24., 4., None).overflow_mask(bounds, rem).unwrap();
3113 assert_eq!(mask.bounds, bounds, "a transparent border is not inset");
3114 assert_eq!(mask.corner_radii, Corners::all(px(24.)), "so it takes nothing off");
3115
3116 let mask = clipping(3., 4., Some(Hsla::black())).overflow_mask(bounds, rem).unwrap();
3117 assert_eq!(mask.corner_radii, Corners::all(px(0.)), "a border wider than the radius");
3118
3119 let avatar = Bounds::new(point(px(0.), px(0.)), size(px(64.), px(64.)));
3120 let mask = clipping(9999., 0., None).overflow_mask(avatar, rem).unwrap();
3121 assert_eq!(mask.corner_radii, Corners::all(px(32.)), "a pill is a circle");
3122
3123 let mask = clipping(0., 0., None).overflow_mask(bounds, rem).unwrap();
3124 assert!(!mask.is_rounded(), "no radius, the plain rect");
3125 }
3126
3127 fn resolve(lengths: [f32; 4], relative: [Option<(DefiniteLength, DefiniteLength)>; 4], w: f32, h: f32) -> [f32; 4] {
3128 let corner = |r: Option<(DefiniteLength, DefiniteLength)>| r.map(|(x, y)| VnCornerRadius { x, y });
3129 let radii = vn_resolve_corner_radii(
3130 &Corners {
3131 top_left: px(lengths[0]).into(),
3132 top_right: px(lengths[1]).into(),
3133 bottom_right: px(lengths[2]).into(),
3134 bottom_left: px(lengths[3]).into(),
3135 },
3136 &Corners {
3137 top_left: corner(relative[0]),
3138 top_right: corner(relative[1]),
3139 bottom_right: corner(relative[2]),
3140 bottom_left: corner(relative[3]),
3141 },
3142 size(px(w), px(h)),
3143 px(16.),
3144 );
3145 [radii.top_left, radii.top_right, radii.bottom_right, radii.bottom_left].map(f32::from)
3146 }
3147
3148 #[test]
3149 fn percentages_resolve_against_the_box_and_overlaps_scale() {
3150 let half = Some((DefiniteLength::Fraction(0.5), DefiniteLength::Fraction(0.5)));
3151 let _ = vn_take_ellipse_drawn_as_circle();
3152
3153 assert_eq!(resolve([0.; 4], [half; 4], 64., 64.), [32.; 4], "50% of a square: a circle");
3154 assert!(!vn_take_ellipse_drawn_as_circle());
3155
3156 assert_eq!(resolve([0.; 4], [half; 4], 120., 48.), [24.; 4]);
3159 assert!(vn_take_ellipse_drawn_as_circle());
3160
3161 assert_eq!(resolve([9999.; 4], [None; 4], 100., 40.), [20.; 4]);
3163 assert_eq!(resolve([9999., 0., 0., 9999.], [None; 4], 100., 40.), [20., 0., 0., 20.]);
3166 assert_eq!(resolve([8., 4., 0., 12.], [None; 4], 100., 40.), [8., 4., 0., 12.]);
3168 assert_eq!(resolve([40., 40., 0., 0.], [None; 4], 60., 200.), [30., 30., 0., 0.]);
3170
3171 let calc = DefiniteLength::Calc { fraction: 0.5, pixels: px(-4.) };
3173 assert_eq!(resolve([0.; 4], [Some((calc, calc)); 4], 64., 64.), [28.; 4]);
3174 let ellipse = Some((DefiniteLength::Absolute(px(10.).into()), DefiniteLength::Absolute(px(20.).into())));
3175 assert_eq!(resolve([0.; 4], [ellipse; 4], 100., 100.), [10.; 4]);
3176 assert!(vn_take_ellipse_drawn_as_circle());
3177 }
3178
3179 #[test]
3180 fn a_percentage_radius_clips_overflow_too() {
3181 let mut avatar = clipping(0., 0., None);
3182 let half = Some(VnCornerRadius {
3183 x: DefiniteLength::Fraction(0.5),
3184 y: DefiniteLength::Fraction(0.5),
3185 });
3186 avatar.vn_corner_radii = Corners {
3187 top_left: half,
3188 top_right: half,
3189 bottom_right: half,
3190 bottom_left: half,
3191 };
3192 let bounds = Bounds::new(point(px(0.), px(0.)), size(px(40.), px(40.)));
3193 let mask = avatar.overflow_mask(bounds, px(16.)).unwrap();
3194 assert_eq!(mask.corner_radii, Corners::all(px(20.)));
3195 }
3196
3197 struct Clips;
3200
3201 impl Render for Clips {
3202 fn render(&mut self, _window: &mut Window, _cx: &mut Context<Self>) -> impl IntoElement {
3203 div()
3204 .child(
3205 div()
3206 .size(px(64.))
3207 .rounded_full()
3208 .overflow_hidden()
3209 .child(div().size_full().bg(Hsla::red())),
3210 )
3211 .child(
3212 div()
3213 .w(px(200.))
3214 .h(px(160.))
3215 .rounded(px(24.))
3216 .overflow_hidden()
3217 .child(
3218 div()
3219 .id("list")
3220 .size_full()
3221 .overflow_y_scroll()
3222 .child(div().w_full().h(px(400.)).bg(Hsla::green())),
3223 ),
3224 )
3225 }
3226 }
3227
3228 #[gpui::test]
3229 fn what_paints_inside_carries_the_rounded_mask(cx: &mut TestAppContext) {
3230 let window = cx.open_window(size(px(400.), px(400.)), |_, _| Clips);
3231 cx.run_until_parked();
3232 let (quads, scale) = window
3233 .update(cx, |_, window, _| (window.painted_quads(), window.scale_factor()))
3234 .unwrap();
3235 let quad = |color: Hsla| {
3236 quads
3237 .iter()
3238 .find(|q| q.background.as_solid() == Some(color))
3239 .copied()
3240 .expect("the quad")
3241 };
3242
3243 let avatar = quad(Hsla::red());
3244 assert_eq!(avatar.content_mask.corner_radii, Corners::all(px(32.)).scale(scale));
3245 assert_eq!(avatar.corner_radii, Corners::default(), "the image itself is square");
3246
3247 let rows = quad(Hsla::green());
3250 assert_eq!(rows.content_mask.corner_radii, Corners::all(px(24.)).scale(scale));
3251 assert_eq!(rows.content_mask.bounds.size, size(px(200.), px(160.)).scale(scale));
3252 }
3253}
3254
3255#[cfg(test)]
3258mod vn_clip_path_tests {
3259 use crate::{
3260 Bounds, BoxShadow, Context, Corners, DefiniteLength, Edges, Hsla, Length, Pixels, Style,
3261 TestAppContext, VnClipBox, VnClipPath, VnCornerRadius, VnShapeRadius, Window, div, point,
3262 prelude::*, px, relative, size,
3263 };
3264
3265 const BOX: VnClipBox = VnClipBox::Border;
3266
3267 fn len(v: f32) -> DefiniteLength {
3268 px(v).into()
3269 }
3270
3271 fn round(x: DefiniteLength, y: DefiniteLength) -> [VnCornerRadius; 4] {
3272 [VnCornerRadius { x, y }; 4]
3273 }
3274
3275 fn mask(clip: VnClipPath, style: Style, bounds: [f32; 4]) -> ([f32; 4], [f32; 4]) {
3277 let bounds = Bounds::new(point(px(bounds[0]), px(bounds[1])), size(px(bounds[2]), px(bounds[3])));
3278 let m = Style { vn_clip_path: clip, ..style }.vn_clip_mask(bounds, px(16.)).expect("a mask");
3279 let (b, r) = (m.bounds, m.corner_radii);
3280 let at = |v: Pixels| (f32::from(v) * 100.).round() / 100.;
3281 (
3282 [b.origin.x, b.origin.y, b.size.width, b.size.height].map(at),
3283 [r.top_left, r.top_right, r.bottom_right, r.bottom_left].map(at),
3284 )
3285 }
3286
3287 fn inset(insets: [DefiniteLength; 4], radii: [VnCornerRadius; 4]) -> VnClipPath {
3288 VnClipPath::Inset { reference: BOX, insets, radii }
3289 }
3290
3291 fn ellipse(center: [DefiniteLength; 2], radius: [VnShapeRadius; 2], circle: bool) -> VnClipPath {
3292 VnClipPath::Ellipse { reference: BOX, center, radius, circle }
3293 }
3294
3295 #[test]
3296 fn inset_takes_its_insets_off_the_box_and_fits_its_radii() {
3297 let none = Style::default;
3298 let square = round(len(0.), len(0.));
3299 assert_eq!(Style::default().vn_clip_mask(Bounds::default(), px(16.)), None, "none is no mask");
3300 let insets = [len(10.), relative(0.2), len(10.), relative(0.2)];
3302 assert_eq!(
3303 mask(inset(insets, round(len(8.), len(8.))), none(), [10., 20., 200., 100.]),
3304 ([50., 30., 120., 80.], [8.; 4])
3305 );
3306 let half = relative(0.5);
3308 assert_eq!(mask(inset([half; 4], square), none(), [0., 0., 30., 10.]).0, [15., 5., 0., 0.]);
3309 assert_eq!(mask(inset([len(80.); 4], square), none(), [0., 0., 100., 100.]).0, [80., 80., 0., 0.]);
3311 let strip = [len(40.), len(0.), len(40.), len(0.)];
3315 assert_eq!(mask(inset(strip, round(len(30.), len(30.))), none(), [0., 0., 200., 100.]).1, [10.; 4]);
3316 let ten = relative(0.1);
3317 assert_eq!(mask(inset([len(0.); 4], round(ten, ten)), none(), [0., 0., 200., 100.]).1, [10.; 4]);
3318 }
3319
3320 #[test]
3321 fn circle_and_ellipse_resolve_against_the_box() {
3322 let none = Style::default;
3323 let mid = [relative(0.5), relative(0.5)];
3324 let circle = ellipse(mid, [VnShapeRadius::Length(relative(0.5)); 2], true);
3326 assert_eq!(mask(circle.clone(), none(), [0., 0., 60., 60.]), ([0., 0., 60., 60.], [30.; 4]));
3327 assert_eq!(mask(circle, none(), [0., 0., 200., 100.]).1, [79.06; 4]);
3329 let at = [relative(0.25), relative(0.5)];
3331 assert_eq!(
3332 mask(ellipse(at, [VnShapeRadius::ClosestSide; 2], true), none(), [0., 0., 200., 100.]),
3333 ([0., 0., 100., 100.], [50.; 4])
3334 );
3335 let far = ellipse(at, [VnShapeRadius::FarthestSide; 2], true);
3336 assert_eq!(mask(far, none(), [0., 0., 200., 100.]).1, [150.; 4]);
3337 let e = ellipse(mid, [VnShapeRadius::ClosestSide, VnShapeRadius::FarthestSide], false);
3341 assert_eq!(mask(e.clone(), none(), [0., 0., 200., 100.]), ([0., 0., 200., 100.], [0.; 4]));
3342 let bounds = Bounds::new(point(px(0.), px(0.)), size(px(200.), px(100.)));
3343 let outline = Style { vn_clip_path: e, ..none() }.vn_clip_outline(bounds, px(16.)).expect("an outline");
3344 let g = crate::VnClipGeometry::new(&outline, 1., crate::TransformationMatrix::unit());
3345 assert!(g.contains([100., 50.]) && g.contains([2., 50.]) && g.contains([100., 2.]));
3346 assert!(!g.contains([20., 10.]), "the corner a capsule would keep");
3347 let right = [DefiniteLength::Calc { fraction: 1., pixels: px(-10.) }, relative(0.5)];
3349 let e = ellipse(right, [VnShapeRadius::Length(len(10.)), VnShapeRadius::Length(relative(0.2))], false);
3350 assert_eq!(mask(e, none(), [0., 0., 200., 100.]), ([180., 30., 20., 40.], [0.; 4]));
3351 let c = Style { vn_clip_path: ellipse(mid, [VnShapeRadius::ClosestSide; 2], true), ..none() };
3353 assert_eq!(c.vn_clip_outline(bounds, px(16.)), None);
3354 }
3355
3356 #[test]
3357 fn a_box_alone_is_rounded_as_the_border_radius_rounds_it() {
3358 let style = || Style {
3359 corner_radii: Corners::all(px(24.)).map(|r| (*r).into()),
3360 border_widths: Edges::all(px(4.).into()),
3361 padding: Edges::all(px(6.).into()),
3362 margin: Edges { top: Length::Auto, ..Edges::all(len(8.).into()) },
3363 ..Style::default()
3364 };
3365 let at = [0., 0., 100., 80.];
3366 assert_eq!(mask(VnClipPath::Box(VnClipBox::Border), style(), at), ([0., 0., 100., 80.], [24.; 4]));
3367 assert_eq!(mask(VnClipPath::Box(VnClipBox::Padding), style(), at), ([4., 4., 92., 72.], [20.; 4]));
3368 assert_eq!(mask(VnClipPath::Box(VnClipBox::Content), style(), at), ([10., 10., 80., 60.], [14.; 4]));
3369 assert_eq!(mask(VnClipPath::Box(VnClipBox::Margin), style(), at), ([-8., 0., 116., 88.], [32.; 4]));
3371 let clip = VnClipPath::Inset { reference: VnClipBox::Content, insets: [len(5.); 4], radii: round(len(0.), len(0.)) };
3373 assert_eq!(mask(clip, style(), at), ([15., 15., 70., 50.], [0.; 4]));
3374 }
3375
3376 struct Clipped;
3379
3380 impl Render for Clipped {
3381 fn render(&mut self, _window: &mut Window, _cx: &mut Context<Self>) -> impl IntoElement {
3382 let mut d = div()
3383 .size(px(60.))
3384 .bg(Hsla::red())
3385 .border_2()
3386 .border_color(Hsla::white())
3387 .shadow(vec![BoxShadow {
3388 color: Hsla::black(),
3389 offset: point(px(0.), px(4.)),
3390 blur_radius: px(8.),
3391 spread_radius: px(0.),
3392 inset: false,
3393 }])
3394 .child(div().size(px(100.)).bg(Hsla::green()));
3395 d.style().vn_clip_path = Some(VnClipPath::Ellipse {
3396 reference: VnClipBox::Border,
3397 center: [relative(0.5), relative(0.5)],
3398 radius: [VnShapeRadius::Length(relative(0.5)); 2],
3399 circle: true,
3400 });
3401 div().child(d)
3402 }
3403 }
3404
3405 #[gpui::test]
3406 fn everything_the_element_paints_carries_the_mask(cx: &mut TestAppContext) {
3407 let window = cx.open_window(size(px(200.), px(200.)), |_, _| Clipped);
3408 cx.run_until_parked();
3409 let (quads, shadows, scale) = window
3410 .update(cx, |_, window, _| {
3411 (window.painted_quads(), window.rendered_frame.scene.shadows.clone(), window.scale_factor())
3412 })
3413 .unwrap();
3414 let disc = Bounds::new(point(px(0.), px(0.)), size(px(60.), px(60.))).scale(scale);
3415 let radius = Corners::all(px(30.)).scale(scale);
3416 for color in [Hsla::red(), Hsla::green()] {
3417 let q = quads.iter().find(|q| q.background.as_solid() == Some(color)).expect("the quad");
3418 assert_eq!((q.content_mask.bounds, q.content_mask.corner_radii), (disc, radius), "{color:?}");
3419 }
3420 let border = quads.iter().find(|q| q.border_color == Hsla::white()).expect("the border");
3421 assert_eq!(border.content_mask.bounds, disc);
3422 assert_eq!(shadows.len(), 1);
3423 assert_eq!((shadows[0].content_mask.bounds, shadows[0].content_mask.corner_radii), (disc, radius));
3424 }
3425
3426 fn polygon(reference: VnClipBox, fill_rule: crate::VnFillRule, points: &[[DefiniteLength; 2]]) -> VnClipPath {
3427 VnClipPath::Polygon { reference, fill_rule, points: points.to_vec().into() }
3428 }
3429
3430 fn outline(clip: VnClipPath, style: Style, at: [f32; 4]) -> crate::VnClipOutline {
3431 let bounds = Bounds::new(point(px(at[0]), px(at[1])), size(px(at[2]), px(at[3])));
3432 Style { vn_clip_path: clip, ..style }.vn_clip_outline(bounds, px(16.)).expect("an outline")
3433 }
3434
3435 #[test]
3436 fn a_polygon_resolves_its_percentages_against_the_reference_box() {
3437 use crate::{VnFillRule, VnPathVerb::*};
3438 let triangle = [[relative(0.5), len(0.)], [relative(1.), relative(1.)], [len(0.), relative(1.)]];
3440 let o = outline(polygon(BOX, VnFillRule::NonZero, &triangle), Style::default(), [10., 20., 200., 100.]);
3441 assert_eq!(o.verbs, vec![MoveTo([110., 20.]), LineTo([210., 120.]), LineTo([10., 120.]), Close]);
3442 assert_eq!(
3444 mask(polygon(BOX, VnFillRule::NonZero, &triangle), Style::default(), [10., 20., 200., 100.]),
3445 ([10., 20., 200., 100.], [0.; 4])
3446 );
3447 let style = || Style {
3449 border_widths: Edges::all(px(4.).into()),
3450 padding: Edges::all(px(6.).into()),
3451 ..Style::default()
3452 };
3453 let o = outline(polygon(VnClipBox::Content, VnFillRule::EvenOdd, &triangle), style(), [0., 0., 100., 100.]);
3454 assert_eq!(o.fill_rule, VnFillRule::EvenOdd);
3455 assert_eq!(o.verbs[0], MoveTo([50., 10.]));
3456 assert_eq!(o.verbs[1], LineTo([90., 90.]));
3457 let past = [[DefiniteLength::Calc { fraction: 1., pixels: px(-10.) }, relative(1.5)]];
3459 assert_eq!(
3460 outline(polygon(BOX, VnFillRule::NonZero, &past), Style::default(), [0., 0., 100., 40.]).verbs[0],
3461 MoveTo([90., 60.])
3462 );
3463 }
3464
3465 #[test]
3466 fn a_path_is_laid_from_the_reference_box_corner() {
3467 use crate::{VnFillRule, VnPathVerb::*};
3468 let verbs = vec![MoveTo([0., 0.]), QuadTo([10., 20.], [20., 0.]), Close];
3469 let path = |reference| VnClipPath::Path { reference, fill_rule: VnFillRule::NonZero, verbs: verbs.clone().into() };
3470 let o = outline(path(BOX), Style::default(), [5., 7., 50., 50.]);
3471 assert_eq!(o.verbs, vec![MoveTo([5., 7.]), QuadTo([15., 27.], [25., 7.]), Close]);
3472 let style = Style { padding: Edges::all(px(3.).into()), ..Style::default() };
3473 let o = outline(path(VnClipBox::Content), style, [0., 0., 50., 50.]);
3474 assert_eq!(o.verbs[0], MoveTo([3., 3.]));
3475 assert_eq!(mask(path(BOX), Style::default(), [5., 7., 50., 50.]).0, [5., 7., 20., 20.]);
3477 }
3478
3479 struct Triangle;
3481
3482 impl Render for Triangle {
3483 fn render(&mut self, _window: &mut Window, _cx: &mut Context<Self>) -> impl IntoElement {
3484 let mut d = div()
3485 .size(px(100.))
3486 .bg(Hsla::red())
3487 .cursor_pointer()
3488 .child(div().size(px(100.)).bg(Hsla::green()))
3489 .child(crate::deferred(div().absolute().top_0().left_0().size(px(50.)).bg(Hsla::blue())).clip_to_ancestors(true));
3490 d.style().vn_clip_path = Some(polygon(
3491 BOX,
3492 crate::VnFillRule::NonZero,
3493 &[[len(0.), len(0.)], [len(100.), len(0.)], [len(0.), len(100.)]],
3494 ));
3495 div().child(d)
3496 }
3497 }
3498
3499 #[gpui::test]
3500 fn a_polygon_paints_into_an_isolated_layer_and_cuts_the_hit_test(cx: &mut TestAppContext) {
3501 let window = cx.open_window(size(px(200.), px(200.)), |_, _| Triangle);
3502 cx.run_until_parked();
3503 window
3504 .update(cx, |_, window, _| {
3505 let scale = window.scale_factor();
3506 let scene = &window.rendered_frame.scene;
3507 assert_eq!(scene.vn_layers.len(), 2, "{:?}", scene.vn_layers);
3510 assert_eq!(scene.vn_group_count(), 3);
3511 let root: Vec<_> = scene.vn_batches(0).collect();
3512 assert!(root.iter().all(|b| matches!(b, crate::VnBatch::Layers(_))), "{root:?}");
3513 let colors = |group: usize| -> Vec<Hsla> {
3514 scene
3515 .vn_batches(group)
3516 .filter_map(|b| match b {
3517 crate::VnBatch::Primitives(crate::PrimitiveBatch::Quads(r)) => Some(r),
3518 _ => None,
3519 })
3520 .flat_map(|r| scene.quads[r].iter().filter_map(|q| q.background.as_solid()).collect::<Vec<_>>())
3521 .collect()
3522 };
3523 let mut groups: Vec<Vec<Hsla>> = scene.vn_layers.iter().map(|l| colors(l.group as usize)).collect();
3524 groups.sort_by_key(|g| g.len());
3525 assert_eq!(groups, vec![vec![Hsla::blue()], vec![Hsla::red(), Hsla::green()]]);
3526 for layer in &scene.vn_layers {
3529 assert_eq!(layer.segment_count, 3);
3530 assert_eq!(layer.fill_rule, 0);
3531 assert!(layer.bounds.size.width.0 >= 100. * scale);
3532 }
3533 assert_eq!(scene.vn_clip_segments.len(), 6);
3534 let flat = scene.batches().count();
3536 assert!(flat >= 2, "{flat}");
3537
3538 let frame = &window.rendered_frame;
3540 let clipped: Vec<_> = frame.hitboxes.iter().filter(|h| h.vn_clip.is_some()).collect();
3541 assert_eq!(clipped.len(), 1);
3542 let id = clipped[0].id;
3543 let hits = |x: f32, y: f32| frame.hit_test(point(px(x), px(y)), scale).ids.contains(&id);
3544 assert!(hits(10., 10.));
3545 assert!(hits(40., 40.));
3546 assert!(!hits(60., 60.), "inside the box, outside the triangle");
3547 assert!(!hits(150., 10.));
3548 })
3549 .unwrap();
3550 }
3551
3552 fn quad_mask(tint_leaf: bool) -> crate::VnMask {
3553 crate::VnMask {
3554 luminance: false,
3555 tint_leaf,
3556 key: 1,
3557 paint: Some(std::rc::Rc::new(|bounds, tint, window: &mut Window, _: &mut crate::App| {
3558 let half = Bounds::new(bounds.origin, size(bounds.size.width / 2., bounds.size.height));
3559 window.paint_quad(crate::fill(half, tint.unwrap_or_else(Hsla::white)));
3560 })),
3561 }
3562 }
3563
3564 struct Masked;
3566
3567 impl Render for Masked {
3568 fn render(&mut self, _window: &mut Window, _cx: &mut Context<Self>) -> impl IntoElement {
3569 let deferred = crate::deferred(div().absolute().top_0().left_0().size(px(20.)).bg(Hsla::black()));
3570 let mut boxed = div()
3571 .size(px(40.))
3572 .bg(Hsla::red())
3573 .opacity(0.5)
3574 .child(div().size(px(10.)).bg(Hsla::green()))
3575 .child(deferred.clip_to_ancestors(true));
3576 boxed.style().vn_mask = Some(quad_mask(false));
3577 let mut icon = div().size(px(20.)).bg(Hsla::blue());
3578 icon.style().vn_mask = Some(quad_mask(true));
3579 div().child(boxed).child(icon)
3580 }
3581 }
3582
3583 #[gpui::test]
3584 fn a_mask_composites_its_group_through_the_mask_group_and_a_leaf_is_tinted(cx: &mut TestAppContext) {
3585 let window = cx.open_window(size(px(200.), px(200.)), |_, _| Masked);
3586 cx.run_until_parked();
3587 window
3588 .update(cx, |_, window, _| {
3589 let scene = &window.rendered_frame.scene;
3590 assert_eq!(scene.vn_layers.len(), 2, "the box, the deferred child, and no layer for the leaf");
3591 let colors = |group: usize| -> Vec<Hsla> {
3592 scene
3593 .vn_batches(group)
3594 .filter_map(|b| match b {
3595 crate::VnBatch::Primitives(crate::PrimitiveBatch::Quads(r)) => Some(r),
3596 _ => None,
3597 })
3598 .flat_map(|r| scene.quads[r].iter().filter_map(|q| q.background.as_solid()).collect::<Vec<_>>())
3599 .collect()
3600 };
3601 let mut groups = Vec::new();
3602 for layer in &scene.vn_layers {
3603 assert_eq!(layer.fill_rule, 1 << 1, "an alpha mask over a nonzero box");
3604 let content = colors(layer.group as usize);
3605 assert!(content.iter().all(|c| (c.a - 0.5).abs() < 1e-3), "{content:?}");
3606 assert_eq!(colors(layer.group as usize + 1), vec![Hsla::white()], "the mask is not faded");
3607 groups.push(content.len());
3608 }
3609 groups.sort();
3610 assert_eq!(groups, vec![1, 2], "the deferred child paints through the mask again");
3611 let root = colors(0);
3612 assert_eq!(root, vec![Hsla::blue()], "the leaf paints the mask in its colour");
3613 let leaf = scene.quads.iter().find(|q| q.background.as_solid() == Some(Hsla::blue())).unwrap();
3614 assert_eq!(leaf.bounds.size.width.0, 10. * window.scale_factor());
3615 })
3616 .unwrap();
3617 }
3618}
3619
3620#[cfg(test)]
3621mod vn_border_color_tests {
3622 use super::*;
3623
3624 #[test]
3625 fn independent_border_colors_keep_shared_fallback_and_transparent_sides() {
3626 let mut style = Style { border_color: Some(Hsla::red()), ..Default::default() };
3627 style.vn_border_colors.left = Some(Hsla::transparent_black());
3628 style.vn_border_colors.top = Some(Hsla::blue());
3629 let colors = style.vn_resolved_border_colors();
3630 assert_eq!(colors.top, Hsla::blue());
3631 assert_eq!(colors.right, Hsla::red());
3632 assert!(colors.left.is_transparent());
3633 }
3634
3635 #[test]
3638 fn overflow_is_clipped_inside_borders_coloured_per_side() {
3639 let mut style = Style::default();
3640 style.overflow = Point { x: Overflow::Hidden, y: Overflow::Hidden };
3641 style.border_widths = Edges::all(px(4.).into());
3642 style.vn_border_colors.top = Some(Hsla::blue());
3643 style.vn_border_colors.left = Some(Hsla::red());
3644 let bounds = Bounds::new(point(px(0.), px(0.)), size(px(100.), px(100.)));
3645 let mask = style.overflow_mask(bounds, px(16.)).unwrap();
3646 assert_eq!(mask.bounds, Bounds::from_corners(point(px(4.), px(4.)), point(px(100.), px(100.))));
3647 }
3648
3649 #[test]
3650 fn colored_border_partitions_cover_rounded_arcs_with_width_weighted_joins() {
3651 let clips = Style::vn_border_side_clips(
3652 Bounds::new(point(px(0.), px(0.)), size(px(80.), px(80.))), Edges::all(px(8.)),
3653 );
3654 let contains = |polygon: &Vec<[f32; 2]>, point: [f32; 2]| {
3655 let mut sign = 0.;
3656 for (a, b) in polygon.iter().zip(polygon.iter().cycle().skip(1)) {
3657 let cross = (b[0] - a[0]) * (point[1] - a[1]) - (b[1] - a[1]) * (point[0] - a[0]);
3658 if cross.abs() < 0.0001 { continue; }
3659 if sign != 0. && cross.signum() != sign { return false; }
3660 sign = cross.signum();
3661 }
3662 polygon.len() >= 3
3663 };
3664 assert!(contains(&clips[0], [15., 13.]), "top rounded arc extends below the rectangular inner top");
3665 assert!(contains(&clips[3], [13., 15.]), "left rounded arc extends beyond the rectangular inner left");
3666 for y in 0..80 {
3667 for x in 0..80 {
3668 assert!(clips.iter().any(|polygon| contains(polygon, [x as f32 + 0.25, y as f32 + 0.25])),
3669 "coloured side clips must cover the entire quad, including rounded corners");
3670 }
3671 }
3672 let clips = Style::vn_border_side_clips(
3673 Bounds::new(point(px(0.), px(0.)), size(px(100.), px(60.))),
3674 Edges { top: px(4.), right: px(8.), bottom: px(6.), left: px(2.) },
3675 );
3676 assert!(contains(&clips[0], [2., 3.]));
3677 assert!(contains(&clips[3], [2., 5.]), "top/left join uses their2:4width ratio");
3678 }
3679}