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, 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
 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, PartialEq, Eq)]
 291pub enum TextOverflow {
 292    /// Truncate the text with an ellipsis, same as: `text-overflow: ellipsis;` in CSS
 293    Ellipsis(&'static str),
 294}
 295
 296/// The properties that can be used to style text in GPUI
 297#[derive(Refineable, Clone, Debug, PartialEq)]
 298#[refineable(Debug)]
 299pub struct TextStyle {
 300    /// The color of the text
 301    pub color: Hsla,
 302
 303    /// The font family to use
 304    pub font_family: SharedString,
 305
 306    /// The font features to use
 307    pub font_features: FontFeatures,
 308
 309    /// The fallback fonts to use
 310    pub font_fallbacks: Option<FontFallbacks>,
 311
 312    /// The font size to use, in pixels or rems.
 313    pub font_size: AbsoluteLength,
 314
 315    /// The line height to use, in pixels or fractions
 316    pub line_height: DefiniteLength,
 317
 318    /// The font weight, e.g. bold
 319    pub font_weight: FontWeight,
 320
 321    /// The font style, e.g. italic
 322    pub font_style: FontStyle,
 323
 324    /// The background color of the text
 325    pub background_color: Option<Hsla>,
 326
 327    /// The underline style of the text
 328    pub underline: Option<UnderlineStyle>,
 329
 330    /// The strikethrough style of the text
 331    pub strikethrough: Option<StrikethroughStyle>,
 332
 333    /// How to handle whitespace in the text
 334    pub white_space: WhiteSpace,
 335
 336    /// The text should be truncated if it overflows the width of the element
 337    pub text_overflow: Option<TextOverflow>,
 338    /// The number of lines to display before truncating the text
 339    pub line_clamp: Option<usize>,
 340}
 341
 342impl Default for TextStyle {
 343    fn default() -> Self {
 344        TextStyle {
 345            color: black(),
 346            // todo(linux) make this configurable or choose better default
 347            font_family: if cfg!(any(target_os = "linux", target_os = "freebsd")) {
 348                "FreeMono".into()
 349            } else if cfg!(target_os = "windows") {
 350                "Segoe UI".into()
 351            } else {
 352                "Helvetica".into()
 353            },
 354            font_features: FontFeatures::default(),
 355            font_fallbacks: None,
 356            font_size: rems(1.).into(),
 357            line_height: phi(),
 358            font_weight: FontWeight::default(),
 359            font_style: FontStyle::default(),
 360            background_color: None,
 361            underline: None,
 362            strikethrough: None,
 363            white_space: WhiteSpace::Normal,
 364            text_overflow: None,
 365            line_clamp: 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        window: &mut Window,
 554        cx: &mut App,
 555        continuation: impl FnOnce(&mut Window, &mut App),
 556    ) {
 557        #[cfg(debug_assertions)]
 558        if self.debug_below {
 559            cx.set_global(DebugBelow)
 560        }
 561
 562        #[cfg(debug_assertions)]
 563        if self.debug || cx.has_global::<DebugBelow>() {
 564            window.paint_quad(crate::outline(bounds, crate::red()));
 565        }
 566
 567        let rem_size = window.rem_size();
 568
 569        window.paint_shadows(
 570            bounds,
 571            self.corner_radii.to_pixels(bounds.size, rem_size),
 572            &self.box_shadow,
 573        );
 574
 575        let background_color = self.background.as_ref().and_then(Fill::color);
 576        if background_color.map_or(false, |color| !color.is_transparent()) {
 577            let mut border_color = match background_color {
 578                Some(color) => match color.tag {
 579                    BackgroundTag::Solid => color.solid,
 580                    BackgroundTag::LinearGradient => color
 581                        .colors
 582                        .first()
 583                        .map(|stop| stop.color)
 584                        .unwrap_or_default(),
 585                    BackgroundTag::PatternSlash => color.solid,
 586                },
 587                None => Hsla::default(),
 588            };
 589            border_color.a = 0.;
 590            window.paint_quad(quad(
 591                bounds,
 592                self.corner_radii.to_pixels(bounds.size, rem_size),
 593                background_color.unwrap_or_default(),
 594                Edges::default(),
 595                border_color,
 596            ));
 597        }
 598
 599        continuation(window, cx);
 600
 601        if self.is_border_visible() {
 602            let corner_radii = self.corner_radii.to_pixels(bounds.size, rem_size);
 603            let border_widths = self.border_widths.to_pixels(rem_size);
 604            let max_border_width = border_widths.max();
 605            let max_corner_radius = corner_radii.max();
 606
 607            let top_bounds = Bounds::from_corners(
 608                bounds.origin,
 609                bounds.top_right() + point(Pixels::ZERO, max_border_width.max(max_corner_radius)),
 610            );
 611            let bottom_bounds = Bounds::from_corners(
 612                bounds.bottom_left() - point(Pixels::ZERO, max_border_width.max(max_corner_radius)),
 613                bounds.bottom_right(),
 614            );
 615            let left_bounds = Bounds::from_corners(
 616                top_bounds.bottom_left(),
 617                bottom_bounds.origin + point(max_border_width, Pixels::ZERO),
 618            );
 619            let right_bounds = Bounds::from_corners(
 620                top_bounds.bottom_right() - point(max_border_width, Pixels::ZERO),
 621                bottom_bounds.top_right(),
 622            );
 623
 624            let mut background = self.border_color.unwrap_or_default();
 625            background.a = 0.;
 626            let quad = quad(
 627                bounds,
 628                corner_radii,
 629                background,
 630                border_widths,
 631                self.border_color.unwrap_or_default(),
 632            );
 633
 634            window.with_content_mask(Some(ContentMask { bounds: top_bounds }), |window| {
 635                window.paint_quad(quad.clone());
 636            });
 637            window.with_content_mask(
 638                Some(ContentMask {
 639                    bounds: right_bounds,
 640                }),
 641                |window| {
 642                    window.paint_quad(quad.clone());
 643                },
 644            );
 645            window.with_content_mask(
 646                Some(ContentMask {
 647                    bounds: bottom_bounds,
 648                }),
 649                |window| {
 650                    window.paint_quad(quad.clone());
 651                },
 652            );
 653            window.with_content_mask(
 654                Some(ContentMask {
 655                    bounds: left_bounds,
 656                }),
 657                |window| {
 658                    window.paint_quad(quad);
 659                },
 660            );
 661        }
 662
 663        #[cfg(debug_assertions)]
 664        if self.debug_below {
 665            cx.remove_global::<DebugBelow>();
 666        }
 667    }
 668
 669    fn is_border_visible(&self) -> bool {
 670        self.border_color
 671            .map_or(false, |color| !color.is_transparent())
 672            && self.border_widths.any(|length| !length.is_zero())
 673    }
 674}
 675
 676impl Default for Style {
 677    fn default() -> Self {
 678        Style {
 679            display: Display::Block,
 680            visibility: Visibility::Visible,
 681            overflow: Point {
 682                x: Overflow::Visible,
 683                y: Overflow::Visible,
 684            },
 685            allow_concurrent_scroll: false,
 686            scrollbar_width: 0.0,
 687            position: Position::Relative,
 688            inset: Edges::auto(),
 689            margin: Edges::<Length>::zero(),
 690            padding: Edges::<DefiniteLength>::zero(),
 691            border_widths: Edges::<AbsoluteLength>::zero(),
 692            size: Size::auto(),
 693            min_size: Size::auto(),
 694            max_size: Size::auto(),
 695            aspect_ratio: None,
 696            gap: Size::default(),
 697            // Alignment
 698            align_items: None,
 699            align_self: None,
 700            align_content: None,
 701            justify_content: None,
 702            // Flexbox
 703            flex_direction: FlexDirection::Row,
 704            flex_wrap: FlexWrap::NoWrap,
 705            flex_grow: 0.0,
 706            flex_shrink: 1.0,
 707            flex_basis: Length::Auto,
 708            background: None,
 709            border_color: None,
 710            corner_radii: Corners::default(),
 711            box_shadow: Default::default(),
 712            text: TextStyleRefinement::default(),
 713            mouse_cursor: None,
 714            opacity: None,
 715
 716            #[cfg(debug_assertions)]
 717            debug: false,
 718            #[cfg(debug_assertions)]
 719            debug_below: false,
 720        }
 721    }
 722}
 723
 724/// The properties that can be applied to an underline.
 725#[derive(Refineable, Copy, Clone, Default, Debug, PartialEq, Eq, Hash)]
 726#[refineable(Debug)]
 727pub struct UnderlineStyle {
 728    /// The thickness of the underline.
 729    pub thickness: Pixels,
 730
 731    /// The color of the underline.
 732    pub color: Option<Hsla>,
 733
 734    /// Whether the underline should be wavy, like in a spell checker.
 735    pub wavy: bool,
 736}
 737
 738/// The properties that can be applied to a strikethrough.
 739#[derive(Refineable, Copy, Clone, Default, Debug, PartialEq, Eq, Hash)]
 740#[refineable(Debug)]
 741pub struct StrikethroughStyle {
 742    /// The thickness of the strikethrough.
 743    pub thickness: Pixels,
 744
 745    /// The color of the strikethrough.
 746    pub color: Option<Hsla>,
 747}
 748
 749/// The kinds of fill that can be applied to a shape.
 750#[derive(Clone, Debug)]
 751pub enum Fill {
 752    /// A solid color fill.
 753    Color(Background),
 754}
 755
 756impl Fill {
 757    /// Unwrap this fill into a solid color, if it is one.
 758    ///
 759    /// If the fill is not a solid color, this method returns `None`.
 760    pub fn color(&self) -> Option<Background> {
 761        match self {
 762            Fill::Color(color) => Some(*color),
 763        }
 764    }
 765}
 766
 767impl Default for Fill {
 768    fn default() -> Self {
 769        Self::Color(Background::default())
 770    }
 771}
 772
 773impl From<Hsla> for Fill {
 774    fn from(color: Hsla) -> Self {
 775        Self::Color(color.into())
 776    }
 777}
 778
 779impl From<Rgba> for Fill {
 780    fn from(color: Rgba) -> Self {
 781        Self::Color(color.into())
 782    }
 783}
 784
 785impl From<Background> for Fill {
 786    fn from(background: Background) -> Self {
 787        Self::Color(background)
 788    }
 789}
 790
 791impl From<TextStyle> for HighlightStyle {
 792    fn from(other: TextStyle) -> Self {
 793        Self::from(&other)
 794    }
 795}
 796
 797impl From<&TextStyle> for HighlightStyle {
 798    fn from(other: &TextStyle) -> Self {
 799        Self {
 800            color: Some(other.color),
 801            font_weight: Some(other.font_weight),
 802            font_style: Some(other.font_style),
 803            background_color: other.background_color,
 804            underline: other.underline,
 805            strikethrough: other.strikethrough,
 806            fade_out: None,
 807        }
 808    }
 809}
 810
 811impl HighlightStyle {
 812    /// Create a highlight style with just a color
 813    pub fn color(color: Hsla) -> Self {
 814        Self {
 815            color: Some(color),
 816            ..Default::default()
 817        }
 818    }
 819    /// Blend this highlight style with another.
 820    /// Non-continuous properties, like font_weight and font_style, are overwritten.
 821    pub fn highlight(&mut self, other: HighlightStyle) {
 822        match (self.color, other.color) {
 823            (Some(self_color), Some(other_color)) => {
 824                self.color = Some(Hsla::blend(other_color, self_color));
 825            }
 826            (None, Some(other_color)) => {
 827                self.color = Some(other_color);
 828            }
 829            _ => {}
 830        }
 831
 832        if other.font_weight.is_some() {
 833            self.font_weight = other.font_weight;
 834        }
 835
 836        if other.font_style.is_some() {
 837            self.font_style = other.font_style;
 838        }
 839
 840        if other.background_color.is_some() {
 841            self.background_color = other.background_color;
 842        }
 843
 844        if other.underline.is_some() {
 845            self.underline = other.underline;
 846        }
 847
 848        if other.strikethrough.is_some() {
 849            self.strikethrough = other.strikethrough;
 850        }
 851
 852        match (other.fade_out, self.fade_out) {
 853            (Some(source_fade), None) => self.fade_out = Some(source_fade),
 854            (Some(source_fade), Some(dest_fade)) => {
 855                self.fade_out = Some((dest_fade * (1. + source_fade)).clamp(0., 1.));
 856            }
 857            _ => {}
 858        }
 859    }
 860}
 861
 862impl From<Hsla> for HighlightStyle {
 863    fn from(color: Hsla) -> Self {
 864        Self {
 865            color: Some(color),
 866            ..Default::default()
 867        }
 868    }
 869}
 870
 871impl From<FontWeight> for HighlightStyle {
 872    fn from(font_weight: FontWeight) -> Self {
 873        Self {
 874            font_weight: Some(font_weight),
 875            ..Default::default()
 876        }
 877    }
 878}
 879
 880impl From<FontStyle> for HighlightStyle {
 881    fn from(font_style: FontStyle) -> Self {
 882        Self {
 883            font_style: Some(font_style),
 884            ..Default::default()
 885        }
 886    }
 887}
 888
 889impl From<Rgba> for HighlightStyle {
 890    fn from(color: Rgba) -> Self {
 891        Self {
 892            color: Some(color.into()),
 893            ..Default::default()
 894        }
 895    }
 896}
 897
 898/// Combine and merge the highlights and ranges in the two iterators.
 899pub fn combine_highlights(
 900    a: impl IntoIterator<Item = (Range<usize>, HighlightStyle)>,
 901    b: impl IntoIterator<Item = (Range<usize>, HighlightStyle)>,
 902) -> impl Iterator<Item = (Range<usize>, HighlightStyle)> {
 903    let mut endpoints = Vec::new();
 904    let mut highlights = Vec::new();
 905    for (range, highlight) in a.into_iter().chain(b) {
 906        if !range.is_empty() {
 907            let highlight_id = highlights.len();
 908            endpoints.push((range.start, highlight_id, true));
 909            endpoints.push((range.end, highlight_id, false));
 910            highlights.push(highlight);
 911        }
 912    }
 913    endpoints.sort_unstable_by_key(|(position, _, _)| *position);
 914    let mut endpoints = endpoints.into_iter().peekable();
 915
 916    let mut active_styles = HashSet::default();
 917    let mut ix = 0;
 918    iter::from_fn(move || {
 919        while let Some((endpoint_ix, highlight_id, is_start)) = endpoints.peek() {
 920            let prev_index = mem::replace(&mut ix, *endpoint_ix);
 921            if ix > prev_index && !active_styles.is_empty() {
 922                let mut current_style = HighlightStyle::default();
 923                for highlight_id in &active_styles {
 924                    current_style.highlight(highlights[*highlight_id]);
 925                }
 926                return Some((prev_index..ix, current_style));
 927            }
 928
 929            if *is_start {
 930                active_styles.insert(*highlight_id);
 931            } else {
 932                active_styles.remove(highlight_id);
 933            }
 934            endpoints.next();
 935        }
 936        None
 937    })
 938}
 939
 940#[cfg(test)]
 941mod tests {
 942    use crate::{blue, green, red, yellow};
 943
 944    use super::*;
 945
 946    #[test]
 947    fn test_combine_highlights() {
 948        assert_eq!(
 949            combine_highlights(
 950                [
 951                    (0..5, green().into()),
 952                    (4..10, FontWeight::BOLD.into()),
 953                    (15..20, yellow().into()),
 954                ],
 955                [
 956                    (2..6, FontStyle::Italic.into()),
 957                    (1..3, blue().into()),
 958                    (21..23, red().into()),
 959                ]
 960            )
 961            .collect::<Vec<_>>(),
 962            [
 963                (
 964                    0..1,
 965                    HighlightStyle {
 966                        color: Some(green()),
 967                        ..Default::default()
 968                    }
 969                ),
 970                (
 971                    1..2,
 972                    HighlightStyle {
 973                        color: Some(green()),
 974                        ..Default::default()
 975                    }
 976                ),
 977                (
 978                    2..3,
 979                    HighlightStyle {
 980                        color: Some(green()),
 981                        font_style: Some(FontStyle::Italic),
 982                        ..Default::default()
 983                    }
 984                ),
 985                (
 986                    3..4,
 987                    HighlightStyle {
 988                        color: Some(green()),
 989                        font_style: Some(FontStyle::Italic),
 990                        ..Default::default()
 991                    }
 992                ),
 993                (
 994                    4..5,
 995                    HighlightStyle {
 996                        color: Some(green()),
 997                        font_weight: Some(FontWeight::BOLD),
 998                        font_style: Some(FontStyle::Italic),
 999                        ..Default::default()
1000                    }
1001                ),
1002                (
1003                    5..6,
1004                    HighlightStyle {
1005                        font_weight: Some(FontWeight::BOLD),
1006                        font_style: Some(FontStyle::Italic),
1007                        ..Default::default()
1008                    }
1009                ),
1010                (
1011                    6..10,
1012                    HighlightStyle {
1013                        font_weight: Some(FontWeight::BOLD),
1014                        ..Default::default()
1015                    }
1016                ),
1017                (
1018                    15..20,
1019                    HighlightStyle {
1020                        color: Some(yellow()),
1021                        ..Default::default()
1022                    }
1023                ),
1024                (
1025                    21..23,
1026                    HighlightStyle {
1027                        color: Some(red()),
1028                        ..Default::default()
1029                    }
1030                )
1031            ]
1032        );
1033    }
1034}