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