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