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