1use std::{iter, mem, ops::Range};
2
3use crate::{
4 black, phi, point, quad, rems, AbsoluteLength, Bounds, ContentMask, Corners, CornersRefinement,
5 CursorStyle, DefiniteLength, Edges, EdgesRefinement, ElementContext, Font, FontFeatures,
6 FontStyle, FontWeight, Hsla, Length, Pixels, Point, PointRefinement, Rgba, SharedString, Size,
7 SizeRefinement, Styled, TextRun,
8};
9use collections::HashSet;
10use refineable::Refineable;
11use smallvec::SmallVec;
12pub use taffy::style::{
13 AlignContent, AlignItems, AlignSelf, Display, FlexDirection, FlexWrap, JustifyContent,
14 Overflow, Position,
15};
16
17/// Use this struct for interfacing with the 'debug_below' styling from your own elements.
18/// If a parent element has this style set on it, then this struct will be set as a global in
19/// GPUI.
20#[cfg(debug_assertions)]
21pub struct DebugBelow;
22
23#[cfg(debug_assertions)]
24impl crate::Global for DebugBelow {}
25
26/// The CSS styling that can be applied to an element via the `Styled` trait
27#[derive(Clone, Refineable, Debug)]
28#[refineable(Debug)]
29pub struct Style {
30 /// What layout strategy should be used?
31 pub display: Display,
32
33 /// Should the element be painted on screen?
34 pub visibility: Visibility,
35
36 // Overflow properties
37 /// How children overflowing their container should affect layout
38 #[refineable]
39 pub overflow: Point<Overflow>,
40 /// How much space (in points) should be reserved for the scrollbars of `Overflow::Scroll` and `Overflow::Auto` nodes.
41 pub scrollbar_width: f32,
42
43 // Position properties
44 /// What should the `position` value of this struct use as a base offset?
45 pub position: Position,
46 /// How should the position of this element be tweaked relative to the layout defined?
47 #[refineable]
48 pub inset: Edges<Length>,
49
50 // Size properties
51 /// Sets the initial size of the item
52 #[refineable]
53 pub size: Size<Length>,
54 /// Controls the minimum size of the item
55 #[refineable]
56 pub min_size: Size<Length>,
57 /// Controls the maximum size of the item
58 #[refineable]
59 pub max_size: Size<Length>,
60 /// Sets the preferred aspect ratio for the item. The ratio is calculated as width divided by height.
61 pub aspect_ratio: Option<f32>,
62
63 // Spacing Properties
64 /// How large should the margin be on each side?
65 #[refineable]
66 pub margin: Edges<Length>,
67 /// How large should the padding be on each side?
68 #[refineable]
69 pub padding: Edges<DefiniteLength>,
70 /// How large should the border be on each side?
71 #[refineable]
72 pub border_widths: Edges<AbsoluteLength>,
73
74 // Alignment properties
75 /// How this node's children aligned in the cross/block axis?
76 pub align_items: Option<AlignItems>,
77 /// How this node should be aligned in the cross/block axis. Falls back to the parents [`AlignItems`] if not set
78 pub align_self: Option<AlignSelf>,
79 /// How should content contained within this item be aligned in the cross/block axis
80 pub align_content: Option<AlignContent>,
81 /// How should contained within this item be aligned in the main/inline axis
82 pub justify_content: Option<JustifyContent>,
83 /// How large should the gaps between items in a flex container be?
84 #[refineable]
85 pub gap: Size<DefiniteLength>,
86
87 // Flexbox properties
88 /// Which direction does the main axis flow in?
89 pub flex_direction: FlexDirection,
90 /// Should elements wrap, or stay in a single line?
91 pub flex_wrap: FlexWrap,
92 /// Sets the initial main axis size of the item
93 pub flex_basis: Length,
94 /// The relative rate at which this item grows when it is expanding to fill space, 0.0 is the default value, and this value must be positive.
95 pub flex_grow: f32,
96 /// The relative rate at which this item shrinks when it is contracting to fit into space, 1.0 is the default value, and this value must be positive.
97 pub flex_shrink: f32,
98
99 /// The fill color of this element
100 pub background: Option<Fill>,
101
102 /// The border color of this element
103 pub border_color: Option<Hsla>,
104
105 /// The radius of the corners of this element
106 #[refineable]
107 pub corner_radii: Corners<AbsoluteLength>,
108
109 /// Box Shadow of the element
110 pub box_shadow: SmallVec<[BoxShadow; 2]>,
111
112 /// The text style of this element
113 pub text: TextStyleRefinement,
114
115 /// The mouse cursor style shown when the mouse pointer is over an element.
116 pub mouse_cursor: Option<CursorStyle>,
117
118 /// The z-index to set for this element
119 pub z_index: Option<u16>,
120
121 /// Whether to draw a red debugging outline around this element
122 #[cfg(debug_assertions)]
123 pub debug: bool,
124
125 /// Whether to draw a red debugging outline around this element and all of it's conforming children
126 #[cfg(debug_assertions)]
127 pub debug_below: bool,
128}
129
130impl Styled for StyleRefinement {
131 fn style(&mut self) -> &mut StyleRefinement {
132 self
133 }
134}
135
136/// The value of the visibility property, similar to the CSS property `visibility`
137#[derive(Default, Clone, Copy, Debug, Eq, PartialEq)]
138pub enum Visibility {
139 /// The element should be drawn as normal.
140 #[default]
141 Visible,
142 /// The element should not be drawn, but should still take up space in the layout.
143 Hidden,
144}
145
146/// The possible values of the box-shadow property
147#[derive(Clone, Debug)]
148pub struct BoxShadow {
149 /// What color should the shadow have?
150 pub color: Hsla,
151 /// How should it be offset from it's element?
152 pub offset: Point<Pixels>,
153 /// How much should the shadow be blurred?
154 pub blur_radius: Pixels,
155 /// How much should the shadow spread?
156 pub spread_radius: Pixels,
157}
158
159/// How to handle whitespace in text
160#[derive(Copy, Clone, Debug, Default, PartialEq, Eq)]
161pub enum WhiteSpace {
162 /// Normal line wrapping when text overflows the width of the element
163 #[default]
164 Normal,
165 /// No line wrapping, text will overflow the width of the element
166 Nowrap,
167}
168
169/// The properties that can be used to style text in GPUI
170#[derive(Refineable, Clone, Debug, PartialEq)]
171#[refineable(Debug)]
172pub struct TextStyle {
173 /// The color of the text
174 pub color: Hsla,
175
176 /// The font family to use
177 pub font_family: SharedString,
178
179 /// The font features to use
180 pub font_features: FontFeatures,
181
182 /// The font size to use, in pixels or rems.
183 pub font_size: AbsoluteLength,
184
185 /// The line height to use, in pixels or fractions
186 pub line_height: DefiniteLength,
187
188 /// The font weight, e.g. bold
189 pub font_weight: FontWeight,
190
191 /// The font style, e.g. italic
192 pub font_style: FontStyle,
193
194 /// The background color of the text
195 pub background_color: Option<Hsla>,
196
197 /// The underline style of the text
198 pub underline: Option<UnderlineStyle>,
199
200 /// How to handle whitespace in the text
201 pub white_space: WhiteSpace,
202}
203
204impl Default for TextStyle {
205 fn default() -> Self {
206 TextStyle {
207 color: black(),
208 // Helvetica is a web safe font, so it should be available
209 font_family: "Helvetica".into(),
210 font_features: FontFeatures::default(),
211 font_size: rems(1.).into(),
212 line_height: phi(),
213 font_weight: FontWeight::default(),
214 font_style: FontStyle::default(),
215 background_color: None,
216 underline: None,
217 white_space: WhiteSpace::Normal,
218 }
219 }
220}
221
222impl TextStyle {
223 /// Create a new text style with the given highlighting applied.
224 pub fn highlight(mut self, style: impl Into<HighlightStyle>) -> Self {
225 let style = style.into();
226 if let Some(weight) = style.font_weight {
227 self.font_weight = weight;
228 }
229 if let Some(style) = style.font_style {
230 self.font_style = style;
231 }
232
233 if let Some(color) = style.color {
234 self.color = self.color.blend(color);
235 }
236
237 if let Some(factor) = style.fade_out {
238 self.color.fade_out(factor);
239 }
240
241 if let Some(background_color) = style.background_color {
242 self.background_color = Some(background_color);
243 }
244
245 if let Some(underline) = style.underline {
246 self.underline = Some(underline);
247 }
248
249 self
250 }
251
252 /// Get the font configured for this text style.
253 pub fn font(&self) -> Font {
254 Font {
255 family: self.font_family.clone(),
256 features: self.font_features,
257 weight: self.font_weight,
258 style: self.font_style,
259 }
260 }
261
262 /// Returns the rounded line height in pixels.
263 pub fn line_height_in_pixels(&self, rem_size: Pixels) -> Pixels {
264 self.line_height.to_pixels(self.font_size, rem_size).round()
265 }
266
267 /// Convert this text style into a [`TextRun`], for the given length of the text.
268 pub fn to_run(&self, len: usize) -> TextRun {
269 TextRun {
270 len,
271 font: Font {
272 family: self.font_family.clone(),
273 features: Default::default(),
274 weight: self.font_weight,
275 style: self.font_style,
276 },
277 color: self.color,
278 background_color: self.background_color,
279 underline: self.underline,
280 }
281 }
282}
283
284/// A highlight style to apply, similar to a `TextStyle` except
285/// for a single font, uniformly sized and spaced text.
286#[derive(Copy, Clone, Debug, Default, PartialEq)]
287pub struct HighlightStyle {
288 /// The color of the text
289 pub color: Option<Hsla>,
290
291 /// The font weight, e.g. bold
292 pub font_weight: Option<FontWeight>,
293
294 /// The font style, e.g. italic
295 pub font_style: Option<FontStyle>,
296
297 /// The background color of the text
298 pub background_color: Option<Hsla>,
299
300 /// The underline style of the text
301 pub underline: Option<UnderlineStyle>,
302
303 /// Similar to the CSS `opacity` property, this will cause the text to be less vibrant.
304 pub fade_out: Option<f32>,
305}
306
307impl Eq for HighlightStyle {}
308
309impl Style {
310 /// Get the text style in this element style.
311 pub fn text_style(&self) -> Option<&TextStyleRefinement> {
312 if self.text.is_some() {
313 Some(&self.text)
314 } else {
315 None
316 }
317 }
318
319 /// Get the content mask for this element style, based on the given bounds.
320 /// If the element does not hide it's overflow, this will return `None`.
321 pub fn overflow_mask(
322 &self,
323 bounds: Bounds<Pixels>,
324 rem_size: Pixels,
325 ) -> Option<ContentMask<Pixels>> {
326 match self.overflow {
327 Point {
328 x: Overflow::Visible,
329 y: Overflow::Visible,
330 } => None,
331 _ => {
332 let mut min = bounds.origin;
333 let mut max = bounds.lower_right();
334
335 if self
336 .border_color
337 .map_or(false, |color| !color.is_transparent())
338 {
339 min.x += self.border_widths.left.to_pixels(rem_size);
340 max.x -= self.border_widths.right.to_pixels(rem_size);
341 min.y += self.border_widths.top.to_pixels(rem_size);
342 max.y -= self.border_widths.bottom.to_pixels(rem_size);
343 }
344
345 let bounds = match (
346 self.overflow.x == Overflow::Visible,
347 self.overflow.y == Overflow::Visible,
348 ) {
349 // x and y both visible
350 (true, true) => return None,
351 // x visible, y hidden
352 (true, false) => Bounds::from_corners(
353 point(min.x, bounds.origin.y),
354 point(max.x, bounds.lower_right().y),
355 ),
356 // x hidden, y visible
357 (false, true) => Bounds::from_corners(
358 point(bounds.origin.x, min.y),
359 point(bounds.lower_right().x, max.y),
360 ),
361 // both hidden
362 (false, false) => Bounds::from_corners(min, max),
363 };
364
365 Some(ContentMask { bounds })
366 }
367 }
368 }
369
370 /// Paints the background of an element styled with this style.
371 pub fn paint(
372 &self,
373 bounds: Bounds<Pixels>,
374 cx: &mut ElementContext,
375 continuation: impl FnOnce(&mut ElementContext),
376 ) {
377 #[cfg(debug_assertions)]
378 if self.debug_below {
379 cx.set_global(DebugBelow)
380 }
381
382 #[cfg(debug_assertions)]
383 if self.debug || cx.has_global::<DebugBelow>() {
384 cx.paint_quad(crate::outline(bounds, crate::red()));
385 }
386
387 let rem_size = cx.rem_size();
388
389 cx.with_z_index(0, |cx| {
390 cx.paint_shadows(
391 bounds,
392 self.corner_radii.to_pixels(bounds.size, rem_size),
393 &self.box_shadow,
394 );
395 });
396
397 let background_color = self.background.as_ref().and_then(Fill::color);
398 if background_color.map_or(false, |color| !color.is_transparent()) {
399 cx.with_z_index(1, |cx| {
400 let mut border_color = background_color.unwrap_or_default();
401 border_color.a = 0.;
402 cx.paint_quad(quad(
403 bounds,
404 self.corner_radii.to_pixels(bounds.size, rem_size),
405 background_color.unwrap_or_default(),
406 Edges::default(),
407 border_color,
408 ));
409 });
410 }
411
412 cx.with_z_index(2, |cx| {
413 continuation(cx);
414 });
415
416 if self.is_border_visible() {
417 cx.with_z_index(3, |cx| {
418 let corner_radii = self.corner_radii.to_pixels(bounds.size, rem_size);
419 let border_widths = self.border_widths.to_pixels(rem_size);
420 let max_border_width = border_widths.max();
421 let max_corner_radius = corner_radii.max();
422
423 let top_bounds = Bounds::from_corners(
424 bounds.origin,
425 bounds.upper_right()
426 + point(Pixels::ZERO, max_border_width.max(max_corner_radius)),
427 );
428 let bottom_bounds = Bounds::from_corners(
429 bounds.lower_left()
430 - point(Pixels::ZERO, max_border_width.max(max_corner_radius)),
431 bounds.lower_right(),
432 );
433 let left_bounds = Bounds::from_corners(
434 top_bounds.lower_left(),
435 bottom_bounds.origin + point(max_border_width, Pixels::ZERO),
436 );
437 let right_bounds = Bounds::from_corners(
438 top_bounds.lower_right() - point(max_border_width, Pixels::ZERO),
439 bottom_bounds.upper_right(),
440 );
441
442 let mut background = self.border_color.unwrap_or_default();
443 background.a = 0.;
444 let quad = quad(
445 bounds,
446 corner_radii,
447 background,
448 border_widths,
449 self.border_color.unwrap_or_default(),
450 );
451
452 cx.with_content_mask(Some(ContentMask { bounds: top_bounds }), |cx| {
453 cx.paint_quad(quad.clone());
454 });
455 cx.with_content_mask(
456 Some(ContentMask {
457 bounds: right_bounds,
458 }),
459 |cx| {
460 cx.paint_quad(quad.clone());
461 },
462 );
463 cx.with_content_mask(
464 Some(ContentMask {
465 bounds: bottom_bounds,
466 }),
467 |cx| {
468 cx.paint_quad(quad.clone());
469 },
470 );
471 cx.with_content_mask(
472 Some(ContentMask {
473 bounds: left_bounds,
474 }),
475 |cx| {
476 cx.paint_quad(quad);
477 },
478 );
479 });
480 }
481
482 #[cfg(debug_assertions)]
483 if self.debug_below {
484 cx.remove_global::<DebugBelow>();
485 }
486 }
487
488 fn is_border_visible(&self) -> bool {
489 self.border_color
490 .map_or(false, |color| !color.is_transparent())
491 && self.border_widths.any(|length| !length.is_zero())
492 }
493}
494
495impl Default for Style {
496 fn default() -> Self {
497 Style {
498 display: Display::Block,
499 visibility: Visibility::Visible,
500 overflow: Point {
501 x: Overflow::Visible,
502 y: Overflow::Visible,
503 },
504 scrollbar_width: 0.0,
505 position: Position::Relative,
506 inset: Edges::auto(),
507 margin: Edges::<Length>::zero(),
508 padding: Edges::<DefiniteLength>::zero(),
509 border_widths: Edges::<AbsoluteLength>::zero(),
510 size: Size::auto(),
511 min_size: Size::auto(),
512 max_size: Size::auto(),
513 aspect_ratio: None,
514 gap: Size::default(),
515 // Alignment
516 align_items: None,
517 align_self: None,
518 align_content: None,
519 justify_content: None,
520 // Flexbox
521 flex_direction: FlexDirection::Row,
522 flex_wrap: FlexWrap::NoWrap,
523 flex_grow: 0.0,
524 flex_shrink: 1.0,
525 flex_basis: Length::Auto,
526 background: None,
527 border_color: None,
528 corner_radii: Corners::default(),
529 box_shadow: Default::default(),
530 text: TextStyleRefinement::default(),
531 mouse_cursor: None,
532 z_index: None,
533
534 #[cfg(debug_assertions)]
535 debug: false,
536 #[cfg(debug_assertions)]
537 debug_below: false,
538 }
539 }
540}
541
542/// The properties that can be applied to an underline.
543#[derive(Refineable, Copy, Clone, Default, Debug, PartialEq, Eq)]
544#[refineable(Debug)]
545pub struct UnderlineStyle {
546 /// The thickness of the underline.
547 pub thickness: Pixels,
548
549 /// The color of the underline.
550 pub color: Option<Hsla>,
551
552 /// Whether the underline should be wavy, like in a spell checker.
553 pub wavy: bool,
554}
555
556/// The kinds of fill that can be applied to a shape.
557#[derive(Clone, Debug)]
558pub enum Fill {
559 /// A solid color fill.
560 Color(Hsla),
561}
562
563impl Fill {
564 /// Unwrap this fill into a solid color, if it is one.
565 pub fn color(&self) -> Option<Hsla> {
566 match self {
567 Fill::Color(color) => Some(*color),
568 }
569 }
570}
571
572impl Default for Fill {
573 fn default() -> Self {
574 Self::Color(Hsla::default())
575 }
576}
577
578impl From<Hsla> for Fill {
579 fn from(color: Hsla) -> Self {
580 Self::Color(color)
581 }
582}
583
584impl From<Rgba> for Fill {
585 fn from(color: Rgba) -> Self {
586 Self::Color(color.into())
587 }
588}
589
590impl From<TextStyle> for HighlightStyle {
591 fn from(other: TextStyle) -> Self {
592 Self::from(&other)
593 }
594}
595
596impl From<&TextStyle> for HighlightStyle {
597 fn from(other: &TextStyle) -> Self {
598 Self {
599 color: Some(other.color),
600 font_weight: Some(other.font_weight),
601 font_style: Some(other.font_style),
602 background_color: other.background_color,
603 underline: other.underline,
604 fade_out: None,
605 }
606 }
607}
608
609impl HighlightStyle {
610 /// Blend this highlight style with another.
611 /// Non-continuous properties, like font_weight and font_style, are overwritten.
612 pub fn highlight(&mut self, other: HighlightStyle) {
613 match (self.color, other.color) {
614 (Some(self_color), Some(other_color)) => {
615 self.color = Some(Hsla::blend(other_color, self_color));
616 }
617 (None, Some(other_color)) => {
618 self.color = Some(other_color);
619 }
620 _ => {}
621 }
622
623 if other.font_weight.is_some() {
624 self.font_weight = other.font_weight;
625 }
626
627 if other.font_style.is_some() {
628 self.font_style = other.font_style;
629 }
630
631 if other.background_color.is_some() {
632 self.background_color = other.background_color;
633 }
634
635 if other.underline.is_some() {
636 self.underline = other.underline;
637 }
638
639 match (other.fade_out, self.fade_out) {
640 (Some(source_fade), None) => self.fade_out = Some(source_fade),
641 (Some(source_fade), Some(dest_fade)) => {
642 self.fade_out = Some((dest_fade * (1. + source_fade)).clamp(0., 1.));
643 }
644 _ => {}
645 }
646 }
647}
648
649impl From<Hsla> for HighlightStyle {
650 fn from(color: Hsla) -> Self {
651 Self {
652 color: Some(color),
653 ..Default::default()
654 }
655 }
656}
657
658impl From<FontWeight> for HighlightStyle {
659 fn from(font_weight: FontWeight) -> Self {
660 Self {
661 font_weight: Some(font_weight),
662 ..Default::default()
663 }
664 }
665}
666
667impl From<FontStyle> for HighlightStyle {
668 fn from(font_style: FontStyle) -> Self {
669 Self {
670 font_style: Some(font_style),
671 ..Default::default()
672 }
673 }
674}
675
676impl From<Rgba> for HighlightStyle {
677 fn from(color: Rgba) -> Self {
678 Self {
679 color: Some(color.into()),
680 ..Default::default()
681 }
682 }
683}
684
685/// Combine and merge the highlights and ranges in the two iterators.
686pub fn combine_highlights(
687 a: impl IntoIterator<Item = (Range<usize>, HighlightStyle)>,
688 b: impl IntoIterator<Item = (Range<usize>, HighlightStyle)>,
689) -> impl Iterator<Item = (Range<usize>, HighlightStyle)> {
690 let mut endpoints = Vec::new();
691 let mut highlights = Vec::new();
692 for (range, highlight) in a.into_iter().chain(b) {
693 if !range.is_empty() {
694 let highlight_id = highlights.len();
695 endpoints.push((range.start, highlight_id, true));
696 endpoints.push((range.end, highlight_id, false));
697 highlights.push(highlight);
698 }
699 }
700 endpoints.sort_unstable_by_key(|(position, _, _)| *position);
701 let mut endpoints = endpoints.into_iter().peekable();
702
703 let mut active_styles = HashSet::default();
704 let mut ix = 0;
705 iter::from_fn(move || {
706 while let Some((endpoint_ix, highlight_id, is_start)) = endpoints.peek() {
707 let prev_index = mem::replace(&mut ix, *endpoint_ix);
708 if ix > prev_index && !active_styles.is_empty() {
709 let mut current_style = HighlightStyle::default();
710 for highlight_id in &active_styles {
711 current_style.highlight(highlights[*highlight_id]);
712 }
713 return Some((prev_index..ix, current_style));
714 }
715
716 if *is_start {
717 active_styles.insert(*highlight_id);
718 } else {
719 active_styles.remove(highlight_id);
720 }
721 endpoints.next();
722 }
723 None
724 })
725}
726
727#[cfg(test)]
728mod tests {
729 use crate::{blue, green, red, yellow};
730
731 use super::*;
732
733 #[test]
734 fn test_combine_highlights() {
735 assert_eq!(
736 combine_highlights(
737 [
738 (0..5, green().into()),
739 (4..10, FontWeight::BOLD.into()),
740 (15..20, yellow().into()),
741 ],
742 [
743 (2..6, FontStyle::Italic.into()),
744 (1..3, blue().into()),
745 (21..23, red().into()),
746 ]
747 )
748 .collect::<Vec<_>>(),
749 [
750 (
751 0..1,
752 HighlightStyle {
753 color: Some(green()),
754 ..Default::default()
755 }
756 ),
757 (
758 1..2,
759 HighlightStyle {
760 color: Some(green()),
761 ..Default::default()
762 }
763 ),
764 (
765 2..3,
766 HighlightStyle {
767 color: Some(green()),
768 font_style: Some(FontStyle::Italic),
769 ..Default::default()
770 }
771 ),
772 (
773 3..4,
774 HighlightStyle {
775 color: Some(green()),
776 font_style: Some(FontStyle::Italic),
777 ..Default::default()
778 }
779 ),
780 (
781 4..5,
782 HighlightStyle {
783 color: Some(green()),
784 font_weight: Some(FontWeight::BOLD),
785 font_style: Some(FontStyle::Italic),
786 ..Default::default()
787 }
788 ),
789 (
790 5..6,
791 HighlightStyle {
792 font_weight: Some(FontWeight::BOLD),
793 font_style: Some(FontStyle::Italic),
794 ..Default::default()
795 }
796 ),
797 (
798 6..10,
799 HighlightStyle {
800 font_weight: Some(FontWeight::BOLD),
801 ..Default::default()
802 }
803 ),
804 (
805 15..20,
806 HighlightStyle {
807 color: Some(yellow()),
808 ..Default::default()
809 }
810 ),
811 (
812 21..23,
813 HighlightStyle {
814 color: Some(red()),
815 ..Default::default()
816 }
817 )
818 ]
819 );
820 }
821}