style.rs

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