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