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