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