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