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/// How to truncate text that overflows the width of the element
286#[derive(Copy, Clone, Debug, Default, PartialEq, Eq)]
287pub enum Truncate {
288 /// Truncate the text without an ellipsis
289 #[default]
290 Truncate,
291 /// Truncate the text with an ellipsis
292 Ellipsis,
293}
294
295/// The properties that can be used to style text in GPUI
296#[derive(Refineable, Clone, Debug, PartialEq)]
297#[refineable(Debug)]
298pub struct TextStyle {
299 /// The color of the text
300 pub color: Hsla,
301
302 /// The font family to use
303 pub font_family: SharedString,
304
305 /// The font features to use
306 pub font_features: FontFeatures,
307
308 /// The fallback fonts to use
309 pub font_fallbacks: Option<FontFallbacks>,
310
311 /// The font size to use, in pixels or rems.
312 pub font_size: AbsoluteLength,
313
314 /// The line height to use, in pixels or fractions
315 pub line_height: DefiniteLength,
316
317 /// The font weight, e.g. bold
318 pub font_weight: FontWeight,
319
320 /// The font style, e.g. italic
321 pub font_style: FontStyle,
322
323 /// The background color of the text
324 pub background_color: Option<Hsla>,
325
326 /// The underline style of the text
327 pub underline: Option<UnderlineStyle>,
328
329 /// The strikethrough style of the text
330 pub strikethrough: Option<StrikethroughStyle>,
331
332 /// How to handle whitespace in the text
333 pub white_space: WhiteSpace,
334
335 /// The text should be truncated if it overflows the width of the element
336 pub truncate: Option<Truncate>,
337}
338
339impl Default for TextStyle {
340 fn default() -> Self {
341 TextStyle {
342 color: black(),
343 // todo(linux) make this configurable or choose better default
344 font_family: if cfg!(target_os = "linux") {
345 "FreeMono".into()
346 } else if cfg!(target_os = "windows") {
347 "Segoe UI".into()
348 } else {
349 "Helvetica".into()
350 },
351 font_features: FontFeatures::default(),
352 font_fallbacks: None,
353 font_size: rems(1.).into(),
354 line_height: phi(),
355 font_weight: FontWeight::default(),
356 font_style: FontStyle::default(),
357 background_color: None,
358 underline: None,
359 strikethrough: None,
360 white_space: WhiteSpace::Normal,
361 truncate: None,
362 }
363 }
364}
365
366impl TextStyle {
367 /// Create a new text style with the given highlighting applied.
368 pub fn highlight(mut self, style: impl Into<HighlightStyle>) -> Self {
369 let style = style.into();
370 if let Some(weight) = style.font_weight {
371 self.font_weight = weight;
372 }
373 if let Some(style) = style.font_style {
374 self.font_style = style;
375 }
376
377 if let Some(color) = style.color {
378 self.color = self.color.blend(color);
379 }
380
381 if let Some(factor) = style.fade_out {
382 self.color.fade_out(factor);
383 }
384
385 if let Some(background_color) = style.background_color {
386 self.background_color = Some(background_color);
387 }
388
389 if let Some(underline) = style.underline {
390 self.underline = Some(underline);
391 }
392
393 if let Some(strikethrough) = style.strikethrough {
394 self.strikethrough = Some(strikethrough);
395 }
396
397 self
398 }
399
400 /// Get the font configured for this text style.
401 pub fn font(&self) -> Font {
402 Font {
403 family: self.font_family.clone(),
404 features: self.font_features.clone(),
405 fallbacks: self.font_fallbacks.clone(),
406 weight: self.font_weight,
407 style: self.font_style,
408 }
409 }
410
411 /// Returns the rounded line height in pixels.
412 pub fn line_height_in_pixels(&self, rem_size: Pixels) -> Pixels {
413 self.line_height.to_pixels(self.font_size, rem_size).round()
414 }
415
416 /// Convert this text style into a [`TextRun`], for the given length of the text.
417 pub fn to_run(&self, len: usize) -> TextRun {
418 TextRun {
419 len,
420 font: Font {
421 family: self.font_family.clone(),
422 features: Default::default(),
423 fallbacks: self.font_fallbacks.clone(),
424 weight: self.font_weight,
425 style: self.font_style,
426 },
427 color: self.color,
428 background_color: self.background_color,
429 underline: self.underline,
430 strikethrough: self.strikethrough,
431 }
432 }
433}
434
435/// A highlight style to apply, similar to a `TextStyle` except
436/// for a single font, uniformly sized and spaced text.
437#[derive(Copy, Clone, Debug, Default, PartialEq)]
438pub struct HighlightStyle {
439 /// The color of the text
440 pub color: Option<Hsla>,
441
442 /// The font weight, e.g. bold
443 pub font_weight: Option<FontWeight>,
444
445 /// The font style, e.g. italic
446 pub font_style: Option<FontStyle>,
447
448 /// The background color of the text
449 pub background_color: Option<Hsla>,
450
451 /// The underline style of the text
452 pub underline: Option<UnderlineStyle>,
453
454 /// The underline style of the text
455 pub strikethrough: Option<StrikethroughStyle>,
456
457 /// Similar to the CSS `opacity` property, this will cause the text to be less vibrant.
458 pub fade_out: Option<f32>,
459}
460
461impl Eq for HighlightStyle {}
462
463impl Hash for HighlightStyle {
464 fn hash<H: Hasher>(&self, state: &mut H) {
465 self.color.hash(state);
466 self.font_weight.hash(state);
467 self.font_style.hash(state);
468 self.background_color.hash(state);
469 self.underline.hash(state);
470 self.strikethrough.hash(state);
471 state.write_u32(u32::from_be_bytes(
472 self.fade_out.map(|f| f.to_be_bytes()).unwrap_or_default(),
473 ));
474 }
475}
476
477impl Style {
478 /// Returns true if the style is visible and the background is opaque.
479 pub fn has_opaque_background(&self) -> bool {
480 self.background
481 .as_ref()
482 .is_some_and(|fill| fill.color().is_some_and(|color| !color.is_transparent()))
483 }
484
485 /// Get the text style in this element style.
486 pub fn text_style(&self) -> Option<&TextStyleRefinement> {
487 if self.text.is_some() {
488 Some(&self.text)
489 } else {
490 None
491 }
492 }
493
494 /// Get the content mask for this element style, based on the given bounds.
495 /// If the element does not hide its overflow, this will return `None`.
496 pub fn overflow_mask(
497 &self,
498 bounds: Bounds<Pixels>,
499 rem_size: Pixels,
500 ) -> Option<ContentMask<Pixels>> {
501 match self.overflow {
502 Point {
503 x: Overflow::Visible,
504 y: Overflow::Visible,
505 } => None,
506 _ => {
507 let mut min = bounds.origin;
508 let mut max = bounds.lower_right();
509
510 if self
511 .border_color
512 .map_or(false, |color| !color.is_transparent())
513 {
514 min.x += self.border_widths.left.to_pixels(rem_size);
515 max.x -= self.border_widths.right.to_pixels(rem_size);
516 min.y += self.border_widths.top.to_pixels(rem_size);
517 max.y -= self.border_widths.bottom.to_pixels(rem_size);
518 }
519
520 let bounds = match (
521 self.overflow.x == Overflow::Visible,
522 self.overflow.y == Overflow::Visible,
523 ) {
524 // x and y both visible
525 (true, true) => return None,
526 // x visible, y hidden
527 (true, false) => Bounds::from_corners(
528 point(min.x, bounds.origin.y),
529 point(max.x, bounds.lower_right().y),
530 ),
531 // x hidden, y visible
532 (false, true) => Bounds::from_corners(
533 point(bounds.origin.x, min.y),
534 point(bounds.lower_right().x, max.y),
535 ),
536 // both hidden
537 (false, false) => Bounds::from_corners(min, max),
538 };
539
540 Some(ContentMask { bounds })
541 }
542 }
543 }
544
545 /// Paints the background of an element styled with this style.
546 pub fn paint(
547 &self,
548 bounds: Bounds<Pixels>,
549 cx: &mut WindowContext,
550 continuation: impl FnOnce(&mut WindowContext),
551 ) {
552 #[cfg(debug_assertions)]
553 if self.debug_below {
554 cx.set_global(DebugBelow)
555 }
556
557 #[cfg(debug_assertions)]
558 if self.debug || cx.has_global::<DebugBelow>() {
559 cx.paint_quad(crate::outline(bounds, crate::red()));
560 }
561
562 let rem_size = cx.rem_size();
563
564 cx.paint_shadows(
565 bounds,
566 self.corner_radii.to_pixels(bounds.size, rem_size),
567 &self.box_shadow,
568 );
569
570 let background_color = self.background.as_ref().and_then(Fill::color);
571 if background_color.map_or(false, |color| !color.is_transparent()) {
572 let mut border_color = background_color.unwrap_or_default();
573 border_color.a = 0.;
574 cx.paint_quad(quad(
575 bounds,
576 self.corner_radii.to_pixels(bounds.size, rem_size),
577 background_color.unwrap_or_default(),
578 Edges::default(),
579 border_color,
580 ));
581 }
582
583 continuation(cx);
584
585 if self.is_border_visible() {
586 let corner_radii = self.corner_radii.to_pixels(bounds.size, rem_size);
587 let border_widths = self.border_widths.to_pixels(rem_size);
588 let max_border_width = border_widths.max();
589 let max_corner_radius = corner_radii.max();
590
591 let top_bounds = Bounds::from_corners(
592 bounds.origin,
593 bounds.upper_right() + point(Pixels::ZERO, max_border_width.max(max_corner_radius)),
594 );
595 let bottom_bounds = Bounds::from_corners(
596 bounds.lower_left() - point(Pixels::ZERO, max_border_width.max(max_corner_radius)),
597 bounds.lower_right(),
598 );
599 let left_bounds = Bounds::from_corners(
600 top_bounds.lower_left(),
601 bottom_bounds.origin + point(max_border_width, Pixels::ZERO),
602 );
603 let right_bounds = Bounds::from_corners(
604 top_bounds.lower_right() - point(max_border_width, Pixels::ZERO),
605 bottom_bounds.upper_right(),
606 );
607
608 let mut background = self.border_color.unwrap_or_default();
609 background.a = 0.;
610 let quad = quad(
611 bounds,
612 corner_radii,
613 background,
614 border_widths,
615 self.border_color.unwrap_or_default(),
616 );
617
618 cx.with_content_mask(Some(ContentMask { bounds: top_bounds }), |cx| {
619 cx.paint_quad(quad.clone());
620 });
621 cx.with_content_mask(
622 Some(ContentMask {
623 bounds: right_bounds,
624 }),
625 |cx| {
626 cx.paint_quad(quad.clone());
627 },
628 );
629 cx.with_content_mask(
630 Some(ContentMask {
631 bounds: bottom_bounds,
632 }),
633 |cx| {
634 cx.paint_quad(quad.clone());
635 },
636 );
637 cx.with_content_mask(
638 Some(ContentMask {
639 bounds: left_bounds,
640 }),
641 |cx| {
642 cx.paint_quad(quad);
643 },
644 );
645 }
646
647 #[cfg(debug_assertions)]
648 if self.debug_below {
649 cx.remove_global::<DebugBelow>();
650 }
651 }
652
653 fn is_border_visible(&self) -> bool {
654 self.border_color
655 .map_or(false, |color| !color.is_transparent())
656 && self.border_widths.any(|length| !length.is_zero())
657 }
658}
659
660impl Default for Style {
661 fn default() -> Self {
662 Style {
663 display: Display::Block,
664 visibility: Visibility::Visible,
665 overflow: Point {
666 x: Overflow::Visible,
667 y: Overflow::Visible,
668 },
669 scrollbar_width: 0.0,
670 position: Position::Relative,
671 inset: Edges::auto(),
672 margin: Edges::<Length>::zero(),
673 padding: Edges::<DefiniteLength>::zero(),
674 border_widths: Edges::<AbsoluteLength>::zero(),
675 size: Size::auto(),
676 min_size: Size::auto(),
677 max_size: Size::auto(),
678 aspect_ratio: None,
679 gap: Size::default(),
680 // Alignment
681 align_items: None,
682 align_self: None,
683 align_content: None,
684 justify_content: None,
685 // Flexbox
686 flex_direction: FlexDirection::Row,
687 flex_wrap: FlexWrap::NoWrap,
688 flex_grow: 0.0,
689 flex_shrink: 1.0,
690 flex_basis: Length::Auto,
691 background: None,
692 border_color: None,
693 corner_radii: Corners::default(),
694 box_shadow: Default::default(),
695 text: TextStyleRefinement::default(),
696 mouse_cursor: None,
697
698 #[cfg(debug_assertions)]
699 debug: false,
700 #[cfg(debug_assertions)]
701 debug_below: false,
702 }
703 }
704}
705
706/// The properties that can be applied to an underline.
707#[derive(Refineable, Copy, Clone, Default, Debug, PartialEq, Eq, Hash)]
708#[refineable(Debug)]
709pub struct UnderlineStyle {
710 /// The thickness of the underline.
711 pub thickness: Pixels,
712
713 /// The color of the underline.
714 pub color: Option<Hsla>,
715
716 /// Whether the underline should be wavy, like in a spell checker.
717 pub wavy: bool,
718}
719
720/// The properties that can be applied to a strikethrough.
721#[derive(Refineable, Copy, Clone, Default, Debug, PartialEq, Eq, Hash)]
722#[refineable(Debug)]
723pub struct StrikethroughStyle {
724 /// The thickness of the strikethrough.
725 pub thickness: Pixels,
726
727 /// The color of the strikethrough.
728 pub color: Option<Hsla>,
729}
730
731/// The kinds of fill that can be applied to a shape.
732#[derive(Clone, Debug)]
733pub enum Fill {
734 /// A solid color fill.
735 Color(Hsla),
736}
737
738impl Fill {
739 /// Unwrap this fill into a solid color, if it is one.
740 pub fn color(&self) -> Option<Hsla> {
741 match self {
742 Fill::Color(color) => Some(*color),
743 }
744 }
745}
746
747impl Default for Fill {
748 fn default() -> Self {
749 Self::Color(Hsla::default())
750 }
751}
752
753impl From<Hsla> for Fill {
754 fn from(color: Hsla) -> Self {
755 Self::Color(color)
756 }
757}
758
759impl From<Rgba> for Fill {
760 fn from(color: Rgba) -> Self {
761 Self::Color(color.into())
762 }
763}
764
765impl From<TextStyle> for HighlightStyle {
766 fn from(other: TextStyle) -> Self {
767 Self::from(&other)
768 }
769}
770
771impl From<&TextStyle> for HighlightStyle {
772 fn from(other: &TextStyle) -> Self {
773 Self {
774 color: Some(other.color),
775 font_weight: Some(other.font_weight),
776 font_style: Some(other.font_style),
777 background_color: other.background_color,
778 underline: other.underline,
779 strikethrough: other.strikethrough,
780 fade_out: None,
781 }
782 }
783}
784
785impl HighlightStyle {
786 /// Create a highlight style with just a color
787 pub fn color(color: Hsla) -> Self {
788 Self {
789 color: Some(color),
790 ..Default::default()
791 }
792 }
793 /// Blend this highlight style with another.
794 /// Non-continuous properties, like font_weight and font_style, are overwritten.
795 pub fn highlight(&mut self, other: HighlightStyle) {
796 match (self.color, other.color) {
797 (Some(self_color), Some(other_color)) => {
798 self.color = Some(Hsla::blend(other_color, self_color));
799 }
800 (None, Some(other_color)) => {
801 self.color = Some(other_color);
802 }
803 _ => {}
804 }
805
806 if other.font_weight.is_some() {
807 self.font_weight = other.font_weight;
808 }
809
810 if other.font_style.is_some() {
811 self.font_style = other.font_style;
812 }
813
814 if other.background_color.is_some() {
815 self.background_color = other.background_color;
816 }
817
818 if other.underline.is_some() {
819 self.underline = other.underline;
820 }
821
822 if other.strikethrough.is_some() {
823 self.strikethrough = other.strikethrough;
824 }
825
826 match (other.fade_out, self.fade_out) {
827 (Some(source_fade), None) => self.fade_out = Some(source_fade),
828 (Some(source_fade), Some(dest_fade)) => {
829 self.fade_out = Some((dest_fade * (1. + source_fade)).clamp(0., 1.));
830 }
831 _ => {}
832 }
833 }
834}
835
836impl From<Hsla> for HighlightStyle {
837 fn from(color: Hsla) -> Self {
838 Self {
839 color: Some(color),
840 ..Default::default()
841 }
842 }
843}
844
845impl From<FontWeight> for HighlightStyle {
846 fn from(font_weight: FontWeight) -> Self {
847 Self {
848 font_weight: Some(font_weight),
849 ..Default::default()
850 }
851 }
852}
853
854impl From<FontStyle> for HighlightStyle {
855 fn from(font_style: FontStyle) -> Self {
856 Self {
857 font_style: Some(font_style),
858 ..Default::default()
859 }
860 }
861}
862
863impl From<Rgba> for HighlightStyle {
864 fn from(color: Rgba) -> Self {
865 Self {
866 color: Some(color.into()),
867 ..Default::default()
868 }
869 }
870}
871
872/// Combine and merge the highlights and ranges in the two iterators.
873pub fn combine_highlights(
874 a: impl IntoIterator<Item = (Range<usize>, HighlightStyle)>,
875 b: impl IntoIterator<Item = (Range<usize>, HighlightStyle)>,
876) -> impl Iterator<Item = (Range<usize>, HighlightStyle)> {
877 let mut endpoints = Vec::new();
878 let mut highlights = Vec::new();
879 for (range, highlight) in a.into_iter().chain(b) {
880 if !range.is_empty() {
881 let highlight_id = highlights.len();
882 endpoints.push((range.start, highlight_id, true));
883 endpoints.push((range.end, highlight_id, false));
884 highlights.push(highlight);
885 }
886 }
887 endpoints.sort_unstable_by_key(|(position, _, _)| *position);
888 let mut endpoints = endpoints.into_iter().peekable();
889
890 let mut active_styles = HashSet::default();
891 let mut ix = 0;
892 iter::from_fn(move || {
893 while let Some((endpoint_ix, highlight_id, is_start)) = endpoints.peek() {
894 let prev_index = mem::replace(&mut ix, *endpoint_ix);
895 if ix > prev_index && !active_styles.is_empty() {
896 let mut current_style = HighlightStyle::default();
897 for highlight_id in &active_styles {
898 current_style.highlight(highlights[*highlight_id]);
899 }
900 return Some((prev_index..ix, current_style));
901 }
902
903 if *is_start {
904 active_styles.insert(*highlight_id);
905 } else {
906 active_styles.remove(highlight_id);
907 }
908 endpoints.next();
909 }
910 None
911 })
912}
913
914#[cfg(test)]
915mod tests {
916 use crate::{blue, green, red, yellow};
917
918 use super::*;
919
920 #[test]
921 fn test_combine_highlights() {
922 assert_eq!(
923 combine_highlights(
924 [
925 (0..5, green().into()),
926 (4..10, FontWeight::BOLD.into()),
927 (15..20, yellow().into()),
928 ],
929 [
930 (2..6, FontStyle::Italic.into()),
931 (1..3, blue().into()),
932 (21..23, red().into()),
933 ]
934 )
935 .collect::<Vec<_>>(),
936 [
937 (
938 0..1,
939 HighlightStyle {
940 color: Some(green()),
941 ..Default::default()
942 }
943 ),
944 (
945 1..2,
946 HighlightStyle {
947 color: Some(green()),
948 ..Default::default()
949 }
950 ),
951 (
952 2..3,
953 HighlightStyle {
954 color: Some(green()),
955 font_style: Some(FontStyle::Italic),
956 ..Default::default()
957 }
958 ),
959 (
960 3..4,
961 HighlightStyle {
962 color: Some(green()),
963 font_style: Some(FontStyle::Italic),
964 ..Default::default()
965 }
966 ),
967 (
968 4..5,
969 HighlightStyle {
970 color: Some(green()),
971 font_weight: Some(FontWeight::BOLD),
972 font_style: Some(FontStyle::Italic),
973 ..Default::default()
974 }
975 ),
976 (
977 5..6,
978 HighlightStyle {
979 font_weight: Some(FontWeight::BOLD),
980 font_style: Some(FontStyle::Italic),
981 ..Default::default()
982 }
983 ),
984 (
985 6..10,
986 HighlightStyle {
987 font_weight: Some(FontWeight::BOLD),
988 ..Default::default()
989 }
990 ),
991 (
992 15..20,
993 HighlightStyle {
994 color: Some(yellow()),
995 ..Default::default()
996 }
997 ),
998 (
999 21..23,
1000 HighlightStyle {
1001 color: Some(red()),
1002 ..Default::default()
1003 }
1004 )
1005 ]
1006 );
1007 }
1008}