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