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