geometry.rs

   1//! The GPUI geometry module is a collection of types and traits that
   2//! can be used to describe common units, concepts, and the relationships
   3//! between them.
   4
   5use core::fmt::Debug;
   6use derive_more::{Add, AddAssign, Div, DivAssign, Mul, Neg, Sub, SubAssign};
   7use refineable::Refineable;
   8use serde_derive::{Deserialize, Serialize};
   9use std::{
  10    cmp::{self, PartialOrd},
  11    fmt,
  12    hash::Hash,
  13    ops::{Add, Div, Mul, MulAssign, Sub},
  14};
  15
  16use crate::{AppContext, DisplayId};
  17
  18/// Axis in a 2D cartesian space.
  19#[derive(Copy, Clone, PartialEq, Eq, Serialize, Deserialize, Debug)]
  20pub enum Axis {
  21    /// The y axis, or up and down
  22    Vertical,
  23    /// The x axis, or left and right
  24    Horizontal,
  25}
  26
  27impl Axis {
  28    /// Swap this axis to the opposite axis.
  29    pub fn invert(self) -> Self {
  30        match self {
  31            Axis::Vertical => Axis::Horizontal,
  32            Axis::Horizontal => Axis::Vertical,
  33        }
  34    }
  35}
  36
  37/// A trait for accessing the given unit along a certain axis.
  38pub trait Along {
  39    /// The unit associated with this type
  40    type Unit;
  41
  42    /// Returns the unit along the given axis.
  43    fn along(&self, axis: Axis) -> Self::Unit;
  44
  45    /// Applies the given function to the unit along the given axis and returns a new value.
  46    fn apply_along(&self, axis: Axis, f: impl FnOnce(Self::Unit) -> Self::Unit) -> Self;
  47}
  48
  49/// Describes a location in a 2D cartesian space.
  50///
  51/// It holds two public fields, `x` and `y`, which represent the coordinates in the space.
  52/// The type `T` for the coordinates can be any type that implements `Default`, `Clone`, and `Debug`.
  53///
  54/// # Examples
  55///
  56/// ```
  57/// # use gpui::Point;
  58/// let point = Point { x: 10, y: 20 };
  59/// println!("{:?}", point); // Outputs: Point { x: 10, y: 20 }
  60/// ```
  61#[derive(
  62    Refineable,
  63    Default,
  64    Add,
  65    AddAssign,
  66    Sub,
  67    SubAssign,
  68    Copy,
  69    Debug,
  70    PartialEq,
  71    Eq,
  72    Serialize,
  73    Deserialize,
  74    Hash,
  75)]
  76#[refineable(Debug)]
  77#[repr(C)]
  78pub struct Point<T: Default + Clone + Debug> {
  79    /// The x coordinate of the point.
  80    pub x: T,
  81    /// The y coordinate of the point.
  82    pub y: T,
  83}
  84
  85/// Constructs a new `Point<T>` with the given x and y coordinates.
  86///
  87/// # Arguments
  88///
  89/// * `x` - The x coordinate of the point.
  90/// * `y` - The y coordinate of the point.
  91///
  92/// # Returns
  93///
  94/// Returns a `Point<T>` with the specified coordinates.
  95///
  96/// # Examples
  97///
  98/// ```
  99/// # use gpui::Point;
 100/// let p = point(10, 20);
 101/// assert_eq!(p.x, 10);
 102/// assert_eq!(p.y, 20);
 103/// ```
 104pub const fn point<T: Clone + Debug + Default>(x: T, y: T) -> Point<T> {
 105    Point { x, y }
 106}
 107
 108impl<T: Clone + Debug + Default> Point<T> {
 109    /// Creates a new `Point` with the specified `x` and `y` coordinates.
 110    ///
 111    /// # Arguments
 112    ///
 113    /// * `x` - The horizontal coordinate of the point.
 114    /// * `y` - The vertical coordinate of the point.
 115    ///
 116    /// # Examples
 117    ///
 118    /// ```
 119    /// let p = Point::new(10, 20);
 120    /// assert_eq!(p.x, 10);
 121    /// assert_eq!(p.y, 20);
 122    /// ```
 123    pub const fn new(x: T, y: T) -> Self {
 124        Self { x, y }
 125    }
 126
 127    /// Transforms the point to a `Point<U>` by applying the given function to both coordinates.
 128    ///
 129    /// This method allows for converting a `Point<T>` to a `Point<U>` by specifying a closure
 130    /// that defines how to convert between the two types. The closure is applied to both the `x`
 131    /// and `y` coordinates, resulting in a new point of the desired type.
 132    ///
 133    /// # Arguments
 134    ///
 135    /// * `f` - A closure that takes a value of type `T` and returns a value of type `U`.
 136    ///
 137    /// # Examples
 138    ///
 139    /// ```
 140    /// # use gpui::Point;
 141    /// let p = Point { x: 3, y: 4 };
 142    /// let p_float = p.map(|coord| coord as f32);
 143    /// assert_eq!(p_float, Point { x: 3.0, y: 4.0 });
 144    /// ```
 145    pub fn map<U: Clone + Default + Debug>(&self, f: impl Fn(T) -> U) -> Point<U> {
 146        Point {
 147            x: f(self.x.clone()),
 148            y: f(self.y.clone()),
 149        }
 150    }
 151}
 152
 153impl<T: Clone + Debug + Default> Along for Point<T> {
 154    type Unit = T;
 155
 156    fn along(&self, axis: Axis) -> T {
 157        match axis {
 158            Axis::Horizontal => self.x.clone(),
 159            Axis::Vertical => self.y.clone(),
 160        }
 161    }
 162
 163    fn apply_along(&self, axis: Axis, f: impl FnOnce(T) -> T) -> Point<T> {
 164        match axis {
 165            Axis::Horizontal => Point {
 166                x: f(self.x.clone()),
 167                y: self.y.clone(),
 168            },
 169            Axis::Vertical => Point {
 170                x: self.x.clone(),
 171                y: f(self.y.clone()),
 172            },
 173        }
 174    }
 175}
 176
 177impl<T: Clone + Debug + Default + Negate> Negate for Point<T> {
 178    fn negate(self) -> Self {
 179        self.map(Negate::negate)
 180    }
 181}
 182
 183impl Point<Pixels> {
 184    /// Scales the point by a given factor, which is typically derived from the resolution
 185    /// of a target display to ensure proper sizing of UI elements.
 186    ///
 187    /// # Arguments
 188    ///
 189    /// * `factor` - The scaling factor to apply to both the x and y coordinates.
 190    ///
 191    /// # Examples
 192    ///
 193    /// ```
 194    /// # use gpui::{Point, Pixels, ScaledPixels};
 195    /// let p = Point { x: Pixels(10.0), y: Pixels(20.0) };
 196    /// let scaled_p = p.scale(1.5);
 197    /// assert_eq!(scaled_p, Point { x: ScaledPixels(15.0), y: ScaledPixels(30.0) });
 198    /// ```
 199    pub fn scale(&self, factor: f32) -> Point<ScaledPixels> {
 200        Point {
 201            x: self.x.scale(factor),
 202            y: self.y.scale(factor),
 203        }
 204    }
 205
 206    /// Calculates the Euclidean distance from the origin (0, 0) to this point.
 207    ///
 208    /// # Examples
 209    ///
 210    /// ```
 211    /// # use gpui::{Pixels, Point};
 212    /// let p = Point { x: Pixels(3.0), y: Pixels(4.0) };
 213    /// assert_eq!(p.magnitude(), 5.0);
 214    /// ```
 215    pub fn magnitude(&self) -> f64 {
 216        ((self.x.0.powi(2) + self.y.0.powi(2)) as f64).sqrt()
 217    }
 218}
 219
 220impl<T, Rhs> Mul<Rhs> for Point<T>
 221where
 222    T: Mul<Rhs, Output = T> + Clone + Default + Debug,
 223    Rhs: Clone + Debug,
 224{
 225    type Output = Point<T>;
 226
 227    fn mul(self, rhs: Rhs) -> Self::Output {
 228        Point {
 229            x: self.x * rhs.clone(),
 230            y: self.y * rhs,
 231        }
 232    }
 233}
 234
 235impl<T, S> MulAssign<S> for Point<T>
 236where
 237    T: Clone + Mul<S, Output = T> + Default + Debug,
 238    S: Clone,
 239{
 240    fn mul_assign(&mut self, rhs: S) {
 241        self.x = self.x.clone() * rhs.clone();
 242        self.y = self.y.clone() * rhs;
 243    }
 244}
 245
 246impl<T, S> Div<S> for Point<T>
 247where
 248    T: Div<S, Output = T> + Clone + Default + Debug,
 249    S: Clone,
 250{
 251    type Output = Self;
 252
 253    fn div(self, rhs: S) -> Self::Output {
 254        Self {
 255            x: self.x / rhs.clone(),
 256            y: self.y / rhs,
 257        }
 258    }
 259}
 260
 261impl<T> Point<T>
 262where
 263    T: PartialOrd + Clone + Default + Debug,
 264{
 265    /// Returns a new point with the maximum values of each dimension from `self` and `other`.
 266    ///
 267    /// # Arguments
 268    ///
 269    /// * `other` - A reference to another `Point` to compare with `self`.
 270    ///
 271    /// # Examples
 272    ///
 273    /// ```
 274    /// # use gpui::Point;
 275    /// let p1 = Point { x: 3, y: 7 };
 276    /// let p2 = Point { x: 5, y: 2 };
 277    /// let max_point = p1.max(&p2);
 278    /// assert_eq!(max_point, Point { x: 5, y: 7 });
 279    /// ```
 280    pub fn max(&self, other: &Self) -> Self {
 281        Point {
 282            x: if self.x > other.x {
 283                self.x.clone()
 284            } else {
 285                other.x.clone()
 286            },
 287            y: if self.y > other.y {
 288                self.y.clone()
 289            } else {
 290                other.y.clone()
 291            },
 292        }
 293    }
 294
 295    /// Returns a new point with the minimum values of each dimension from `self` and `other`.
 296    ///
 297    /// # Arguments
 298    ///
 299    /// * `other` - A reference to another `Point` to compare with `self`.
 300    ///
 301    /// # Examples
 302    ///
 303    /// ```
 304    /// # use gpui::Point;
 305    /// let p1 = Point { x: 3, y: 7 };
 306    /// let p2 = Point { x: 5, y: 2 };
 307    /// let min_point = p1.min(&p2);
 308    /// assert_eq!(min_point, Point { x: 3, y: 2 });
 309    /// ```
 310    pub fn min(&self, other: &Self) -> Self {
 311        Point {
 312            x: if self.x <= other.x {
 313                self.x.clone()
 314            } else {
 315                other.x.clone()
 316            },
 317            y: if self.y <= other.y {
 318                self.y.clone()
 319            } else {
 320                other.y.clone()
 321            },
 322        }
 323    }
 324
 325    /// Clamps the point to a specified range.
 326    ///
 327    /// Given a minimum point and a maximum point, this method constrains the current point
 328    /// such that its coordinates do not exceed the range defined by the minimum and maximum points.
 329    /// If the current point's coordinates are less than the minimum, they are set to the minimum.
 330    /// If they are greater than the maximum, they are set to the maximum.
 331    ///
 332    /// # Arguments
 333    ///
 334    /// * `min` - A reference to a `Point` representing the minimum allowable coordinates.
 335    /// * `max` - A reference to a `Point` representing the maximum allowable coordinates.
 336    ///
 337    /// # Examples
 338    ///
 339    /// ```
 340    /// # use gpui::Point;
 341    /// let p = Point { x: 10, y: 20 };
 342    /// let min = Point { x: 0, y: 5 };
 343    /// let max = Point { x: 15, y: 25 };
 344    /// let clamped_p = p.clamp(&min, &max);
 345    /// assert_eq!(clamped_p, Point { x: 10, y: 20 });
 346    ///
 347    /// let p_out_of_bounds = Point { x: -5, y: 30 };
 348    /// let clamped_p_out_of_bounds = p_out_of_bounds.clamp(&min, &max);
 349    /// assert_eq!(clamped_p_out_of_bounds, Point { x: 0, y: 25 });
 350    /// ```
 351    pub fn clamp(&self, min: &Self, max: &Self) -> Self {
 352        self.max(min).min(max)
 353    }
 354}
 355
 356impl<T: Clone + Default + Debug> Clone for Point<T> {
 357    fn clone(&self) -> Self {
 358        Self {
 359            x: self.x.clone(),
 360            y: self.y.clone(),
 361        }
 362    }
 363}
 364
 365/// A structure representing a two-dimensional size with width and height in a given unit.
 366///
 367/// This struct is generic over the type `T`, which can be any type that implements `Clone`, `Default`, and `Debug`.
 368/// It is commonly used to specify dimensions for elements in a UI, such as a window or element.
 369#[derive(Refineable, Default, Clone, Copy, PartialEq, Div, Hash, Serialize, Deserialize)]
 370#[refineable(Debug)]
 371#[repr(C)]
 372pub struct Size<T: Clone + Default + Debug> {
 373    /// The width component of the size.
 374    pub width: T,
 375    /// The height component of the size.
 376    pub height: T,
 377}
 378
 379/// Constructs a new `Size<T>` with the provided width and height.
 380///
 381/// # Arguments
 382///
 383/// * `width` - The width component of the `Size`.
 384/// * `height` - The height component of the `Size`.
 385///
 386/// # Examples
 387///
 388/// ```
 389/// # use gpui::Size;
 390/// let my_size = size(10, 20);
 391/// assert_eq!(my_size.width, 10);
 392/// assert_eq!(my_size.height, 20);
 393/// ```
 394pub const fn size<T>(width: T, height: T) -> Size<T>
 395where
 396    T: Clone + Default + Debug,
 397{
 398    Size { width, height }
 399}
 400
 401impl<T> Size<T>
 402where
 403    T: Clone + Default + Debug,
 404{
 405    /// Applies a function to the width and height of the size, producing a new `Size<U>`.
 406    ///
 407    /// This method allows for converting a `Size<T>` to a `Size<U>` by specifying a closure
 408    /// that defines how to convert between the two types. The closure is applied to both the `width`
 409    /// and `height`, resulting in a new size of the desired type.
 410    ///
 411    /// # Arguments
 412    ///
 413    /// * `f` - A closure that takes a value of type `T` and returns a value of type `U`.
 414    ///
 415    /// # Examples
 416    ///
 417    /// ```
 418    /// # use gpui::Size;
 419    /// let my_size = Size { width: 10, height: 20 };
 420    /// let my_new_size = my_size.map(|dimension| dimension as f32 * 1.5);
 421    /// assert_eq!(my_new_size, Size { width: 15.0, height: 30.0 });
 422    /// ```
 423    pub fn map<U>(&self, f: impl Fn(T) -> U) -> Size<U>
 424    where
 425        U: Clone + Default + Debug,
 426    {
 427        Size {
 428            width: f(self.width.clone()),
 429            height: f(self.height.clone()),
 430        }
 431    }
 432}
 433
 434impl<T> Size<T>
 435where
 436    T: Clone + Default + Debug + Half,
 437{
 438    /// Compute the center point of the size.g
 439    pub fn center(&self) -> Point<T> {
 440        Point {
 441            x: self.width.half(),
 442            y: self.height.half(),
 443        }
 444    }
 445}
 446
 447impl Size<Pixels> {
 448    /// Scales the size by a given factor.
 449    ///
 450    /// This method multiplies both the width and height by the provided scaling factor,
 451    /// resulting in a new `Size<ScaledPixels>` that is proportionally larger or smaller
 452    /// depending on the factor.
 453    ///
 454    /// # Arguments
 455    ///
 456    /// * `factor` - The scaling factor to apply to the width and height.
 457    ///
 458    /// # Examples
 459    ///
 460    /// ```
 461    /// # use gpui::{Size, Pixels, ScaledPixels};
 462    /// let size = Size { width: Pixels(100.0), height: Pixels(50.0) };
 463    /// let scaled_size = size.scale(2.0);
 464    /// assert_eq!(scaled_size, Size { width: ScaledPixels(200.0), height: ScaledPixels(100.0) });
 465    /// ```
 466    pub fn scale(&self, factor: f32) -> Size<ScaledPixels> {
 467        Size {
 468            width: self.width.scale(factor),
 469            height: self.height.scale(factor),
 470        }
 471    }
 472}
 473
 474impl<T> Along for Size<T>
 475where
 476    T: Clone + Default + Debug,
 477{
 478    type Unit = T;
 479
 480    fn along(&self, axis: Axis) -> T {
 481        match axis {
 482            Axis::Horizontal => self.width.clone(),
 483            Axis::Vertical => self.height.clone(),
 484        }
 485    }
 486
 487    /// Returns the value of this size along the given axis.
 488    fn apply_along(&self, axis: Axis, f: impl FnOnce(T) -> T) -> Self {
 489        match axis {
 490            Axis::Horizontal => Size {
 491                width: f(self.width.clone()),
 492                height: self.height.clone(),
 493            },
 494            Axis::Vertical => Size {
 495                width: self.width.clone(),
 496                height: f(self.height.clone()),
 497            },
 498        }
 499    }
 500}
 501
 502impl<T> Size<T>
 503where
 504    T: PartialOrd + Clone + Default + Debug,
 505{
 506    /// Returns a new `Size` with the maximum width and height from `self` and `other`.
 507    ///
 508    /// # Arguments
 509    ///
 510    /// * `other` - A reference to another `Size` to compare with `self`.
 511    ///
 512    /// # Examples
 513    ///
 514    /// ```
 515    /// # use gpui::Size;
 516    /// let size1 = Size { width: 30, height: 40 };
 517    /// let size2 = Size { width: 50, height: 20 };
 518    /// let max_size = size1.max(&size2);
 519    /// assert_eq!(max_size, Size { width: 50, height: 40 });
 520    /// ```
 521    pub fn max(&self, other: &Self) -> Self {
 522        Size {
 523            width: if self.width >= other.width {
 524                self.width.clone()
 525            } else {
 526                other.width.clone()
 527            },
 528            height: if self.height >= other.height {
 529                self.height.clone()
 530            } else {
 531                other.height.clone()
 532            },
 533        }
 534    }
 535
 536    /// Returns a new `Size` with the minimum width and height from `self` and `other`.
 537    ///
 538    /// # Arguments
 539    ///
 540    /// * `other` - A reference to another `Size` to compare with `self`.
 541    ///
 542    /// # Examples
 543    ///
 544    /// ```
 545    /// # use gpui::Size;
 546    /// let size1 = Size { width: 30, height: 40 };
 547    /// let size2 = Size { width: 50, height: 20 };
 548    /// let min_size = size1.min(&size2);
 549    /// assert_eq!(min_size, Size { width: 30, height: 20 });
 550    /// ```
 551    pub fn min(&self, other: &Self) -> Self {
 552        Size {
 553            width: if self.width >= other.width {
 554                other.width.clone()
 555            } else {
 556                self.width.clone()
 557            },
 558            height: if self.height >= other.height {
 559                other.height.clone()
 560            } else {
 561                self.height.clone()
 562            },
 563        }
 564    }
 565}
 566
 567impl<T> Sub for Size<T>
 568where
 569    T: Sub<Output = T> + Clone + Default + Debug,
 570{
 571    type Output = Size<T>;
 572
 573    fn sub(self, rhs: Self) -> Self::Output {
 574        Size {
 575            width: self.width - rhs.width,
 576            height: self.height - rhs.height,
 577        }
 578    }
 579}
 580
 581impl<T> Add for Size<T>
 582where
 583    T: Add<Output = T> + Clone + Default + Debug,
 584{
 585    type Output = Size<T>;
 586
 587    fn add(self, rhs: Self) -> Self::Output {
 588        Size {
 589            width: self.width + rhs.width,
 590            height: self.height + rhs.height,
 591        }
 592    }
 593}
 594
 595impl<T, Rhs> Mul<Rhs> for Size<T>
 596where
 597    T: Mul<Rhs, Output = Rhs> + Clone + Default + Debug,
 598    Rhs: Clone + Default + Debug,
 599{
 600    type Output = Size<Rhs>;
 601
 602    fn mul(self, rhs: Rhs) -> Self::Output {
 603        Size {
 604            width: self.width * rhs.clone(),
 605            height: self.height * rhs,
 606        }
 607    }
 608}
 609
 610impl<T, S> MulAssign<S> for Size<T>
 611where
 612    T: Mul<S, Output = T> + Clone + Default + Debug,
 613    S: Clone,
 614{
 615    fn mul_assign(&mut self, rhs: S) {
 616        self.width = self.width.clone() * rhs.clone();
 617        self.height = self.height.clone() * rhs;
 618    }
 619}
 620
 621impl<T> Eq for Size<T> where T: Eq + Default + Debug + Clone {}
 622
 623impl<T> Debug for Size<T>
 624where
 625    T: Clone + Default + Debug,
 626{
 627    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
 628        write!(f, "Size {{ {:?} × {:?} }}", self.width, self.height)
 629    }
 630}
 631
 632impl<T: Clone + Default + Debug> From<Point<T>> for Size<T> {
 633    fn from(point: Point<T>) -> Self {
 634        Self {
 635            width: point.x,
 636            height: point.y,
 637        }
 638    }
 639}
 640
 641impl From<Size<Pixels>> for Size<DefiniteLength> {
 642    fn from(size: Size<Pixels>) -> Self {
 643        Size {
 644            width: size.width.into(),
 645            height: size.height.into(),
 646        }
 647    }
 648}
 649
 650impl From<Size<Pixels>> for Size<AbsoluteLength> {
 651    fn from(size: Size<Pixels>) -> Self {
 652        Size {
 653            width: size.width.into(),
 654            height: size.height.into(),
 655        }
 656    }
 657}
 658
 659impl Size<Length> {
 660    /// Returns a `Size` with both width and height set to fill the available space.
 661    ///
 662    /// This function creates a `Size` instance where both the width and height are set to `Length::Definite(DefiniteLength::Fraction(1.0))`,
 663    /// which represents 100% of the available space in both dimensions.
 664    ///
 665    /// # Returns
 666    ///
 667    /// A `Size<Length>` that will fill the available space when used in a layout.
 668    pub fn full() -> Self {
 669        Self {
 670            width: relative(1.).into(),
 671            height: relative(1.).into(),
 672        }
 673    }
 674}
 675
 676impl Size<Length> {
 677    /// Returns a `Size` with both width and height set to `auto`, which allows the layout engine to determine the size.
 678    ///
 679    /// This function creates a `Size` instance where both the width and height are set to `Length::Auto`,
 680    /// indicating that their size should be computed based on the layout context, such as the content size or
 681    /// available space.
 682    ///
 683    /// # Returns
 684    ///
 685    /// A `Size<Length>` with width and height set to `Length::Auto`.
 686    pub fn auto() -> Self {
 687        Self {
 688            width: Length::Auto,
 689            height: Length::Auto,
 690        }
 691    }
 692}
 693
 694/// Represents a rectangular area in a 2D space with an origin point and a size.
 695///
 696/// The `Bounds` struct is generic over a type `T` which represents the type of the coordinate system.
 697/// The origin is represented as a `Point<T>` which defines the top left corner of the rectangle,
 698/// and the size is represented as a `Size<T>` which defines the width and height of the rectangle.
 699///
 700/// # Examples
 701///
 702/// ```
 703/// # use gpui::{Bounds, Point, Size};
 704/// let origin = Point { x: 0, y: 0 };
 705/// let size = Size { width: 10, height: 20 };
 706/// let bounds = Bounds::new(origin, size);
 707///
 708/// assert_eq!(bounds.origin, origin);
 709/// assert_eq!(bounds.size, size);
 710/// ```
 711#[derive(Refineable, Clone, Default, Debug, Eq, PartialEq, Serialize, Deserialize, Hash)]
 712#[refineable(Debug)]
 713#[repr(C)]
 714pub struct Bounds<T: Clone + Default + Debug> {
 715    /// The origin point of this area.
 716    pub origin: Point<T>,
 717    /// The size of the rectangle.
 718    pub size: Size<T>,
 719}
 720
 721/// Create a bounds with the given origin and size
 722pub fn bounds<T: Clone + Default + Debug>(origin: Point<T>, size: Size<T>) -> Bounds<T> {
 723    Bounds { origin, size }
 724}
 725
 726impl Bounds<Pixels> {
 727    /// Generate a centered bounds for the given display or primary display if none is provided
 728    pub fn centered(display_id: Option<DisplayId>, size: Size<Pixels>, cx: &AppContext) -> Self {
 729        let display = display_id
 730            .and_then(|id| cx.find_display(id))
 731            .or_else(|| cx.primary_display());
 732
 733        display
 734            .map(|display| Bounds::centered_at(display.bounds().center(), size))
 735            .unwrap_or_else(|| Bounds {
 736                origin: point(px(0.), px(0.)),
 737                size,
 738            })
 739    }
 740
 741    /// Generate maximized bounds for the given display or primary display if none is provided
 742    pub fn maximized(display_id: Option<DisplayId>, cx: &AppContext) -> Self {
 743        let display = display_id
 744            .and_then(|id| cx.find_display(id))
 745            .or_else(|| cx.primary_display());
 746
 747        display
 748            .map(|display| display.bounds())
 749            .unwrap_or_else(|| Bounds {
 750                origin: point(px(0.), px(0.)),
 751                size: size(px(1024.), px(768.)),
 752            })
 753    }
 754}
 755
 756impl<T> Bounds<T>
 757where
 758    T: Clone + Debug + Sub<Output = T> + Default,
 759{
 760    /// Constructs a `Bounds` from two corner points: the top left and bottom right corners.
 761    ///
 762    /// This function calculates the origin and size of the `Bounds` based on the provided corner points.
 763    /// The origin is set to the top left corner, and the size is determined by the difference between
 764    /// the x and y coordinates of the bottom right and top left points.
 765    ///
 766    /// # Arguments
 767    ///
 768    /// * `upper_left` - A `Point<T>` representing the top left corner of the rectangle.
 769    /// * `bottom_right` - A `Point<T>` representing the bottom right corner of the rectangle.
 770    ///
 771    /// # Returns
 772    ///
 773    /// Returns a `Bounds<T>` that encompasses the area defined by the two corner points.
 774    ///
 775    /// # Examples
 776    ///
 777    /// ```
 778    /// # use gpui::{Bounds, Point};
 779    /// let upper_left = Point { x: 0, y: 0 };
 780    /// let bottom_right = Point { x: 10, y: 10 };
 781    /// let bounds = Bounds::from_corners(upper_left, bottom_right);
 782    ///
 783    /// assert_eq!(bounds.origin, upper_left);
 784    /// assert_eq!(bounds.size.width, 10);
 785    /// assert_eq!(bounds.size.height, 10);
 786    /// ```
 787    pub fn from_corners(upper_left: Point<T>, bottom_right: Point<T>) -> Self {
 788        let origin = Point {
 789            x: upper_left.x.clone(),
 790            y: upper_left.y.clone(),
 791        };
 792        let size = Size {
 793            width: bottom_right.x - upper_left.x,
 794            height: bottom_right.y - upper_left.y,
 795        };
 796        Bounds { origin, size }
 797    }
 798
 799    /// Constructs a `Bounds` from a corner point and size.
 800    ///
 801    /// # Examples
 802    ///
 803    /// ```
 804    /// # use zed::{Bounds, Corner, Point};
 805    /// todo!
 806    /// ```
 807    pub fn from_corner_and_size(corner: Corner, origin: Point<T>, size: Size<T>) -> Bounds<T> {
 808        let origin = match corner {
 809            Corner::TopLeft => origin,
 810            Corner::TopRight => Point {
 811                x: origin.x - size.width.clone(),
 812                y: origin.y,
 813            },
 814            Corner::BottomLeft => Point {
 815                x: origin.x,
 816                y: origin.y - size.height.clone(),
 817            },
 818            Corner::BottomRight => Point {
 819                x: origin.x - size.width.clone(),
 820                y: origin.y - size.height.clone(),
 821            },
 822        };
 823
 824        Bounds { origin, size }
 825    }
 826
 827    /// Creates a new `Bounds` with the specified origin and size.
 828    ///
 829    /// # Arguments
 830    ///
 831    /// * `origin` - A `Point<T>` representing the origin of the bounds.
 832    /// * `size` - A `Size<T>` representing the size of the bounds.
 833    ///
 834    /// # Returns
 835    ///
 836    /// Returns a `Bounds<T>` that has the given origin and size.
 837    pub fn new(origin: Point<T>, size: Size<T>) -> Self {
 838        Bounds { origin, size }
 839    }
 840}
 841
 842impl<T> Bounds<T>
 843where
 844    T: Clone + Debug + PartialOrd + Add<T, Output = T> + Sub<Output = T> + Default + Half,
 845{
 846    /// Checks if this `Bounds` intersects with another `Bounds`.
 847    ///
 848    /// Two `Bounds` instances intersect if they overlap in the 2D space they occupy.
 849    /// This method checks if there is any overlapping area between the two bounds.
 850    ///
 851    /// # Arguments
 852    ///
 853    /// * `other` - A reference to another `Bounds` to check for intersection with.
 854    ///
 855    /// # Returns
 856    ///
 857    /// Returns `true` if there is any intersection between the two bounds, `false` otherwise.
 858    ///
 859    /// # Examples
 860    ///
 861    /// ```
 862    /// # use gpui::{Bounds, Point, Size};
 863    /// let bounds1 = Bounds {
 864    ///     origin: Point { x: 0, y: 0 },
 865    ///     size: Size { width: 10, height: 10 },
 866    /// };
 867    /// let bounds2 = Bounds {
 868    ///     origin: Point { x: 5, y: 5 },
 869    ///     size: Size { width: 10, height: 10 },
 870    /// };
 871    /// let bounds3 = Bounds {
 872    ///     origin: Point { x: 20, y: 20 },
 873    ///     size: Size { width: 10, height: 10 },
 874    /// };
 875    ///
 876    /// assert_eq!(bounds1.intersects(&bounds2), true); // Overlapping bounds
 877    /// assert_eq!(bounds1.intersects(&bounds3), false); // Non-overlapping bounds
 878    /// ```
 879    pub fn intersects(&self, other: &Bounds<T>) -> bool {
 880        let my_lower_right = self.bottom_right();
 881        let their_lower_right = other.bottom_right();
 882
 883        self.origin.x < their_lower_right.x
 884            && my_lower_right.x > other.origin.x
 885            && self.origin.y < their_lower_right.y
 886            && my_lower_right.y > other.origin.y
 887    }
 888
 889    /// Dilates the bounds by a specified amount in all directions.
 890    ///
 891    /// This method expands the bounds by the given `amount`, increasing the size
 892    /// and adjusting the origin so that the bounds grow outwards equally in all directions.
 893    /// The resulting bounds will have its width and height increased by twice the `amount`
 894    /// (since it grows in both directions), and the origin will be moved by `-amount`
 895    /// in both the x and y directions.
 896    ///
 897    /// # Arguments
 898    ///
 899    /// * `amount` - The amount by which to dilate the bounds.
 900    ///
 901    /// # Examples
 902    ///
 903    /// ```
 904    /// # use gpui::{Bounds, Point, Size};
 905    /// let mut bounds = Bounds {
 906    ///     origin: Point { x: 10, y: 10 },
 907    ///     size: Size { width: 10, height: 10 },
 908    /// };
 909    /// bounds.dilate(5);
 910    /// assert_eq!(bounds, Bounds {
 911    ///     origin: Point { x: 5, y: 5 },
 912    ///     size: Size { width: 20, height: 20 },
 913    /// });
 914    /// ```
 915    pub fn dilate(&mut self, amount: T) {
 916        self.origin.x = self.origin.x.clone() - amount.clone();
 917        self.origin.y = self.origin.y.clone() - amount.clone();
 918        let double_amount = amount.clone() + amount;
 919        self.size.width = self.size.width.clone() + double_amount.clone();
 920        self.size.height = self.size.height.clone() + double_amount;
 921    }
 922
 923    /// inset the bounds by a specified amount
 924    /// Note that this may panic if T does not support negative values
 925    pub fn inset(&self, amount: T) -> Self {
 926        let mut result = self.clone();
 927        result.dilate(T::default() - amount);
 928        result
 929    }
 930
 931    /// Returns the center point of the bounds.
 932    ///
 933    /// Calculates the center by taking the origin's x and y coordinates and adding half the width and height
 934    /// of the bounds, respectively. The center is represented as a `Point<T>` where `T` is the type of the
 935    /// coordinate system.
 936    ///
 937    /// # Returns
 938    ///
 939    /// A `Point<T>` representing the center of the bounds.
 940    ///
 941    /// # Examples
 942    ///
 943    /// ```
 944    /// # use gpui::{Bounds, Point, Size};
 945    /// let bounds = Bounds {
 946    ///     origin: Point { x: 0, y: 0 },
 947    ///     size: Size { width: 10, height: 20 },
 948    /// };
 949    /// let center = bounds.center();
 950    /// assert_eq!(center, Point { x: 5, y: 10 });
 951    /// ```
 952    pub fn center(&self) -> Point<T> {
 953        Point {
 954            x: self.origin.x.clone() + self.size.width.clone().half(),
 955            y: self.origin.y.clone() + self.size.height.clone().half(),
 956        }
 957    }
 958
 959    /// Calculates the half perimeter of a rectangle defined by the bounds.
 960    ///
 961    /// The half perimeter is calculated as the sum of the width and the height of the rectangle.
 962    /// This method is generic over the type `T` which must implement the `Sub` trait to allow
 963    /// calculation of the width and height from the bounds' origin and size, as well as the `Add` trait
 964    /// to sum the width and height for the half perimeter.
 965    ///
 966    /// # Examples
 967    ///
 968    /// ```
 969    /// # use gpui::{Bounds, Point, Size};
 970    /// let bounds = Bounds {
 971    ///     origin: Point { x: 0, y: 0 },
 972    ///     size: Size { width: 10, height: 20 },
 973    /// };
 974    /// let half_perimeter = bounds.half_perimeter();
 975    /// assert_eq!(half_perimeter, 30);
 976    /// ```
 977    pub fn half_perimeter(&self) -> T {
 978        self.size.width.clone() + self.size.height.clone()
 979    }
 980
 981    /// centered_at creates a new bounds centered at the given point.
 982    pub fn centered_at(center: Point<T>, size: Size<T>) -> Self {
 983        let origin = Point {
 984            x: center.x - size.width.half(),
 985            y: center.y - size.height.half(),
 986        };
 987        Self::new(origin, size)
 988    }
 989}
 990
 991impl<T: Clone + Default + Debug + PartialOrd + Add<T, Output = T> + Sub<Output = T>> Bounds<T> {
 992    /// Calculates the intersection of two `Bounds` objects.
 993    ///
 994    /// This method computes the overlapping region of two `Bounds`. If the bounds do not intersect,
 995    /// the resulting `Bounds` will have a size with width and height of zero.
 996    ///
 997    /// # Arguments
 998    ///
 999    /// * `other` - A reference to another `Bounds` to intersect with.
1000    ///
1001    /// # Returns
1002    ///
1003    /// Returns a `Bounds` representing the intersection area. If there is no intersection,
1004    /// the returned `Bounds` will have a size with width and height of zero.
1005    ///
1006    /// # Examples
1007    ///
1008    /// ```
1009    /// # use gpui::{Bounds, Point, Size};
1010    /// let bounds1 = Bounds {
1011    ///     origin: Point { x: 0, y: 0 },
1012    ///     size: Size { width: 10, height: 10 },
1013    /// };
1014    /// let bounds2 = Bounds {
1015    ///     origin: Point { x: 5, y: 5 },
1016    ///     size: Size { width: 10, height: 10 },
1017    /// };
1018    /// let intersection = bounds1.intersect(&bounds2);
1019    ///
1020    /// assert_eq!(intersection, Bounds {
1021    ///     origin: Point { x: 5, y: 5 },
1022    ///     size: Size { width: 5, height: 5 },
1023    /// });
1024    /// ```
1025    pub fn intersect(&self, other: &Self) -> Self {
1026        let upper_left = self.origin.max(&other.origin);
1027        let bottom_right = self.bottom_right().min(&other.bottom_right());
1028        Self::from_corners(upper_left, bottom_right)
1029    }
1030
1031    /// Computes the union of two `Bounds`.
1032    ///
1033    /// This method calculates the smallest `Bounds` that contains both the current `Bounds` and the `other` `Bounds`.
1034    /// The resulting `Bounds` will have an origin that is the minimum of the origins of the two `Bounds`,
1035    /// and a size that encompasses the furthest extents of both `Bounds`.
1036    ///
1037    /// # Arguments
1038    ///
1039    /// * `other` - A reference to another `Bounds` to create a union with.
1040    ///
1041    /// # Returns
1042    ///
1043    /// Returns a `Bounds` representing the union of the two `Bounds`.
1044    ///
1045    /// # Examples
1046    ///
1047    /// ```
1048    /// # use gpui::{Bounds, Point, Size};
1049    /// let bounds1 = Bounds {
1050    ///     origin: Point { x: 0, y: 0 },
1051    ///     size: Size { width: 10, height: 10 },
1052    /// };
1053    /// let bounds2 = Bounds {
1054    ///     origin: Point { x: 5, y: 5 },
1055    ///     size: Size { width: 15, height: 15 },
1056    /// };
1057    /// let union_bounds = bounds1.union(&bounds2);
1058    ///
1059    /// assert_eq!(union_bounds, Bounds {
1060    ///     origin: Point { x: 0, y: 0 },
1061    ///     size: Size { width: 20, height: 20 },
1062    /// });
1063    /// ```
1064    pub fn union(&self, other: &Self) -> Self {
1065        let top_left = self.origin.min(&other.origin);
1066        let bottom_right = self.bottom_right().max(&other.bottom_right());
1067        Bounds::from_corners(top_left, bottom_right)
1068    }
1069}
1070
1071impl<T, Rhs> Mul<Rhs> for Bounds<T>
1072where
1073    T: Mul<Rhs, Output = Rhs> + Clone + Default + Debug,
1074    Point<T>: Mul<Rhs, Output = Point<Rhs>>,
1075    Rhs: Clone + Default + Debug,
1076{
1077    type Output = Bounds<Rhs>;
1078
1079    fn mul(self, rhs: Rhs) -> Self::Output {
1080        Bounds {
1081            origin: self.origin * rhs.clone(),
1082            size: self.size * rhs,
1083        }
1084    }
1085}
1086
1087impl<T, S> MulAssign<S> for Bounds<T>
1088where
1089    T: Mul<S, Output = T> + Clone + Default + Debug,
1090    S: Clone,
1091{
1092    fn mul_assign(&mut self, rhs: S) {
1093        self.origin *= rhs.clone();
1094        self.size *= rhs;
1095    }
1096}
1097
1098impl<T, S> Div<S> for Bounds<T>
1099where
1100    Size<T>: Div<S, Output = Size<T>>,
1101    T: Div<S, Output = T> + Default + Clone + Debug,
1102    S: Clone,
1103{
1104    type Output = Self;
1105
1106    fn div(self, rhs: S) -> Self {
1107        Self {
1108            origin: self.origin / rhs.clone(),
1109            size: self.size / rhs,
1110        }
1111    }
1112}
1113
1114impl<T> Bounds<T>
1115where
1116    T: Add<T, Output = T> + Clone + Default + Debug,
1117{
1118    /// Returns the top edge of the bounds.
1119    ///
1120    /// # Returns
1121    ///
1122    /// A value of type `T` representing the y-coordinate of the top edge of the bounds.
1123    pub fn top(&self) -> T {
1124        self.origin.y.clone()
1125    }
1126
1127    /// Returns the bottom edge of the bounds.
1128    ///
1129    /// # Returns
1130    ///
1131    /// A value of type `T` representing the y-coordinate of the bottom edge of the bounds.
1132    pub fn bottom(&self) -> T {
1133        self.origin.y.clone() + self.size.height.clone()
1134    }
1135
1136    /// Returns the left edge of the bounds.
1137    ///
1138    /// # Returns
1139    ///
1140    /// A value of type `T` representing the x-coordinate of the left edge of the bounds.
1141    pub fn left(&self) -> T {
1142        self.origin.x.clone()
1143    }
1144
1145    /// Returns the right edge of the bounds.
1146    ///
1147    /// # Returns
1148    ///
1149    /// A value of type `T` representing the x-coordinate of the right edge of the bounds.
1150    pub fn right(&self) -> T {
1151        self.origin.x.clone() + self.size.width.clone()
1152    }
1153
1154    /// Returns the top right corner point of the bounds.
1155    ///
1156    /// # Returns
1157    ///
1158    /// A `Point<T>` representing the top right corner of the bounds.
1159    ///
1160    /// # Examples
1161    ///
1162    /// ```
1163    /// # use gpui::{Bounds, Point, Size};
1164    /// let bounds = Bounds {
1165    ///     origin: Point { x: 0, y: 0 },
1166    ///     size: Size { width: 10, height: 20 },
1167    /// };
1168    /// let top_right = bounds.top_right();
1169    /// assert_eq!(top_right, Point { x: 10, y: 0 });
1170    /// ```
1171    pub fn top_right(&self) -> Point<T> {
1172        Point {
1173            x: self.origin.x.clone() + self.size.width.clone(),
1174            y: self.origin.y.clone(),
1175        }
1176    }
1177
1178    /// Returns the bottom right corner point of the bounds.
1179    ///
1180    /// # Returns
1181    ///
1182    /// A `Point<T>` representing the bottom right corner of the bounds.
1183    ///
1184    /// # Examples
1185    ///
1186    /// ```
1187    /// # use gpui::{Bounds, Point, Size};
1188    /// let bounds = Bounds {
1189    ///     origin: Point { x: 0, y: 0 },
1190    ///     size: Size { width: 10, height: 20 },
1191    /// };
1192    /// let bottom_right = bounds.bottom_right();
1193    /// assert_eq!(bottom_right, Point { x: 10, y: 20 });
1194    /// ```
1195    pub fn bottom_right(&self) -> Point<T> {
1196        Point {
1197            x: self.origin.x.clone() + self.size.width.clone(),
1198            y: self.origin.y.clone() + self.size.height.clone(),
1199        }
1200    }
1201
1202    /// Returns the bottom left corner point of the bounds.
1203    ///
1204    /// # Returns
1205    ///
1206    /// A `Point<T>` representing the bottom left corner of the bounds.
1207    ///
1208    /// # Examples
1209    ///
1210    /// ```
1211    /// # use gpui::{Bounds, Point, Size};
1212    /// let bounds = Bounds {
1213    ///     origin: Point { x: 0, y: 0 },
1214    ///     size: Size { width: 10, height: 20 },
1215    /// };
1216    /// let bottom_left = bounds.bottom_left();
1217    /// assert_eq!(bottom_left, Point { x: 0, y: 20 });
1218    /// ```
1219    pub fn bottom_left(&self) -> Point<T> {
1220        Point {
1221            x: self.origin.x.clone(),
1222            y: self.origin.y.clone() + self.size.height.clone(),
1223        }
1224    }
1225
1226    /// Returns the requested corner point of the bounds.
1227    ///
1228    /// # Returns
1229    ///
1230    /// A `Point<T>` representing the corner of the bounds requested by the parameter.
1231    ///
1232    /// # Examples
1233    ///
1234    /// ```
1235    /// # use zed::{Bounds, Corner, Point, Size};
1236    /// let bounds = Bounds {
1237    ///     origin: Point { x: 0, y: 0 },
1238    ///     size: Size { width: 10, height: 20 },
1239    /// };
1240    /// let bottom_left = bounds.corner(Corner::BottomLeft);
1241    /// assert_eq!(bottom_left, Point { x: 0, y: 20 });
1242    /// ```
1243    pub fn corner(&self, corner: Corner) -> Point<T> {
1244        match corner {
1245            Corner::TopLeft => self.origin.clone(),
1246            Corner::TopRight => self.top_right(),
1247            Corner::BottomLeft => self.bottom_left(),
1248            Corner::BottomRight => self.bottom_right(),
1249        }
1250    }
1251}
1252
1253impl<T> Bounds<T>
1254where
1255    T: Add<T, Output = T> + PartialOrd + Clone + Default + Debug,
1256{
1257    /// Checks if the given point is within the bounds.
1258    ///
1259    /// This method determines whether a point lies inside the rectangle defined by the bounds,
1260    /// including the edges. The point is considered inside if its x-coordinate is greater than
1261    /// or equal to the left edge and less than or equal to the right edge, and its y-coordinate
1262    /// is greater than or equal to the top edge and less than or equal to the bottom edge of the bounds.
1263    ///
1264    /// # Arguments
1265    ///
1266    /// * `point` - A reference to a `Point<T>` that represents the point to check.
1267    ///
1268    /// # Returns
1269    ///
1270    /// Returns `true` if the point is within the bounds, `false` otherwise.
1271    ///
1272    /// # Examples
1273    ///
1274    /// ```
1275    /// # use gpui::{Point, Bounds};
1276    /// let bounds = Bounds {
1277    ///     origin: Point { x: 0, y: 0 },
1278    ///     size: Size { width: 10, height: 10 },
1279    /// };
1280    /// let inside_point = Point { x: 5, y: 5 };
1281    /// let outside_point = Point { x: 15, y: 15 };
1282    ///
1283    /// assert!(bounds.contains_point(&inside_point));
1284    /// assert!(!bounds.contains_point(&outside_point));
1285    /// ```
1286    pub fn contains(&self, point: &Point<T>) -> bool {
1287        point.x >= self.origin.x
1288            && point.x <= self.origin.x.clone() + self.size.width.clone()
1289            && point.y >= self.origin.y
1290            && point.y <= self.origin.y.clone() + self.size.height.clone()
1291    }
1292
1293    /// Applies a function to the origin and size of the bounds, producing a new `Bounds<U>`.
1294    ///
1295    /// This method allows for converting a `Bounds<T>` to a `Bounds<U>` by specifying a closure
1296    /// that defines how to convert between the two types. The closure is applied to the `origin` and
1297    /// `size` fields, resulting in new bounds of the desired type.
1298    ///
1299    /// # Arguments
1300    ///
1301    /// * `f` - A closure that takes a value of type `T` and returns a value of type `U`.
1302    ///
1303    /// # Returns
1304    ///
1305    /// Returns a new `Bounds<U>` with the origin and size mapped by the provided function.
1306    ///
1307    /// # Examples
1308    ///
1309    /// ```
1310    /// # use gpui::{Bounds, Point, Size};
1311    /// let bounds = Bounds {
1312    ///     origin: Point { x: 10.0, y: 10.0 },
1313    ///     size: Size { width: 10.0, height: 20.0 },
1314    /// };
1315    /// let new_bounds = bounds.map(|value| value as f64 * 1.5);
1316    ///
1317    /// assert_eq!(new_bounds, Bounds {
1318    ///     origin: Point { x: 15.0, y: 15.0 },
1319    ///     size: Size { width: 15.0, height: 30.0 },
1320    /// });
1321    /// ```
1322    pub fn map<U>(&self, f: impl Fn(T) -> U) -> Bounds<U>
1323    where
1324        U: Clone + Default + Debug,
1325    {
1326        Bounds {
1327            origin: self.origin.map(&f),
1328            size: self.size.map(f),
1329        }
1330    }
1331
1332    /// Applies a function to the origin  of the bounds, producing a new `Bounds` with the new origin
1333    ///
1334    /// # Examples
1335    ///
1336    /// ```
1337    /// # use gpui::{Bounds, Point, Size};
1338    /// let bounds = Bounds {
1339    ///     origin: Point { x: 10.0, y: 10.0 },
1340    ///     size: Size { width: 10.0, height: 20.0 },
1341    /// };
1342    /// let new_bounds = bounds.map_origin(|value| value * 1.5);
1343    ///
1344    /// assert_eq!(new_bounds, Bounds {
1345    ///     origin: Point { x: 15.0, y: 15.0 },
1346    ///     size: Size { width: 10.0, height: 20.0 },
1347    /// });
1348    /// ```
1349    pub fn map_origin(self, f: impl Fn(T) -> T) -> Bounds<T> {
1350        Bounds {
1351            origin: self.origin.map(f),
1352            size: self.size,
1353        }
1354    }
1355
1356    /// Applies a function to the origin  of the bounds, producing a new `Bounds` with the new origin
1357    ///
1358    /// # Examples
1359    ///
1360    /// ```
1361    /// # use gpui::{Bounds, Point, Size};
1362    /// let bounds = Bounds {
1363    ///     origin: Point { x: 10.0, y: 10.0 },
1364    ///     size: Size { width: 10.0, height: 20.0 },
1365    /// };
1366    /// let new_bounds = bounds.map_size(|value| value * 1.5);
1367    ///
1368    /// assert_eq!(new_bounds, Bounds {
1369    ///     origin: Point { x: 10.0, y: 10.0 },
1370    ///     size: Size { width: 15.0, height: 30.0 },
1371    /// });
1372    /// ```
1373    pub fn map_size(self, f: impl Fn(T) -> T) -> Bounds<T> {
1374        Bounds {
1375            origin: self.origin,
1376            size: self.size.map(f),
1377        }
1378    }
1379}
1380
1381/// Checks if the bounds represent an empty area.
1382///
1383/// # Returns
1384///
1385/// Returns `true` if either the width or the height of the bounds is less than or equal to zero, indicating an empty area.
1386impl<T: PartialOrd + Default + Debug + Clone> Bounds<T> {
1387    /// Checks if the bounds represent an empty area.
1388    ///
1389    /// # Returns
1390    ///
1391    /// Returns `true` if either the width or the height of the bounds is less than or equal to zero, indicating an empty area.
1392    pub fn is_empty(&self) -> bool {
1393        self.size.width <= T::default() || self.size.height <= T::default()
1394    }
1395}
1396
1397impl Size<DevicePixels> {
1398    /// Converts the size from physical to logical pixels.
1399    pub(crate) fn to_pixels(self, scale_factor: f32) -> Size<Pixels> {
1400        size(
1401            px(self.width.0 as f32 / scale_factor),
1402            px(self.height.0 as f32 / scale_factor),
1403        )
1404    }
1405}
1406
1407impl Size<Pixels> {
1408    /// Converts the size from physical to logical pixels.
1409    pub(crate) fn to_device_pixels(self, scale_factor: f32) -> Size<DevicePixels> {
1410        size(
1411            DevicePixels((self.width.0 * scale_factor) as i32),
1412            DevicePixels((self.height.0 * scale_factor) as i32),
1413        )
1414    }
1415}
1416
1417impl Bounds<Pixels> {
1418    /// Scales the bounds by a given factor, typically used to adjust for display scaling.
1419    ///
1420    /// This method multiplies the origin and size of the bounds by the provided scaling factor,
1421    /// resulting in a new `Bounds<ScaledPixels>` that is proportionally larger or smaller
1422    /// depending on the scaling factor. This can be used to ensure that the bounds are properly
1423    /// scaled for different display densities.
1424    ///
1425    /// # Arguments
1426    ///
1427    /// * `factor` - The scaling factor to apply to the origin and size, typically the display's scaling factor.
1428    ///
1429    /// # Returns
1430    ///
1431    /// Returns a new `Bounds<ScaledPixels>` that represents the scaled bounds.
1432    ///
1433    /// # Examples
1434    ///
1435    /// ```
1436    /// # use gpui::{Bounds, Point, Size, Pixels};
1437    /// let bounds = Bounds {
1438    ///     origin: Point { x: Pixels(10.0), y: Pixels(20.0) },
1439    ///     size: Size { width: Pixels(30.0), height: Pixels(40.0) },
1440    /// };
1441    /// let display_scale_factor = 2.0;
1442    /// let scaled_bounds = bounds.scale(display_scale_factor);
1443    /// assert_eq!(scaled_bounds, Bounds {
1444    ///     origin: Point { x: ScaledPixels(20.0), y: ScaledPixels(40.0) },
1445    ///     size: Size { width: ScaledPixels(60.0), height: ScaledPixels(80.0) },
1446    /// });
1447    /// ```
1448    pub fn scale(&self, factor: f32) -> Bounds<ScaledPixels> {
1449        Bounds {
1450            origin: self.origin.scale(factor),
1451            size: self.size.scale(factor),
1452        }
1453    }
1454
1455    /// Convert the bounds from logical pixels to physical pixels
1456    pub fn to_device_pixels(&self, factor: f32) -> Bounds<DevicePixels> {
1457        Bounds {
1458            origin: point(
1459                DevicePixels((self.origin.x.0 * factor) as i32),
1460                DevicePixels((self.origin.y.0 * factor) as i32),
1461            ),
1462            size: self.size.to_device_pixels(factor),
1463        }
1464    }
1465}
1466
1467impl Bounds<DevicePixels> {
1468    /// Convert the bounds from physical pixels to logical pixels
1469    pub fn to_pixels(self, scale_factor: f32) -> Bounds<Pixels> {
1470        Bounds {
1471            origin: point(
1472                px(self.origin.x.0 as f32 / scale_factor),
1473                px(self.origin.y.0 as f32 / scale_factor),
1474            ),
1475            size: self.size.to_pixels(scale_factor),
1476        }
1477    }
1478}
1479
1480impl<T: Clone + Debug + Copy + Default> Copy for Bounds<T> {}
1481
1482/// Represents the edges of a box in a 2D space, such as padding or margin.
1483///
1484/// Each field represents the size of the edge on one side of the box: `top`, `right`, `bottom`, and `left`.
1485///
1486/// # Examples
1487///
1488/// ```
1489/// # use gpui::Edges;
1490/// let edges = Edges {
1491///     top: 10.0,
1492///     right: 20.0,
1493///     bottom: 30.0,
1494///     left: 40.0,
1495/// };
1496///
1497/// assert_eq!(edges.top, 10.0);
1498/// assert_eq!(edges.right, 20.0);
1499/// assert_eq!(edges.bottom, 30.0);
1500/// assert_eq!(edges.left, 40.0);
1501/// ```
1502#[derive(Refineable, Clone, Default, Debug, Eq, PartialEq)]
1503#[refineable(Debug)]
1504#[repr(C)]
1505pub struct Edges<T: Clone + Default + Debug> {
1506    /// The size of the top edge.
1507    pub top: T,
1508    /// The size of the right edge.
1509    pub right: T,
1510    /// The size of the bottom edge.
1511    pub bottom: T,
1512    /// The size of the left edge.
1513    pub left: T,
1514}
1515
1516impl<T> Mul for Edges<T>
1517where
1518    T: Mul<Output = T> + Clone + Default + Debug,
1519{
1520    type Output = Self;
1521
1522    fn mul(self, rhs: Self) -> Self::Output {
1523        Self {
1524            top: self.top.clone() * rhs.top,
1525            right: self.right.clone() * rhs.right,
1526            bottom: self.bottom.clone() * rhs.bottom,
1527            left: self.left.clone() * rhs.left,
1528        }
1529    }
1530}
1531
1532impl<T, S> MulAssign<S> for Edges<T>
1533where
1534    T: Mul<S, Output = T> + Clone + Default + Debug,
1535    S: Clone,
1536{
1537    fn mul_assign(&mut self, rhs: S) {
1538        self.top = self.top.clone() * rhs.clone();
1539        self.right = self.right.clone() * rhs.clone();
1540        self.bottom = self.bottom.clone() * rhs.clone();
1541        self.left = self.left.clone() * rhs;
1542    }
1543}
1544
1545impl<T: Clone + Default + Debug + Copy> Copy for Edges<T> {}
1546
1547impl<T: Clone + Default + Debug> Edges<T> {
1548    /// Constructs `Edges` where all sides are set to the same specified value.
1549    ///
1550    /// This function creates an `Edges` instance with the `top`, `right`, `bottom`, and `left` fields all initialized
1551    /// to the same value provided as an argument. This is useful when you want to have uniform edges around a box,
1552    /// such as padding or margin with the same size on all sides.
1553    ///
1554    /// # Arguments
1555    ///
1556    /// * `value` - The value to set for all four sides of the edges.
1557    ///
1558    /// # Returns
1559    ///
1560    /// An `Edges` instance with all sides set to the given value.
1561    ///
1562    /// # Examples
1563    ///
1564    /// ```
1565    /// # use gpui::Edges;
1566    /// let uniform_edges = Edges::all(10.0);
1567    /// assert_eq!(uniform_edges.top, 10.0);
1568    /// assert_eq!(uniform_edges.right, 10.0);
1569    /// assert_eq!(uniform_edges.bottom, 10.0);
1570    /// assert_eq!(uniform_edges.left, 10.0);
1571    /// ```
1572    pub fn all(value: T) -> Self {
1573        Self {
1574            top: value.clone(),
1575            right: value.clone(),
1576            bottom: value.clone(),
1577            left: value,
1578        }
1579    }
1580
1581    /// Applies a function to each field of the `Edges`, producing a new `Edges<U>`.
1582    ///
1583    /// This method allows for converting an `Edges<T>` to an `Edges<U>` by specifying a closure
1584    /// that defines how to convert between the two types. The closure is applied to each field
1585    /// (`top`, `right`, `bottom`, `left`), resulting in new edges of the desired type.
1586    ///
1587    /// # Arguments
1588    ///
1589    /// * `f` - A closure that takes a reference to a value of type `T` and returns a value of type `U`.
1590    ///
1591    /// # Returns
1592    ///
1593    /// Returns a new `Edges<U>` with each field mapped by the provided function.
1594    ///
1595    /// # Examples
1596    ///
1597    /// ```
1598    /// # use gpui::Edges;
1599    /// let edges = Edges { top: 10, right: 20, bottom: 30, left: 40 };
1600    /// let edges_float = edges.map(|&value| value as f32 * 1.1);
1601    /// assert_eq!(edges_float, Edges { top: 11.0, right: 22.0, bottom: 33.0, left: 44.0 });
1602    /// ```
1603    pub fn map<U>(&self, f: impl Fn(&T) -> U) -> Edges<U>
1604    where
1605        U: Clone + Default + Debug,
1606    {
1607        Edges {
1608            top: f(&self.top),
1609            right: f(&self.right),
1610            bottom: f(&self.bottom),
1611            left: f(&self.left),
1612        }
1613    }
1614
1615    /// Checks if any of the edges satisfy a given predicate.
1616    ///
1617    /// This method applies a predicate function to each field of the `Edges` and returns `true` if any field satisfies the predicate.
1618    ///
1619    /// # Arguments
1620    ///
1621    /// * `predicate` - A closure that takes a reference to a value of type `T` and returns a `bool`.
1622    ///
1623    /// # Returns
1624    ///
1625    /// Returns `true` if the predicate returns `true` for any of the edge values, `false` otherwise.
1626    ///
1627    /// # Examples
1628    ///
1629    /// ```
1630    /// # use gpui::Edges;
1631    /// let edges = Edges {
1632    ///     top: 10,
1633    ///     right: 0,
1634    ///     bottom: 5,
1635    ///     left: 0,
1636    /// };
1637    ///
1638    /// assert!(edges.any(|value| *value == 0));
1639    /// assert!(edges.any(|value| *value > 0));
1640    /// assert!(!edges.any(|value| *value > 10));
1641    /// ```
1642    pub fn any<F: Fn(&T) -> bool>(&self, predicate: F) -> bool {
1643        predicate(&self.top)
1644            || predicate(&self.right)
1645            || predicate(&self.bottom)
1646            || predicate(&self.left)
1647    }
1648}
1649
1650impl Edges<Length> {
1651    /// Sets the edges of the `Edges` struct to `auto`, which is a special value that allows the layout engine to automatically determine the size of the edges.
1652    ///
1653    /// This is typically used in layout contexts where the exact size of the edges is not important, or when the size should be calculated based on the content or container.
1654    ///
1655    /// # Returns
1656    ///
1657    /// Returns an `Edges<Length>` with all edges set to `Length::Auto`.
1658    ///
1659    /// # Examples
1660    ///
1661    /// ```
1662    /// # use gpui::Edges;
1663    /// let auto_edges = Edges::auto();
1664    /// assert_eq!(auto_edges.top, Length::Auto);
1665    /// assert_eq!(auto_edges.right, Length::Auto);
1666    /// assert_eq!(auto_edges.bottom, Length::Auto);
1667    /// assert_eq!(auto_edges.left, Length::Auto);
1668    /// ```
1669    pub fn auto() -> Self {
1670        Self {
1671            top: Length::Auto,
1672            right: Length::Auto,
1673            bottom: Length::Auto,
1674            left: Length::Auto,
1675        }
1676    }
1677
1678    /// Sets the edges of the `Edges` struct to zero, which means no size or thickness.
1679    ///
1680    /// This is typically used when you want to specify that a box (like a padding or margin area)
1681    /// should have no edges, effectively making it non-existent or invisible in layout calculations.
1682    ///
1683    /// # Returns
1684    ///
1685    /// Returns an `Edges<Length>` with all edges set to zero length.
1686    ///
1687    /// # Examples
1688    ///
1689    /// ```
1690    /// # use gpui::Edges;
1691    /// let no_edges = Edges::zero();
1692    /// assert_eq!(no_edges.top, Length::Definite(DefiniteLength::from(Pixels(0.))));
1693    /// assert_eq!(no_edges.right, Length::Definite(DefiniteLength::from(Pixels(0.))));
1694    /// assert_eq!(no_edges.bottom, Length::Definite(DefiniteLength::from(Pixels(0.))));
1695    /// assert_eq!(no_edges.left, Length::Definite(DefiniteLength::from(Pixels(0.))));
1696    /// ```
1697    pub fn zero() -> Self {
1698        Self {
1699            top: px(0.).into(),
1700            right: px(0.).into(),
1701            bottom: px(0.).into(),
1702            left: px(0.).into(),
1703        }
1704    }
1705}
1706
1707impl Edges<DefiniteLength> {
1708    /// Sets the edges of the `Edges` struct to zero, which means no size or thickness.
1709    ///
1710    /// This is typically used when you want to specify that a box (like a padding or margin area)
1711    /// should have no edges, effectively making it non-existent or invisible in layout calculations.
1712    ///
1713    /// # Returns
1714    ///
1715    /// Returns an `Edges<DefiniteLength>` with all edges set to zero length.
1716    ///
1717    /// # Examples
1718    ///
1719    /// ```
1720    /// # use gpui::{px, Edges};
1721    /// let no_edges = Edges::zero();
1722    /// assert_eq!(no_edges.top, DefiniteLength::from(px(0.)));
1723    /// assert_eq!(no_edges.right, DefiniteLength::from(px(0.)));
1724    /// assert_eq!(no_edges.bottom, DefiniteLength::from(px(0.)));
1725    /// assert_eq!(no_edges.left, DefiniteLength::from(px(0.)));
1726    /// ```
1727    pub fn zero() -> Self {
1728        Self {
1729            top: px(0.).into(),
1730            right: px(0.).into(),
1731            bottom: px(0.).into(),
1732            left: px(0.).into(),
1733        }
1734    }
1735
1736    /// Converts the `DefiniteLength` to `Pixels` based on the parent size and the REM size.
1737    ///
1738    /// This method allows for a `DefiniteLength` value to be converted into pixels, taking into account
1739    /// the size of the parent element (for percentage-based lengths) and the size of a rem unit (for rem-based lengths).
1740    ///
1741    /// # Arguments
1742    ///
1743    /// * `parent_size` - `Size<AbsoluteLength>` representing the size of the parent element.
1744    /// * `rem_size` - `Pixels` representing the size of one REM unit.
1745    ///
1746    /// # Returns
1747    ///
1748    /// Returns an `Edges<Pixels>` representing the edges with lengths converted to pixels.
1749    ///
1750    /// # Examples
1751    ///
1752    /// ```
1753    /// # use gpui::{Edges, DefiniteLength, px, AbsoluteLength, Size};
1754    /// let edges = Edges {
1755    ///     top: DefiniteLength::Absolute(AbsoluteLength::Pixels(px(10.0))),
1756    ///     right: DefiniteLength::Fraction(0.5),
1757    ///     bottom: DefiniteLength::Absolute(AbsoluteLength::Rems(rems(2.0))),
1758    ///     left: DefiniteLength::Fraction(0.25),
1759    /// };
1760    /// let parent_size = Size {
1761    ///     width: AbsoluteLength::Pixels(px(200.0)),
1762    ///     height: AbsoluteLength::Pixels(px(100.0)),
1763    /// };
1764    /// let rem_size = px(16.0);
1765    /// let edges_in_pixels = edges.to_pixels(parent_size, rem_size);
1766    ///
1767    /// assert_eq!(edges_in_pixels.top, px(10.0)); // Absolute length in pixels
1768    /// assert_eq!(edges_in_pixels.right, px(100.0)); // 50% of parent width
1769    /// assert_eq!(edges_in_pixels.bottom, px(32.0)); // 2 rems
1770    /// assert_eq!(edges_in_pixels.left, px(50.0)); // 25% of parent width
1771    /// ```
1772    pub fn to_pixels(&self, parent_size: Size<AbsoluteLength>, rem_size: Pixels) -> Edges<Pixels> {
1773        Edges {
1774            top: self.top.to_pixels(parent_size.height, rem_size),
1775            right: self.right.to_pixels(parent_size.width, rem_size),
1776            bottom: self.bottom.to_pixels(parent_size.height, rem_size),
1777            left: self.left.to_pixels(parent_size.width, rem_size),
1778        }
1779    }
1780}
1781
1782impl Edges<AbsoluteLength> {
1783    /// Sets the edges of the `Edges` struct to zero, which means no size or thickness.
1784    ///
1785    /// This is typically used when you want to specify that a box (like a padding or margin area)
1786    /// should have no edges, effectively making it non-existent or invisible in layout calculations.
1787    ///
1788    /// # Returns
1789    ///
1790    /// Returns an `Edges<AbsoluteLength>` with all edges set to zero length.
1791    ///
1792    /// # Examples
1793    ///
1794    /// ```
1795    /// # use gpui::Edges;
1796    /// let no_edges = Edges::zero();
1797    /// assert_eq!(no_edges.top, AbsoluteLength::Pixels(Pixels(0.0)));
1798    /// assert_eq!(no_edges.right, AbsoluteLength::Pixels(Pixels(0.0)));
1799    /// assert_eq!(no_edges.bottom, AbsoluteLength::Pixels(Pixels(0.0)));
1800    /// assert_eq!(no_edges.left, AbsoluteLength::Pixels(Pixels(0.0)));
1801    /// ```
1802    pub fn zero() -> Self {
1803        Self {
1804            top: px(0.).into(),
1805            right: px(0.).into(),
1806            bottom: px(0.).into(),
1807            left: px(0.).into(),
1808        }
1809    }
1810
1811    /// Converts the `AbsoluteLength` to `Pixels` based on the `rem_size`.
1812    ///
1813    /// If the `AbsoluteLength` is already in pixels, it simply returns the corresponding `Pixels` value.
1814    /// If the `AbsoluteLength` is in rems, it multiplies the number of rems by the `rem_size` to convert it to pixels.
1815    ///
1816    /// # Arguments
1817    ///
1818    /// * `rem_size` - The size of one rem unit in pixels.
1819    ///
1820    /// # Returns
1821    ///
1822    /// Returns an `Edges<Pixels>` representing the edges with lengths converted to pixels.
1823    ///
1824    /// # Examples
1825    ///
1826    /// ```
1827    /// # use gpui::{Edges, AbsoluteLength, Pixels, px};
1828    /// let edges = Edges {
1829    ///     top: AbsoluteLength::Pixels(px(10.0)),
1830    ///     right: AbsoluteLength::Rems(rems(1.0)),
1831    ///     bottom: AbsoluteLength::Pixels(px(20.0)),
1832    ///     left: AbsoluteLength::Rems(rems(2.0)),
1833    /// };
1834    /// let rem_size = px(16.0);
1835    /// let edges_in_pixels = edges.to_pixels(rem_size);
1836    ///
1837    /// assert_eq!(edges_in_pixels.top, px(10.0)); // Already in pixels
1838    /// assert_eq!(edges_in_pixels.right, px(16.0)); // 1 rem converted to pixels
1839    /// assert_eq!(edges_in_pixels.bottom, px(20.0)); // Already in pixels
1840    /// assert_eq!(edges_in_pixels.left, px(32.0)); // 2 rems converted to pixels
1841    /// ```
1842    pub fn to_pixels(&self, rem_size: Pixels) -> Edges<Pixels> {
1843        Edges {
1844            top: self.top.to_pixels(rem_size),
1845            right: self.right.to_pixels(rem_size),
1846            bottom: self.bottom.to_pixels(rem_size),
1847            left: self.left.to_pixels(rem_size),
1848        }
1849    }
1850}
1851
1852impl Edges<Pixels> {
1853    /// Scales the `Edges<Pixels>` by a given factor, returning `Edges<ScaledPixels>`.
1854    ///
1855    /// This method is typically used for adjusting the edge sizes for different display densities or scaling factors.
1856    ///
1857    /// # Arguments
1858    ///
1859    /// * `factor` - The scaling factor to apply to each edge.
1860    ///
1861    /// # Returns
1862    ///
1863    /// Returns a new `Edges<ScaledPixels>` where each edge is the result of scaling the original edge by the given factor.
1864    ///
1865    /// # Examples
1866    ///
1867    /// ```
1868    /// # use gpui::{Edges, Pixels};
1869    /// let edges = Edges {
1870    ///     top: Pixels(10.0),
1871    ///     right: Pixels(20.0),
1872    ///     bottom: Pixels(30.0),
1873    ///     left: Pixels(40.0),
1874    /// };
1875    /// let scaled_edges = edges.scale(2.0);
1876    /// assert_eq!(scaled_edges.top, ScaledPixels(20.0));
1877    /// assert_eq!(scaled_edges.right, ScaledPixels(40.0));
1878    /// assert_eq!(scaled_edges.bottom, ScaledPixels(60.0));
1879    /// assert_eq!(scaled_edges.left, ScaledPixels(80.0));
1880    /// ```
1881    pub fn scale(&self, factor: f32) -> Edges<ScaledPixels> {
1882        Edges {
1883            top: self.top.scale(factor),
1884            right: self.right.scale(factor),
1885            bottom: self.bottom.scale(factor),
1886            left: self.left.scale(factor),
1887        }
1888    }
1889
1890    /// Returns the maximum value of any edge.
1891    ///
1892    /// # Returns
1893    ///
1894    /// The maximum `Pixels` value among all four edges.
1895    pub fn max(&self) -> Pixels {
1896        self.top.max(self.right).max(self.bottom).max(self.left)
1897    }
1898}
1899
1900impl From<f32> for Edges<Pixels> {
1901    fn from(val: f32) -> Self {
1902        let val: Pixels = val.into();
1903        val.into()
1904    }
1905}
1906
1907impl From<Pixels> for Edges<Pixels> {
1908    fn from(val: Pixels) -> Self {
1909        Edges {
1910            top: val,
1911            right: val,
1912            bottom: val,
1913            left: val,
1914        }
1915    }
1916}
1917
1918/// Identifies a corner of a 2d box.
1919#[derive(Clone, Copy, PartialEq, Eq)]
1920pub enum Corner {
1921    /// The top left corner
1922    TopLeft,
1923    /// The top right corner
1924    TopRight,
1925    /// The bottom left corner
1926    BottomLeft,
1927    /// The bottom right corner
1928    BottomRight,
1929}
1930
1931impl Corner {
1932    /// Returns the directly opposite corner.
1933    ///
1934    /// # Examples
1935    ///
1936    /// ```
1937    /// # use zed::Corner;
1938    /// assert_eq!(Corner::TopLeft.opposite_corner(), Corner::BottomRight);
1939    /// ```
1940    pub fn opposite_corner(self) -> Self {
1941        match self {
1942            Corner::TopLeft => Corner::BottomRight,
1943            Corner::TopRight => Corner::BottomLeft,
1944            Corner::BottomLeft => Corner::TopRight,
1945            Corner::BottomRight => Corner::TopLeft,
1946        }
1947    }
1948
1949    /// Returns the corner across from this corner, moving along the specified axis.
1950    ///
1951    /// # Examples
1952    ///
1953    /// ```
1954    /// # use zed::Corner;
1955    /// let result = Corner::TopLeft.other_side_corner_along(Axis::Horizontal);
1956    /// assert_eq!(result, Corner::TopRight);
1957    /// ```
1958    pub fn other_side_corner_along(self, axis: Axis) -> Self {
1959        match axis {
1960            Axis::Vertical => match self {
1961                Corner::TopLeft => Corner::BottomLeft,
1962                Corner::TopRight => Corner::BottomRight,
1963                Corner::BottomLeft => Corner::TopLeft,
1964                Corner::BottomRight => Corner::TopRight,
1965            },
1966            Axis::Horizontal => match self {
1967                Corner::TopLeft => Corner::TopRight,
1968                Corner::TopRight => Corner::TopLeft,
1969                Corner::BottomLeft => Corner::BottomRight,
1970                Corner::BottomRight => Corner::BottomLeft,
1971            },
1972        }
1973    }
1974}
1975
1976/// Represents the corners of a box in a 2D space, such as border radius.
1977///
1978/// Each field represents the size of the corner on one side of the box: `top_left`, `top_right`, `bottom_right`, and `bottom_left`.
1979#[derive(Refineable, Clone, Default, Debug, Eq, PartialEq)]
1980#[refineable(Debug)]
1981#[repr(C)]
1982pub struct Corners<T: Clone + Default + Debug> {
1983    /// The value associated with the top left corner.
1984    pub top_left: T,
1985    /// The value associated with the top right corner.
1986    pub top_right: T,
1987    /// The value associated with the bottom right corner.
1988    pub bottom_right: T,
1989    /// The value associated with the bottom left corner.
1990    pub bottom_left: T,
1991}
1992
1993impl<T> Corners<T>
1994where
1995    T: Clone + Default + Debug,
1996{
1997    /// Constructs `Corners` where all sides are set to the same specified value.
1998    ///
1999    /// This function creates a `Corners` instance with the `top_left`, `top_right`, `bottom_right`, and `bottom_left` fields all initialized
2000    /// to the same value provided as an argument. This is useful when you want to have uniform corners around a box,
2001    /// such as a uniform border radius on a rectangle.
2002    ///
2003    /// # Arguments
2004    ///
2005    /// * `value` - The value to set for all four corners.
2006    ///
2007    /// # Returns
2008    ///
2009    /// An `Corners` instance with all corners set to the given value.
2010    ///
2011    /// # Examples
2012    ///
2013    /// ```
2014    /// # use gpui::Corners;
2015    /// let uniform_corners = Corners::all(5.0);
2016    /// assert_eq!(uniform_corners.top_left, 5.0);
2017    /// assert_eq!(uniform_corners.top_right, 5.0);
2018    /// assert_eq!(uniform_corners.bottom_right, 5.0);
2019    /// assert_eq!(uniform_corners.bottom_left, 5.0);
2020    /// ```
2021    pub fn all(value: T) -> Self {
2022        Self {
2023            top_left: value.clone(),
2024            top_right: value.clone(),
2025            bottom_right: value.clone(),
2026            bottom_left: value,
2027        }
2028    }
2029
2030    /// Returns the requested corner.
2031    ///
2032    /// # Returns
2033    ///
2034    /// A `Point<T>` representing the corner requested by the parameter.
2035    ///
2036    /// # Examples
2037    ///
2038    /// ```
2039    /// # use zed::{Corner, Corners};
2040    /// let corners = Corners {
2041    ///     top_left: 1,
2042    ///     top_right: 2,
2043    ///     bottom_left: 3,
2044    ///     bottom_right: 4
2045    /// };
2046    /// assert_eq!(corners.corner(Corner::BottomLeft), 3);
2047    /// ```
2048    pub fn corner(&self, corner: Corner) -> T {
2049        match corner {
2050            Corner::TopLeft => self.top_left.clone(),
2051            Corner::TopRight => self.top_right.clone(),
2052            Corner::BottomLeft => self.bottom_left.clone(),
2053            Corner::BottomRight => self.bottom_right.clone(),
2054        }
2055    }
2056}
2057
2058impl Corners<AbsoluteLength> {
2059    /// Converts the `AbsoluteLength` to `Pixels` based on the provided size and rem size, ensuring the resulting
2060    /// `Pixels` do not exceed half of the minimum of the provided size's width and height.
2061    ///
2062    /// This method is particularly useful when dealing with corner radii, where the radius in pixels should not
2063    /// exceed half the size of the box it applies to, to avoid the corners overlapping.
2064    ///
2065    /// # Arguments
2066    ///
2067    /// * `size` - The `Size<Pixels>` against which the minimum allowable radius is determined.
2068    /// * `rem_size` - The size of one REM unit in pixels, used for conversion if the `AbsoluteLength` is in REMs.
2069    ///
2070    /// # Returns
2071    ///
2072    /// Returns a `Corners<Pixels>` instance with each corner's length converted to pixels and clamped to the
2073    /// minimum allowable radius based on the provided size.
2074    ///
2075    /// # Examples
2076    ///
2077    /// ```
2078    /// # use gpui::{Corners, AbsoluteLength, Pixels, Size};
2079    /// let corners = Corners {
2080    ///     top_left: AbsoluteLength::Pixels(Pixels(15.0)),
2081    ///     top_right: AbsoluteLength::Rems(Rems(1.0)),
2082    ///     bottom_right: AbsoluteLength::Pixels(Pixels(30.0)),
2083    ///     bottom_left: AbsoluteLength::Rems(Rems(2.0)),
2084    /// };
2085    /// let size = Size { width: Pixels(100.0), height: Pixels(50.0) };
2086    /// let rem_size = Pixels(16.0);
2087    /// let corners_in_pixels = corners.to_pixels(size, rem_size);
2088    ///
2089    /// // The resulting corners should not exceed half the size of the smallest dimension (50.0 / 2.0 = 25.0).
2090    /// assert_eq!(corners_in_pixels.top_left, Pixels(15.0));
2091    /// assert_eq!(corners_in_pixels.top_right, Pixels(16.0)); // 1 rem converted to pixels
2092    /// assert_eq!(corners_in_pixels.bottom_right, Pixels(30.0).min(Pixels(25.0))); // Clamped to 25.0
2093    /// assert_eq!(corners_in_pixels.bottom_left, Pixels(32.0).min(Pixels(25.0))); // 2 rems converted to pixels and clamped to 25.0
2094    /// ```
2095    pub fn to_pixels(&self, size: Size<Pixels>, rem_size: Pixels) -> Corners<Pixels> {
2096        let max = size.width.min(size.height) / 2.;
2097        Corners {
2098            top_left: self.top_left.to_pixels(rem_size).min(max),
2099            top_right: self.top_right.to_pixels(rem_size).min(max),
2100            bottom_right: self.bottom_right.to_pixels(rem_size).min(max),
2101            bottom_left: self.bottom_left.to_pixels(rem_size).min(max),
2102        }
2103    }
2104}
2105
2106impl Corners<Pixels> {
2107    /// Scales the `Corners<Pixels>` by a given factor, returning `Corners<ScaledPixels>`.
2108    ///
2109    /// This method is typically used for adjusting the corner sizes for different display densities or scaling factors.
2110    ///
2111    /// # Arguments
2112    ///
2113    /// * `factor` - The scaling factor to apply to each corner.
2114    ///
2115    /// # Returns
2116    ///
2117    /// Returns a new `Corners<ScaledPixels>` where each corner is the result of scaling the original corner by the given factor.
2118    ///
2119    /// # Examples
2120    ///
2121    /// ```
2122    /// # use gpui::{Corners, Pixels};
2123    /// let corners = Corners {
2124    ///     top_left: Pixels(10.0),
2125    ///     top_right: Pixels(20.0),
2126    ///     bottom_right: Pixels(30.0),
2127    ///     bottom_left: Pixels(40.0),
2128    /// };
2129    /// let scaled_corners = corners.scale(2.0);
2130    /// assert_eq!(scaled_corners.top_left, ScaledPixels(20.0));
2131    /// assert_eq!(scaled_corners.top_right, ScaledPixels(40.0));
2132    /// assert_eq!(scaled_corners.bottom_right, ScaledPixels(60.0));
2133    /// assert_eq!(scaled_corners.bottom_left, ScaledPixels(80.0));
2134    /// ```
2135    pub fn scale(&self, factor: f32) -> Corners<ScaledPixels> {
2136        Corners {
2137            top_left: self.top_left.scale(factor),
2138            top_right: self.top_right.scale(factor),
2139            bottom_right: self.bottom_right.scale(factor),
2140            bottom_left: self.bottom_left.scale(factor),
2141        }
2142    }
2143
2144    /// Returns the maximum value of any corner.
2145    ///
2146    /// # Returns
2147    ///
2148    /// The maximum `Pixels` value among all four corners.
2149    pub fn max(&self) -> Pixels {
2150        self.top_left
2151            .max(self.top_right)
2152            .max(self.bottom_right)
2153            .max(self.bottom_left)
2154    }
2155}
2156
2157impl<T: Clone + Default + Debug> Corners<T> {
2158    /// Applies a function to each field of the `Corners`, producing a new `Corners<U>`.
2159    ///
2160    /// This method allows for converting a `Corners<T>` to a `Corners<U>` by specifying a closure
2161    /// that defines how to convert between the two types. The closure is applied to each field
2162    /// (`top_left`, `top_right`, `bottom_right`, `bottom_left`), resulting in new corners of the desired type.
2163    ///
2164    /// # Arguments
2165    ///
2166    /// * `f` - A closure that takes a reference to a value of type `T` and returns a value of type `U`.
2167    ///
2168    /// # Returns
2169    ///
2170    /// Returns a new `Corners<U>` with each field mapped by the provided function.
2171    ///
2172    /// # Examples
2173    ///
2174    /// ```
2175    /// # use gpui::{Corners, Pixels};
2176    /// let corners = Corners {
2177    ///     top_left: Pixels(10.0),
2178    ///     top_right: Pixels(20.0),
2179    ///     bottom_right: Pixels(30.0),
2180    ///     bottom_left: Pixels(40.0),
2181    /// };
2182    /// let corners_in_rems = corners.map(|&px| Rems(px.0 / 16.0));
2183    /// assert_eq!(corners_in_rems, Corners {
2184    ///     top_left: Rems(0.625),
2185    ///     top_right: Rems(1.25),
2186    ///     bottom_right: Rems(1.875),
2187    ///     bottom_left: Rems(2.5),
2188    /// });
2189    /// ```
2190    pub fn map<U>(&self, f: impl Fn(&T) -> U) -> Corners<U>
2191    where
2192        U: Clone + Default + Debug,
2193    {
2194        Corners {
2195            top_left: f(&self.top_left),
2196            top_right: f(&self.top_right),
2197            bottom_right: f(&self.bottom_right),
2198            bottom_left: f(&self.bottom_left),
2199        }
2200    }
2201}
2202
2203impl<T> Mul for Corners<T>
2204where
2205    T: Mul<Output = T> + Clone + Default + Debug,
2206{
2207    type Output = Self;
2208
2209    fn mul(self, rhs: Self) -> Self::Output {
2210        Self {
2211            top_left: self.top_left.clone() * rhs.top_left,
2212            top_right: self.top_right.clone() * rhs.top_right,
2213            bottom_right: self.bottom_right.clone() * rhs.bottom_right,
2214            bottom_left: self.bottom_left.clone() * rhs.bottom_left,
2215        }
2216    }
2217}
2218
2219impl<T, S> MulAssign<S> for Corners<T>
2220where
2221    T: Mul<S, Output = T> + Clone + Default + Debug,
2222    S: Clone,
2223{
2224    fn mul_assign(&mut self, rhs: S) {
2225        self.top_left = self.top_left.clone() * rhs.clone();
2226        self.top_right = self.top_right.clone() * rhs.clone();
2227        self.bottom_right = self.bottom_right.clone() * rhs.clone();
2228        self.bottom_left = self.bottom_left.clone() * rhs;
2229    }
2230}
2231
2232impl<T> Copy for Corners<T> where T: Copy + Clone + Default + Debug {}
2233
2234impl From<f32> for Corners<Pixels> {
2235    fn from(val: f32) -> Self {
2236        Corners {
2237            top_left: val.into(),
2238            top_right: val.into(),
2239            bottom_right: val.into(),
2240            bottom_left: val.into(),
2241        }
2242    }
2243}
2244
2245impl From<Pixels> for Corners<Pixels> {
2246    fn from(val: Pixels) -> Self {
2247        Corners {
2248            top_left: val,
2249            top_right: val,
2250            bottom_right: val,
2251            bottom_left: val,
2252        }
2253    }
2254}
2255
2256/// Represents an angle in Radians
2257#[derive(
2258    Clone,
2259    Copy,
2260    Default,
2261    Add,
2262    AddAssign,
2263    Sub,
2264    SubAssign,
2265    Neg,
2266    Div,
2267    DivAssign,
2268    PartialEq,
2269    Serialize,
2270    Deserialize,
2271    Debug,
2272)]
2273#[repr(transparent)]
2274pub struct Radians(pub f32);
2275
2276/// Create a `Radian` from a raw value
2277pub fn radians(value: f32) -> Radians {
2278    Radians(value)
2279}
2280
2281/// A type representing a percentage value.
2282#[derive(
2283    Clone,
2284    Copy,
2285    Default,
2286    Add,
2287    AddAssign,
2288    Sub,
2289    SubAssign,
2290    Neg,
2291    Div,
2292    DivAssign,
2293    PartialEq,
2294    Serialize,
2295    Deserialize,
2296    Debug,
2297)]
2298#[repr(transparent)]
2299pub struct Percentage(pub f32);
2300
2301/// Generate a `Radian` from a percentage of a full circle.
2302pub fn percentage(value: f32) -> Percentage {
2303    debug_assert!(
2304        (0.0..=1.0).contains(&value),
2305        "Percentage must be between 0 and 1"
2306    );
2307    Percentage(value)
2308}
2309
2310impl From<Percentage> for Radians {
2311    fn from(value: Percentage) -> Self {
2312        radians(value.0 * std::f32::consts::PI * 2.0)
2313    }
2314}
2315
2316/// Represents a length in pixels, the base unit of measurement in the UI framework.
2317///
2318/// `Pixels` is a value type that represents an absolute length in pixels, which is used
2319/// for specifying sizes, positions, and distances in the UI. It is the fundamental unit
2320/// of measurement for all visual elements and layout calculations.
2321///
2322/// The inner value is an `f32`, allowing for sub-pixel precision which can be useful for
2323/// anti-aliasing and animations. However, when applied to actual pixel grids, the value
2324/// is typically rounded to the nearest integer.
2325///
2326/// # Examples
2327///
2328/// ```
2329/// use gpui::Pixels;
2330///
2331/// // Define a length of 10 pixels
2332/// let length = Pixels(10.0);
2333///
2334/// // Define a length and scale it by a factor of 2
2335/// let scaled_length = length.scale(2.0);
2336/// assert_eq!(scaled_length, Pixels(20.0));
2337/// ```
2338#[derive(
2339    Clone,
2340    Copy,
2341    Default,
2342    Add,
2343    AddAssign,
2344    Sub,
2345    SubAssign,
2346    Neg,
2347    Div,
2348    DivAssign,
2349    PartialEq,
2350    Serialize,
2351    Deserialize,
2352)]
2353#[repr(transparent)]
2354pub struct Pixels(pub f32);
2355
2356impl std::fmt::Display for Pixels {
2357    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
2358        f.write_fmt(format_args!("{}px", self.0))
2359    }
2360}
2361
2362impl std::ops::Div for Pixels {
2363    type Output = f32;
2364
2365    fn div(self, rhs: Self) -> Self::Output {
2366        self.0 / rhs.0
2367    }
2368}
2369
2370impl std::ops::DivAssign for Pixels {
2371    fn div_assign(&mut self, rhs: Self) {
2372        *self = Self(self.0 / rhs.0);
2373    }
2374}
2375
2376impl std::ops::RemAssign for Pixels {
2377    fn rem_assign(&mut self, rhs: Self) {
2378        self.0 %= rhs.0;
2379    }
2380}
2381
2382impl std::ops::Rem for Pixels {
2383    type Output = Self;
2384
2385    fn rem(self, rhs: Self) -> Self {
2386        Self(self.0 % rhs.0)
2387    }
2388}
2389
2390impl Mul<f32> for Pixels {
2391    type Output = Pixels;
2392
2393    fn mul(self, other: f32) -> Pixels {
2394        Pixels(self.0 * other)
2395    }
2396}
2397
2398impl Mul<usize> for Pixels {
2399    type Output = Pixels;
2400
2401    fn mul(self, other: usize) -> Pixels {
2402        Pixels(self.0 * other as f32)
2403    }
2404}
2405
2406impl Mul<Pixels> for f32 {
2407    type Output = Pixels;
2408
2409    fn mul(self, rhs: Pixels) -> Self::Output {
2410        Pixels(self * rhs.0)
2411    }
2412}
2413
2414impl MulAssign<f32> for Pixels {
2415    fn mul_assign(&mut self, other: f32) {
2416        self.0 *= other;
2417    }
2418}
2419
2420impl Pixels {
2421    /// Represents zero pixels.
2422    pub const ZERO: Pixels = Pixels(0.0);
2423    /// The maximum value that can be represented by `Pixels`.
2424    pub const MAX: Pixels = Pixels(f32::MAX);
2425
2426    /// Floors the `Pixels` value to the nearest whole number.
2427    ///
2428    /// # Returns
2429    ///
2430    /// Returns a new `Pixels` instance with the floored value.
2431    pub fn floor(&self) -> Self {
2432        Self(self.0.floor())
2433    }
2434
2435    /// Rounds the `Pixels` value to the nearest whole number.
2436    ///
2437    /// # Returns
2438    ///
2439    /// Returns a new `Pixels` instance with the rounded value.
2440    pub fn round(&self) -> Self {
2441        Self(self.0.round())
2442    }
2443
2444    /// Returns the ceiling of the `Pixels` value to the nearest whole number.
2445    ///
2446    /// # Returns
2447    ///
2448    /// Returns a new `Pixels` instance with the ceiling value.
2449    pub fn ceil(&self) -> Self {
2450        Self(self.0.ceil())
2451    }
2452
2453    /// Scales the `Pixels` value by a given factor, producing `ScaledPixels`.
2454    ///
2455    /// This method is used when adjusting pixel values for display scaling factors,
2456    /// such as high DPI (dots per inch) or Retina displays, where the pixel density is higher and
2457    /// thus requires scaling to maintain visual consistency and readability.
2458    ///
2459    /// The resulting `ScaledPixels` represent the scaled value which can be used for rendering
2460    /// calculations where display scaling is considered.
2461    pub fn scale(&self, factor: f32) -> ScaledPixels {
2462        ScaledPixels(self.0 * factor)
2463    }
2464
2465    /// Raises the `Pixels` value to a given power.
2466    ///
2467    /// # Arguments
2468    ///
2469    /// * `exponent` - The exponent to raise the `Pixels` value by.
2470    ///
2471    /// # Returns
2472    ///
2473    /// Returns a new `Pixels` instance with the value raised to the given exponent.
2474    pub fn pow(&self, exponent: f32) -> Self {
2475        Self(self.0.powf(exponent))
2476    }
2477
2478    /// Returns the absolute value of the `Pixels`.
2479    ///
2480    /// # Returns
2481    ///
2482    /// A new `Pixels` instance with the absolute value of the original `Pixels`.
2483    pub fn abs(&self) -> Self {
2484        Self(self.0.abs())
2485    }
2486
2487    /// Returns the sign of the `Pixels` value.
2488    ///
2489    /// # Returns
2490    ///
2491    /// Returns:
2492    /// * `1.0` if the value is positive
2493    /// * `-1.0` if the value is negative
2494    /// * `0.0` if the value is zero
2495    pub fn signum(&self) -> f32 {
2496        self.0.signum()
2497    }
2498
2499    /// Returns the f64 value of `Pixels`.
2500    ///
2501    /// # Returns
2502    ///
2503    /// A f64 value of the `Pixels`.
2504    pub fn to_f64(self) -> f64 {
2505        self.0 as f64
2506    }
2507}
2508
2509impl Mul<Pixels> for Pixels {
2510    type Output = Pixels;
2511
2512    fn mul(self, rhs: Pixels) -> Self::Output {
2513        Pixels(self.0 * rhs.0)
2514    }
2515}
2516
2517impl Eq for Pixels {}
2518
2519impl PartialOrd for Pixels {
2520    fn partial_cmp(&self, other: &Self) -> Option<cmp::Ordering> {
2521        Some(self.cmp(other))
2522    }
2523}
2524
2525impl Ord for Pixels {
2526    fn cmp(&self, other: &Self) -> cmp::Ordering {
2527        self.0.total_cmp(&other.0)
2528    }
2529}
2530
2531impl std::hash::Hash for Pixels {
2532    fn hash<H: std::hash::Hasher>(&self, state: &mut H) {
2533        self.0.to_bits().hash(state);
2534    }
2535}
2536
2537impl From<f64> for Pixels {
2538    fn from(pixels: f64) -> Self {
2539        Pixels(pixels as f32)
2540    }
2541}
2542
2543impl From<f32> for Pixels {
2544    fn from(pixels: f32) -> Self {
2545        Pixels(pixels)
2546    }
2547}
2548
2549impl Debug for Pixels {
2550    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
2551        write!(f, "{} px", self.0)
2552    }
2553}
2554
2555impl From<Pixels> for f32 {
2556    fn from(pixels: Pixels) -> Self {
2557        pixels.0
2558    }
2559}
2560
2561impl From<&Pixels> for f32 {
2562    fn from(pixels: &Pixels) -> Self {
2563        pixels.0
2564    }
2565}
2566
2567impl From<Pixels> for f64 {
2568    fn from(pixels: Pixels) -> Self {
2569        pixels.0 as f64
2570    }
2571}
2572
2573impl From<Pixels> for u32 {
2574    fn from(pixels: Pixels) -> Self {
2575        pixels.0 as u32
2576    }
2577}
2578
2579impl From<u32> for Pixels {
2580    fn from(pixels: u32) -> Self {
2581        Pixels(pixels as f32)
2582    }
2583}
2584
2585impl From<Pixels> for usize {
2586    fn from(pixels: Pixels) -> Self {
2587        pixels.0 as usize
2588    }
2589}
2590
2591impl From<usize> for Pixels {
2592    fn from(pixels: usize) -> Self {
2593        Pixels(pixels as f32)
2594    }
2595}
2596
2597/// Represents physical pixels on the display.
2598///
2599/// `DevicePixels` is a unit of measurement that refers to the actual pixels on a device's screen.
2600/// This type is used when precise pixel manipulation is required, such as rendering graphics or
2601/// interfacing with hardware that operates on the pixel level. Unlike logical pixels that may be
2602/// affected by the device's scale factor, `DevicePixels` always correspond to real pixels on the
2603/// display.
2604#[derive(
2605    Add,
2606    AddAssign,
2607    Clone,
2608    Copy,
2609    Default,
2610    Div,
2611    Eq,
2612    Hash,
2613    Ord,
2614    PartialEq,
2615    PartialOrd,
2616    Sub,
2617    SubAssign,
2618    Serialize,
2619    Deserialize,
2620)]
2621#[repr(transparent)]
2622pub struct DevicePixels(pub i32);
2623
2624impl DevicePixels {
2625    /// Converts the `DevicePixels` value to the number of bytes needed to represent it in memory.
2626    ///
2627    /// This function is useful when working with graphical data that needs to be stored in a buffer,
2628    /// such as images or framebuffers, where each pixel may be represented by a specific number of bytes.
2629    ///
2630    /// # Arguments
2631    ///
2632    /// * `bytes_per_pixel` - The number of bytes used to represent a single pixel.
2633    ///
2634    /// # Returns
2635    ///
2636    /// The number of bytes required to represent the `DevicePixels` value in memory.
2637    ///
2638    /// # Examples
2639    ///
2640    /// ```
2641    /// # use gpui::DevicePixels;
2642    /// let pixels = DevicePixels(10); // 10 device pixels
2643    /// let bytes_per_pixel = 4; // Assume each pixel is represented by 4 bytes (e.g., RGBA)
2644    /// let total_bytes = pixels.to_bytes(bytes_per_pixel);
2645    /// assert_eq!(total_bytes, 40); // 10 pixels * 4 bytes/pixel = 40 bytes
2646    /// ```
2647    pub fn to_bytes(&self, bytes_per_pixel: u8) -> u32 {
2648        self.0 as u32 * bytes_per_pixel as u32
2649    }
2650}
2651
2652impl fmt::Debug for DevicePixels {
2653    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
2654        write!(f, "{} px (device)", self.0)
2655    }
2656}
2657
2658impl From<DevicePixels> for i32 {
2659    fn from(device_pixels: DevicePixels) -> Self {
2660        device_pixels.0
2661    }
2662}
2663
2664impl From<i32> for DevicePixels {
2665    fn from(device_pixels: i32) -> Self {
2666        DevicePixels(device_pixels)
2667    }
2668}
2669
2670impl From<u32> for DevicePixels {
2671    fn from(device_pixels: u32) -> Self {
2672        DevicePixels(device_pixels as i32)
2673    }
2674}
2675
2676impl From<DevicePixels> for u32 {
2677    fn from(device_pixels: DevicePixels) -> Self {
2678        device_pixels.0 as u32
2679    }
2680}
2681
2682impl From<DevicePixels> for u64 {
2683    fn from(device_pixels: DevicePixels) -> Self {
2684        device_pixels.0 as u64
2685    }
2686}
2687
2688impl From<u64> for DevicePixels {
2689    fn from(device_pixels: u64) -> Self {
2690        DevicePixels(device_pixels as i32)
2691    }
2692}
2693
2694impl From<DevicePixels> for usize {
2695    fn from(device_pixels: DevicePixels) -> Self {
2696        device_pixels.0 as usize
2697    }
2698}
2699
2700impl From<usize> for DevicePixels {
2701    fn from(device_pixels: usize) -> Self {
2702        DevicePixels(device_pixels as i32)
2703    }
2704}
2705
2706/// Represents scaled pixels that take into account the device's scale factor.
2707///
2708/// `ScaledPixels` are used to ensure that UI elements appear at the correct size on devices
2709/// with different pixel densities. When a device has a higher scale factor (such as Retina displays),
2710/// a single logical pixel may correspond to multiple physical pixels. By using `ScaledPixels`,
2711/// dimensions and positions can be specified in a way that scales appropriately across different
2712/// display resolutions.
2713#[derive(Clone, Copy, Default, Add, AddAssign, Sub, SubAssign, Div, PartialEq, PartialOrd)]
2714#[repr(transparent)]
2715pub struct ScaledPixels(pub(crate) f32);
2716
2717impl ScaledPixels {
2718    /// Floors the `ScaledPixels` value to the nearest whole number.
2719    ///
2720    /// # Returns
2721    ///
2722    /// Returns a new `ScaledPixels` instance with the floored value.
2723    pub fn floor(&self) -> Self {
2724        Self(self.0.floor())
2725    }
2726
2727    /// Rounds the `ScaledPixels` value to the nearest whole number.
2728    ///
2729    /// # Returns
2730    ///
2731    /// Returns a new `ScaledPixels` instance with the rounded value.
2732    pub fn ceil(&self) -> Self {
2733        Self(self.0.ceil())
2734    }
2735}
2736
2737impl Eq for ScaledPixels {}
2738
2739impl Debug for ScaledPixels {
2740    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
2741        write!(f, "{} px (scaled)", self.0)
2742    }
2743}
2744
2745impl From<ScaledPixels> for DevicePixels {
2746    fn from(scaled: ScaledPixels) -> Self {
2747        DevicePixels(scaled.0.ceil() as i32)
2748    }
2749}
2750
2751impl From<DevicePixels> for ScaledPixels {
2752    fn from(device: DevicePixels) -> Self {
2753        ScaledPixels(device.0 as f32)
2754    }
2755}
2756
2757impl From<ScaledPixels> for f64 {
2758    fn from(scaled_pixels: ScaledPixels) -> Self {
2759        scaled_pixels.0 as f64
2760    }
2761}
2762
2763impl From<ScaledPixels> for u32 {
2764    fn from(pixels: ScaledPixels) -> Self {
2765        pixels.0 as u32
2766    }
2767}
2768
2769/// Represents a length in rems, a unit based on the font-size of the window, which can be assigned with [`WindowContext::set_rem_size`][set_rem_size].
2770///
2771/// Rems are used for defining lengths that are scalable and consistent across different UI elements.
2772/// The value of `1rem` is typically equal to the font-size of the root element (often the `<html>` element in browsers),
2773/// making it a flexible unit that adapts to the user's text size preferences. In this framework, `rems` serve a similar
2774/// purpose, allowing for scalable and accessible design that can adjust to different display settings or user preferences.
2775///
2776/// For example, if the root element's font-size is `16px`, then `1rem` equals `16px`. A length of `2rems` would then be `32px`.
2777///
2778/// [set_rem_size]: crate::WindowContext::set_rem_size
2779#[derive(Clone, Copy, Default, Add, Sub, Mul, Div, Neg, PartialEq)]
2780pub struct Rems(pub f32);
2781
2782impl Rems {
2783    /// Convert this Rem value to pixels.
2784    pub fn to_pixels(&self, rem_size: Pixels) -> Pixels {
2785        *self * rem_size
2786    }
2787}
2788
2789impl Mul<Pixels> for Rems {
2790    type Output = Pixels;
2791
2792    fn mul(self, other: Pixels) -> Pixels {
2793        Pixels(self.0 * other.0)
2794    }
2795}
2796
2797impl Debug for Rems {
2798    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
2799        write!(f, "{} rem", self.0)
2800    }
2801}
2802
2803/// Represents an absolute length in pixels or rems.
2804///
2805/// `AbsoluteLength` can be either a fixed number of pixels, which is an absolute measurement not
2806/// affected by the current font size, or a number of rems, which is relative to the font size of
2807/// the root element. It is used for specifying dimensions that are either independent of or
2808/// related to the typographic scale.
2809#[derive(Clone, Copy, Debug, Neg, PartialEq)]
2810pub enum AbsoluteLength {
2811    /// A length in pixels.
2812    Pixels(Pixels),
2813    /// A length in rems.
2814    Rems(Rems),
2815}
2816
2817impl AbsoluteLength {
2818    /// Checks if the absolute length is zero.
2819    pub fn is_zero(&self) -> bool {
2820        match self {
2821            AbsoluteLength::Pixels(px) => px.0 == 0.0,
2822            AbsoluteLength::Rems(rems) => rems.0 == 0.0,
2823        }
2824    }
2825}
2826
2827impl From<Pixels> for AbsoluteLength {
2828    fn from(pixels: Pixels) -> Self {
2829        AbsoluteLength::Pixels(pixels)
2830    }
2831}
2832
2833impl From<Rems> for AbsoluteLength {
2834    fn from(rems: Rems) -> Self {
2835        AbsoluteLength::Rems(rems)
2836    }
2837}
2838
2839impl AbsoluteLength {
2840    /// Converts an `AbsoluteLength` to `Pixels` based on a given `rem_size`.
2841    ///
2842    /// # Arguments
2843    ///
2844    /// * `rem_size` - The size of one rem in pixels.
2845    ///
2846    /// # Returns
2847    ///
2848    /// Returns the `AbsoluteLength` as `Pixels`.
2849    ///
2850    /// # Examples
2851    ///
2852    /// ```
2853    /// # use gpui::{AbsoluteLength, Pixels};
2854    /// let length_in_pixels = AbsoluteLength::Pixels(Pixels(42.0));
2855    /// let length_in_rems = AbsoluteLength::Rems(Rems(2.0));
2856    /// let rem_size = Pixels(16.0);
2857    ///
2858    /// assert_eq!(length_in_pixels.to_pixels(rem_size), Pixels(42.0));
2859    /// assert_eq!(length_in_rems.to_pixels(rem_size), Pixels(32.0));
2860    /// ```
2861    pub fn to_pixels(&self, rem_size: Pixels) -> Pixels {
2862        match self {
2863            AbsoluteLength::Pixels(pixels) => *pixels,
2864            AbsoluteLength::Rems(rems) => rems.to_pixels(rem_size),
2865        }
2866    }
2867}
2868
2869impl Default for AbsoluteLength {
2870    fn default() -> Self {
2871        px(0.).into()
2872    }
2873}
2874
2875/// A non-auto length that can be defined in pixels, rems, or percent of parent.
2876///
2877/// This enum represents lengths that have a specific value, as opposed to lengths that are automatically
2878/// determined by the context. It includes absolute lengths in pixels or rems, and relative lengths as a
2879/// fraction of the parent's size.
2880#[derive(Clone, Copy, Neg, PartialEq)]
2881pub enum DefiniteLength {
2882    /// An absolute length specified in pixels or rems.
2883    Absolute(AbsoluteLength),
2884    /// A relative length specified as a fraction of the parent's size, between 0 and 1.
2885    Fraction(f32),
2886}
2887
2888impl DefiniteLength {
2889    /// Converts the `DefiniteLength` to `Pixels` based on a given `base_size` and `rem_size`.
2890    ///
2891    /// If the `DefiniteLength` is an absolute length, it will be directly converted to `Pixels`.
2892    /// If it is a fraction, the fraction will be multiplied by the `base_size` to get the length in pixels.
2893    ///
2894    /// # Arguments
2895    ///
2896    /// * `base_size` - The base size in `AbsoluteLength` to which the fraction will be applied.
2897    /// * `rem_size` - The size of one rem in pixels, used to convert rems to pixels.
2898    ///
2899    /// # Returns
2900    ///
2901    /// Returns the `DefiniteLength` as `Pixels`.
2902    ///
2903    /// # Examples
2904    ///
2905    /// ```
2906    /// # use gpui::{DefiniteLength, AbsoluteLength, Pixels, px, rems};
2907    /// let length_in_pixels = DefiniteLength::Absolute(AbsoluteLength::Pixels(px(42.0)));
2908    /// let length_in_rems = DefiniteLength::Absolute(AbsoluteLength::Rems(rems(2.0)));
2909    /// let length_as_fraction = DefiniteLength::Fraction(0.5);
2910    /// let base_size = AbsoluteLength::Pixels(px(100.0));
2911    /// let rem_size = px(16.0);
2912    ///
2913    /// assert_eq!(length_in_pixels.to_pixels(base_size, rem_size), Pixels(42.0));
2914    /// assert_eq!(length_in_rems.to_pixels(base_size, rem_size), Pixels(32.0));
2915    /// assert_eq!(length_as_fraction.to_pixels(base_size, rem_size), Pixels(50.0));
2916    /// ```
2917    pub fn to_pixels(&self, base_size: AbsoluteLength, rem_size: Pixels) -> Pixels {
2918        match self {
2919            DefiniteLength::Absolute(size) => size.to_pixels(rem_size),
2920            DefiniteLength::Fraction(fraction) => match base_size {
2921                AbsoluteLength::Pixels(px) => px * *fraction,
2922                AbsoluteLength::Rems(rems) => rems * rem_size * *fraction,
2923            },
2924        }
2925    }
2926}
2927
2928impl Debug for DefiniteLength {
2929    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
2930        match self {
2931            DefiniteLength::Absolute(length) => Debug::fmt(length, f),
2932            DefiniteLength::Fraction(fract) => write!(f, "{}%", (fract * 100.0) as i32),
2933        }
2934    }
2935}
2936
2937impl From<Pixels> for DefiniteLength {
2938    fn from(pixels: Pixels) -> Self {
2939        Self::Absolute(pixels.into())
2940    }
2941}
2942
2943impl From<Rems> for DefiniteLength {
2944    fn from(rems: Rems) -> Self {
2945        Self::Absolute(rems.into())
2946    }
2947}
2948
2949impl From<AbsoluteLength> for DefiniteLength {
2950    fn from(length: AbsoluteLength) -> Self {
2951        Self::Absolute(length)
2952    }
2953}
2954
2955impl Default for DefiniteLength {
2956    fn default() -> Self {
2957        Self::Absolute(AbsoluteLength::default())
2958    }
2959}
2960
2961/// A length that can be defined in pixels, rems, percent of parent, or auto.
2962#[derive(Clone, Copy)]
2963pub enum Length {
2964    /// A definite length specified either in pixels, rems, or as a fraction of the parent's size.
2965    Definite(DefiniteLength),
2966    /// An automatic length that is determined by the context in which it is used.
2967    Auto,
2968}
2969
2970impl Debug for Length {
2971    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
2972        match self {
2973            Length::Definite(definite_length) => write!(f, "{:?}", definite_length),
2974            Length::Auto => write!(f, "auto"),
2975        }
2976    }
2977}
2978
2979/// Constructs a `DefiniteLength` representing a relative fraction of a parent size.
2980///
2981/// This function creates a `DefiniteLength` that is a specified fraction of a parent's dimension.
2982/// The fraction should be a floating-point number between 0.0 and 1.0, where 1.0 represents 100% of the parent's size.
2983///
2984/// # Arguments
2985///
2986/// * `fraction` - The fraction of the parent's size, between 0.0 and 1.0.
2987///
2988/// # Returns
2989///
2990/// A `DefiniteLength` representing the relative length as a fraction of the parent's size.
2991pub fn relative(fraction: f32) -> DefiniteLength {
2992    DefiniteLength::Fraction(fraction)
2993}
2994
2995/// Returns the Golden Ratio, i.e. `~(1.0 + sqrt(5.0)) / 2.0`.
2996pub fn phi() -> DefiniteLength {
2997    relative(1.618_034)
2998}
2999
3000/// Constructs a `Rems` value representing a length in rems.
3001///
3002/// # Arguments
3003///
3004/// * `rems` - The number of rems for the length.
3005///
3006/// # Returns
3007///
3008/// A `Rems` representing the specified number of rems.
3009pub fn rems(rems: f32) -> Rems {
3010    Rems(rems)
3011}
3012
3013/// Constructs a `Pixels` value representing a length in pixels.
3014///
3015/// # Arguments
3016///
3017/// * `pixels` - The number of pixels for the length.
3018///
3019/// # Returns
3020///
3021/// A `Pixels` representing the specified number of pixels.
3022pub const fn px(pixels: f32) -> Pixels {
3023    Pixels(pixels)
3024}
3025
3026/// Returns a `Length` representing an automatic length.
3027///
3028/// The `auto` length is often used in layout calculations where the length should be determined
3029/// by the layout context itself rather than being explicitly set. This is commonly used in CSS
3030/// for properties like `width`, `height`, `margin`, `padding`, etc., where `auto` can be used
3031/// to instruct the layout engine to calculate the size based on other factors like the size of the
3032/// container or the intrinsic size of the content.
3033///
3034/// # Returns
3035///
3036/// A `Length` variant set to `Auto`.
3037pub fn auto() -> Length {
3038    Length::Auto
3039}
3040
3041impl From<Pixels> for Length {
3042    fn from(pixels: Pixels) -> Self {
3043        Self::Definite(pixels.into())
3044    }
3045}
3046
3047impl From<Rems> for Length {
3048    fn from(rems: Rems) -> Self {
3049        Self::Definite(rems.into())
3050    }
3051}
3052
3053impl From<DefiniteLength> for Length {
3054    fn from(length: DefiniteLength) -> Self {
3055        Self::Definite(length)
3056    }
3057}
3058
3059impl From<AbsoluteLength> for Length {
3060    fn from(length: AbsoluteLength) -> Self {
3061        Self::Definite(length.into())
3062    }
3063}
3064
3065impl Default for Length {
3066    fn default() -> Self {
3067        Self::Definite(DefiniteLength::default())
3068    }
3069}
3070
3071impl From<()> for Length {
3072    fn from(_: ()) -> Self {
3073        Self::Definite(DefiniteLength::default())
3074    }
3075}
3076
3077/// Provides a trait for types that can calculate half of their value.
3078///
3079/// The `Half` trait is used for types that can be evenly divided, returning a new instance of the same type
3080/// representing half of the original value. This is commonly used for types that represent measurements or sizes,
3081/// such as lengths or pixels, where halving is a frequent operation during layout calculations or animations.
3082pub trait Half {
3083    /// Returns half of the current value.
3084    ///
3085    /// # Returns
3086    ///
3087    /// A new instance of the implementing type, representing half of the original value.
3088    fn half(&self) -> Self;
3089}
3090
3091impl Half for i32 {
3092    fn half(&self) -> Self {
3093        self / 2
3094    }
3095}
3096
3097impl Half for f32 {
3098    fn half(&self) -> Self {
3099        self / 2.
3100    }
3101}
3102
3103impl Half for DevicePixels {
3104    fn half(&self) -> Self {
3105        Self(self.0 / 2)
3106    }
3107}
3108
3109impl Half for ScaledPixels {
3110    fn half(&self) -> Self {
3111        Self(self.0 / 2.)
3112    }
3113}
3114
3115impl Half for Pixels {
3116    fn half(&self) -> Self {
3117        Self(self.0 / 2.)
3118    }
3119}
3120
3121impl Half for Rems {
3122    fn half(&self) -> Self {
3123        Self(self.0 / 2.)
3124    }
3125}
3126
3127/// Provides a trait for types that can negate their values.
3128pub trait Negate {
3129    /// Returns the negation of the given value
3130    fn negate(self) -> Self;
3131}
3132
3133impl Negate for i32 {
3134    fn negate(self) -> Self {
3135        -self
3136    }
3137}
3138
3139impl Negate for f32 {
3140    fn negate(self) -> Self {
3141        -self
3142    }
3143}
3144
3145impl Negate for DevicePixels {
3146    fn negate(self) -> Self {
3147        Self(-self.0)
3148    }
3149}
3150
3151impl Negate for ScaledPixels {
3152    fn negate(self) -> Self {
3153        Self(-self.0)
3154    }
3155}
3156
3157impl Negate for Pixels {
3158    fn negate(self) -> Self {
3159        Self(-self.0)
3160    }
3161}
3162
3163impl Negate for Rems {
3164    fn negate(self) -> Self {
3165        Self(-self.0)
3166    }
3167}
3168
3169/// A trait for checking if a value is zero.
3170///
3171/// This trait provides a method to determine if a value is considered to be zero.
3172/// It is implemented for various numeric and length-related types where the concept
3173/// of zero is applicable. This can be useful for comparisons, optimizations, or
3174/// determining if an operation has a neutral effect.
3175pub trait IsZero {
3176    /// Determines if the value is zero.
3177    ///
3178    /// # Returns
3179    ///
3180    /// Returns `true` if the value is zero, `false` otherwise.
3181    fn is_zero(&self) -> bool;
3182}
3183
3184impl IsZero for DevicePixels {
3185    fn is_zero(&self) -> bool {
3186        self.0 == 0
3187    }
3188}
3189
3190impl IsZero for ScaledPixels {
3191    fn is_zero(&self) -> bool {
3192        self.0 == 0.
3193    }
3194}
3195
3196impl IsZero for Pixels {
3197    fn is_zero(&self) -> bool {
3198        self.0 == 0.
3199    }
3200}
3201
3202impl IsZero for Rems {
3203    fn is_zero(&self) -> bool {
3204        self.0 == 0.
3205    }
3206}
3207
3208impl IsZero for AbsoluteLength {
3209    fn is_zero(&self) -> bool {
3210        match self {
3211            AbsoluteLength::Pixels(pixels) => pixels.is_zero(),
3212            AbsoluteLength::Rems(rems) => rems.is_zero(),
3213        }
3214    }
3215}
3216
3217impl IsZero for DefiniteLength {
3218    fn is_zero(&self) -> bool {
3219        match self {
3220            DefiniteLength::Absolute(length) => length.is_zero(),
3221            DefiniteLength::Fraction(fraction) => *fraction == 0.,
3222        }
3223    }
3224}
3225
3226impl IsZero for Length {
3227    fn is_zero(&self) -> bool {
3228        match self {
3229            Length::Definite(length) => length.is_zero(),
3230            Length::Auto => false,
3231        }
3232    }
3233}
3234
3235impl<T: IsZero + Debug + Clone + Default> IsZero for Point<T> {
3236    fn is_zero(&self) -> bool {
3237        self.x.is_zero() && self.y.is_zero()
3238    }
3239}
3240
3241impl<T> IsZero for Size<T>
3242where
3243    T: IsZero + Default + Debug + Clone,
3244{
3245    fn is_zero(&self) -> bool {
3246        self.width.is_zero() || self.height.is_zero()
3247    }
3248}
3249
3250impl<T: IsZero + Debug + Clone + Default> IsZero for Bounds<T> {
3251    fn is_zero(&self) -> bool {
3252        self.size.is_zero()
3253    }
3254}
3255
3256impl<T> IsZero for Corners<T>
3257where
3258    T: IsZero + Clone + Default + Debug,
3259{
3260    fn is_zero(&self) -> bool {
3261        self.top_left.is_zero()
3262            && self.top_right.is_zero()
3263            && self.bottom_right.is_zero()
3264            && self.bottom_left.is_zero()
3265    }
3266}
3267
3268#[cfg(test)]
3269mod tests {
3270    use super::*;
3271
3272    #[test]
3273    fn test_bounds_intersects() {
3274        let bounds1 = Bounds {
3275            origin: Point { x: 0.0, y: 0.0 },
3276            size: Size {
3277                width: 5.0,
3278                height: 5.0,
3279            },
3280        };
3281        let bounds2 = Bounds {
3282            origin: Point { x: 4.0, y: 4.0 },
3283            size: Size {
3284                width: 5.0,
3285                height: 5.0,
3286            },
3287        };
3288        let bounds3 = Bounds {
3289            origin: Point { x: 10.0, y: 10.0 },
3290            size: Size {
3291                width: 5.0,
3292                height: 5.0,
3293            },
3294        };
3295
3296        // Test Case 1: Intersecting bounds
3297        assert!(bounds1.intersects(&bounds2));
3298
3299        // Test Case 2: Non-Intersecting bounds
3300        assert!(!bounds1.intersects(&bounds3));
3301
3302        // Test Case 3: Bounds intersecting with themselves
3303        assert!(bounds1.intersects(&bounds1));
3304    }
3305}