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