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, Neg, 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 + Default,
 759{
 760    /// Creates a new `Bounds` with the specified origin and size.
 761    ///
 762    /// # Arguments
 763    ///
 764    /// * `origin` - A `Point<T>` representing the origin of the bounds.
 765    /// * `size` - A `Size<T>` representing the size of the bounds.
 766    ///
 767    /// # Returns
 768    ///
 769    /// Returns a `Bounds<T>` that has the given origin and size.
 770    pub fn new(origin: Point<T>, size: Size<T>) -> Self {
 771        Bounds { origin, size }
 772    }
 773}
 774
 775impl<T> Bounds<T>
 776where
 777    T: Clone + Debug + Sub<Output = T> + Default,
 778{
 779    /// Constructs a `Bounds` from two corner points: the top left and bottom right corners.
 780    ///
 781    /// This function calculates the origin and size of the `Bounds` based on the provided corner points.
 782    /// The origin is set to the top left corner, and the size is determined by the difference between
 783    /// the x and y coordinates of the bottom right and top left points.
 784    ///
 785    /// # Arguments
 786    ///
 787    /// * `upper_left` - A `Point<T>` representing the top left corner of the rectangle.
 788    /// * `bottom_right` - A `Point<T>` representing the bottom right corner of the rectangle.
 789    ///
 790    /// # Returns
 791    ///
 792    /// Returns a `Bounds<T>` that encompasses the area defined by the two corner points.
 793    ///
 794    /// # Examples
 795    ///
 796    /// ```
 797    /// # use gpui::{Bounds, Point};
 798    /// let upper_left = Point { x: 0, y: 0 };
 799    /// let bottom_right = Point { x: 10, y: 10 };
 800    /// let bounds = Bounds::from_corners(upper_left, bottom_right);
 801    ///
 802    /// assert_eq!(bounds.origin, upper_left);
 803    /// assert_eq!(bounds.size.width, 10);
 804    /// assert_eq!(bounds.size.height, 10);
 805    /// ```
 806    pub fn from_corners(upper_left: Point<T>, bottom_right: Point<T>) -> Self {
 807        let origin = Point {
 808            x: upper_left.x.clone(),
 809            y: upper_left.y.clone(),
 810        };
 811        let size = Size {
 812            width: bottom_right.x - upper_left.x,
 813            height: bottom_right.y - upper_left.y,
 814        };
 815        Bounds { origin, size }
 816    }
 817
 818    /// Constructs a `Bounds` from a corner point and size.
 819    ///
 820    /// # Examples
 821    ///
 822    /// ```
 823    /// # use zed::{Bounds, Corner, Point};
 824    /// todo!
 825    /// ```
 826    pub fn from_corner_and_size(corner: Corner, origin: Point<T>, size: Size<T>) -> Bounds<T> {
 827        let origin = match corner {
 828            Corner::TopLeft => origin,
 829            Corner::TopRight => Point {
 830                x: origin.x - size.width.clone(),
 831                y: origin.y,
 832            },
 833            Corner::BottomLeft => Point {
 834                x: origin.x,
 835                y: origin.y - size.height.clone(),
 836            },
 837            Corner::BottomRight => Point {
 838                x: origin.x - size.width.clone(),
 839                y: origin.y - size.height.clone(),
 840            },
 841        };
 842
 843        Bounds { origin, size }
 844    }
 845}
 846
 847impl<T> Bounds<T>
 848where
 849    T: Clone + Debug + Sub<T, Output = T> + Default + Half,
 850{
 851    /// Creates a new bounds centered at the given point.
 852    pub fn centered_at(center: Point<T>, size: Size<T>) -> Self {
 853        let origin = Point {
 854            x: center.x - size.width.half(),
 855            y: center.y - size.height.half(),
 856        };
 857        Self::new(origin, size)
 858    }
 859}
 860
 861impl<T> Bounds<T>
 862where
 863    T: Clone + Debug + PartialOrd + Add<T, Output = T> + Default,
 864{
 865    /// Checks if this `Bounds` intersects with another `Bounds`.
 866    ///
 867    /// Two `Bounds` instances intersect if they overlap in the 2D space they occupy.
 868    /// This method checks if there is any overlapping area between the two bounds.
 869    ///
 870    /// # Arguments
 871    ///
 872    /// * `other` - A reference to another `Bounds` to check for intersection with.
 873    ///
 874    /// # Returns
 875    ///
 876    /// Returns `true` if there is any intersection between the two bounds, `false` otherwise.
 877    ///
 878    /// # Examples
 879    ///
 880    /// ```
 881    /// # use gpui::{Bounds, Point, Size};
 882    /// let bounds1 = Bounds {
 883    ///     origin: Point { x: 0, y: 0 },
 884    ///     size: Size { width: 10, height: 10 },
 885    /// };
 886    /// let bounds2 = Bounds {
 887    ///     origin: Point { x: 5, y: 5 },
 888    ///     size: Size { width: 10, height: 10 },
 889    /// };
 890    /// let bounds3 = Bounds {
 891    ///     origin: Point { x: 20, y: 20 },
 892    ///     size: Size { width: 10, height: 10 },
 893    /// };
 894    ///
 895    /// assert_eq!(bounds1.intersects(&bounds2), true); // Overlapping bounds
 896    /// assert_eq!(bounds1.intersects(&bounds3), false); // Non-overlapping bounds
 897    /// ```
 898    pub fn intersects(&self, other: &Bounds<T>) -> bool {
 899        let my_lower_right = self.bottom_right();
 900        let their_lower_right = other.bottom_right();
 901
 902        self.origin.x < their_lower_right.x
 903            && my_lower_right.x > other.origin.x
 904            && self.origin.y < their_lower_right.y
 905            && my_lower_right.y > other.origin.y
 906    }
 907}
 908
 909impl<T> Bounds<T>
 910where
 911    T: Clone + Debug + Add<T, Output = T> + Default + Half,
 912{
 913    /// Returns the center point of the bounds.
 914    ///
 915    /// Calculates the center by taking the origin's x and y coordinates and adding half the width and height
 916    /// of the bounds, respectively. The center is represented as a `Point<T>` where `T` is the type of the
 917    /// coordinate system.
 918    ///
 919    /// # Returns
 920    ///
 921    /// A `Point<T>` representing the center of the bounds.
 922    ///
 923    /// # Examples
 924    ///
 925    /// ```
 926    /// # use gpui::{Bounds, Point, Size};
 927    /// let bounds = Bounds {
 928    ///     origin: Point { x: 0, y: 0 },
 929    ///     size: Size { width: 10, height: 20 },
 930    /// };
 931    /// let center = bounds.center();
 932    /// assert_eq!(center, Point { x: 5, y: 10 });
 933    /// ```
 934    pub fn center(&self) -> Point<T> {
 935        Point {
 936            x: self.origin.x.clone() + self.size.width.clone().half(),
 937            y: self.origin.y.clone() + self.size.height.clone().half(),
 938        }
 939    }
 940}
 941
 942impl<T> Bounds<T>
 943where
 944    T: Clone + Debug + Add<T, Output = T> + Default,
 945{
 946    /// Calculates the half perimeter of a rectangle defined by the bounds.
 947    ///
 948    /// The half perimeter is calculated as the sum of the width and the height of the rectangle.
 949    /// This method is generic over the type `T` which must implement the `Sub` trait to allow
 950    /// calculation of the width and height from the bounds' origin and size, as well as the `Add` trait
 951    /// to sum the width and height for the half perimeter.
 952    ///
 953    /// # Examples
 954    ///
 955    /// ```
 956    /// # use gpui::{Bounds, Point, Size};
 957    /// let bounds = Bounds {
 958    ///     origin: Point { x: 0, y: 0 },
 959    ///     size: Size { width: 10, height: 20 },
 960    /// };
 961    /// let half_perimeter = bounds.half_perimeter();
 962    /// assert_eq!(half_perimeter, 30);
 963    /// ```
 964    pub fn half_perimeter(&self) -> T {
 965        self.size.width.clone() + self.size.height.clone()
 966    }
 967}
 968
 969impl<T> Bounds<T>
 970where
 971    T: Clone + Debug + Add<T, Output = T> + Sub<Output = T> + Default,
 972{
 973    /// Dilates the bounds by a specified amount in all directions.
 974    ///
 975    /// This method expands the bounds by the given `amount`, increasing the size
 976    /// and adjusting the origin so that the bounds grow outwards equally in all directions.
 977    /// The resulting bounds will have its width and height increased by twice the `amount`
 978    /// (since it grows in both directions), and the origin will be moved by `-amount`
 979    /// in both the x and y directions.
 980    ///
 981    /// # Arguments
 982    ///
 983    /// * `amount` - The amount by which to dilate the bounds.
 984    ///
 985    /// # Examples
 986    ///
 987    /// ```
 988    /// # use gpui::{Bounds, Point, Size};
 989    /// let mut bounds = Bounds {
 990    ///     origin: Point { x: 10, y: 10 },
 991    ///     size: Size { width: 10, height: 10 },
 992    /// };
 993    /// bounds.dilate(5);
 994    /// assert_eq!(bounds, Bounds {
 995    ///     origin: Point { x: 5, y: 5 },
 996    ///     size: Size { width: 20, height: 20 },
 997    /// });
 998    /// ```
 999    pub fn dilate(&self, amount: T) -> Bounds<T> {
1000        let double_amount = amount.clone() + amount.clone();
1001        Bounds {
1002            origin: self.origin.clone() - point(amount.clone(), amount),
1003            size: self.size.clone() + size(double_amount.clone(), double_amount),
1004        }
1005    }
1006
1007    /// Extends the bounds different amounts in each direction.
1008    pub fn extend(&self, amount: Edges<T>) -> Bounds<T> {
1009        Bounds {
1010            origin: self.origin.clone() - point(amount.left.clone(), amount.top.clone()),
1011            size: self.size.clone()
1012                + size(
1013                    amount.left.clone() + amount.right.clone(),
1014                    amount.top.clone() + amount.bottom.clone(),
1015                ),
1016        }
1017    }
1018}
1019
1020impl<T> Bounds<T>
1021where
1022    T: Clone + Debug + Add<T, Output = T> + Sub<T, Output = T> + Neg<Output = T> + Default,
1023{
1024    /// Inset the bounds by a specified amount. Equivalent to `dilate` with the amount negated.
1025    ///
1026    /// Note that this may panic if T does not support negative values.
1027    pub fn inset(&self, amount: T) -> Self {
1028        self.dilate(-amount)
1029    }
1030}
1031
1032impl<T: Clone + Default + Debug + PartialOrd + Add<T, Output = T> + Sub<Output = T>> Bounds<T> {
1033    /// Calculates the intersection of two `Bounds` objects.
1034    ///
1035    /// This method computes the overlapping region of two `Bounds`. If the bounds do not intersect,
1036    /// the resulting `Bounds` will have a size with width and height of zero.
1037    ///
1038    /// # Arguments
1039    ///
1040    /// * `other` - A reference to another `Bounds` to intersect with.
1041    ///
1042    /// # Returns
1043    ///
1044    /// Returns a `Bounds` representing the intersection area. If there is no intersection,
1045    /// the returned `Bounds` will have a size with width and height of zero.
1046    ///
1047    /// # Examples
1048    ///
1049    /// ```
1050    /// # use gpui::{Bounds, Point, Size};
1051    /// let bounds1 = Bounds {
1052    ///     origin: Point { x: 0, y: 0 },
1053    ///     size: Size { width: 10, height: 10 },
1054    /// };
1055    /// let bounds2 = Bounds {
1056    ///     origin: Point { x: 5, y: 5 },
1057    ///     size: Size { width: 10, height: 10 },
1058    /// };
1059    /// let intersection = bounds1.intersect(&bounds2);
1060    ///
1061    /// assert_eq!(intersection, Bounds {
1062    ///     origin: Point { x: 5, y: 5 },
1063    ///     size: Size { width: 5, height: 5 },
1064    /// });
1065    /// ```
1066    pub fn intersect(&self, other: &Self) -> Self {
1067        let upper_left = self.origin.max(&other.origin);
1068        let bottom_right = self.bottom_right().min(&other.bottom_right());
1069        Self::from_corners(upper_left, bottom_right)
1070    }
1071
1072    /// Computes the union of two `Bounds`.
1073    ///
1074    /// This method calculates the smallest `Bounds` that contains both the current `Bounds` and the `other` `Bounds`.
1075    /// The resulting `Bounds` will have an origin that is the minimum of the origins of the two `Bounds`,
1076    /// and a size that encompasses the furthest extents of both `Bounds`.
1077    ///
1078    /// # Arguments
1079    ///
1080    /// * `other` - A reference to another `Bounds` to create a union with.
1081    ///
1082    /// # Returns
1083    ///
1084    /// Returns a `Bounds` representing the union of the two `Bounds`.
1085    ///
1086    /// # Examples
1087    ///
1088    /// ```
1089    /// # use gpui::{Bounds, Point, Size};
1090    /// let bounds1 = Bounds {
1091    ///     origin: Point { x: 0, y: 0 },
1092    ///     size: Size { width: 10, height: 10 },
1093    /// };
1094    /// let bounds2 = Bounds {
1095    ///     origin: Point { x: 5, y: 5 },
1096    ///     size: Size { width: 15, height: 15 },
1097    /// };
1098    /// let union_bounds = bounds1.union(&bounds2);
1099    ///
1100    /// assert_eq!(union_bounds, Bounds {
1101    ///     origin: Point { x: 0, y: 0 },
1102    ///     size: Size { width: 20, height: 20 },
1103    /// });
1104    /// ```
1105    pub fn union(&self, other: &Self) -> Self {
1106        let top_left = self.origin.min(&other.origin);
1107        let bottom_right = self.bottom_right().max(&other.bottom_right());
1108        Bounds::from_corners(top_left, bottom_right)
1109    }
1110}
1111
1112impl<T> Bounds<T>
1113where
1114    T: Clone + Debug + Add<T, Output = T> + Sub<T, Output = T> + Default,
1115{
1116    /// Computes the space available within outer bounds.
1117    pub fn space_within(&self, outer: &Self) -> Edges<T> {
1118        Edges {
1119            top: self.top().clone() - outer.top().clone(),
1120            right: outer.right().clone() - self.right().clone(),
1121            bottom: outer.bottom().clone() - self.bottom().clone(),
1122            left: self.left().clone() - outer.left().clone(),
1123        }
1124    }
1125}
1126
1127impl<T, Rhs> Mul<Rhs> for Bounds<T>
1128where
1129    T: Mul<Rhs, Output = Rhs> + Clone + Default + Debug,
1130    Point<T>: Mul<Rhs, Output = Point<Rhs>>,
1131    Rhs: Clone + Default + Debug,
1132{
1133    type Output = Bounds<Rhs>;
1134
1135    fn mul(self, rhs: Rhs) -> Self::Output {
1136        Bounds {
1137            origin: self.origin * rhs.clone(),
1138            size: self.size * rhs,
1139        }
1140    }
1141}
1142
1143impl<T, S> MulAssign<S> for Bounds<T>
1144where
1145    T: Mul<S, Output = T> + Clone + Default + Debug,
1146    S: Clone,
1147{
1148    fn mul_assign(&mut self, rhs: S) {
1149        self.origin *= rhs.clone();
1150        self.size *= rhs;
1151    }
1152}
1153
1154impl<T, S> Div<S> for Bounds<T>
1155where
1156    Size<T>: Div<S, Output = Size<T>>,
1157    T: Div<S, Output = T> + Default + Clone + Debug,
1158    S: Clone,
1159{
1160    type Output = Self;
1161
1162    fn div(self, rhs: S) -> Self {
1163        Self {
1164            origin: self.origin / rhs.clone(),
1165            size: self.size / rhs,
1166        }
1167    }
1168}
1169
1170impl<T> Add<Point<T>> for Bounds<T>
1171where
1172    T: Add<T, Output = T> + Default + Clone + Debug,
1173{
1174    type Output = Self;
1175
1176    fn add(self, rhs: Point<T>) -> Self {
1177        Self {
1178            origin: self.origin + rhs,
1179            size: self.size,
1180        }
1181    }
1182}
1183
1184impl<T> Sub<Point<T>> for Bounds<T>
1185where
1186    T: Sub<T, Output = T> + Default + Clone + Debug,
1187{
1188    type Output = Self;
1189
1190    fn sub(self, rhs: Point<T>) -> Self {
1191        Self {
1192            origin: self.origin - rhs,
1193            size: self.size,
1194        }
1195    }
1196}
1197
1198impl<T> Bounds<T>
1199where
1200    T: Add<T, Output = T> + Clone + Default + Debug,
1201{
1202    /// Returns the top edge of the bounds.
1203    ///
1204    /// # Returns
1205    ///
1206    /// A value of type `T` representing the y-coordinate of the top edge of the bounds.
1207    pub fn top(&self) -> T {
1208        self.origin.y.clone()
1209    }
1210
1211    /// Returns the bottom edge of the bounds.
1212    ///
1213    /// # Returns
1214    ///
1215    /// A value of type `T` representing the y-coordinate of the bottom edge of the bounds.
1216    pub fn bottom(&self) -> T {
1217        self.origin.y.clone() + self.size.height.clone()
1218    }
1219
1220    /// Returns the left edge of the bounds.
1221    ///
1222    /// # Returns
1223    ///
1224    /// A value of type `T` representing the x-coordinate of the left edge of the bounds.
1225    pub fn left(&self) -> T {
1226        self.origin.x.clone()
1227    }
1228
1229    /// Returns the right edge of the bounds.
1230    ///
1231    /// # Returns
1232    ///
1233    /// A value of type `T` representing the x-coordinate of the right edge of the bounds.
1234    pub fn right(&self) -> T {
1235        self.origin.x.clone() + self.size.width.clone()
1236    }
1237
1238    /// Returns the top right corner point of the bounds.
1239    ///
1240    /// # Returns
1241    ///
1242    /// A `Point<T>` representing the top right corner of the bounds.
1243    ///
1244    /// # Examples
1245    ///
1246    /// ```
1247    /// # use gpui::{Bounds, Point, Size};
1248    /// let bounds = Bounds {
1249    ///     origin: Point { x: 0, y: 0 },
1250    ///     size: Size { width: 10, height: 20 },
1251    /// };
1252    /// let top_right = bounds.top_right();
1253    /// assert_eq!(top_right, Point { x: 10, y: 0 });
1254    /// ```
1255    pub fn top_right(&self) -> Point<T> {
1256        Point {
1257            x: self.origin.x.clone() + self.size.width.clone(),
1258            y: self.origin.y.clone(),
1259        }
1260    }
1261
1262    /// Returns the bottom right corner point of the bounds.
1263    ///
1264    /// # Returns
1265    ///
1266    /// A `Point<T>` representing the bottom right corner of the bounds.
1267    ///
1268    /// # Examples
1269    ///
1270    /// ```
1271    /// # use gpui::{Bounds, Point, Size};
1272    /// let bounds = Bounds {
1273    ///     origin: Point { x: 0, y: 0 },
1274    ///     size: Size { width: 10, height: 20 },
1275    /// };
1276    /// let bottom_right = bounds.bottom_right();
1277    /// assert_eq!(bottom_right, Point { x: 10, y: 20 });
1278    /// ```
1279    pub fn bottom_right(&self) -> Point<T> {
1280        Point {
1281            x: self.origin.x.clone() + self.size.width.clone(),
1282            y: self.origin.y.clone() + self.size.height.clone(),
1283        }
1284    }
1285
1286    /// Returns the bottom left corner point of the bounds.
1287    ///
1288    /// # Returns
1289    ///
1290    /// A `Point<T>` representing the bottom left corner of the bounds.
1291    ///
1292    /// # Examples
1293    ///
1294    /// ```
1295    /// # use gpui::{Bounds, Point, Size};
1296    /// let bounds = Bounds {
1297    ///     origin: Point { x: 0, y: 0 },
1298    ///     size: Size { width: 10, height: 20 },
1299    /// };
1300    /// let bottom_left = bounds.bottom_left();
1301    /// assert_eq!(bottom_left, Point { x: 0, y: 20 });
1302    /// ```
1303    pub fn bottom_left(&self) -> Point<T> {
1304        Point {
1305            x: self.origin.x.clone(),
1306            y: self.origin.y.clone() + self.size.height.clone(),
1307        }
1308    }
1309
1310    /// Returns the requested corner point of the bounds.
1311    ///
1312    /// # Returns
1313    ///
1314    /// A `Point<T>` representing the corner of the bounds requested by the parameter.
1315    ///
1316    /// # Examples
1317    ///
1318    /// ```
1319    /// # use zed::{Bounds, Corner, Point, Size};
1320    /// let bounds = Bounds {
1321    ///     origin: Point { x: 0, y: 0 },
1322    ///     size: Size { width: 10, height: 20 },
1323    /// };
1324    /// let bottom_left = bounds.corner(Corner::BottomLeft);
1325    /// assert_eq!(bottom_left, Point { x: 0, y: 20 });
1326    /// ```
1327    pub fn corner(&self, corner: Corner) -> Point<T> {
1328        match corner {
1329            Corner::TopLeft => self.origin.clone(),
1330            Corner::TopRight => self.top_right(),
1331            Corner::BottomLeft => self.bottom_left(),
1332            Corner::BottomRight => self.bottom_right(),
1333        }
1334    }
1335}
1336
1337impl<T> Bounds<T>
1338where
1339    T: Add<T, Output = T> + PartialOrd + Clone + Default + Debug,
1340{
1341    /// Checks if the given point is within the bounds.
1342    ///
1343    /// This method determines whether a point lies inside the rectangle defined by the bounds,
1344    /// including the edges. The point is considered inside if its x-coordinate is greater than
1345    /// or equal to the left edge and less than or equal to the right edge, and its y-coordinate
1346    /// is greater than or equal to the top edge and less than or equal to the bottom edge of the bounds.
1347    ///
1348    /// # Arguments
1349    ///
1350    /// * `point` - A reference to a `Point<T>` that represents the point to check.
1351    ///
1352    /// # Returns
1353    ///
1354    /// Returns `true` if the point is within the bounds, `false` otherwise.
1355    ///
1356    /// # Examples
1357    ///
1358    /// ```
1359    /// # use gpui::{Point, Bounds};
1360    /// let bounds = Bounds {
1361    ///     origin: Point { x: 0, y: 0 },
1362    ///     size: Size { width: 10, height: 10 },
1363    /// };
1364    /// let inside_point = Point { x: 5, y: 5 };
1365    /// let outside_point = Point { x: 15, y: 15 };
1366    ///
1367    /// assert!(bounds.contains_point(&inside_point));
1368    /// assert!(!bounds.contains_point(&outside_point));
1369    /// ```
1370    pub fn contains(&self, point: &Point<T>) -> bool {
1371        point.x >= self.origin.x
1372            && point.x <= self.origin.x.clone() + self.size.width.clone()
1373            && point.y >= self.origin.y
1374            && point.y <= self.origin.y.clone() + self.size.height.clone()
1375    }
1376
1377    /// Applies a function to the origin and size of the bounds, producing a new `Bounds<U>`.
1378    ///
1379    /// This method allows for converting a `Bounds<T>` to a `Bounds<U>` by specifying a closure
1380    /// that defines how to convert between the two types. The closure is applied to the `origin` and
1381    /// `size` fields, resulting in new bounds of the desired type.
1382    ///
1383    /// # Arguments
1384    ///
1385    /// * `f` - A closure that takes a value of type `T` and returns a value of type `U`.
1386    ///
1387    /// # Returns
1388    ///
1389    /// Returns a new `Bounds<U>` with the origin and size mapped by the provided function.
1390    ///
1391    /// # Examples
1392    ///
1393    /// ```
1394    /// # use gpui::{Bounds, Point, Size};
1395    /// let bounds = Bounds {
1396    ///     origin: Point { x: 10.0, y: 10.0 },
1397    ///     size: Size { width: 10.0, height: 20.0 },
1398    /// };
1399    /// let new_bounds = bounds.map(|value| value as f64 * 1.5);
1400    ///
1401    /// assert_eq!(new_bounds, Bounds {
1402    ///     origin: Point { x: 15.0, y: 15.0 },
1403    ///     size: Size { width: 15.0, height: 30.0 },
1404    /// });
1405    /// ```
1406    pub fn map<U>(&self, f: impl Fn(T) -> U) -> Bounds<U>
1407    where
1408        U: Clone + Default + Debug,
1409    {
1410        Bounds {
1411            origin: self.origin.map(&f),
1412            size: self.size.map(f),
1413        }
1414    }
1415
1416    /// Applies a function to the origin  of the bounds, producing a new `Bounds` with the new origin
1417    ///
1418    /// # Examples
1419    ///
1420    /// ```
1421    /// # use gpui::{Bounds, Point, Size};
1422    /// let bounds = Bounds {
1423    ///     origin: Point { x: 10.0, y: 10.0 },
1424    ///     size: Size { width: 10.0, height: 20.0 },
1425    /// };
1426    /// let new_bounds = bounds.map_origin(|value| value * 1.5);
1427    ///
1428    /// assert_eq!(new_bounds, Bounds {
1429    ///     origin: Point { x: 15.0, y: 15.0 },
1430    ///     size: Size { width: 10.0, height: 20.0 },
1431    /// });
1432    /// ```
1433    pub fn map_origin(self, f: impl Fn(T) -> T) -> Bounds<T> {
1434        Bounds {
1435            origin: self.origin.map(f),
1436            size: self.size,
1437        }
1438    }
1439
1440    /// Applies a function to the origin  of the bounds, producing a new `Bounds` with the new origin
1441    ///
1442    /// # Examples
1443    ///
1444    /// ```
1445    /// # use gpui::{Bounds, Point, Size};
1446    /// let bounds = Bounds {
1447    ///     origin: Point { x: 10.0, y: 10.0 },
1448    ///     size: Size { width: 10.0, height: 20.0 },
1449    /// };
1450    /// let new_bounds = bounds.map_size(|value| value * 1.5);
1451    ///
1452    /// assert_eq!(new_bounds, Bounds {
1453    ///     origin: Point { x: 10.0, y: 10.0 },
1454    ///     size: Size { width: 15.0, height: 30.0 },
1455    /// });
1456    /// ```
1457    pub fn map_size(self, f: impl Fn(T) -> T) -> Bounds<T> {
1458        Bounds {
1459            origin: self.origin,
1460            size: self.size.map(f),
1461        }
1462    }
1463}
1464
1465/// Checks if the bounds represent an empty area.
1466///
1467/// # Returns
1468///
1469/// Returns `true` if either the width or the height of the bounds is less than or equal to zero, indicating an empty area.
1470impl<T: PartialOrd + Default + Debug + Clone> Bounds<T> {
1471    /// Checks if the bounds represent an empty area.
1472    ///
1473    /// # Returns
1474    ///
1475    /// Returns `true` if either the width or the height of the bounds is less than or equal to zero, indicating an empty area.
1476    pub fn is_empty(&self) -> bool {
1477        self.size.width <= T::default() || self.size.height <= T::default()
1478    }
1479}
1480
1481impl Size<DevicePixels> {
1482    /// Converts the size from physical to logical pixels.
1483    pub(crate) fn to_pixels(self, scale_factor: f32) -> Size<Pixels> {
1484        size(
1485            px(self.width.0 as f32 / scale_factor),
1486            px(self.height.0 as f32 / scale_factor),
1487        )
1488    }
1489}
1490
1491impl Size<Pixels> {
1492    /// Converts the size from physical to logical pixels.
1493    pub(crate) fn to_device_pixels(self, scale_factor: f32) -> Size<DevicePixels> {
1494        size(
1495            DevicePixels((self.width.0 * scale_factor) as i32),
1496            DevicePixels((self.height.0 * scale_factor) as i32),
1497        )
1498    }
1499}
1500
1501impl Bounds<Pixels> {
1502    /// Scales the bounds by a given factor, typically used to adjust for display scaling.
1503    ///
1504    /// This method multiplies the origin and size of the bounds by the provided scaling factor,
1505    /// resulting in a new `Bounds<ScaledPixels>` that is proportionally larger or smaller
1506    /// depending on the scaling factor. This can be used to ensure that the bounds are properly
1507    /// scaled for different display densities.
1508    ///
1509    /// # Arguments
1510    ///
1511    /// * `factor` - The scaling factor to apply to the origin and size, typically the display's scaling factor.
1512    ///
1513    /// # Returns
1514    ///
1515    /// Returns a new `Bounds<ScaledPixels>` that represents the scaled bounds.
1516    ///
1517    /// # Examples
1518    ///
1519    /// ```
1520    /// # use gpui::{Bounds, Point, Size, Pixels};
1521    /// let bounds = Bounds {
1522    ///     origin: Point { x: Pixels(10.0), y: Pixels(20.0) },
1523    ///     size: Size { width: Pixels(30.0), height: Pixels(40.0) },
1524    /// };
1525    /// let display_scale_factor = 2.0;
1526    /// let scaled_bounds = bounds.scale(display_scale_factor);
1527    /// assert_eq!(scaled_bounds, Bounds {
1528    ///     origin: Point { x: ScaledPixels(20.0), y: ScaledPixels(40.0) },
1529    ///     size: Size { width: ScaledPixels(60.0), height: ScaledPixels(80.0) },
1530    /// });
1531    /// ```
1532    pub fn scale(&self, factor: f32) -> Bounds<ScaledPixels> {
1533        Bounds {
1534            origin: self.origin.scale(factor),
1535            size: self.size.scale(factor),
1536        }
1537    }
1538
1539    /// Convert the bounds from logical pixels to physical pixels
1540    pub fn to_device_pixels(&self, factor: f32) -> Bounds<DevicePixels> {
1541        Bounds {
1542            origin: point(
1543                DevicePixels((self.origin.x.0 * factor) as i32),
1544                DevicePixels((self.origin.y.0 * factor) as i32),
1545            ),
1546            size: self.size.to_device_pixels(factor),
1547        }
1548    }
1549}
1550
1551impl Bounds<DevicePixels> {
1552    /// Convert the bounds from physical pixels to logical pixels
1553    pub fn to_pixels(self, scale_factor: f32) -> Bounds<Pixels> {
1554        Bounds {
1555            origin: point(
1556                px(self.origin.x.0 as f32 / scale_factor),
1557                px(self.origin.y.0 as f32 / scale_factor),
1558            ),
1559            size: self.size.to_pixels(scale_factor),
1560        }
1561    }
1562}
1563
1564impl<T: Clone + Debug + Copy + Default> Copy for Bounds<T> {}
1565
1566/// Represents the edges of a box in a 2D space, such as padding or margin.
1567///
1568/// Each field represents the size of the edge on one side of the box: `top`, `right`, `bottom`, and `left`.
1569///
1570/// # Examples
1571///
1572/// ```
1573/// # use gpui::Edges;
1574/// let edges = Edges {
1575///     top: 10.0,
1576///     right: 20.0,
1577///     bottom: 30.0,
1578///     left: 40.0,
1579/// };
1580///
1581/// assert_eq!(edges.top, 10.0);
1582/// assert_eq!(edges.right, 20.0);
1583/// assert_eq!(edges.bottom, 30.0);
1584/// assert_eq!(edges.left, 40.0);
1585/// ```
1586#[derive(Refineable, Clone, Default, Debug, Eq, PartialEq)]
1587#[refineable(Debug)]
1588#[repr(C)]
1589pub struct Edges<T: Clone + Default + Debug> {
1590    /// The size of the top edge.
1591    pub top: T,
1592    /// The size of the right edge.
1593    pub right: T,
1594    /// The size of the bottom edge.
1595    pub bottom: T,
1596    /// The size of the left edge.
1597    pub left: T,
1598}
1599
1600impl<T> Mul for Edges<T>
1601where
1602    T: Mul<Output = T> + Clone + Default + Debug,
1603{
1604    type Output = Self;
1605
1606    fn mul(self, rhs: Self) -> Self::Output {
1607        Self {
1608            top: self.top.clone() * rhs.top,
1609            right: self.right.clone() * rhs.right,
1610            bottom: self.bottom.clone() * rhs.bottom,
1611            left: self.left.clone() * rhs.left,
1612        }
1613    }
1614}
1615
1616impl<T, S> MulAssign<S> for Edges<T>
1617where
1618    T: Mul<S, Output = T> + Clone + Default + Debug,
1619    S: Clone,
1620{
1621    fn mul_assign(&mut self, rhs: S) {
1622        self.top = self.top.clone() * rhs.clone();
1623        self.right = self.right.clone() * rhs.clone();
1624        self.bottom = self.bottom.clone() * rhs.clone();
1625        self.left = self.left.clone() * rhs;
1626    }
1627}
1628
1629impl<T: Clone + Default + Debug + Copy> Copy for Edges<T> {}
1630
1631impl<T: Clone + Default + Debug> Edges<T> {
1632    /// Constructs `Edges` where all sides are set to the same specified value.
1633    ///
1634    /// This function creates an `Edges` instance with the `top`, `right`, `bottom`, and `left` fields all initialized
1635    /// to the same value provided as an argument. This is useful when you want to have uniform edges around a box,
1636    /// such as padding or margin with the same size on all sides.
1637    ///
1638    /// # Arguments
1639    ///
1640    /// * `value` - The value to set for all four sides of the edges.
1641    ///
1642    /// # Returns
1643    ///
1644    /// An `Edges` instance with all sides set to the given value.
1645    ///
1646    /// # Examples
1647    ///
1648    /// ```
1649    /// # use gpui::Edges;
1650    /// let uniform_edges = Edges::all(10.0);
1651    /// assert_eq!(uniform_edges.top, 10.0);
1652    /// assert_eq!(uniform_edges.right, 10.0);
1653    /// assert_eq!(uniform_edges.bottom, 10.0);
1654    /// assert_eq!(uniform_edges.left, 10.0);
1655    /// ```
1656    pub fn all(value: T) -> Self {
1657        Self {
1658            top: value.clone(),
1659            right: value.clone(),
1660            bottom: value.clone(),
1661            left: value,
1662        }
1663    }
1664
1665    /// Applies a function to each field of the `Edges`, producing a new `Edges<U>`.
1666    ///
1667    /// This method allows for converting an `Edges<T>` to an `Edges<U>` by specifying a closure
1668    /// that defines how to convert between the two types. The closure is applied to each field
1669    /// (`top`, `right`, `bottom`, `left`), resulting in new edges of the desired type.
1670    ///
1671    /// # Arguments
1672    ///
1673    /// * `f` - A closure that takes a reference to a value of type `T` and returns a value of type `U`.
1674    ///
1675    /// # Returns
1676    ///
1677    /// Returns a new `Edges<U>` with each field mapped by the provided function.
1678    ///
1679    /// # Examples
1680    ///
1681    /// ```
1682    /// # use gpui::Edges;
1683    /// let edges = Edges { top: 10, right: 20, bottom: 30, left: 40 };
1684    /// let edges_float = edges.map(|&value| value as f32 * 1.1);
1685    /// assert_eq!(edges_float, Edges { top: 11.0, right: 22.0, bottom: 33.0, left: 44.0 });
1686    /// ```
1687    pub fn map<U>(&self, f: impl Fn(&T) -> U) -> Edges<U>
1688    where
1689        U: Clone + Default + Debug,
1690    {
1691        Edges {
1692            top: f(&self.top),
1693            right: f(&self.right),
1694            bottom: f(&self.bottom),
1695            left: f(&self.left),
1696        }
1697    }
1698
1699    /// Checks if any of the edges satisfy a given predicate.
1700    ///
1701    /// This method applies a predicate function to each field of the `Edges` and returns `true` if any field satisfies the predicate.
1702    ///
1703    /// # Arguments
1704    ///
1705    /// * `predicate` - A closure that takes a reference to a value of type `T` and returns a `bool`.
1706    ///
1707    /// # Returns
1708    ///
1709    /// Returns `true` if the predicate returns `true` for any of the edge values, `false` otherwise.
1710    ///
1711    /// # Examples
1712    ///
1713    /// ```
1714    /// # use gpui::Edges;
1715    /// let edges = Edges {
1716    ///     top: 10,
1717    ///     right: 0,
1718    ///     bottom: 5,
1719    ///     left: 0,
1720    /// };
1721    ///
1722    /// assert!(edges.any(|value| *value == 0));
1723    /// assert!(edges.any(|value| *value > 0));
1724    /// assert!(!edges.any(|value| *value > 10));
1725    /// ```
1726    pub fn any<F: Fn(&T) -> bool>(&self, predicate: F) -> bool {
1727        predicate(&self.top)
1728            || predicate(&self.right)
1729            || predicate(&self.bottom)
1730            || predicate(&self.left)
1731    }
1732}
1733
1734impl Edges<Length> {
1735    /// 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.
1736    ///
1737    /// 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.
1738    ///
1739    /// # Returns
1740    ///
1741    /// Returns an `Edges<Length>` with all edges set to `Length::Auto`.
1742    ///
1743    /// # Examples
1744    ///
1745    /// ```
1746    /// # use gpui::Edges;
1747    /// let auto_edges = Edges::auto();
1748    /// assert_eq!(auto_edges.top, Length::Auto);
1749    /// assert_eq!(auto_edges.right, Length::Auto);
1750    /// assert_eq!(auto_edges.bottom, Length::Auto);
1751    /// assert_eq!(auto_edges.left, Length::Auto);
1752    /// ```
1753    pub fn auto() -> Self {
1754        Self {
1755            top: Length::Auto,
1756            right: Length::Auto,
1757            bottom: Length::Auto,
1758            left: Length::Auto,
1759        }
1760    }
1761
1762    /// Sets the edges of the `Edges` struct to zero, which means no size or thickness.
1763    ///
1764    /// This is typically used when you want to specify that a box (like a padding or margin area)
1765    /// should have no edges, effectively making it non-existent or invisible in layout calculations.
1766    ///
1767    /// # Returns
1768    ///
1769    /// Returns an `Edges<Length>` with all edges set to zero length.
1770    ///
1771    /// # Examples
1772    ///
1773    /// ```
1774    /// # use gpui::Edges;
1775    /// let no_edges = Edges::zero();
1776    /// assert_eq!(no_edges.top, Length::Definite(DefiniteLength::from(Pixels(0.))));
1777    /// assert_eq!(no_edges.right, Length::Definite(DefiniteLength::from(Pixels(0.))));
1778    /// assert_eq!(no_edges.bottom, Length::Definite(DefiniteLength::from(Pixels(0.))));
1779    /// assert_eq!(no_edges.left, Length::Definite(DefiniteLength::from(Pixels(0.))));
1780    /// ```
1781    pub fn zero() -> Self {
1782        Self {
1783            top: px(0.).into(),
1784            right: px(0.).into(),
1785            bottom: px(0.).into(),
1786            left: px(0.).into(),
1787        }
1788    }
1789}
1790
1791impl Edges<DefiniteLength> {
1792    /// Sets the edges of the `Edges` struct to zero, which means no size or thickness.
1793    ///
1794    /// This is typically used when you want to specify that a box (like a padding or margin area)
1795    /// should have no edges, effectively making it non-existent or invisible in layout calculations.
1796    ///
1797    /// # Returns
1798    ///
1799    /// Returns an `Edges<DefiniteLength>` with all edges set to zero length.
1800    ///
1801    /// # Examples
1802    ///
1803    /// ```
1804    /// # use gpui::{px, Edges};
1805    /// let no_edges = Edges::zero();
1806    /// assert_eq!(no_edges.top, DefiniteLength::from(px(0.)));
1807    /// assert_eq!(no_edges.right, DefiniteLength::from(px(0.)));
1808    /// assert_eq!(no_edges.bottom, DefiniteLength::from(px(0.)));
1809    /// assert_eq!(no_edges.left, DefiniteLength::from(px(0.)));
1810    /// ```
1811    pub fn zero() -> Self {
1812        Self {
1813            top: px(0.).into(),
1814            right: px(0.).into(),
1815            bottom: px(0.).into(),
1816            left: px(0.).into(),
1817        }
1818    }
1819
1820    /// Converts the `DefiniteLength` to `Pixels` based on the parent size and the REM size.
1821    ///
1822    /// This method allows for a `DefiniteLength` value to be converted into pixels, taking into account
1823    /// the size of the parent element (for percentage-based lengths) and the size of a rem unit (for rem-based lengths).
1824    ///
1825    /// # Arguments
1826    ///
1827    /// * `parent_size` - `Size<AbsoluteLength>` representing the size of the parent element.
1828    /// * `rem_size` - `Pixels` representing the size of one REM unit.
1829    ///
1830    /// # Returns
1831    ///
1832    /// Returns an `Edges<Pixels>` representing the edges with lengths converted to pixels.
1833    ///
1834    /// # Examples
1835    ///
1836    /// ```
1837    /// # use gpui::{Edges, DefiniteLength, px, AbsoluteLength, Size};
1838    /// let edges = Edges {
1839    ///     top: DefiniteLength::Absolute(AbsoluteLength::Pixels(px(10.0))),
1840    ///     right: DefiniteLength::Fraction(0.5),
1841    ///     bottom: DefiniteLength::Absolute(AbsoluteLength::Rems(rems(2.0))),
1842    ///     left: DefiniteLength::Fraction(0.25),
1843    /// };
1844    /// let parent_size = Size {
1845    ///     width: AbsoluteLength::Pixels(px(200.0)),
1846    ///     height: AbsoluteLength::Pixels(px(100.0)),
1847    /// };
1848    /// let rem_size = px(16.0);
1849    /// let edges_in_pixels = edges.to_pixels(parent_size, rem_size);
1850    ///
1851    /// assert_eq!(edges_in_pixels.top, px(10.0)); // Absolute length in pixels
1852    /// assert_eq!(edges_in_pixels.right, px(100.0)); // 50% of parent width
1853    /// assert_eq!(edges_in_pixels.bottom, px(32.0)); // 2 rems
1854    /// assert_eq!(edges_in_pixels.left, px(50.0)); // 25% of parent width
1855    /// ```
1856    pub fn to_pixels(&self, parent_size: Size<AbsoluteLength>, rem_size: Pixels) -> Edges<Pixels> {
1857        Edges {
1858            top: self.top.to_pixels(parent_size.height, rem_size),
1859            right: self.right.to_pixels(parent_size.width, rem_size),
1860            bottom: self.bottom.to_pixels(parent_size.height, rem_size),
1861            left: self.left.to_pixels(parent_size.width, rem_size),
1862        }
1863    }
1864}
1865
1866impl Edges<AbsoluteLength> {
1867    /// Sets the edges of the `Edges` struct to zero, which means no size or thickness.
1868    ///
1869    /// This is typically used when you want to specify that a box (like a padding or margin area)
1870    /// should have no edges, effectively making it non-existent or invisible in layout calculations.
1871    ///
1872    /// # Returns
1873    ///
1874    /// Returns an `Edges<AbsoluteLength>` with all edges set to zero length.
1875    ///
1876    /// # Examples
1877    ///
1878    /// ```
1879    /// # use gpui::Edges;
1880    /// let no_edges = Edges::zero();
1881    /// assert_eq!(no_edges.top, AbsoluteLength::Pixels(Pixels(0.0)));
1882    /// assert_eq!(no_edges.right, AbsoluteLength::Pixels(Pixels(0.0)));
1883    /// assert_eq!(no_edges.bottom, AbsoluteLength::Pixels(Pixels(0.0)));
1884    /// assert_eq!(no_edges.left, AbsoluteLength::Pixels(Pixels(0.0)));
1885    /// ```
1886    pub fn zero() -> Self {
1887        Self {
1888            top: px(0.).into(),
1889            right: px(0.).into(),
1890            bottom: px(0.).into(),
1891            left: px(0.).into(),
1892        }
1893    }
1894
1895    /// Converts the `AbsoluteLength` to `Pixels` based on the `rem_size`.
1896    ///
1897    /// If the `AbsoluteLength` is already in pixels, it simply returns the corresponding `Pixels` value.
1898    /// If the `AbsoluteLength` is in rems, it multiplies the number of rems by the `rem_size` to convert it to pixels.
1899    ///
1900    /// # Arguments
1901    ///
1902    /// * `rem_size` - The size of one rem unit in pixels.
1903    ///
1904    /// # Returns
1905    ///
1906    /// Returns an `Edges<Pixels>` representing the edges with lengths converted to pixels.
1907    ///
1908    /// # Examples
1909    ///
1910    /// ```
1911    /// # use gpui::{Edges, AbsoluteLength, Pixels, px};
1912    /// let edges = Edges {
1913    ///     top: AbsoluteLength::Pixels(px(10.0)),
1914    ///     right: AbsoluteLength::Rems(rems(1.0)),
1915    ///     bottom: AbsoluteLength::Pixels(px(20.0)),
1916    ///     left: AbsoluteLength::Rems(rems(2.0)),
1917    /// };
1918    /// let rem_size = px(16.0);
1919    /// let edges_in_pixels = edges.to_pixels(rem_size);
1920    ///
1921    /// assert_eq!(edges_in_pixels.top, px(10.0)); // Already in pixels
1922    /// assert_eq!(edges_in_pixels.right, px(16.0)); // 1 rem converted to pixels
1923    /// assert_eq!(edges_in_pixels.bottom, px(20.0)); // Already in pixels
1924    /// assert_eq!(edges_in_pixels.left, px(32.0)); // 2 rems converted to pixels
1925    /// ```
1926    pub fn to_pixels(&self, rem_size: Pixels) -> Edges<Pixels> {
1927        Edges {
1928            top: self.top.to_pixels(rem_size),
1929            right: self.right.to_pixels(rem_size),
1930            bottom: self.bottom.to_pixels(rem_size),
1931            left: self.left.to_pixels(rem_size),
1932        }
1933    }
1934}
1935
1936impl Edges<Pixels> {
1937    /// Scales the `Edges<Pixels>` by a given factor, returning `Edges<ScaledPixels>`.
1938    ///
1939    /// This method is typically used for adjusting the edge sizes for different display densities or scaling factors.
1940    ///
1941    /// # Arguments
1942    ///
1943    /// * `factor` - The scaling factor to apply to each edge.
1944    ///
1945    /// # Returns
1946    ///
1947    /// Returns a new `Edges<ScaledPixels>` where each edge is the result of scaling the original edge by the given factor.
1948    ///
1949    /// # Examples
1950    ///
1951    /// ```
1952    /// # use gpui::{Edges, Pixels};
1953    /// let edges = Edges {
1954    ///     top: Pixels(10.0),
1955    ///     right: Pixels(20.0),
1956    ///     bottom: Pixels(30.0),
1957    ///     left: Pixels(40.0),
1958    /// };
1959    /// let scaled_edges = edges.scale(2.0);
1960    /// assert_eq!(scaled_edges.top, ScaledPixels(20.0));
1961    /// assert_eq!(scaled_edges.right, ScaledPixels(40.0));
1962    /// assert_eq!(scaled_edges.bottom, ScaledPixels(60.0));
1963    /// assert_eq!(scaled_edges.left, ScaledPixels(80.0));
1964    /// ```
1965    pub fn scale(&self, factor: f32) -> Edges<ScaledPixels> {
1966        Edges {
1967            top: self.top.scale(factor),
1968            right: self.right.scale(factor),
1969            bottom: self.bottom.scale(factor),
1970            left: self.left.scale(factor),
1971        }
1972    }
1973
1974    /// Returns the maximum value of any edge.
1975    ///
1976    /// # Returns
1977    ///
1978    /// The maximum `Pixels` value among all four edges.
1979    pub fn max(&self) -> Pixels {
1980        self.top.max(self.right).max(self.bottom).max(self.left)
1981    }
1982}
1983
1984impl From<f32> for Edges<Pixels> {
1985    fn from(val: f32) -> Self {
1986        let val: Pixels = val.into();
1987        val.into()
1988    }
1989}
1990
1991impl From<Pixels> for Edges<Pixels> {
1992    fn from(val: Pixels) -> Self {
1993        Edges {
1994            top: val,
1995            right: val,
1996            bottom: val,
1997            left: val,
1998        }
1999    }
2000}
2001
2002/// Identifies a corner of a 2d box.
2003#[derive(Clone, Copy, PartialEq, Eq)]
2004pub enum Corner {
2005    /// The top left corner
2006    TopLeft,
2007    /// The top right corner
2008    TopRight,
2009    /// The bottom left corner
2010    BottomLeft,
2011    /// The bottom right corner
2012    BottomRight,
2013}
2014
2015impl Corner {
2016    /// Returns the directly opposite corner.
2017    ///
2018    /// # Examples
2019    ///
2020    /// ```
2021    /// # use zed::Corner;
2022    /// assert_eq!(Corner::TopLeft.opposite_corner(), Corner::BottomRight);
2023    /// ```
2024    pub fn opposite_corner(self) -> Self {
2025        match self {
2026            Corner::TopLeft => Corner::BottomRight,
2027            Corner::TopRight => Corner::BottomLeft,
2028            Corner::BottomLeft => Corner::TopRight,
2029            Corner::BottomRight => Corner::TopLeft,
2030        }
2031    }
2032
2033    /// Returns the corner across from this corner, moving along the specified axis.
2034    ///
2035    /// # Examples
2036    ///
2037    /// ```
2038    /// # use zed::Corner;
2039    /// let result = Corner::TopLeft.other_side_corner_along(Axis::Horizontal);
2040    /// assert_eq!(result, Corner::TopRight);
2041    /// ```
2042    pub fn other_side_corner_along(self, axis: Axis) -> Self {
2043        match axis {
2044            Axis::Vertical => match self {
2045                Corner::TopLeft => Corner::BottomLeft,
2046                Corner::TopRight => Corner::BottomRight,
2047                Corner::BottomLeft => Corner::TopLeft,
2048                Corner::BottomRight => Corner::TopRight,
2049            },
2050            Axis::Horizontal => match self {
2051                Corner::TopLeft => Corner::TopRight,
2052                Corner::TopRight => Corner::TopLeft,
2053                Corner::BottomLeft => Corner::BottomRight,
2054                Corner::BottomRight => Corner::BottomLeft,
2055            },
2056        }
2057    }
2058}
2059
2060/// Represents the corners of a box in a 2D space, such as border radius.
2061///
2062/// Each field represents the size of the corner on one side of the box: `top_left`, `top_right`, `bottom_right`, and `bottom_left`.
2063#[derive(Refineable, Clone, Default, Debug, Eq, PartialEq)]
2064#[refineable(Debug)]
2065#[repr(C)]
2066pub struct Corners<T: Clone + Default + Debug> {
2067    /// The value associated with the top left corner.
2068    pub top_left: T,
2069    /// The value associated with the top right corner.
2070    pub top_right: T,
2071    /// The value associated with the bottom right corner.
2072    pub bottom_right: T,
2073    /// The value associated with the bottom left corner.
2074    pub bottom_left: T,
2075}
2076
2077impl<T> Corners<T>
2078where
2079    T: Clone + Default + Debug,
2080{
2081    /// Constructs `Corners` where all sides are set to the same specified value.
2082    ///
2083    /// This function creates a `Corners` instance with the `top_left`, `top_right`, `bottom_right`, and `bottom_left` fields all initialized
2084    /// to the same value provided as an argument. This is useful when you want to have uniform corners around a box,
2085    /// such as a uniform border radius on a rectangle.
2086    ///
2087    /// # Arguments
2088    ///
2089    /// * `value` - The value to set for all four corners.
2090    ///
2091    /// # Returns
2092    ///
2093    /// An `Corners` instance with all corners set to the given value.
2094    ///
2095    /// # Examples
2096    ///
2097    /// ```
2098    /// # use gpui::Corners;
2099    /// let uniform_corners = Corners::all(5.0);
2100    /// assert_eq!(uniform_corners.top_left, 5.0);
2101    /// assert_eq!(uniform_corners.top_right, 5.0);
2102    /// assert_eq!(uniform_corners.bottom_right, 5.0);
2103    /// assert_eq!(uniform_corners.bottom_left, 5.0);
2104    /// ```
2105    pub fn all(value: T) -> Self {
2106        Self {
2107            top_left: value.clone(),
2108            top_right: value.clone(),
2109            bottom_right: value.clone(),
2110            bottom_left: value,
2111        }
2112    }
2113
2114    /// Returns the requested corner.
2115    ///
2116    /// # Returns
2117    ///
2118    /// A `Point<T>` representing the corner requested by the parameter.
2119    ///
2120    /// # Examples
2121    ///
2122    /// ```
2123    /// # use zed::{Corner, Corners};
2124    /// let corners = Corners {
2125    ///     top_left: 1,
2126    ///     top_right: 2,
2127    ///     bottom_left: 3,
2128    ///     bottom_right: 4
2129    /// };
2130    /// assert_eq!(corners.corner(Corner::BottomLeft), 3);
2131    /// ```
2132    pub fn corner(&self, corner: Corner) -> T {
2133        match corner {
2134            Corner::TopLeft => self.top_left.clone(),
2135            Corner::TopRight => self.top_right.clone(),
2136            Corner::BottomLeft => self.bottom_left.clone(),
2137            Corner::BottomRight => self.bottom_right.clone(),
2138        }
2139    }
2140}
2141
2142impl Corners<AbsoluteLength> {
2143    /// Converts the `AbsoluteLength` to `Pixels` based on the provided size and rem size, ensuring the resulting
2144    /// `Pixels` do not exceed half of the minimum of the provided size's width and height.
2145    ///
2146    /// This method is particularly useful when dealing with corner radii, where the radius in pixels should not
2147    /// exceed half the size of the box it applies to, to avoid the corners overlapping.
2148    ///
2149    /// # Arguments
2150    ///
2151    /// * `size` - The `Size<Pixels>` against which the minimum allowable radius is determined.
2152    /// * `rem_size` - The size of one REM unit in pixels, used for conversion if the `AbsoluteLength` is in REMs.
2153    ///
2154    /// # Returns
2155    ///
2156    /// Returns a `Corners<Pixels>` instance with each corner's length converted to pixels and clamped to the
2157    /// minimum allowable radius based on the provided size.
2158    ///
2159    /// # Examples
2160    ///
2161    /// ```
2162    /// # use gpui::{Corners, AbsoluteLength, Pixels, Size};
2163    /// let corners = Corners {
2164    ///     top_left: AbsoluteLength::Pixels(Pixels(15.0)),
2165    ///     top_right: AbsoluteLength::Rems(Rems(1.0)),
2166    ///     bottom_right: AbsoluteLength::Pixels(Pixels(30.0)),
2167    ///     bottom_left: AbsoluteLength::Rems(Rems(2.0)),
2168    /// };
2169    /// let size = Size { width: Pixels(100.0), height: Pixels(50.0) };
2170    /// let rem_size = Pixels(16.0);
2171    /// let corners_in_pixels = corners.to_pixels(size, rem_size);
2172    ///
2173    /// // The resulting corners should not exceed half the size of the smallest dimension (50.0 / 2.0 = 25.0).
2174    /// assert_eq!(corners_in_pixels.top_left, Pixels(15.0));
2175    /// assert_eq!(corners_in_pixels.top_right, Pixels(16.0)); // 1 rem converted to pixels
2176    /// assert_eq!(corners_in_pixels.bottom_right, Pixels(30.0).min(Pixels(25.0))); // Clamped to 25.0
2177    /// assert_eq!(corners_in_pixels.bottom_left, Pixels(32.0).min(Pixels(25.0))); // 2 rems converted to pixels and clamped to 25.0
2178    /// ```
2179    pub fn to_pixels(&self, size: Size<Pixels>, rem_size: Pixels) -> Corners<Pixels> {
2180        let max = size.width.min(size.height) / 2.;
2181        Corners {
2182            top_left: self.top_left.to_pixels(rem_size).min(max),
2183            top_right: self.top_right.to_pixels(rem_size).min(max),
2184            bottom_right: self.bottom_right.to_pixels(rem_size).min(max),
2185            bottom_left: self.bottom_left.to_pixels(rem_size).min(max),
2186        }
2187    }
2188}
2189
2190impl Corners<Pixels> {
2191    /// Scales the `Corners<Pixels>` by a given factor, returning `Corners<ScaledPixels>`.
2192    ///
2193    /// This method is typically used for adjusting the corner sizes for different display densities or scaling factors.
2194    ///
2195    /// # Arguments
2196    ///
2197    /// * `factor` - The scaling factor to apply to each corner.
2198    ///
2199    /// # Returns
2200    ///
2201    /// Returns a new `Corners<ScaledPixels>` where each corner is the result of scaling the original corner by the given factor.
2202    ///
2203    /// # Examples
2204    ///
2205    /// ```
2206    /// # use gpui::{Corners, Pixels};
2207    /// let corners = Corners {
2208    ///     top_left: Pixels(10.0),
2209    ///     top_right: Pixels(20.0),
2210    ///     bottom_right: Pixels(30.0),
2211    ///     bottom_left: Pixels(40.0),
2212    /// };
2213    /// let scaled_corners = corners.scale(2.0);
2214    /// assert_eq!(scaled_corners.top_left, ScaledPixels(20.0));
2215    /// assert_eq!(scaled_corners.top_right, ScaledPixels(40.0));
2216    /// assert_eq!(scaled_corners.bottom_right, ScaledPixels(60.0));
2217    /// assert_eq!(scaled_corners.bottom_left, ScaledPixels(80.0));
2218    /// ```
2219    pub fn scale(&self, factor: f32) -> Corners<ScaledPixels> {
2220        Corners {
2221            top_left: self.top_left.scale(factor),
2222            top_right: self.top_right.scale(factor),
2223            bottom_right: self.bottom_right.scale(factor),
2224            bottom_left: self.bottom_left.scale(factor),
2225        }
2226    }
2227
2228    /// Returns the maximum value of any corner.
2229    ///
2230    /// # Returns
2231    ///
2232    /// The maximum `Pixels` value among all four corners.
2233    pub fn max(&self) -> Pixels {
2234        self.top_left
2235            .max(self.top_right)
2236            .max(self.bottom_right)
2237            .max(self.bottom_left)
2238    }
2239}
2240
2241impl<T: Clone + Default + Debug> Corners<T> {
2242    /// Applies a function to each field of the `Corners`, producing a new `Corners<U>`.
2243    ///
2244    /// This method allows for converting a `Corners<T>` to a `Corners<U>` by specifying a closure
2245    /// that defines how to convert between the two types. The closure is applied to each field
2246    /// (`top_left`, `top_right`, `bottom_right`, `bottom_left`), resulting in new corners of the desired type.
2247    ///
2248    /// # Arguments
2249    ///
2250    /// * `f` - A closure that takes a reference to a value of type `T` and returns a value of type `U`.
2251    ///
2252    /// # Returns
2253    ///
2254    /// Returns a new `Corners<U>` with each field mapped by the provided function.
2255    ///
2256    /// # Examples
2257    ///
2258    /// ```
2259    /// # use gpui::{Corners, Pixels};
2260    /// let corners = Corners {
2261    ///     top_left: Pixels(10.0),
2262    ///     top_right: Pixels(20.0),
2263    ///     bottom_right: Pixels(30.0),
2264    ///     bottom_left: Pixels(40.0),
2265    /// };
2266    /// let corners_in_rems = corners.map(|&px| Rems(px.0 / 16.0));
2267    /// assert_eq!(corners_in_rems, Corners {
2268    ///     top_left: Rems(0.625),
2269    ///     top_right: Rems(1.25),
2270    ///     bottom_right: Rems(1.875),
2271    ///     bottom_left: Rems(2.5),
2272    /// });
2273    /// ```
2274    pub fn map<U>(&self, f: impl Fn(&T) -> U) -> Corners<U>
2275    where
2276        U: Clone + Default + Debug,
2277    {
2278        Corners {
2279            top_left: f(&self.top_left),
2280            top_right: f(&self.top_right),
2281            bottom_right: f(&self.bottom_right),
2282            bottom_left: f(&self.bottom_left),
2283        }
2284    }
2285}
2286
2287impl<T> Mul for Corners<T>
2288where
2289    T: Mul<Output = T> + Clone + Default + Debug,
2290{
2291    type Output = Self;
2292
2293    fn mul(self, rhs: Self) -> Self::Output {
2294        Self {
2295            top_left: self.top_left.clone() * rhs.top_left,
2296            top_right: self.top_right.clone() * rhs.top_right,
2297            bottom_right: self.bottom_right.clone() * rhs.bottom_right,
2298            bottom_left: self.bottom_left.clone() * rhs.bottom_left,
2299        }
2300    }
2301}
2302
2303impl<T, S> MulAssign<S> for Corners<T>
2304where
2305    T: Mul<S, Output = T> + Clone + Default + Debug,
2306    S: Clone,
2307{
2308    fn mul_assign(&mut self, rhs: S) {
2309        self.top_left = self.top_left.clone() * rhs.clone();
2310        self.top_right = self.top_right.clone() * rhs.clone();
2311        self.bottom_right = self.bottom_right.clone() * rhs.clone();
2312        self.bottom_left = self.bottom_left.clone() * rhs;
2313    }
2314}
2315
2316impl<T> Copy for Corners<T> where T: Copy + Clone + Default + Debug {}
2317
2318impl From<f32> for Corners<Pixels> {
2319    fn from(val: f32) -> Self {
2320        Corners {
2321            top_left: val.into(),
2322            top_right: val.into(),
2323            bottom_right: val.into(),
2324            bottom_left: val.into(),
2325        }
2326    }
2327}
2328
2329impl From<Pixels> for Corners<Pixels> {
2330    fn from(val: Pixels) -> Self {
2331        Corners {
2332            top_left: val,
2333            top_right: val,
2334            bottom_right: val,
2335            bottom_left: val,
2336        }
2337    }
2338}
2339
2340/// Represents an angle in Radians
2341#[derive(
2342    Clone,
2343    Copy,
2344    Default,
2345    Add,
2346    AddAssign,
2347    Sub,
2348    SubAssign,
2349    Neg,
2350    Div,
2351    DivAssign,
2352    PartialEq,
2353    Serialize,
2354    Deserialize,
2355    Debug,
2356)]
2357#[repr(transparent)]
2358pub struct Radians(pub f32);
2359
2360/// Create a `Radian` from a raw value
2361pub fn radians(value: f32) -> Radians {
2362    Radians(value)
2363}
2364
2365/// A type representing a percentage value.
2366#[derive(
2367    Clone,
2368    Copy,
2369    Default,
2370    Add,
2371    AddAssign,
2372    Sub,
2373    SubAssign,
2374    Neg,
2375    Div,
2376    DivAssign,
2377    PartialEq,
2378    Serialize,
2379    Deserialize,
2380    Debug,
2381)]
2382#[repr(transparent)]
2383pub struct Percentage(pub f32);
2384
2385/// Generate a `Radian` from a percentage of a full circle.
2386pub fn percentage(value: f32) -> Percentage {
2387    debug_assert!(
2388        (0.0..=1.0).contains(&value),
2389        "Percentage must be between 0 and 1"
2390    );
2391    Percentage(value)
2392}
2393
2394impl From<Percentage> for Radians {
2395    fn from(value: Percentage) -> Self {
2396        radians(value.0 * std::f32::consts::PI * 2.0)
2397    }
2398}
2399
2400/// Represents a length in pixels, the base unit of measurement in the UI framework.
2401///
2402/// `Pixels` is a value type that represents an absolute length in pixels, which is used
2403/// for specifying sizes, positions, and distances in the UI. It is the fundamental unit
2404/// of measurement for all visual elements and layout calculations.
2405///
2406/// The inner value is an `f32`, allowing for sub-pixel precision which can be useful for
2407/// anti-aliasing and animations. However, when applied to actual pixel grids, the value
2408/// is typically rounded to the nearest integer.
2409///
2410/// # Examples
2411///
2412/// ```
2413/// use gpui::Pixels;
2414///
2415/// // Define a length of 10 pixels
2416/// let length = Pixels(10.0);
2417///
2418/// // Define a length and scale it by a factor of 2
2419/// let scaled_length = length.scale(2.0);
2420/// assert_eq!(scaled_length, Pixels(20.0));
2421/// ```
2422#[derive(
2423    Clone,
2424    Copy,
2425    Default,
2426    Add,
2427    AddAssign,
2428    Sub,
2429    SubAssign,
2430    Neg,
2431    Div,
2432    DivAssign,
2433    PartialEq,
2434    Serialize,
2435    Deserialize,
2436)]
2437#[repr(transparent)]
2438pub struct Pixels(pub f32);
2439
2440impl std::fmt::Display for Pixels {
2441    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
2442        f.write_fmt(format_args!("{}px", self.0))
2443    }
2444}
2445
2446impl std::ops::Div for Pixels {
2447    type Output = f32;
2448
2449    fn div(self, rhs: Self) -> Self::Output {
2450        self.0 / rhs.0
2451    }
2452}
2453
2454impl std::ops::DivAssign for Pixels {
2455    fn div_assign(&mut self, rhs: Self) {
2456        *self = Self(self.0 / rhs.0);
2457    }
2458}
2459
2460impl std::ops::RemAssign for Pixels {
2461    fn rem_assign(&mut self, rhs: Self) {
2462        self.0 %= rhs.0;
2463    }
2464}
2465
2466impl std::ops::Rem for Pixels {
2467    type Output = Self;
2468
2469    fn rem(self, rhs: Self) -> Self {
2470        Self(self.0 % rhs.0)
2471    }
2472}
2473
2474impl Mul<f32> for Pixels {
2475    type Output = Pixels;
2476
2477    fn mul(self, other: f32) -> Pixels {
2478        Pixels(self.0 * other)
2479    }
2480}
2481
2482impl Mul<usize> for Pixels {
2483    type Output = Pixels;
2484
2485    fn mul(self, other: usize) -> Pixels {
2486        Pixels(self.0 * other as f32)
2487    }
2488}
2489
2490impl Mul<Pixels> for f32 {
2491    type Output = Pixels;
2492
2493    fn mul(self, rhs: Pixels) -> Self::Output {
2494        Pixels(self * rhs.0)
2495    }
2496}
2497
2498impl MulAssign<f32> for Pixels {
2499    fn mul_assign(&mut self, other: f32) {
2500        self.0 *= other;
2501    }
2502}
2503
2504impl Pixels {
2505    /// Represents zero pixels.
2506    pub const ZERO: Pixels = Pixels(0.0);
2507    /// The maximum value that can be represented by `Pixels`.
2508    pub const MAX: Pixels = Pixels(f32::MAX);
2509
2510    /// Floors the `Pixels` value to the nearest whole number.
2511    ///
2512    /// # Returns
2513    ///
2514    /// Returns a new `Pixels` instance with the floored value.
2515    pub fn floor(&self) -> Self {
2516        Self(self.0.floor())
2517    }
2518
2519    /// Rounds the `Pixels` value to the nearest whole number.
2520    ///
2521    /// # Returns
2522    ///
2523    /// Returns a new `Pixels` instance with the rounded value.
2524    pub fn round(&self) -> Self {
2525        Self(self.0.round())
2526    }
2527
2528    /// Returns the ceiling of the `Pixels` value to the nearest whole number.
2529    ///
2530    /// # Returns
2531    ///
2532    /// Returns a new `Pixels` instance with the ceiling value.
2533    pub fn ceil(&self) -> Self {
2534        Self(self.0.ceil())
2535    }
2536
2537    /// Scales the `Pixels` value by a given factor, producing `ScaledPixels`.
2538    ///
2539    /// This method is used when adjusting pixel values for display scaling factors,
2540    /// such as high DPI (dots per inch) or Retina displays, where the pixel density is higher and
2541    /// thus requires scaling to maintain visual consistency and readability.
2542    ///
2543    /// The resulting `ScaledPixels` represent the scaled value which can be used for rendering
2544    /// calculations where display scaling is considered.
2545    pub fn scale(&self, factor: f32) -> ScaledPixels {
2546        ScaledPixels(self.0 * factor)
2547    }
2548
2549    /// Raises the `Pixels` value to a given power.
2550    ///
2551    /// # Arguments
2552    ///
2553    /// * `exponent` - The exponent to raise the `Pixels` value by.
2554    ///
2555    /// # Returns
2556    ///
2557    /// Returns a new `Pixels` instance with the value raised to the given exponent.
2558    pub fn pow(&self, exponent: f32) -> Self {
2559        Self(self.0.powf(exponent))
2560    }
2561
2562    /// Returns the absolute value of the `Pixels`.
2563    ///
2564    /// # Returns
2565    ///
2566    /// A new `Pixels` instance with the absolute value of the original `Pixels`.
2567    pub fn abs(&self) -> Self {
2568        Self(self.0.abs())
2569    }
2570
2571    /// Returns the sign of the `Pixels` value.
2572    ///
2573    /// # Returns
2574    ///
2575    /// Returns:
2576    /// * `1.0` if the value is positive
2577    /// * `-1.0` if the value is negative
2578    /// * `0.0` if the value is zero
2579    pub fn signum(&self) -> f32 {
2580        self.0.signum()
2581    }
2582
2583    /// Returns the f64 value of `Pixels`.
2584    ///
2585    /// # Returns
2586    ///
2587    /// A f64 value of the `Pixels`.
2588    pub fn to_f64(self) -> f64 {
2589        self.0 as f64
2590    }
2591}
2592
2593impl Mul<Pixels> for Pixels {
2594    type Output = Pixels;
2595
2596    fn mul(self, rhs: Pixels) -> Self::Output {
2597        Pixels(self.0 * rhs.0)
2598    }
2599}
2600
2601impl Eq for Pixels {}
2602
2603impl PartialOrd for Pixels {
2604    fn partial_cmp(&self, other: &Self) -> Option<cmp::Ordering> {
2605        Some(self.cmp(other))
2606    }
2607}
2608
2609impl Ord for Pixels {
2610    fn cmp(&self, other: &Self) -> cmp::Ordering {
2611        self.0.total_cmp(&other.0)
2612    }
2613}
2614
2615impl std::hash::Hash for Pixels {
2616    fn hash<H: std::hash::Hasher>(&self, state: &mut H) {
2617        self.0.to_bits().hash(state);
2618    }
2619}
2620
2621impl From<f64> for Pixels {
2622    fn from(pixels: f64) -> Self {
2623        Pixels(pixels as f32)
2624    }
2625}
2626
2627impl From<f32> for Pixels {
2628    fn from(pixels: f32) -> Self {
2629        Pixels(pixels)
2630    }
2631}
2632
2633impl Debug for Pixels {
2634    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
2635        write!(f, "{} px", self.0)
2636    }
2637}
2638
2639impl From<Pixels> for f32 {
2640    fn from(pixels: Pixels) -> Self {
2641        pixels.0
2642    }
2643}
2644
2645impl From<&Pixels> for f32 {
2646    fn from(pixels: &Pixels) -> Self {
2647        pixels.0
2648    }
2649}
2650
2651impl From<Pixels> for f64 {
2652    fn from(pixels: Pixels) -> Self {
2653        pixels.0 as f64
2654    }
2655}
2656
2657impl From<Pixels> for u32 {
2658    fn from(pixels: Pixels) -> Self {
2659        pixels.0 as u32
2660    }
2661}
2662
2663impl From<u32> for Pixels {
2664    fn from(pixels: u32) -> Self {
2665        Pixels(pixels as f32)
2666    }
2667}
2668
2669impl From<Pixels> for usize {
2670    fn from(pixels: Pixels) -> Self {
2671        pixels.0 as usize
2672    }
2673}
2674
2675impl From<usize> for Pixels {
2676    fn from(pixels: usize) -> Self {
2677        Pixels(pixels as f32)
2678    }
2679}
2680
2681/// Represents physical pixels on the display.
2682///
2683/// `DevicePixels` is a unit of measurement that refers to the actual pixels on a device's screen.
2684/// This type is used when precise pixel manipulation is required, such as rendering graphics or
2685/// interfacing with hardware that operates on the pixel level. Unlike logical pixels that may be
2686/// affected by the device's scale factor, `DevicePixels` always correspond to real pixels on the
2687/// display.
2688#[derive(
2689    Add,
2690    AddAssign,
2691    Clone,
2692    Copy,
2693    Default,
2694    Div,
2695    Eq,
2696    Hash,
2697    Ord,
2698    PartialEq,
2699    PartialOrd,
2700    Sub,
2701    SubAssign,
2702    Serialize,
2703    Deserialize,
2704)]
2705#[repr(transparent)]
2706pub struct DevicePixels(pub i32);
2707
2708impl DevicePixels {
2709    /// Converts the `DevicePixels` value to the number of bytes needed to represent it in memory.
2710    ///
2711    /// This function is useful when working with graphical data that needs to be stored in a buffer,
2712    /// such as images or framebuffers, where each pixel may be represented by a specific number of bytes.
2713    ///
2714    /// # Arguments
2715    ///
2716    /// * `bytes_per_pixel` - The number of bytes used to represent a single pixel.
2717    ///
2718    /// # Returns
2719    ///
2720    /// The number of bytes required to represent the `DevicePixels` value in memory.
2721    ///
2722    /// # Examples
2723    ///
2724    /// ```
2725    /// # use gpui::DevicePixels;
2726    /// let pixels = DevicePixels(10); // 10 device pixels
2727    /// let bytes_per_pixel = 4; // Assume each pixel is represented by 4 bytes (e.g., RGBA)
2728    /// let total_bytes = pixels.to_bytes(bytes_per_pixel);
2729    /// assert_eq!(total_bytes, 40); // 10 pixels * 4 bytes/pixel = 40 bytes
2730    /// ```
2731    pub fn to_bytes(&self, bytes_per_pixel: u8) -> u32 {
2732        self.0 as u32 * bytes_per_pixel as u32
2733    }
2734}
2735
2736impl fmt::Debug for DevicePixels {
2737    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
2738        write!(f, "{} px (device)", self.0)
2739    }
2740}
2741
2742impl From<DevicePixels> for i32 {
2743    fn from(device_pixels: DevicePixels) -> Self {
2744        device_pixels.0
2745    }
2746}
2747
2748impl From<i32> for DevicePixels {
2749    fn from(device_pixels: i32) -> Self {
2750        DevicePixels(device_pixels)
2751    }
2752}
2753
2754impl From<u32> for DevicePixels {
2755    fn from(device_pixels: u32) -> Self {
2756        DevicePixels(device_pixels as i32)
2757    }
2758}
2759
2760impl From<DevicePixels> for u32 {
2761    fn from(device_pixels: DevicePixels) -> Self {
2762        device_pixels.0 as u32
2763    }
2764}
2765
2766impl From<DevicePixels> for u64 {
2767    fn from(device_pixels: DevicePixels) -> Self {
2768        device_pixels.0 as u64
2769    }
2770}
2771
2772impl From<u64> for DevicePixels {
2773    fn from(device_pixels: u64) -> Self {
2774        DevicePixels(device_pixels as i32)
2775    }
2776}
2777
2778impl From<DevicePixels> for usize {
2779    fn from(device_pixels: DevicePixels) -> Self {
2780        device_pixels.0 as usize
2781    }
2782}
2783
2784impl From<usize> for DevicePixels {
2785    fn from(device_pixels: usize) -> Self {
2786        DevicePixels(device_pixels as i32)
2787    }
2788}
2789
2790/// Represents scaled pixels that take into account the device's scale factor.
2791///
2792/// `ScaledPixels` are used to ensure that UI elements appear at the correct size on devices
2793/// with different pixel densities. When a device has a higher scale factor (such as Retina displays),
2794/// a single logical pixel may correspond to multiple physical pixels. By using `ScaledPixels`,
2795/// dimensions and positions can be specified in a way that scales appropriately across different
2796/// display resolutions.
2797#[derive(Clone, Copy, Default, Add, AddAssign, Sub, SubAssign, Div, PartialEq, PartialOrd)]
2798#[repr(transparent)]
2799pub struct ScaledPixels(pub(crate) f32);
2800
2801impl ScaledPixels {
2802    /// Floors the `ScaledPixels` value to the nearest whole number.
2803    ///
2804    /// # Returns
2805    ///
2806    /// Returns a new `ScaledPixels` instance with the floored value.
2807    pub fn floor(&self) -> Self {
2808        Self(self.0.floor())
2809    }
2810
2811    /// Rounds the `ScaledPixels` value to the nearest whole number.
2812    ///
2813    /// # Returns
2814    ///
2815    /// Returns a new `ScaledPixels` instance with the rounded value.
2816    pub fn ceil(&self) -> Self {
2817        Self(self.0.ceil())
2818    }
2819}
2820
2821impl Eq for ScaledPixels {}
2822
2823impl Debug for ScaledPixels {
2824    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
2825        write!(f, "{} px (scaled)", self.0)
2826    }
2827}
2828
2829impl From<ScaledPixels> for DevicePixels {
2830    fn from(scaled: ScaledPixels) -> Self {
2831        DevicePixels(scaled.0.ceil() as i32)
2832    }
2833}
2834
2835impl From<DevicePixels> for ScaledPixels {
2836    fn from(device: DevicePixels) -> Self {
2837        ScaledPixels(device.0 as f32)
2838    }
2839}
2840
2841impl From<ScaledPixels> for f64 {
2842    fn from(scaled_pixels: ScaledPixels) -> Self {
2843        scaled_pixels.0 as f64
2844    }
2845}
2846
2847impl From<ScaledPixels> for u32 {
2848    fn from(pixels: ScaledPixels) -> Self {
2849        pixels.0 as u32
2850    }
2851}
2852
2853/// 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].
2854///
2855/// Rems are used for defining lengths that are scalable and consistent across different UI elements.
2856/// The value of `1rem` is typically equal to the font-size of the root element (often the `<html>` element in browsers),
2857/// making it a flexible unit that adapts to the user's text size preferences. In this framework, `rems` serve a similar
2858/// purpose, allowing for scalable and accessible design that can adjust to different display settings or user preferences.
2859///
2860/// For example, if the root element's font-size is `16px`, then `1rem` equals `16px`. A length of `2rems` would then be `32px`.
2861///
2862/// [set_rem_size]: crate::WindowContext::set_rem_size
2863#[derive(Clone, Copy, Default, Add, Sub, Mul, Div, Neg, PartialEq)]
2864pub struct Rems(pub f32);
2865
2866impl Rems {
2867    /// Convert this Rem value to pixels.
2868    pub fn to_pixels(&self, rem_size: Pixels) -> Pixels {
2869        *self * rem_size
2870    }
2871}
2872
2873impl Mul<Pixels> for Rems {
2874    type Output = Pixels;
2875
2876    fn mul(self, other: Pixels) -> Pixels {
2877        Pixels(self.0 * other.0)
2878    }
2879}
2880
2881impl Debug for Rems {
2882    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
2883        write!(f, "{} rem", self.0)
2884    }
2885}
2886
2887/// Represents an absolute length in pixels or rems.
2888///
2889/// `AbsoluteLength` can be either a fixed number of pixels, which is an absolute measurement not
2890/// affected by the current font size, or a number of rems, which is relative to the font size of
2891/// the root element. It is used for specifying dimensions that are either independent of or
2892/// related to the typographic scale.
2893#[derive(Clone, Copy, Debug, Neg, PartialEq)]
2894pub enum AbsoluteLength {
2895    /// A length in pixels.
2896    Pixels(Pixels),
2897    /// A length in rems.
2898    Rems(Rems),
2899}
2900
2901impl AbsoluteLength {
2902    /// Checks if the absolute length is zero.
2903    pub fn is_zero(&self) -> bool {
2904        match self {
2905            AbsoluteLength::Pixels(px) => px.0 == 0.0,
2906            AbsoluteLength::Rems(rems) => rems.0 == 0.0,
2907        }
2908    }
2909}
2910
2911impl From<Pixels> for AbsoluteLength {
2912    fn from(pixels: Pixels) -> Self {
2913        AbsoluteLength::Pixels(pixels)
2914    }
2915}
2916
2917impl From<Rems> for AbsoluteLength {
2918    fn from(rems: Rems) -> Self {
2919        AbsoluteLength::Rems(rems)
2920    }
2921}
2922
2923impl AbsoluteLength {
2924    /// Converts an `AbsoluteLength` to `Pixels` based on a given `rem_size`.
2925    ///
2926    /// # Arguments
2927    ///
2928    /// * `rem_size` - The size of one rem in pixels.
2929    ///
2930    /// # Returns
2931    ///
2932    /// Returns the `AbsoluteLength` as `Pixels`.
2933    ///
2934    /// # Examples
2935    ///
2936    /// ```
2937    /// # use gpui::{AbsoluteLength, Pixels};
2938    /// let length_in_pixels = AbsoluteLength::Pixels(Pixels(42.0));
2939    /// let length_in_rems = AbsoluteLength::Rems(Rems(2.0));
2940    /// let rem_size = Pixels(16.0);
2941    ///
2942    /// assert_eq!(length_in_pixels.to_pixels(rem_size), Pixels(42.0));
2943    /// assert_eq!(length_in_rems.to_pixels(rem_size), Pixels(32.0));
2944    /// ```
2945    pub fn to_pixels(&self, rem_size: Pixels) -> Pixels {
2946        match self {
2947            AbsoluteLength::Pixels(pixels) => *pixels,
2948            AbsoluteLength::Rems(rems) => rems.to_pixels(rem_size),
2949        }
2950    }
2951}
2952
2953impl Default for AbsoluteLength {
2954    fn default() -> Self {
2955        px(0.).into()
2956    }
2957}
2958
2959/// A non-auto length that can be defined in pixels, rems, or percent of parent.
2960///
2961/// This enum represents lengths that have a specific value, as opposed to lengths that are automatically
2962/// determined by the context. It includes absolute lengths in pixels or rems, and relative lengths as a
2963/// fraction of the parent's size.
2964#[derive(Clone, Copy, Neg, PartialEq)]
2965pub enum DefiniteLength {
2966    /// An absolute length specified in pixels or rems.
2967    Absolute(AbsoluteLength),
2968    /// A relative length specified as a fraction of the parent's size, between 0 and 1.
2969    Fraction(f32),
2970}
2971
2972impl DefiniteLength {
2973    /// Converts the `DefiniteLength` to `Pixels` based on a given `base_size` and `rem_size`.
2974    ///
2975    /// If the `DefiniteLength` is an absolute length, it will be directly converted to `Pixels`.
2976    /// If it is a fraction, the fraction will be multiplied by the `base_size` to get the length in pixels.
2977    ///
2978    /// # Arguments
2979    ///
2980    /// * `base_size` - The base size in `AbsoluteLength` to which the fraction will be applied.
2981    /// * `rem_size` - The size of one rem in pixels, used to convert rems to pixels.
2982    ///
2983    /// # Returns
2984    ///
2985    /// Returns the `DefiniteLength` as `Pixels`.
2986    ///
2987    /// # Examples
2988    ///
2989    /// ```
2990    /// # use gpui::{DefiniteLength, AbsoluteLength, Pixels, px, rems};
2991    /// let length_in_pixels = DefiniteLength::Absolute(AbsoluteLength::Pixels(px(42.0)));
2992    /// let length_in_rems = DefiniteLength::Absolute(AbsoluteLength::Rems(rems(2.0)));
2993    /// let length_as_fraction = DefiniteLength::Fraction(0.5);
2994    /// let base_size = AbsoluteLength::Pixels(px(100.0));
2995    /// let rem_size = px(16.0);
2996    ///
2997    /// assert_eq!(length_in_pixels.to_pixels(base_size, rem_size), Pixels(42.0));
2998    /// assert_eq!(length_in_rems.to_pixels(base_size, rem_size), Pixels(32.0));
2999    /// assert_eq!(length_as_fraction.to_pixels(base_size, rem_size), Pixels(50.0));
3000    /// ```
3001    pub fn to_pixels(&self, base_size: AbsoluteLength, rem_size: Pixels) -> Pixels {
3002        match self {
3003            DefiniteLength::Absolute(size) => size.to_pixels(rem_size),
3004            DefiniteLength::Fraction(fraction) => match base_size {
3005                AbsoluteLength::Pixels(px) => px * *fraction,
3006                AbsoluteLength::Rems(rems) => rems * rem_size * *fraction,
3007            },
3008        }
3009    }
3010}
3011
3012impl Debug for DefiniteLength {
3013    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
3014        match self {
3015            DefiniteLength::Absolute(length) => Debug::fmt(length, f),
3016            DefiniteLength::Fraction(fract) => write!(f, "{}%", (fract * 100.0) as i32),
3017        }
3018    }
3019}
3020
3021impl From<Pixels> for DefiniteLength {
3022    fn from(pixels: Pixels) -> Self {
3023        Self::Absolute(pixels.into())
3024    }
3025}
3026
3027impl From<Rems> for DefiniteLength {
3028    fn from(rems: Rems) -> Self {
3029        Self::Absolute(rems.into())
3030    }
3031}
3032
3033impl From<AbsoluteLength> for DefiniteLength {
3034    fn from(length: AbsoluteLength) -> Self {
3035        Self::Absolute(length)
3036    }
3037}
3038
3039impl Default for DefiniteLength {
3040    fn default() -> Self {
3041        Self::Absolute(AbsoluteLength::default())
3042    }
3043}
3044
3045/// A length that can be defined in pixels, rems, percent of parent, or auto.
3046#[derive(Clone, Copy)]
3047pub enum Length {
3048    /// A definite length specified either in pixels, rems, or as a fraction of the parent's size.
3049    Definite(DefiniteLength),
3050    /// An automatic length that is determined by the context in which it is used.
3051    Auto,
3052}
3053
3054impl Debug for Length {
3055    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
3056        match self {
3057            Length::Definite(definite_length) => write!(f, "{:?}", definite_length),
3058            Length::Auto => write!(f, "auto"),
3059        }
3060    }
3061}
3062
3063/// Constructs a `DefiniteLength` representing a relative fraction of a parent size.
3064///
3065/// This function creates a `DefiniteLength` that is a specified fraction of a parent's dimension.
3066/// The fraction should be a floating-point number between 0.0 and 1.0, where 1.0 represents 100% of the parent's size.
3067///
3068/// # Arguments
3069///
3070/// * `fraction` - The fraction of the parent's size, between 0.0 and 1.0.
3071///
3072/// # Returns
3073///
3074/// A `DefiniteLength` representing the relative length as a fraction of the parent's size.
3075pub fn relative(fraction: f32) -> DefiniteLength {
3076    DefiniteLength::Fraction(fraction)
3077}
3078
3079/// Returns the Golden Ratio, i.e. `~(1.0 + sqrt(5.0)) / 2.0`.
3080pub fn phi() -> DefiniteLength {
3081    relative(1.618_034)
3082}
3083
3084/// Constructs a `Rems` value representing a length in rems.
3085///
3086/// # Arguments
3087///
3088/// * `rems` - The number of rems for the length.
3089///
3090/// # Returns
3091///
3092/// A `Rems` representing the specified number of rems.
3093pub fn rems(rems: f32) -> Rems {
3094    Rems(rems)
3095}
3096
3097/// Constructs a `Pixels` value representing a length in pixels.
3098///
3099/// # Arguments
3100///
3101/// * `pixels` - The number of pixels for the length.
3102///
3103/// # Returns
3104///
3105/// A `Pixels` representing the specified number of pixels.
3106pub const fn px(pixels: f32) -> Pixels {
3107    Pixels(pixels)
3108}
3109
3110/// Returns a `Length` representing an automatic length.
3111///
3112/// The `auto` length is often used in layout calculations where the length should be determined
3113/// by the layout context itself rather than being explicitly set. This is commonly used in CSS
3114/// for properties like `width`, `height`, `margin`, `padding`, etc., where `auto` can be used
3115/// to instruct the layout engine to calculate the size based on other factors like the size of the
3116/// container or the intrinsic size of the content.
3117///
3118/// # Returns
3119///
3120/// A `Length` variant set to `Auto`.
3121pub fn auto() -> Length {
3122    Length::Auto
3123}
3124
3125impl From<Pixels> for Length {
3126    fn from(pixels: Pixels) -> Self {
3127        Self::Definite(pixels.into())
3128    }
3129}
3130
3131impl From<Rems> for Length {
3132    fn from(rems: Rems) -> Self {
3133        Self::Definite(rems.into())
3134    }
3135}
3136
3137impl From<DefiniteLength> for Length {
3138    fn from(length: DefiniteLength) -> Self {
3139        Self::Definite(length)
3140    }
3141}
3142
3143impl From<AbsoluteLength> for Length {
3144    fn from(length: AbsoluteLength) -> Self {
3145        Self::Definite(length.into())
3146    }
3147}
3148
3149impl Default for Length {
3150    fn default() -> Self {
3151        Self::Definite(DefiniteLength::default())
3152    }
3153}
3154
3155impl From<()> for Length {
3156    fn from(_: ()) -> Self {
3157        Self::Definite(DefiniteLength::default())
3158    }
3159}
3160
3161/// Provides a trait for types that can calculate half of their value.
3162///
3163/// The `Half` trait is used for types that can be evenly divided, returning a new instance of the same type
3164/// representing half of the original value. This is commonly used for types that represent measurements or sizes,
3165/// such as lengths or pixels, where halving is a frequent operation during layout calculations or animations.
3166pub trait Half {
3167    /// Returns half of the current value.
3168    ///
3169    /// # Returns
3170    ///
3171    /// A new instance of the implementing type, representing half of the original value.
3172    fn half(&self) -> Self;
3173}
3174
3175impl Half for i32 {
3176    fn half(&self) -> Self {
3177        self / 2
3178    }
3179}
3180
3181impl Half for f32 {
3182    fn half(&self) -> Self {
3183        self / 2.
3184    }
3185}
3186
3187impl Half for DevicePixels {
3188    fn half(&self) -> Self {
3189        Self(self.0 / 2)
3190    }
3191}
3192
3193impl Half for ScaledPixels {
3194    fn half(&self) -> Self {
3195        Self(self.0 / 2.)
3196    }
3197}
3198
3199impl Half for Pixels {
3200    fn half(&self) -> Self {
3201        Self(self.0 / 2.)
3202    }
3203}
3204
3205impl Half for Rems {
3206    fn half(&self) -> Self {
3207        Self(self.0 / 2.)
3208    }
3209}
3210
3211/// Provides a trait for types that can negate their values.
3212pub trait Negate {
3213    /// Returns the negation of the given value
3214    fn negate(self) -> Self;
3215}
3216
3217impl Negate for i32 {
3218    fn negate(self) -> Self {
3219        -self
3220    }
3221}
3222
3223impl Negate for f32 {
3224    fn negate(self) -> Self {
3225        -self
3226    }
3227}
3228
3229impl Negate for DevicePixels {
3230    fn negate(self) -> Self {
3231        Self(-self.0)
3232    }
3233}
3234
3235impl Negate for ScaledPixels {
3236    fn negate(self) -> Self {
3237        Self(-self.0)
3238    }
3239}
3240
3241impl Negate for Pixels {
3242    fn negate(self) -> Self {
3243        Self(-self.0)
3244    }
3245}
3246
3247impl Negate for Rems {
3248    fn negate(self) -> Self {
3249        Self(-self.0)
3250    }
3251}
3252
3253/// A trait for checking if a value is zero.
3254///
3255/// This trait provides a method to determine if a value is considered to be zero.
3256/// It is implemented for various numeric and length-related types where the concept
3257/// of zero is applicable. This can be useful for comparisons, optimizations, or
3258/// determining if an operation has a neutral effect.
3259pub trait IsZero {
3260    /// Determines if the value is zero.
3261    ///
3262    /// # Returns
3263    ///
3264    /// Returns `true` if the value is zero, `false` otherwise.
3265    fn is_zero(&self) -> bool;
3266}
3267
3268impl IsZero for DevicePixels {
3269    fn is_zero(&self) -> bool {
3270        self.0 == 0
3271    }
3272}
3273
3274impl IsZero for ScaledPixels {
3275    fn is_zero(&self) -> bool {
3276        self.0 == 0.
3277    }
3278}
3279
3280impl IsZero for Pixels {
3281    fn is_zero(&self) -> bool {
3282        self.0 == 0.
3283    }
3284}
3285
3286impl IsZero for Rems {
3287    fn is_zero(&self) -> bool {
3288        self.0 == 0.
3289    }
3290}
3291
3292impl IsZero for AbsoluteLength {
3293    fn is_zero(&self) -> bool {
3294        match self {
3295            AbsoluteLength::Pixels(pixels) => pixels.is_zero(),
3296            AbsoluteLength::Rems(rems) => rems.is_zero(),
3297        }
3298    }
3299}
3300
3301impl IsZero for DefiniteLength {
3302    fn is_zero(&self) -> bool {
3303        match self {
3304            DefiniteLength::Absolute(length) => length.is_zero(),
3305            DefiniteLength::Fraction(fraction) => *fraction == 0.,
3306        }
3307    }
3308}
3309
3310impl IsZero for Length {
3311    fn is_zero(&self) -> bool {
3312        match self {
3313            Length::Definite(length) => length.is_zero(),
3314            Length::Auto => false,
3315        }
3316    }
3317}
3318
3319impl<T: IsZero + Debug + Clone + Default> IsZero for Point<T> {
3320    fn is_zero(&self) -> bool {
3321        self.x.is_zero() && self.y.is_zero()
3322    }
3323}
3324
3325impl<T> IsZero for Size<T>
3326where
3327    T: IsZero + Default + Debug + Clone,
3328{
3329    fn is_zero(&self) -> bool {
3330        self.width.is_zero() || self.height.is_zero()
3331    }
3332}
3333
3334impl<T: IsZero + Debug + Clone + Default> IsZero for Bounds<T> {
3335    fn is_zero(&self) -> bool {
3336        self.size.is_zero()
3337    }
3338}
3339
3340impl<T> IsZero for Corners<T>
3341where
3342    T: IsZero + Clone + Default + Debug,
3343{
3344    fn is_zero(&self) -> bool {
3345        self.top_left.is_zero()
3346            && self.top_right.is_zero()
3347            && self.bottom_right.is_zero()
3348            && self.bottom_left.is_zero()
3349    }
3350}
3351
3352#[cfg(test)]
3353mod tests {
3354    use super::*;
3355
3356    #[test]
3357    fn test_bounds_intersects() {
3358        let bounds1 = Bounds {
3359            origin: Point { x: 0.0, y: 0.0 },
3360            size: Size {
3361                width: 5.0,
3362                height: 5.0,
3363            },
3364        };
3365        let bounds2 = Bounds {
3366            origin: Point { x: 4.0, y: 4.0 },
3367            size: Size {
3368                width: 5.0,
3369                height: 5.0,
3370            },
3371        };
3372        let bounds3 = Bounds {
3373            origin: Point { x: 10.0, y: 10.0 },
3374            size: Size {
3375                width: 5.0,
3376                height: 5.0,
3377            },
3378        };
3379
3380        // Test Case 1: Intersecting bounds
3381        assert!(bounds1.intersects(&bounds2));
3382
3383        // Test Case 2: Non-Intersecting bounds
3384        assert!(!bounds1.intersects(&bounds3));
3385
3386        // Test Case 3: Bounds intersecting with themselves
3387        assert!(bounds1.intersects(&bounds1));
3388    }
3389}