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