1use std::{
2 hash::{Hash, Hasher},
3 iter, mem,
4 ops::Range,
5};
6
7use crate::{
8 AbsoluteLength, App, Background, BackgroundTag, BorderStyle, Bounds, ContentMask, Corners,
9 CornersRefinement, CursorStyle, DefiniteLength, DevicePixels, Edges, EdgesRefinement, Font,
10 FontFallbacks, FontFeatures, FontStyle, FontWeight, GridLocation, Hsla, Length, Pixels, Point,
11 PointRefinement, Rgba, SharedString, Size, SizeRefinement, Styled, TextRun, Window, black, phi,
12 point, quad, rems, size,
13};
14use open_gpui_collections::HashSet;
15use open_gpui_refineable::Refineable;
16use schemars::JsonSchema;
17use serde::{Deserialize, Serialize};
18
19#[cfg(debug_assertions)]
23pub struct DebugBelow;
24
25#[cfg(debug_assertions)]
26impl crate::Global for DebugBelow {}
27
28pub enum ObjectFit {
30 Fill,
32 Contain,
34 Cover,
36 ScaleDown,
38 None,
40}
41
42impl ObjectFit {
43 pub fn get_bounds(
45 &self,
46 bounds: Bounds<Pixels>,
47 image_size: Size<DevicePixels>,
48 ) -> Bounds<Pixels> {
49 let image_size = image_size.map(|dimension| Pixels::from(u32::from(dimension)));
50 let image_ratio = image_size.width / image_size.height;
51 let bounds_ratio = bounds.size.width / bounds.size.height;
52
53 match self {
54 ObjectFit::Fill => bounds,
55 ObjectFit::Contain => {
56 let new_size = if bounds_ratio > image_ratio {
57 size(
58 image_size.width * (bounds.size.height / image_size.height),
59 bounds.size.height,
60 )
61 } else {
62 size(
63 bounds.size.width,
64 image_size.height * (bounds.size.width / image_size.width),
65 )
66 };
67
68 Bounds {
69 origin: point(
70 bounds.origin.x + (bounds.size.width - new_size.width) / 2.0,
71 bounds.origin.y + (bounds.size.height - new_size.height) / 2.0,
72 ),
73 size: new_size,
74 }
75 }
76 ObjectFit::ScaleDown => {
77 if image_size.width > bounds.size.width || image_size.height > bounds.size.height {
79 let new_size = if bounds_ratio > image_ratio {
81 size(
82 image_size.width * (bounds.size.height / image_size.height),
83 bounds.size.height,
84 )
85 } else {
86 size(
87 bounds.size.width,
88 image_size.height * (bounds.size.width / image_size.width),
89 )
90 };
91
92 Bounds {
93 origin: point(
94 bounds.origin.x + (bounds.size.width - new_size.width) / 2.0,
95 bounds.origin.y + (bounds.size.height - new_size.height) / 2.0,
96 ),
97 size: new_size,
98 }
99 } else {
100 let original_size = size(image_size.width, image_size.height);
103 Bounds {
104 origin: point(
105 bounds.origin.x + (bounds.size.width - original_size.width) / 2.0,
106 bounds.origin.y + (bounds.size.height - original_size.height) / 2.0,
107 ),
108 size: original_size,
109 }
110 }
111 }
112 ObjectFit::Cover => {
113 let new_size = if bounds_ratio > image_ratio {
114 size(
115 bounds.size.width,
116 image_size.height * (bounds.size.width / image_size.width),
117 )
118 } else {
119 size(
120 image_size.width * (bounds.size.height / image_size.height),
121 bounds.size.height,
122 )
123 };
124
125 Bounds {
126 origin: point(
127 bounds.origin.x + (bounds.size.width - new_size.width) / 2.0,
128 bounds.origin.y + (bounds.size.height - new_size.height) / 2.0,
129 ),
130 size: new_size,
131 }
132 }
133 ObjectFit::None => Bounds {
134 origin: bounds.origin,
135 size: image_size,
136 },
137 }
138 }
139}
140
141#[derive(
143 Copy, Clone, PartialEq, Eq, PartialOrd, Ord, Debug, Default, JsonSchema, Serialize, Deserialize,
144)]
145pub enum TemplateColumnMinSize {
146 #[default]
148 Zero,
149 MinContent,
151 MaxContent,
153}
154
155#[derive(
157 Copy,
158 Clone,
159 Refineable,
160 PartialEq,
161 Eq,
162 PartialOrd,
163 Ord,
164 Debug,
165 Default,
166 JsonSchema,
167 Serialize,
168 Deserialize,
169)]
170pub struct GridTemplate {
171 pub repeat: u16,
173 pub min_size: TemplateColumnMinSize,
175}
176
177#[derive(Clone, Refineable, Debug)]
179#[refineable(Debug, PartialEq, Serialize, Deserialize, JsonSchema)]
180pub struct Style {
181 pub display: Display,
183
184 pub visibility: Visibility,
186
187 #[refineable]
190 pub overflow: Point<Overflow>,
191 pub scrollbar_width: AbsoluteLength,
193 pub allow_concurrent_scroll: bool,
195 pub restrict_scroll_to_axis: bool,
217
218 pub position: Position,
221 #[refineable]
223 pub inset: Edges<Length>,
224
225 #[refineable]
228 pub size: Size<Length>,
229 #[refineable]
231 pub min_size: Size<Length>,
232 #[refineable]
234 pub max_size: Size<Length>,
235 pub aspect_ratio: Option<f32>,
237
238 #[refineable]
241 pub margin: Edges<Length>,
242 #[refineable]
244 pub padding: Edges<DefiniteLength>,
245 #[refineable]
247 pub border_widths: Edges<AbsoluteLength>,
248
249 pub align_items: Option<AlignItems>,
252 pub align_self: Option<AlignSelf>,
254 pub align_content: Option<AlignContent>,
256 pub justify_content: Option<JustifyContent>,
258 #[refineable]
260 pub gap: Size<DefiniteLength>,
261
262 pub flex_direction: FlexDirection,
265 pub flex_wrap: FlexWrap,
267 pub flex_basis: Length,
269 pub flex_grow: f32,
271 pub flex_shrink: f32,
273
274 pub background: Option<Fill>,
276
277 pub border_color: Option<Hsla>,
279
280 pub border_style: BorderStyle,
282
283 #[refineable]
285 pub corner_radii: Corners<AbsoluteLength>,
286
287 pub box_shadow: Vec<BoxShadow>,
289
290 #[refineable]
292 pub text: TextStyleRefinement,
293
294 pub mouse_cursor: Option<CursorStyle>,
296
297 pub opacity: Option<f32>,
299
300 pub grid_cols: Option<GridTemplate>,
303
304 pub grid_rows: Option<GridTemplate>,
307
308 pub grid_location: Option<GridLocation>,
310
311 #[cfg(debug_assertions)]
313 pub debug: bool,
314
315 #[cfg(debug_assertions)]
317 pub debug_below: bool,
318}
319
320impl Styled for StyleRefinement {
321 fn style(&mut self) -> &mut StyleRefinement {
322 self
323 }
324}
325
326impl StyleRefinement {
327 pub fn grid_location_mut(&mut self) -> &mut GridLocation {
329 self.grid_location.get_or_insert_default()
330 }
331}
332
333#[derive(Default, Clone, Copy, Debug, Eq, PartialEq, Serialize, Deserialize, JsonSchema)]
335pub enum Visibility {
336 #[default]
338 Visible,
339 Hidden,
341}
342
343#[derive(Clone, Debug, PartialEq, Serialize, Deserialize, JsonSchema)]
345pub struct BoxShadow {
346 pub color: Hsla,
348 pub offset: Point<Pixels>,
350 pub blur_radius: Pixels,
352 pub spread_radius: Pixels,
354 pub inset: bool,
356}
357
358#[derive(Copy, Clone, Debug, Default, PartialEq, Eq, Serialize, Deserialize, JsonSchema)]
360pub enum WhiteSpace {
361 #[default]
363 Normal,
364 Nowrap,
366}
367
368#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize, JsonSchema)]
370pub enum TextOverflow {
371 Truncate(SharedString),
374 TruncateStart(SharedString),
378}
379
380#[derive(Copy, Clone, Debug, Default, PartialEq, Eq, Serialize, Deserialize, JsonSchema)]
382pub enum TextAlign {
383 #[default]
385 Left,
386
387 Center,
389
390 Right,
392}
393
394#[derive(Refineable, Clone, Debug, PartialEq)]
396#[refineable(Debug, PartialEq, Serialize, Deserialize, JsonSchema)]
397pub struct TextStyle {
398 pub color: Hsla,
400
401 pub font_family: SharedString,
403
404 pub font_features: FontFeatures,
406
407 pub font_fallbacks: Option<FontFallbacks>,
409
410 pub font_size: AbsoluteLength,
412
413 pub line_height: DefiniteLength,
415
416 pub font_weight: FontWeight,
418
419 pub font_style: FontStyle,
421
422 pub background_color: Option<Hsla>,
424
425 pub underline: Option<UnderlineStyle>,
427
428 pub strikethrough: Option<StrikethroughStyle>,
430
431 pub white_space: WhiteSpace,
433
434 pub text_overflow: Option<TextOverflow>,
436
437 pub text_align: TextAlign,
439
440 pub line_clamp: Option<usize>,
442}
443
444impl Default for TextStyle {
445 fn default() -> Self {
446 TextStyle {
447 color: black(),
448 font_family: ".SystemUIFont".into(),
450 font_features: FontFeatures::default(),
451 font_fallbacks: None,
452 font_size: rems(1.).into(),
453 line_height: phi(),
454 font_weight: FontWeight::default(),
455 font_style: FontStyle::default(),
456 background_color: None,
457 underline: None,
458 strikethrough: None,
459 white_space: WhiteSpace::Normal,
460 text_overflow: None,
461 text_align: TextAlign::default(),
462 line_clamp: None,
463 }
464 }
465}
466
467impl TextStyle {
468 pub fn highlight(mut self, style: impl Into<HighlightStyle>) -> Self {
470 let style = style.into();
471 if let Some(weight) = style.font_weight {
472 self.font_weight = weight;
473 }
474 if let Some(style) = style.font_style {
475 self.font_style = style;
476 }
477
478 if let Some(color) = style.color {
479 self.color = self.color.blend(color);
480 }
481
482 if let Some(factor) = style.fade_out {
483 self.color.fade_out(factor);
484 }
485
486 if let Some(background_color) = style.background_color {
487 self.background_color = Some(background_color);
488 }
489
490 if let Some(underline) = style.underline {
491 self.underline = Some(underline);
492 }
493
494 if let Some(strikethrough) = style.strikethrough {
495 self.strikethrough = Some(strikethrough);
496 }
497
498 self
499 }
500
501 pub fn font(&self) -> Font {
503 Font {
504 family: self.font_family.clone(),
505 features: self.font_features.clone(),
506 fallbacks: self.font_fallbacks.clone(),
507 weight: self.font_weight,
508 style: self.font_style,
509 }
510 }
511
512 pub fn line_height_in_pixels(&self, rem_size: Pixels) -> Pixels {
514 self.line_height.to_pixels(self.font_size, rem_size).round()
515 }
516
517 pub fn to_run(&self, len: usize) -> TextRun {
519 TextRun {
520 len,
521 font: Font {
522 family: self.font_family.clone(),
523 features: self.font_features.clone(),
524 fallbacks: self.font_fallbacks.clone(),
525 weight: self.font_weight,
526 style: self.font_style,
527 },
528 color: self.color,
529 background_color: self.background_color,
530 underline: self.underline,
531 strikethrough: self.strikethrough,
532 }
533 }
534}
535
536#[derive(Copy, Clone, Debug, Default, PartialEq)]
539pub struct HighlightStyle {
540 pub color: Option<Hsla>,
542
543 pub font_weight: Option<FontWeight>,
545
546 pub font_style: Option<FontStyle>,
548
549 pub background_color: Option<Hsla>,
551
552 pub underline: Option<UnderlineStyle>,
554
555 pub strikethrough: Option<StrikethroughStyle>,
557
558 pub fade_out: Option<f32>,
560}
561
562impl Eq for HighlightStyle {}
563
564impl Hash for HighlightStyle {
565 fn hash<H: Hasher>(&self, state: &mut H) {
566 self.color.hash(state);
567 self.font_weight.hash(state);
568 self.font_style.hash(state);
569 self.background_color.hash(state);
570 self.underline.hash(state);
571 self.strikethrough.hash(state);
572 state.write_u32(u32::from_be_bytes(
573 self.fade_out.map(|f| f.to_be_bytes()).unwrap_or_default(),
574 ));
575 }
576}
577
578impl Style {
579 pub fn has_opaque_background(&self) -> bool {
581 self.background
582 .as_ref()
583 .is_some_and(|fill| fill.color().is_some_and(|color| !color.is_transparent()))
584 }
585
586 pub fn text_style(&self) -> Option<&TextStyleRefinement> {
588 if self.text.is_some() {
589 Some(&self.text)
590 } else {
591 None
592 }
593 }
594
595 pub fn overflow_mask(
598 &self,
599 bounds: Bounds<Pixels>,
600 rem_size: Pixels,
601 ) -> Option<ContentMask<Pixels>> {
602 match self.overflow {
603 Point {
604 x: Overflow::Visible,
605 y: Overflow::Visible,
606 } => None,
607 _ => {
608 let mut min = bounds.origin;
609 let mut max = bounds.bottom_right();
610
611 if self
612 .border_color
613 .is_some_and(|color| !color.is_transparent())
614 {
615 min.x += self.border_widths.left.to_pixels(rem_size);
616 max.x -= self.border_widths.right.to_pixels(rem_size);
617 min.y += self.border_widths.top.to_pixels(rem_size);
618 max.y -= self.border_widths.bottom.to_pixels(rem_size);
619 }
620
621 let bounds = match (
622 self.overflow.x == Overflow::Visible,
623 self.overflow.y == Overflow::Visible,
624 ) {
625 (true, true) => return None,
627 (true, false) => Bounds::from_corners(
629 point(min.x, bounds.origin.y),
630 point(max.x, bounds.bottom_right().y),
631 ),
632 (false, true) => Bounds::from_corners(
634 point(bounds.origin.x, min.y),
635 point(bounds.bottom_right().x, max.y),
636 ),
637 (false, false) => Bounds::from_corners(min, max),
639 };
640
641 Some(ContentMask { bounds })
642 }
643 }
644 }
645
646 pub fn paint(
648 &self,
649 bounds: Bounds<Pixels>,
650 window: &mut Window,
651 cx: &mut App,
652 continuation: impl FnOnce(&mut Window, &mut App),
653 ) {
654 #[cfg(debug_assertions)]
655 if self.debug_below {
656 cx.set_global(DebugBelow)
657 }
658
659 #[cfg(debug_assertions)]
660 if self.debug || cx.has_global::<DebugBelow>() {
661 window.paint_quad(crate::outline(bounds, crate::red(), BorderStyle::default()));
662 }
663
664 let rem_size = window.rem_size();
665 let corner_radii = self
666 .corner_radii
667 .to_pixels(rem_size)
668 .clamp_radii_for_quad_size(bounds.size);
669
670 window.paint_drop_shadows(bounds, corner_radii, &self.box_shadow);
671
672 let background_color = self.background.as_ref().and_then(Fill::color);
673 if background_color.is_some_and(|color| !color.is_transparent()) {
674 let mut border_color = match background_color {
675 Some(color) => match color.tag {
676 BackgroundTag::Solid
677 | BackgroundTag::PatternSlash
678 | BackgroundTag::Checkerboard => color.solid,
679
680 BackgroundTag::LinearGradient => color
681 .colors
682 .first()
683 .map(|stop| stop.color)
684 .unwrap_or_default(),
685 },
686 None => Hsla::default(),
687 };
688 border_color.a = 0.;
689 window.paint_quad(quad(
690 bounds,
691 corner_radii,
692 background_color.unwrap_or_default(),
693 Edges::default(),
694 border_color,
695 self.border_style,
696 ));
697 }
698
699 window.paint_inset_shadows(bounds, corner_radii, &self.box_shadow);
700
701 continuation(window, cx);
702
703 if self.is_border_visible() {
704 let border_widths = self.border_widths.to_pixels(rem_size);
705 let mut background = self.border_color.unwrap_or_default();
706 background.a = 0.;
707 window.paint_quad(quad(
708 bounds,
709 corner_radii,
710 background,
711 border_widths,
712 self.border_color.unwrap_or_default(),
713 self.border_style,
714 ));
715 }
716
717 #[cfg(debug_assertions)]
718 if self.debug_below {
719 cx.remove_global::<DebugBelow>();
720 }
721 }
722
723 fn is_border_visible(&self) -> bool {
724 self.border_color
725 .is_some_and(|color| !color.is_transparent())
726 && self.border_widths.any(|length| !length.is_zero())
727 }
728}
729
730impl Default for Style {
731 fn default() -> Self {
732 Style {
733 display: Display::Block,
734 visibility: Visibility::Visible,
735 overflow: Point {
736 x: Overflow::Visible,
737 y: Overflow::Visible,
738 },
739 allow_concurrent_scroll: false,
740 restrict_scroll_to_axis: false,
741 scrollbar_width: AbsoluteLength::default(),
742 position: Position::Relative,
743 inset: Edges::auto(),
744 margin: Edges::<Length>::zero(),
745 padding: Edges::<DefiniteLength>::zero(),
746 border_widths: Edges::<AbsoluteLength>::zero(),
747 size: Size::auto(),
748 min_size: Size::auto(),
749 max_size: Size::auto(),
750 aspect_ratio: None,
751 gap: Size::default(),
752 align_items: None,
754 align_self: None,
755 align_content: None,
756 justify_content: None,
757 flex_direction: FlexDirection::Row,
759 flex_wrap: FlexWrap::NoWrap,
760 flex_grow: 0.0,
761 flex_shrink: 1.0,
762 flex_basis: Length::Auto,
763 background: None,
764 border_color: None,
765 border_style: BorderStyle::default(),
766 corner_radii: Corners::default(),
767 box_shadow: Default::default(),
768 text: TextStyleRefinement::default(),
769 mouse_cursor: None,
770 opacity: None,
771 grid_rows: None,
772 grid_cols: None,
773 grid_location: None,
774
775 #[cfg(debug_assertions)]
776 debug: false,
777 #[cfg(debug_assertions)]
778 debug_below: false,
779 }
780 }
781}
782
783#[derive(
785 Refineable, Copy, Clone, Default, Debug, PartialEq, Eq, Hash, Serialize, Deserialize, JsonSchema,
786)]
787pub struct UnderlineStyle {
788 pub thickness: Pixels,
790
791 pub color: Option<Hsla>,
793
794 pub wavy: bool,
796}
797
798#[derive(
800 Refineable, Copy, Clone, Default, Debug, PartialEq, Eq, Hash, Serialize, Deserialize, JsonSchema,
801)]
802pub struct StrikethroughStyle {
803 pub thickness: Pixels,
805
806 pub color: Option<Hsla>,
808}
809
810#[derive(Clone, Debug, PartialEq, Serialize, Deserialize, JsonSchema)]
812pub enum Fill {
813 Color(Background),
815}
816
817impl Fill {
818 pub fn color(&self) -> Option<Background> {
822 match self {
823 Fill::Color(color) => Some(*color),
824 }
825 }
826}
827
828impl Default for Fill {
829 fn default() -> Self {
830 Self::Color(Background::default())
831 }
832}
833
834impl From<Hsla> for Fill {
835 fn from(color: Hsla) -> Self {
836 Self::Color(color.into())
837 }
838}
839
840impl From<Rgba> for Fill {
841 fn from(color: Rgba) -> Self {
842 Self::Color(color.into())
843 }
844}
845
846impl From<Background> for Fill {
847 fn from(background: Background) -> Self {
848 Self::Color(background)
849 }
850}
851
852impl From<TextStyle> for HighlightStyle {
853 fn from(other: TextStyle) -> Self {
854 Self::from(&other)
855 }
856}
857
858impl From<&TextStyle> for HighlightStyle {
859 fn from(other: &TextStyle) -> Self {
860 Self {
861 color: Some(other.color),
862 font_weight: Some(other.font_weight),
863 font_style: Some(other.font_style),
864 background_color: other.background_color,
865 underline: other.underline,
866 strikethrough: other.strikethrough,
867 fade_out: None,
868 }
869 }
870}
871
872impl HighlightStyle {
873 pub fn color(color: Hsla) -> Self {
875 Self {
876 color: Some(color),
877 ..Default::default()
878 }
879 }
880 #[must_use]
883 pub fn highlight(self, other: HighlightStyle) -> Self {
884 Self {
885 color: other
886 .color
887 .map(|other_color| {
888 if let Some(color) = self.color {
889 color.blend(other_color)
890 } else {
891 other_color
892 }
893 })
894 .or(self.color),
895 font_weight: other.font_weight.or(self.font_weight),
896 font_style: other.font_style.or(self.font_style),
897 background_color: other.background_color.or(self.background_color),
898 underline: other.underline.or(self.underline),
899 strikethrough: other.strikethrough.or(self.strikethrough),
900 fade_out: other
901 .fade_out
902 .map(|source_fade| {
903 self.fade_out
904 .map(|dest_fade| (dest_fade * (1. + source_fade)).clamp(0., 1.))
905 .unwrap_or(source_fade)
906 })
907 .or(self.fade_out),
908 }
909 }
910}
911
912impl From<Hsla> for HighlightStyle {
913 fn from(color: Hsla) -> Self {
914 Self {
915 color: Some(color),
916 ..Default::default()
917 }
918 }
919}
920
921impl From<FontWeight> for HighlightStyle {
922 fn from(font_weight: FontWeight) -> Self {
923 Self {
924 font_weight: Some(font_weight),
925 ..Default::default()
926 }
927 }
928}
929
930impl From<FontStyle> for HighlightStyle {
931 fn from(font_style: FontStyle) -> Self {
932 Self {
933 font_style: Some(font_style),
934 ..Default::default()
935 }
936 }
937}
938
939impl From<Rgba> for HighlightStyle {
940 fn from(color: Rgba) -> Self {
941 Self {
942 color: Some(color.into()),
943 ..Default::default()
944 }
945 }
946}
947
948pub fn combine_highlights(
950 a: impl IntoIterator<Item = (Range<usize>, HighlightStyle)>,
951 b: impl IntoIterator<Item = (Range<usize>, HighlightStyle)>,
952) -> impl Iterator<Item = (Range<usize>, HighlightStyle)> {
953 let mut endpoints = Vec::new();
954 let mut highlights = Vec::new();
955 for (range, highlight) in a.into_iter().chain(b) {
956 if !range.is_empty() {
957 let highlight_id = highlights.len();
958 endpoints.push((range.start, highlight_id, true));
959 endpoints.push((range.end, highlight_id, false));
960 highlights.push(highlight);
961 }
962 }
963 endpoints.sort_unstable_by_key(|(position, _, _)| *position);
964 let mut endpoints = endpoints.into_iter().peekable();
965
966 let mut active_styles = HashSet::default();
967 let mut ix = 0;
968 iter::from_fn(move || {
969 while let Some((endpoint_ix, highlight_id, is_start)) = endpoints.peek() {
970 let prev_index = mem::replace(&mut ix, *endpoint_ix);
971 if ix > prev_index && !active_styles.is_empty() {
972 let current_style = active_styles
973 .iter()
974 .fold(HighlightStyle::default(), |acc, highlight_id| {
975 acc.highlight(highlights[*highlight_id])
976 });
977 return Some((prev_index..ix, current_style));
978 }
979
980 if *is_start {
981 active_styles.insert(*highlight_id);
982 } else {
983 active_styles.remove(highlight_id);
984 }
985 endpoints.next();
986 }
987 None
988 })
989}
990
991#[derive(Copy, Clone, PartialEq, Eq, Debug, Serialize, Deserialize, JsonSchema)]
997pub enum AlignItems {
999 Start,
1001 End,
1003 FlexStart,
1008 FlexEnd,
1013 Center,
1015 Baseline,
1017 Stretch,
1019}
1020pub type JustifyItems = AlignItems;
1026pub type AlignSelf = AlignItems;
1033pub type JustifySelf = AlignItems;
1040
1041#[derive(Copy, Clone, PartialEq, Eq, Debug, Serialize, Deserialize, JsonSchema)]
1047pub enum AlignContent {
1049 Start,
1051 End,
1053 FlexStart,
1058 FlexEnd,
1063 Center,
1065 Stretch,
1067 SpaceBetween,
1070 SpaceEvenly,
1073 SpaceAround,
1076}
1077
1078pub type JustifyContent = AlignContent;
1084
1085#[derive(Copy, Clone, PartialEq, Eq, Debug, Default, Serialize, Deserialize, JsonSchema)]
1089pub enum Display {
1091 Block,
1093 #[default]
1095 Flex,
1096 Grid,
1098 None,
1100}
1101
1102#[derive(Copy, Clone, PartialEq, Eq, Debug, Default, Serialize, Deserialize, JsonSchema)]
1108pub enum FlexWrap {
1110 #[default]
1112 NoWrap,
1113 Wrap,
1115 WrapReverse,
1117}
1118
1119#[derive(Copy, Clone, PartialEq, Eq, Debug, Default, Serialize, Deserialize, JsonSchema)]
1131pub enum FlexDirection {
1133 #[default]
1137 Row,
1138 Column,
1142 RowReverse,
1146 ColumnReverse,
1150}
1151
1152#[derive(Copy, Clone, PartialEq, Eq, Debug, Default, Serialize, Deserialize, JsonSchema)]
1166pub enum Overflow {
1168 #[default]
1171 Visible,
1172 Clip,
1175 Hidden,
1178 Scroll,
1182}
1183
1184#[derive(Copy, Clone, PartialEq, Eq, Debug, Default, Serialize, Deserialize, JsonSchema)]
1194pub enum Position {
1196 #[default]
1199 Relative,
1200 Absolute,
1206}
1207
1208impl From<AlignItems> for taffy::style::AlignItems {
1209 fn from(value: AlignItems) -> Self {
1210 match value {
1211 AlignItems::Start => Self::Start,
1212 AlignItems::End => Self::End,
1213 AlignItems::FlexStart => Self::FlexStart,
1214 AlignItems::FlexEnd => Self::FlexEnd,
1215 AlignItems::Center => Self::Center,
1216 AlignItems::Baseline => Self::Baseline,
1217 AlignItems::Stretch => Self::Stretch,
1218 }
1219 }
1220}
1221
1222impl From<AlignContent> for taffy::style::AlignContent {
1223 fn from(value: AlignContent) -> Self {
1224 match value {
1225 AlignContent::Start => Self::Start,
1226 AlignContent::End => Self::End,
1227 AlignContent::FlexStart => Self::FlexStart,
1228 AlignContent::FlexEnd => Self::FlexEnd,
1229 AlignContent::Center => Self::Center,
1230 AlignContent::Stretch => Self::Stretch,
1231 AlignContent::SpaceBetween => Self::SpaceBetween,
1232 AlignContent::SpaceEvenly => Self::SpaceEvenly,
1233 AlignContent::SpaceAround => Self::SpaceAround,
1234 }
1235 }
1236}
1237
1238impl From<Display> for taffy::style::Display {
1239 fn from(value: Display) -> Self {
1240 match value {
1241 Display::Block => Self::Block,
1242 Display::Flex => Self::Flex,
1243 Display::Grid => Self::Grid,
1244 Display::None => Self::None,
1245 }
1246 }
1247}
1248
1249impl From<FlexWrap> for taffy::style::FlexWrap {
1250 fn from(value: FlexWrap) -> Self {
1251 match value {
1252 FlexWrap::NoWrap => Self::NoWrap,
1253 FlexWrap::Wrap => Self::Wrap,
1254 FlexWrap::WrapReverse => Self::WrapReverse,
1255 }
1256 }
1257}
1258
1259impl From<FlexDirection> for taffy::style::FlexDirection {
1260 fn from(value: FlexDirection) -> Self {
1261 match value {
1262 FlexDirection::Row => Self::Row,
1263 FlexDirection::Column => Self::Column,
1264 FlexDirection::RowReverse => Self::RowReverse,
1265 FlexDirection::ColumnReverse => Self::ColumnReverse,
1266 }
1267 }
1268}
1269
1270impl From<Overflow> for taffy::style::Overflow {
1271 fn from(value: Overflow) -> Self {
1272 match value {
1273 Overflow::Visible => Self::Visible,
1274 Overflow::Clip => Self::Clip,
1275 Overflow::Hidden => Self::Hidden,
1276 Overflow::Scroll => Self::Scroll,
1277 }
1278 }
1279}
1280
1281impl From<Position> for taffy::style::Position {
1282 fn from(value: Position) -> Self {
1283 match value {
1284 Position::Relative => Self::Relative,
1285 Position::Absolute => Self::Absolute,
1286 }
1287 }
1288}
1289
1290#[cfg(test)]
1291mod tests {
1292 use crate::{blue, green, px, red, yellow};
1293
1294 use super::*;
1295
1296 use open_gpui_util_macros::perf;
1297
1298 #[perf]
1299 fn test_basic_highlight_style_combination() {
1300 let style_a = HighlightStyle::default();
1301 let style_b = HighlightStyle::default();
1302 let style_a = style_a.highlight(style_b);
1303 assert_eq!(
1304 style_a,
1305 HighlightStyle::default(),
1306 "Combining empty styles should not produce a non-empty style."
1307 );
1308
1309 let mut style_b = HighlightStyle {
1310 color: Some(red()),
1311 strikethrough: Some(StrikethroughStyle {
1312 thickness: px(2.),
1313 color: Some(blue()),
1314 }),
1315 fade_out: Some(0.),
1316 font_style: Some(FontStyle::Italic),
1317 font_weight: Some(FontWeight(300.)),
1318 background_color: Some(yellow()),
1319 underline: Some(UnderlineStyle {
1320 thickness: px(2.),
1321 color: Some(red()),
1322 wavy: true,
1323 }),
1324 };
1325 let expected_style = style_b;
1326
1327 let style_a = style_a.highlight(style_b);
1328 assert_eq!(
1329 style_a, expected_style,
1330 "Blending an empty style with another style should return the other style"
1331 );
1332
1333 let style_b = style_b.highlight(Default::default());
1334 assert_eq!(
1335 style_b, expected_style,
1336 "Blending a style with an empty style should not change the style."
1337 );
1338
1339 let mut style_c = expected_style;
1340
1341 let style_d = HighlightStyle {
1342 color: Some(blue().alpha(0.7)),
1343 strikethrough: Some(StrikethroughStyle {
1344 thickness: px(4.),
1345 color: Some(crate::red()),
1346 }),
1347 fade_out: Some(0.),
1348 font_style: Some(FontStyle::Oblique),
1349 font_weight: Some(FontWeight(800.)),
1350 background_color: Some(green()),
1351 underline: Some(UnderlineStyle {
1352 thickness: px(4.),
1353 color: None,
1354 wavy: false,
1355 }),
1356 };
1357
1358 let expected_style = HighlightStyle {
1359 color: Some(red().blend(blue().alpha(0.7))),
1360 strikethrough: Some(StrikethroughStyle {
1361 thickness: px(4.),
1362 color: Some(red()),
1363 }),
1364 fade_out: Some(0.),
1366 font_style: Some(FontStyle::Oblique),
1367 font_weight: Some(FontWeight(800.)),
1368 background_color: Some(green()),
1369 underline: Some(UnderlineStyle {
1370 thickness: px(4.),
1371 color: None,
1372 wavy: false,
1373 }),
1374 };
1375
1376 let style_c = style_c.highlight(style_d);
1377 assert_eq!(
1378 style_c, expected_style,
1379 "Blending styles should blend properties where possible and override all others"
1380 );
1381 }
1382
1383 #[perf]
1384 fn test_combine_highlights() {
1385 assert_eq!(
1386 combine_highlights(
1387 [
1388 (0..5, green().into()),
1389 (4..10, FontWeight::BOLD.into()),
1390 (15..20, yellow().into()),
1391 ],
1392 [
1393 (2..6, FontStyle::Italic.into()),
1394 (1..3, blue().into()),
1395 (21..23, red().into()),
1396 ]
1397 )
1398 .collect::<Vec<_>>(),
1399 [
1400 (
1401 0..1,
1402 HighlightStyle {
1403 color: Some(green()),
1404 ..Default::default()
1405 }
1406 ),
1407 (
1408 1..2,
1409 HighlightStyle {
1410 color: Some(blue()),
1411 ..Default::default()
1412 }
1413 ),
1414 (
1415 2..3,
1416 HighlightStyle {
1417 color: Some(blue()),
1418 font_style: Some(FontStyle::Italic),
1419 ..Default::default()
1420 }
1421 ),
1422 (
1423 3..4,
1424 HighlightStyle {
1425 color: Some(green()),
1426 font_style: Some(FontStyle::Italic),
1427 ..Default::default()
1428 }
1429 ),
1430 (
1431 4..5,
1432 HighlightStyle {
1433 color: Some(green()),
1434 font_weight: Some(FontWeight::BOLD),
1435 font_style: Some(FontStyle::Italic),
1436 ..Default::default()
1437 }
1438 ),
1439 (
1440 5..6,
1441 HighlightStyle {
1442 font_weight: Some(FontWeight::BOLD),
1443 font_style: Some(FontStyle::Italic),
1444 ..Default::default()
1445 }
1446 ),
1447 (
1448 6..10,
1449 HighlightStyle {
1450 font_weight: Some(FontWeight::BOLD),
1451 ..Default::default()
1452 }
1453 ),
1454 (
1455 15..20,
1456 HighlightStyle {
1457 color: Some(yellow()),
1458 ..Default::default()
1459 }
1460 ),
1461 (
1462 21..23,
1463 HighlightStyle {
1464 color: Some(red()),
1465 ..Default::default()
1466 }
1467 )
1468 ]
1469 );
1470 }
1471
1472 #[perf]
1473 fn test_text_style_refinement() {
1474 let mut style = Style::default();
1475 style.refine(&StyleRefinement::default().text_size(px(20.0)));
1476 style.refine(&StyleRefinement::default().font_weight(FontWeight::SEMIBOLD));
1477
1478 assert_eq!(
1479 Some(AbsoluteLength::from(px(20.0))),
1480 style.text_style().unwrap().font_size
1481 );
1482
1483 assert_eq!(
1484 Some(FontWeight::SEMIBOLD),
1485 style.text_style().unwrap().font_weight
1486 );
1487 }
1488}