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