1use std::{
2 hash::{Hash, Hasher},
3 iter, mem,
4 ops::Range,
5};
6
7use crate::{
8 black, phi, point, quad, rems, size, AbsoluteLength, App, Background, BackgroundTag, Bounds,
9 ContentMask, Corners, CornersRefinement, CursorStyle, DefiniteLength, DevicePixels, Edges,
10 EdgesRefinement, Font, FontFallbacks, FontFeatures, FontStyle, FontWeight, Hsla, Length,
11 Pixels, Point, PointRefinement, Rgba, SharedString, Size, SizeRefinement, Styled, TextRun,
12 Window,
13};
14use collections::HashSet;
15use refineable::Refineable;
16use smallvec::SmallVec;
17pub use taffy::style::{
18 AlignContent, AlignItems, AlignSelf, Display, FlexDirection, FlexWrap, JustifyContent,
19 Overflow, Position,
20};
21
22/// Use this struct for interfacing with the 'debug_below' styling from your own elements.
23/// If a parent element has this style set on it, then this struct will be set as a global in
24/// GPUI.
25#[cfg(debug_assertions)]
26pub struct DebugBelow;
27
28#[cfg(debug_assertions)]
29impl crate::Global for DebugBelow {}
30
31/// How to fit the image into the bounds of the element.
32pub enum ObjectFit {
33 /// The image will be stretched to fill the bounds of the element.
34 Fill,
35 /// The image will be scaled to fit within the bounds of the element.
36 Contain,
37 /// The image will be scaled to cover the bounds of the element.
38 Cover,
39 /// The image will be scaled down to fit within the bounds of the element.
40 ScaleDown,
41 /// The image will maintain its original size.
42 None,
43}
44
45impl ObjectFit {
46 /// Get the bounds of the image within the given bounds.
47 pub fn get_bounds(
48 &self,
49 bounds: Bounds<Pixels>,
50 image_size: Size<DevicePixels>,
51 ) -> Bounds<Pixels> {
52 let image_size = image_size.map(|dimension| Pixels::from(u32::from(dimension)));
53 let image_ratio = image_size.width / image_size.height;
54 let bounds_ratio = bounds.size.width / bounds.size.height;
55
56 match self {
57 ObjectFit::Fill => bounds,
58 ObjectFit::Contain => {
59 let new_size = if bounds_ratio > image_ratio {
60 size(
61 image_size.width * (bounds.size.height / image_size.height),
62 bounds.size.height,
63 )
64 } else {
65 size(
66 bounds.size.width,
67 image_size.height * (bounds.size.width / image_size.width),
68 )
69 };
70
71 Bounds {
72 origin: point(
73 bounds.origin.x + (bounds.size.width - new_size.width) / 2.0,
74 bounds.origin.y + (bounds.size.height - new_size.height) / 2.0,
75 ),
76 size: new_size,
77 }
78 }
79 ObjectFit::ScaleDown => {
80 // Check if the image is larger than the bounds in either dimension.
81 if image_size.width > bounds.size.width || image_size.height > bounds.size.height {
82 // If the image is larger, use the same logic as Contain to scale it down.
83 let new_size = if bounds_ratio > image_ratio {
84 size(
85 image_size.width * (bounds.size.height / image_size.height),
86 bounds.size.height,
87 )
88 } else {
89 size(
90 bounds.size.width,
91 image_size.height * (bounds.size.width / image_size.width),
92 )
93 };
94
95 Bounds {
96 origin: point(
97 bounds.origin.x + (bounds.size.width - new_size.width) / 2.0,
98 bounds.origin.y + (bounds.size.height - new_size.height) / 2.0,
99 ),
100 size: new_size,
101 }
102 } else {
103 // If the image is smaller than or equal to the container, display it at its original size,
104 // centered within the container.
105 let original_size = size(image_size.width, image_size.height);
106 Bounds {
107 origin: point(
108 bounds.origin.x + (bounds.size.width - original_size.width) / 2.0,
109 bounds.origin.y + (bounds.size.height - original_size.height) / 2.0,
110 ),
111 size: original_size,
112 }
113 }
114 }
115 ObjectFit::Cover => {
116 let new_size = if bounds_ratio > image_ratio {
117 size(
118 bounds.size.width,
119 image_size.height * (bounds.size.width / image_size.width),
120 )
121 } else {
122 size(
123 image_size.width * (bounds.size.height / image_size.height),
124 bounds.size.height,
125 )
126 };
127
128 Bounds {
129 origin: point(
130 bounds.origin.x + (bounds.size.width - new_size.width) / 2.0,
131 bounds.origin.y + (bounds.size.height - new_size.height) / 2.0,
132 ),
133 size: new_size,
134 }
135 }
136 ObjectFit::None => Bounds {
137 origin: bounds.origin,
138 size: image_size,
139 },
140 }
141 }
142}
143
144/// The CSS styling that can be applied to an element via the `Styled` trait
145#[derive(Clone, Refineable, Debug)]
146#[refineable(Debug)]
147pub struct Style {
148 /// What layout strategy should be used?
149 pub display: Display,
150
151 /// Should the element be painted on screen?
152 pub visibility: Visibility,
153
154 // Overflow properties
155 /// How children overflowing their container should affect layout
156 #[refineable]
157 pub overflow: Point<Overflow>,
158 /// How much space (in points) should be reserved for the scrollbars of `Overflow::Scroll` and `Overflow::Auto` nodes.
159 pub scrollbar_width: f32,
160 /// Whether both x and y axis should be scrollable at the same time.
161 pub allow_concurrent_scroll: bool,
162
163 // Position properties
164 /// What should the `position` value of this struct use as a base offset?
165 pub position: Position,
166 /// How should the position of this element be tweaked relative to the layout defined?
167 #[refineable]
168 pub inset: Edges<Length>,
169
170 // Size properties
171 /// Sets the initial size of the item
172 #[refineable]
173 pub size: Size<Length>,
174 /// Controls the minimum size of the item
175 #[refineable]
176 pub min_size: Size<Length>,
177 /// Controls the maximum size of the item
178 #[refineable]
179 pub max_size: Size<Length>,
180 /// Sets the preferred aspect ratio for the item. The ratio is calculated as width divided by height.
181 pub aspect_ratio: Option<f32>,
182
183 // Spacing Properties
184 /// How large should the margin be on each side?
185 #[refineable]
186 pub margin: Edges<Length>,
187 /// How large should the padding be on each side?
188 #[refineable]
189 pub padding: Edges<DefiniteLength>,
190 /// How large should the border be on each side?
191 #[refineable]
192 pub border_widths: Edges<AbsoluteLength>,
193
194 // Alignment properties
195 /// How this node's children aligned in the cross/block axis?
196 pub align_items: Option<AlignItems>,
197 /// How this node should be aligned in the cross/block axis. Falls back to the parents [`AlignItems`] if not set
198 pub align_self: Option<AlignSelf>,
199 /// How should content contained within this item be aligned in the cross/block axis
200 pub align_content: Option<AlignContent>,
201 /// How should contained within this item be aligned in the main/inline axis
202 pub justify_content: Option<JustifyContent>,
203 /// How large should the gaps between items in a flex container be?
204 #[refineable]
205 pub gap: Size<DefiniteLength>,
206
207 // Flexbox properties
208 /// Which direction does the main axis flow in?
209 pub flex_direction: FlexDirection,
210 /// Should elements wrap, or stay in a single line?
211 pub flex_wrap: FlexWrap,
212 /// Sets the initial main axis size of the item
213 pub flex_basis: Length,
214 /// 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.
215 pub flex_grow: f32,
216 /// 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.
217 pub flex_shrink: f32,
218
219 /// The fill color of this element
220 pub background: Option<Fill>,
221
222 /// The border color of this element
223 pub border_color: Option<Hsla>,
224
225 /// The radius of the corners of this element
226 #[refineable]
227 pub corner_radii: Corners<AbsoluteLength>,
228
229 /// Box Shadow of the element
230 pub box_shadow: SmallVec<[BoxShadow; 2]>,
231
232 /// The text style of this element
233 pub text: TextStyleRefinement,
234
235 /// The mouse cursor style shown when the mouse pointer is over an element.
236 pub mouse_cursor: Option<CursorStyle>,
237
238 /// The opacity of this element
239 pub opacity: Option<f32>,
240
241 /// Whether to draw a red debugging outline around this element
242 #[cfg(debug_assertions)]
243 pub debug: bool,
244
245 /// Whether to draw a red debugging outline around this element and all of its conforming children
246 #[cfg(debug_assertions)]
247 pub debug_below: bool,
248}
249
250impl Styled for StyleRefinement {
251 fn style(&mut self) -> &mut StyleRefinement {
252 self
253 }
254}
255
256/// The value of the visibility property, similar to the CSS property `visibility`
257#[derive(Default, Clone, Copy, Debug, Eq, PartialEq)]
258pub enum Visibility {
259 /// The element should be drawn as normal.
260 #[default]
261 Visible,
262 /// The element should not be drawn, but should still take up space in the layout.
263 Hidden,
264}
265
266/// The possible values of the box-shadow property
267#[derive(Clone, Debug)]
268pub struct BoxShadow {
269 /// What color should the shadow have?
270 pub color: Hsla,
271 /// How should it be offset from its element?
272 pub offset: Point<Pixels>,
273 /// How much should the shadow be blurred?
274 pub blur_radius: Pixels,
275 /// How much should the shadow spread?
276 pub spread_radius: Pixels,
277}
278
279/// How to handle whitespace in text
280#[derive(Copy, Clone, Debug, Default, PartialEq, Eq)]
281pub enum WhiteSpace {
282 /// Normal line wrapping when text overflows the width of the element
283 #[default]
284 Normal,
285 /// No line wrapping, text will overflow the width of the element
286 Nowrap,
287}
288
289/// How to truncate text that overflows the width of the element
290#[derive(Copy, Clone, Debug, PartialEq, Eq)]
291pub enum TextOverflow {
292 /// Truncate the text with an ellipsis, same as: `text-overflow: ellipsis;` in CSS
293 Ellipsis(&'static str),
294}
295
296/// How to align text within the element
297#[derive(Copy, Clone, Debug, Default, PartialEq, Eq)]
298pub enum TextAlign {
299 /// Align the text to the left of the element
300 #[default]
301 Left,
302
303 /// Center the text within the element
304 Center,
305
306 /// Align the text to the right of the element
307 Right,
308}
309
310/// The properties that can be used to style text in GPUI
311#[derive(Refineable, Clone, Debug, PartialEq)]
312#[refineable(Debug)]
313pub struct TextStyle {
314 /// The color of the text
315 pub color: Hsla,
316
317 /// The font family to use
318 pub font_family: SharedString,
319
320 /// The font features to use
321 pub font_features: FontFeatures,
322
323 /// The fallback fonts to use
324 pub font_fallbacks: Option<FontFallbacks>,
325
326 /// The font size to use, in pixels or rems.
327 pub font_size: AbsoluteLength,
328
329 /// The line height to use, in pixels or fractions
330 pub line_height: DefiniteLength,
331
332 /// The font weight, e.g. bold
333 pub font_weight: FontWeight,
334
335 /// The font style, e.g. italic
336 pub font_style: FontStyle,
337
338 /// The background color of the text
339 pub background_color: Option<Hsla>,
340
341 /// The underline style of the text
342 pub underline: Option<UnderlineStyle>,
343
344 /// The strikethrough style of the text
345 pub strikethrough: Option<StrikethroughStyle>,
346
347 /// How to handle whitespace in the text
348 pub white_space: WhiteSpace,
349
350 /// The text should be truncated if it overflows the width of the element
351 pub text_overflow: Option<TextOverflow>,
352
353 /// How the text should be aligned within the element
354 pub text_align: TextAlign,
355
356 /// The number of lines to display before truncating the text
357 pub line_clamp: Option<usize>,
358}
359
360impl Default for TextStyle {
361 fn default() -> Self {
362 TextStyle {
363 color: black(),
364 // todo(linux) make this configurable or choose better default
365 font_family: if cfg!(any(target_os = "linux", target_os = "freebsd")) {
366 "FreeMono".into()
367 } else if cfg!(target_os = "windows") {
368 "Segoe UI".into()
369 } else {
370 "Helvetica".into()
371 },
372 font_features: FontFeatures::default(),
373 font_fallbacks: None,
374 font_size: rems(1.).into(),
375 line_height: phi(),
376 font_weight: FontWeight::default(),
377 font_style: FontStyle::default(),
378 background_color: None,
379 underline: None,
380 strikethrough: None,
381 white_space: WhiteSpace::Normal,
382 text_overflow: None,
383 text_align: TextAlign::default(),
384 line_clamp: None,
385 }
386 }
387}
388
389impl TextStyle {
390 /// Create a new text style with the given highlighting applied.
391 pub fn highlight(mut self, style: impl Into<HighlightStyle>) -> Self {
392 let style = style.into();
393 if let Some(weight) = style.font_weight {
394 self.font_weight = weight;
395 }
396 if let Some(style) = style.font_style {
397 self.font_style = style;
398 }
399
400 if let Some(color) = style.color {
401 self.color = self.color.blend(color);
402 }
403
404 if let Some(factor) = style.fade_out {
405 self.color.fade_out(factor);
406 }
407
408 if let Some(background_color) = style.background_color {
409 self.background_color = Some(background_color);
410 }
411
412 if let Some(underline) = style.underline {
413 self.underline = Some(underline);
414 }
415
416 if let Some(strikethrough) = style.strikethrough {
417 self.strikethrough = Some(strikethrough);
418 }
419
420 self
421 }
422
423 /// Get the font configured for this text style.
424 pub fn font(&self) -> Font {
425 Font {
426 family: self.font_family.clone(),
427 features: self.font_features.clone(),
428 fallbacks: self.font_fallbacks.clone(),
429 weight: self.font_weight,
430 style: self.font_style,
431 }
432 }
433
434 /// Returns the rounded line height in pixels.
435 pub fn line_height_in_pixels(&self, rem_size: Pixels) -> Pixels {
436 self.line_height.to_pixels(self.font_size, rem_size).round()
437 }
438
439 /// Convert this text style into a [`TextRun`], for the given length of the text.
440 pub fn to_run(&self, len: usize) -> TextRun {
441 TextRun {
442 len,
443 font: Font {
444 family: self.font_family.clone(),
445 features: Default::default(),
446 fallbacks: self.font_fallbacks.clone(),
447 weight: self.font_weight,
448 style: self.font_style,
449 },
450 color: self.color,
451 background_color: self.background_color,
452 underline: self.underline,
453 strikethrough: self.strikethrough,
454 }
455 }
456}
457
458/// A highlight style to apply, similar to a `TextStyle` except
459/// for a single font, uniformly sized and spaced text.
460#[derive(Copy, Clone, Debug, Default, PartialEq)]
461pub struct HighlightStyle {
462 /// The color of the text
463 pub color: Option<Hsla>,
464
465 /// The font weight, e.g. bold
466 pub font_weight: Option<FontWeight>,
467
468 /// The font style, e.g. italic
469 pub font_style: Option<FontStyle>,
470
471 /// The background color of the text
472 pub background_color: Option<Hsla>,
473
474 /// The underline style of the text
475 pub underline: Option<UnderlineStyle>,
476
477 /// The underline style of the text
478 pub strikethrough: Option<StrikethroughStyle>,
479
480 /// Similar to the CSS `opacity` property, this will cause the text to be less vibrant.
481 pub fade_out: Option<f32>,
482}
483
484impl Eq for HighlightStyle {}
485
486impl Hash for HighlightStyle {
487 fn hash<H: Hasher>(&self, state: &mut H) {
488 self.color.hash(state);
489 self.font_weight.hash(state);
490 self.font_style.hash(state);
491 self.background_color.hash(state);
492 self.underline.hash(state);
493 self.strikethrough.hash(state);
494 state.write_u32(u32::from_be_bytes(
495 self.fade_out.map(|f| f.to_be_bytes()).unwrap_or_default(),
496 ));
497 }
498}
499
500impl Style {
501 /// Returns true if the style is visible and the background is opaque.
502 pub fn has_opaque_background(&self) -> bool {
503 self.background
504 .as_ref()
505 .is_some_and(|fill| fill.color().is_some_and(|color| !color.is_transparent()))
506 }
507
508 /// Get the text style in this element style.
509 pub fn text_style(&self) -> Option<&TextStyleRefinement> {
510 if self.text.is_some() {
511 Some(&self.text)
512 } else {
513 None
514 }
515 }
516
517 /// Get the content mask for this element style, based on the given bounds.
518 /// If the element does not hide its overflow, this will return `None`.
519 pub fn overflow_mask(
520 &self,
521 bounds: Bounds<Pixels>,
522 rem_size: Pixels,
523 ) -> Option<ContentMask<Pixels>> {
524 match self.overflow {
525 Point {
526 x: Overflow::Visible,
527 y: Overflow::Visible,
528 } => None,
529 _ => {
530 let mut min = bounds.origin;
531 let mut max = bounds.bottom_right();
532
533 if self
534 .border_color
535 .map_or(false, |color| !color.is_transparent())
536 {
537 min.x += self.border_widths.left.to_pixels(rem_size);
538 max.x -= self.border_widths.right.to_pixels(rem_size);
539 min.y += self.border_widths.top.to_pixels(rem_size);
540 max.y -= self.border_widths.bottom.to_pixels(rem_size);
541 }
542
543 let bounds = match (
544 self.overflow.x == Overflow::Visible,
545 self.overflow.y == Overflow::Visible,
546 ) {
547 // x and y both visible
548 (true, true) => return None,
549 // x visible, y hidden
550 (true, false) => Bounds::from_corners(
551 point(min.x, bounds.origin.y),
552 point(max.x, bounds.bottom_right().y),
553 ),
554 // x hidden, y visible
555 (false, true) => Bounds::from_corners(
556 point(bounds.origin.x, min.y),
557 point(bounds.bottom_right().x, max.y),
558 ),
559 // both hidden
560 (false, false) => Bounds::from_corners(min, max),
561 };
562
563 Some(ContentMask { bounds })
564 }
565 }
566 }
567
568 /// Paints the background of an element styled with this style.
569 pub fn paint(
570 &self,
571 bounds: Bounds<Pixels>,
572 window: &mut Window,
573 cx: &mut App,
574 continuation: impl FnOnce(&mut Window, &mut App),
575 ) {
576 #[cfg(debug_assertions)]
577 if self.debug_below {
578 cx.set_global(DebugBelow)
579 }
580
581 #[cfg(debug_assertions)]
582 if self.debug || cx.has_global::<DebugBelow>() {
583 window.paint_quad(crate::outline(bounds, crate::red()));
584 }
585
586 let rem_size = window.rem_size();
587
588 window.paint_shadows(
589 bounds,
590 self.corner_radii.to_pixels(bounds.size, rem_size),
591 &self.box_shadow,
592 );
593
594 let background_color = self.background.as_ref().and_then(Fill::color);
595 if background_color.map_or(false, |color| !color.is_transparent()) {
596 let mut border_color = match background_color {
597 Some(color) => match color.tag {
598 BackgroundTag::Solid => color.solid,
599 BackgroundTag::LinearGradient => color
600 .colors
601 .first()
602 .map(|stop| stop.color)
603 .unwrap_or_default(),
604 BackgroundTag::PatternSlash => color.solid,
605 },
606 None => Hsla::default(),
607 };
608 border_color.a = 0.;
609 window.paint_quad(quad(
610 bounds,
611 self.corner_radii.to_pixels(bounds.size, rem_size),
612 background_color.unwrap_or_default(),
613 Edges::default(),
614 border_color,
615 ));
616 }
617
618 continuation(window, cx);
619
620 if self.is_border_visible() {
621 let corner_radii = self.corner_radii.to_pixels(bounds.size, rem_size);
622 let border_widths = self.border_widths.to_pixels(rem_size);
623 let max_border_width = border_widths.max();
624 let max_corner_radius = corner_radii.max();
625
626 let top_bounds = Bounds::from_corners(
627 bounds.origin,
628 bounds.top_right() + point(Pixels::ZERO, max_border_width.max(max_corner_radius)),
629 );
630 let bottom_bounds = Bounds::from_corners(
631 bounds.bottom_left() - point(Pixels::ZERO, max_border_width.max(max_corner_radius)),
632 bounds.bottom_right(),
633 );
634 let left_bounds = Bounds::from_corners(
635 top_bounds.bottom_left(),
636 bottom_bounds.origin + point(max_border_width, Pixels::ZERO),
637 );
638 let right_bounds = Bounds::from_corners(
639 top_bounds.bottom_right() - point(max_border_width, Pixels::ZERO),
640 bottom_bounds.top_right(),
641 );
642
643 let mut background = self.border_color.unwrap_or_default();
644 background.a = 0.;
645 let quad = quad(
646 bounds,
647 corner_radii,
648 background,
649 border_widths,
650 self.border_color.unwrap_or_default(),
651 );
652
653 window.with_content_mask(Some(ContentMask { bounds: top_bounds }), |window| {
654 window.paint_quad(quad.clone());
655 });
656 window.with_content_mask(
657 Some(ContentMask {
658 bounds: right_bounds,
659 }),
660 |window| {
661 window.paint_quad(quad.clone());
662 },
663 );
664 window.with_content_mask(
665 Some(ContentMask {
666 bounds: bottom_bounds,
667 }),
668 |window| {
669 window.paint_quad(quad.clone());
670 },
671 );
672 window.with_content_mask(
673 Some(ContentMask {
674 bounds: left_bounds,
675 }),
676 |window| {
677 window.paint_quad(quad);
678 },
679 );
680 }
681
682 #[cfg(debug_assertions)]
683 if self.debug_below {
684 cx.remove_global::<DebugBelow>();
685 }
686 }
687
688 fn is_border_visible(&self) -> bool {
689 self.border_color
690 .map_or(false, |color| !color.is_transparent())
691 && self.border_widths.any(|length| !length.is_zero())
692 }
693}
694
695impl Default for Style {
696 fn default() -> Self {
697 Style {
698 display: Display::Block,
699 visibility: Visibility::Visible,
700 overflow: Point {
701 x: Overflow::Visible,
702 y: Overflow::Visible,
703 },
704 allow_concurrent_scroll: false,
705 scrollbar_width: 0.0,
706 position: Position::Relative,
707 inset: Edges::auto(),
708 margin: Edges::<Length>::zero(),
709 padding: Edges::<DefiniteLength>::zero(),
710 border_widths: Edges::<AbsoluteLength>::zero(),
711 size: Size::auto(),
712 min_size: Size::auto(),
713 max_size: Size::auto(),
714 aspect_ratio: None,
715 gap: Size::default(),
716 // Alignment
717 align_items: None,
718 align_self: None,
719 align_content: None,
720 justify_content: None,
721 // Flexbox
722 flex_direction: FlexDirection::Row,
723 flex_wrap: FlexWrap::NoWrap,
724 flex_grow: 0.0,
725 flex_shrink: 1.0,
726 flex_basis: Length::Auto,
727 background: None,
728 border_color: None,
729 corner_radii: Corners::default(),
730 box_shadow: Default::default(),
731 text: TextStyleRefinement::default(),
732 mouse_cursor: None,
733 opacity: None,
734
735 #[cfg(debug_assertions)]
736 debug: false,
737 #[cfg(debug_assertions)]
738 debug_below: false,
739 }
740 }
741}
742
743/// The properties that can be applied to an underline.
744#[derive(Refineable, Copy, Clone, Default, Debug, PartialEq, Eq, Hash)]
745#[refineable(Debug)]
746pub struct UnderlineStyle {
747 /// The thickness of the underline.
748 pub thickness: Pixels,
749
750 /// The color of the underline.
751 pub color: Option<Hsla>,
752
753 /// Whether the underline should be wavy, like in a spell checker.
754 pub wavy: bool,
755}
756
757/// The properties that can be applied to a strikethrough.
758#[derive(Refineable, Copy, Clone, Default, Debug, PartialEq, Eq, Hash)]
759#[refineable(Debug)]
760pub struct StrikethroughStyle {
761 /// The thickness of the strikethrough.
762 pub thickness: Pixels,
763
764 /// The color of the strikethrough.
765 pub color: Option<Hsla>,
766}
767
768/// The kinds of fill that can be applied to a shape.
769#[derive(Clone, Debug)]
770pub enum Fill {
771 /// A solid color fill.
772 Color(Background),
773}
774
775impl Fill {
776 /// Unwrap this fill into a solid color, if it is one.
777 ///
778 /// If the fill is not a solid color, this method returns `None`.
779 pub fn color(&self) -> Option<Background> {
780 match self {
781 Fill::Color(color) => Some(*color),
782 }
783 }
784}
785
786impl Default for Fill {
787 fn default() -> Self {
788 Self::Color(Background::default())
789 }
790}
791
792impl From<Hsla> for Fill {
793 fn from(color: Hsla) -> Self {
794 Self::Color(color.into())
795 }
796}
797
798impl From<Rgba> for Fill {
799 fn from(color: Rgba) -> Self {
800 Self::Color(color.into())
801 }
802}
803
804impl From<Background> for Fill {
805 fn from(background: Background) -> Self {
806 Self::Color(background)
807 }
808}
809
810impl From<TextStyle> for HighlightStyle {
811 fn from(other: TextStyle) -> Self {
812 Self::from(&other)
813 }
814}
815
816impl From<&TextStyle> for HighlightStyle {
817 fn from(other: &TextStyle) -> Self {
818 Self {
819 color: Some(other.color),
820 font_weight: Some(other.font_weight),
821 font_style: Some(other.font_style),
822 background_color: other.background_color,
823 underline: other.underline,
824 strikethrough: other.strikethrough,
825 fade_out: None,
826 }
827 }
828}
829
830impl HighlightStyle {
831 /// Create a highlight style with just a color
832 pub fn color(color: Hsla) -> Self {
833 Self {
834 color: Some(color),
835 ..Default::default()
836 }
837 }
838 /// Blend this highlight style with another.
839 /// Non-continuous properties, like font_weight and font_style, are overwritten.
840 pub fn highlight(&mut self, other: HighlightStyle) {
841 match (self.color, other.color) {
842 (Some(self_color), Some(other_color)) => {
843 self.color = Some(Hsla::blend(other_color, self_color));
844 }
845 (None, Some(other_color)) => {
846 self.color = Some(other_color);
847 }
848 _ => {}
849 }
850
851 if other.font_weight.is_some() {
852 self.font_weight = other.font_weight;
853 }
854
855 if other.font_style.is_some() {
856 self.font_style = other.font_style;
857 }
858
859 if other.background_color.is_some() {
860 self.background_color = other.background_color;
861 }
862
863 if other.underline.is_some() {
864 self.underline = other.underline;
865 }
866
867 if other.strikethrough.is_some() {
868 self.strikethrough = other.strikethrough;
869 }
870
871 match (other.fade_out, self.fade_out) {
872 (Some(source_fade), None) => self.fade_out = Some(source_fade),
873 (Some(source_fade), Some(dest_fade)) => {
874 self.fade_out = Some((dest_fade * (1. + source_fade)).clamp(0., 1.));
875 }
876 _ => {}
877 }
878 }
879}
880
881impl From<Hsla> for HighlightStyle {
882 fn from(color: Hsla) -> Self {
883 Self {
884 color: Some(color),
885 ..Default::default()
886 }
887 }
888}
889
890impl From<FontWeight> for HighlightStyle {
891 fn from(font_weight: FontWeight) -> Self {
892 Self {
893 font_weight: Some(font_weight),
894 ..Default::default()
895 }
896 }
897}
898
899impl From<FontStyle> for HighlightStyle {
900 fn from(font_style: FontStyle) -> Self {
901 Self {
902 font_style: Some(font_style),
903 ..Default::default()
904 }
905 }
906}
907
908impl From<Rgba> for HighlightStyle {
909 fn from(color: Rgba) -> Self {
910 Self {
911 color: Some(color.into()),
912 ..Default::default()
913 }
914 }
915}
916
917/// Combine and merge the highlights and ranges in the two iterators.
918pub fn combine_highlights(
919 a: impl IntoIterator<Item = (Range<usize>, HighlightStyle)>,
920 b: impl IntoIterator<Item = (Range<usize>, HighlightStyle)>,
921) -> impl Iterator<Item = (Range<usize>, HighlightStyle)> {
922 let mut endpoints = Vec::new();
923 let mut highlights = Vec::new();
924 for (range, highlight) in a.into_iter().chain(b) {
925 if !range.is_empty() {
926 let highlight_id = highlights.len();
927 endpoints.push((range.start, highlight_id, true));
928 endpoints.push((range.end, highlight_id, false));
929 highlights.push(highlight);
930 }
931 }
932 endpoints.sort_unstable_by_key(|(position, _, _)| *position);
933 let mut endpoints = endpoints.into_iter().peekable();
934
935 let mut active_styles = HashSet::default();
936 let mut ix = 0;
937 iter::from_fn(move || {
938 while let Some((endpoint_ix, highlight_id, is_start)) = endpoints.peek() {
939 let prev_index = mem::replace(&mut ix, *endpoint_ix);
940 if ix > prev_index && !active_styles.is_empty() {
941 let mut current_style = HighlightStyle::default();
942 for highlight_id in &active_styles {
943 current_style.highlight(highlights[*highlight_id]);
944 }
945 return Some((prev_index..ix, current_style));
946 }
947
948 if *is_start {
949 active_styles.insert(*highlight_id);
950 } else {
951 active_styles.remove(highlight_id);
952 }
953 endpoints.next();
954 }
955 None
956 })
957}
958
959#[cfg(test)]
960mod tests {
961 use crate::{blue, green, red, yellow};
962
963 use super::*;
964
965 #[test]
966 fn test_combine_highlights() {
967 assert_eq!(
968 combine_highlights(
969 [
970 (0..5, green().into()),
971 (4..10, FontWeight::BOLD.into()),
972 (15..20, yellow().into()),
973 ],
974 [
975 (2..6, FontStyle::Italic.into()),
976 (1..3, blue().into()),
977 (21..23, red().into()),
978 ]
979 )
980 .collect::<Vec<_>>(),
981 [
982 (
983 0..1,
984 HighlightStyle {
985 color: Some(green()),
986 ..Default::default()
987 }
988 ),
989 (
990 1..2,
991 HighlightStyle {
992 color: Some(green()),
993 ..Default::default()
994 }
995 ),
996 (
997 2..3,
998 HighlightStyle {
999 color: Some(green()),
1000 font_style: Some(FontStyle::Italic),
1001 ..Default::default()
1002 }
1003 ),
1004 (
1005 3..4,
1006 HighlightStyle {
1007 color: Some(green()),
1008 font_style: Some(FontStyle::Italic),
1009 ..Default::default()
1010 }
1011 ),
1012 (
1013 4..5,
1014 HighlightStyle {
1015 color: Some(green()),
1016 font_weight: Some(FontWeight::BOLD),
1017 font_style: Some(FontStyle::Italic),
1018 ..Default::default()
1019 }
1020 ),
1021 (
1022 5..6,
1023 HighlightStyle {
1024 font_weight: Some(FontWeight::BOLD),
1025 font_style: Some(FontStyle::Italic),
1026 ..Default::default()
1027 }
1028 ),
1029 (
1030 6..10,
1031 HighlightStyle {
1032 font_weight: Some(FontWeight::BOLD),
1033 ..Default::default()
1034 }
1035 ),
1036 (
1037 15..20,
1038 HighlightStyle {
1039 color: Some(yellow()),
1040 ..Default::default()
1041 }
1042 ),
1043 (
1044 21..23,
1045 HighlightStyle {
1046 color: Some(red()),
1047 ..Default::default()
1048 }
1049 )
1050 ]
1051 );
1052 }
1053}