Skip to main content

layout/
geom.rs

1/* This Source Code Form is subject to the terms of the Mozilla Public
2 * License, v. 2.0. If a copy of the MPL was not distributed with this
3 * file, You can obtain one at https://mozilla.org/MPL/2.0/. */
4
5use std::convert::From;
6use std::fmt;
7use std::ops::{Add, AddAssign, Neg, Sub, SubAssign};
8use std::sync::atomic::{AtomicI32, Ordering};
9
10use app_units::Au;
11use euclid::{Point2D, Size2D};
12use malloc_size_of_derive::MallocSizeOf;
13use style::Zero;
14use style::logical_geometry::{BlockFlowDirection, InlineBaseDirection, WritingMode};
15use style::values::computed::{CSSPixelLength, LengthPercentage};
16use style::values::generics::length::GenericLengthPercentageOrAuto as AutoOr;
17use style_traits::CSSPixel;
18
19use crate::containing_block::ContainingBlock;
20use crate::sizing::Size;
21use crate::style_ext::WritingModeExt;
22
23pub type PhysicalPoint<U> = euclid::Point2D<U, CSSPixel>;
24pub type PhysicalSize<U> = euclid::Size2D<U, CSSPixel>;
25pub type PhysicalVec<U> = euclid::Vector2D<U, CSSPixel>;
26pub type PhysicalRect<U> = euclid::Rect<U, CSSPixel>;
27pub type PhysicalSides<U> = euclid::SideOffsets2D<U, CSSPixel>;
28pub type AuOrAuto = AutoOr<Au>;
29pub type LengthPercentageOrAuto<'a> = AutoOr<&'a LengthPercentage>;
30
31#[derive(Clone, Copy, MallocSizeOf, PartialEq)]
32pub struct LogicalVec2<T> {
33    pub inline: T,
34    pub block: T,
35}
36
37#[derive(Clone, Copy, MallocSizeOf, PartialEq)]
38pub struct LogicalRect<T> {
39    pub start_corner: LogicalVec2<T>,
40    pub size: LogicalVec2<T>,
41}
42
43#[derive(Clone, Copy, Debug, Default)]
44pub struct LogicalSides<T> {
45    pub inline_start: T,
46    pub inline_end: T,
47    pub block_start: T,
48    pub block_end: T,
49}
50
51#[derive(Clone, Copy, Debug, Default, MallocSizeOf, PartialEq)]
52pub(crate) struct LogicalSides1D<T> {
53    pub start: T,
54    pub end: T,
55}
56
57impl<T> LogicalSides1D<T> {
58    pub(crate) fn map<U>(&self, f: impl Fn(&T) -> U) -> LogicalSides1D<U> {
59        LogicalSides1D {
60            start: f(&self.start),
61            end: f(&self.end),
62        }
63    }
64}
65
66impl LogicalSides1D<AutoOr<&LengthPercentage>> {
67    pub(crate) fn percentages_relative_to(&self, basis: Au) -> LogicalSides1D<AutoOr<Au>> {
68        self.map(|value| value.map(|length_percentage| length_percentage.to_used_value(basis)))
69    }
70}
71
72impl<T: fmt::Debug> fmt::Debug for LogicalVec2<T> {
73    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
74        // Not using f.debug_struct on purpose here, to keep {:?} output somewhat compact
75        f.write_str("Vec2 { i: ")?;
76        self.inline.fmt(f)?;
77        f.write_str(", b: ")?;
78        self.block.fmt(f)?;
79        f.write_str(" }")
80    }
81}
82
83impl<T: Default> Default for LogicalVec2<T> {
84    fn default() -> Self {
85        Self {
86            inline: T::default(),
87            block: T::default(),
88        }
89    }
90}
91
92impl<T: Copy> From<T> for LogicalVec2<T> {
93    fn from(value: T) -> Self {
94        Self {
95            inline: value,
96            block: value,
97        }
98    }
99}
100
101impl<T> LogicalVec2<T> {
102    pub fn map_inline_and_block_axes<U>(
103        &self,
104        inline_f: impl FnOnce(&T) -> U,
105        block_f: impl FnOnce(&T) -> U,
106    ) -> LogicalVec2<U> {
107        LogicalVec2 {
108            inline: inline_f(&self.inline),
109            block: block_f(&self.block),
110        }
111    }
112}
113
114impl<T: Clone> LogicalVec2<Size<T>> {
115    pub fn map_inline_and_block_sizes<U>(
116        &self,
117        inline_f: impl FnOnce(T) -> U,
118        block_f: impl FnOnce(T) -> U,
119    ) -> LogicalVec2<Size<U>> {
120        self.map_inline_and_block_axes(|size| size.map(inline_f), |size| size.map(block_f))
121    }
122}
123
124impl<T: Clone> LogicalVec2<T> {
125    pub(crate) fn from_physical_size(physical_size: &PhysicalSize<T>, mode: WritingMode) -> Self {
126        // https://drafts.csswg.org/css-writing-modes/#logical-to-physical
127        let (i, b) = if mode.is_horizontal() {
128            (&physical_size.width, &physical_size.height)
129        } else {
130            (&physical_size.height, &physical_size.width)
131        };
132        LogicalVec2 {
133            inline: i.clone(),
134            block: b.clone(),
135        }
136    }
137
138    pub fn map<U>(&self, f: impl Fn(&T) -> U) -> LogicalVec2<U> {
139        LogicalVec2 {
140            inline: f(&self.inline),
141            block: f(&self.block),
142        }
143    }
144
145    pub(crate) fn map_with<U, V>(
146        &self,
147        other: &LogicalVec2<U>,
148        f: impl Fn(&T, &U) -> V,
149    ) -> LogicalVec2<V> {
150        LogicalVec2 {
151            inline: f(&self.inline, &other.inline),
152            block: f(&self.block, &other.block),
153        }
154    }
155}
156
157impl<T: Add<Output = T> + Copy> Add<LogicalVec2<T>> for LogicalVec2<T> {
158    type Output = LogicalVec2<T>;
159    fn add(self, other: Self) -> Self::Output {
160        LogicalVec2 {
161            inline: self.inline + other.inline,
162            block: self.block + other.block,
163        }
164    }
165}
166
167impl<T: Sub<Output = T> + Copy> Sub<LogicalVec2<T>> for LogicalVec2<T> {
168    type Output = LogicalVec2<T>;
169    fn sub(self, other: Self) -> Self::Output {
170        LogicalVec2 {
171            inline: self.inline - other.inline,
172            block: self.block - other.block,
173        }
174    }
175}
176
177impl<T: AddAssign<T> + Copy> AddAssign<LogicalVec2<T>> for LogicalVec2<T> {
178    fn add_assign(&mut self, other: LogicalVec2<T>) {
179        self.inline += other.inline;
180        self.block += other.block;
181    }
182}
183
184impl<T: SubAssign<T> + Copy> SubAssign<LogicalVec2<T>> for LogicalVec2<T> {
185    fn sub_assign(&mut self, other: LogicalVec2<T>) {
186        self.inline -= other.inline;
187        self.block -= other.block;
188    }
189}
190
191impl<T: Neg<Output = T> + Copy> Neg for LogicalVec2<T> {
192    type Output = LogicalVec2<T>;
193    fn neg(self) -> Self::Output {
194        Self {
195            inline: -self.inline,
196            block: -self.block,
197        }
198    }
199}
200
201impl<T: Zero> LogicalVec2<T> {
202    pub fn zero() -> Self {
203        Self {
204            inline: T::zero(),
205            block: T::zero(),
206        }
207    }
208}
209
210impl<T: Clone> LogicalVec2<AutoOr<T>> {
211    pub fn auto_is(&self, f: impl Fn() -> T) -> LogicalVec2<T> {
212        self.map(|t| t.auto_is(&f))
213    }
214}
215
216impl<T: Zero> LogicalRect<T> {
217    pub fn zero() -> Self {
218        Self {
219            start_corner: LogicalVec2::zero(),
220            size: LogicalVec2::zero(),
221        }
222    }
223}
224
225impl fmt::Debug for LogicalRect<Au> {
226    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
227        write!(
228            f,
229            "Rect(i{}×b{} @ (i{},b{}))",
230            self.size.inline.to_f32_px(),
231            self.size.block.to_f32_px(),
232            self.start_corner.inline.to_f32_px(),
233            self.start_corner.block.to_f32_px(),
234        )
235    }
236}
237
238impl<T: Clone> LogicalVec2<T> {
239    pub fn to_physical_size(&self, mode: WritingMode) -> PhysicalSize<T> {
240        // https://drafts.csswg.org/css-writing-modes/#logical-to-physical
241        if mode.is_horizontal() {
242            PhysicalSize::new(self.inline.clone(), self.block.clone())
243        } else {
244            PhysicalSize::new(self.block.clone(), self.inline.clone())
245        }
246    }
247}
248
249impl LogicalVec2<Au> {
250    /// Convert from a physical point in the parent container to a [`LogicalVec2`] point.
251    ///
252    /// TODO: This will eventually need to be passed the parent container size.
253    pub(crate) fn from_physical_point_deprecated(
254        point: &PhysicalPoint<Au>,
255        containing_block: &ContainingBlock,
256    ) -> LogicalVec2<Au> {
257        let writing_mode = containing_block.style.writing_mode;
258        let (inline, block) = if writing_mode.is_horizontal() {
259            (point.x, point.y)
260        } else {
261            (point.y, point.x)
262        };
263
264        let inline = flip(
265            inline,
266            Au::zero(),
267            containing_block.size.inline,
268            writing_mode.is_inline_flipped(),
269        );
270
271        LogicalVec2 { inline, block }
272    }
273
274    /// Convert the vector to an offset in the parent container.
275    pub(crate) fn to_physical_offset(self, mode: WritingMode) -> PhysicalVec<Au> {
276        let inline = if mode.is_inline_flipped() {
277            -self.inline
278        } else {
279            self.inline
280        };
281        let block = if mode.is_block_flipped() {
282            -self.block
283        } else {
284            self.block
285        };
286
287        if mode.is_horizontal() {
288            PhysicalVec::new(inline, block)
289        } else {
290            debug_assert!(mode.is_vertical());
291            PhysicalVec::new(block, inline)
292        }
293    }
294
295    /// Convert the vector to an offset in the parent container, but without flipping anything
296    /// in the block axis.
297    pub(crate) fn to_physical_offset_deprecated(self, mode: WritingMode) -> PhysicalVec<Au> {
298        let inline = if mode.is_inline_flipped() {
299            -self.inline
300        } else {
301            self.inline
302        };
303        if mode.is_horizontal() {
304            PhysicalVec::new(inline, self.block)
305        } else {
306            debug_assert!(mode.is_vertical());
307            PhysicalVec::new(self.block, inline)
308        }
309    }
310}
311
312impl<T: Clone> LogicalSides<T> {
313    pub(crate) fn from_physical(sides: &PhysicalSides<T>, mode: WritingMode) -> Self {
314        // https://drafts.csswg.org/css-writing-modes/#logical-to-physical
315        let block_flow = mode.block_flow_direction();
316        let (bs, be) = match mode.block_flow_direction() {
317            BlockFlowDirection::TopToBottom => (&sides.top, &sides.bottom),
318            BlockFlowDirection::RightToLeft => (&sides.right, &sides.left),
319            BlockFlowDirection::LeftToRight => (&sides.left, &sides.right),
320        };
321        use BlockFlowDirection::TopToBottom;
322        let (is, ie) = match (block_flow, mode.inline_base_direction()) {
323            (TopToBottom, InlineBaseDirection::LeftToRight) => (&sides.left, &sides.right),
324            (TopToBottom, InlineBaseDirection::RightToLeft) => (&sides.right, &sides.left),
325            (_, InlineBaseDirection::LeftToRight) => (&sides.top, &sides.bottom),
326            (_, InlineBaseDirection::RightToLeft) => (&sides.bottom, &sides.top),
327        };
328        Self {
329            inline_start: is.clone(),
330            inline_end: ie.clone(),
331            block_start: bs.clone(),
332            block_end: be.clone(),
333        }
334    }
335}
336
337impl<T> LogicalSides<T> {
338    pub fn map<U>(&self, f: impl Fn(&T) -> U) -> LogicalSides<U> {
339        LogicalSides {
340            inline_start: f(&self.inline_start),
341            inline_end: f(&self.inline_end),
342            block_start: f(&self.block_start),
343            block_end: f(&self.block_end),
344        }
345    }
346
347    pub fn map_inline_and_block_axes<U>(
348        &self,
349        inline_f: impl Fn(&T) -> U,
350        block_f: impl Fn(&T) -> U,
351    ) -> LogicalSides<U> {
352        LogicalSides {
353            inline_start: inline_f(&self.inline_start),
354            inline_end: inline_f(&self.inline_end),
355            block_start: block_f(&self.block_start),
356            block_end: block_f(&self.block_end),
357        }
358    }
359
360    pub fn inline_sum(&self) -> T::Output
361    where
362        T: Add + Copy,
363    {
364        self.inline_start + self.inline_end
365    }
366
367    pub fn block_sum(&self) -> T::Output
368    where
369        T: Add + Copy,
370    {
371        self.block_start + self.block_end
372    }
373
374    pub fn sum(&self) -> LogicalVec2<T::Output>
375    where
376        T: Add + Copy,
377    {
378        LogicalVec2 {
379            inline: self.inline_sum(),
380            block: self.block_sum(),
381        }
382    }
383
384    pub fn to_physical(&self, mode: WritingMode) -> PhysicalSides<T>
385    where
386        T: Clone,
387    {
388        let top;
389        let right;
390        let bottom;
391        let left;
392        if mode.is_vertical() {
393            if mode.is_vertical_lr() {
394                left = self.block_start.clone();
395                right = self.block_end.clone();
396            } else {
397                right = self.block_start.clone();
398                left = self.block_end.clone();
399            }
400
401            if mode.is_inline_tb() {
402                top = self.inline_start.clone();
403                bottom = self.inline_end.clone();
404            } else {
405                bottom = self.inline_start.clone();
406                top = self.inline_end.clone();
407            }
408        } else {
409            top = self.block_start.clone();
410            bottom = self.block_end.clone();
411            if mode.is_bidi_ltr() {
412                left = self.inline_start.clone();
413                right = self.inline_end.clone();
414            } else {
415                right = self.inline_start.clone();
416                left = self.inline_end.clone();
417            }
418        }
419        PhysicalSides::new(top, right, bottom, left)
420    }
421}
422
423impl<T: Copy> LogicalSides<T> {
424    pub fn start_offset(&self) -> LogicalVec2<T> {
425        LogicalVec2 {
426            inline: self.inline_start,
427            block: self.block_start,
428        }
429    }
430
431    #[inline]
432    pub(crate) fn inline_sides(&self) -> LogicalSides1D<T> {
433        LogicalSides1D::new(self.inline_start, self.inline_end)
434    }
435
436    #[inline]
437    pub(crate) fn block_sides(&self) -> LogicalSides1D<T> {
438        LogicalSides1D::new(self.block_start, self.block_end)
439    }
440}
441
442impl LogicalSides<LengthPercentage> {
443    pub fn percentages_relative_to(&self, basis: Au) -> LogicalSides<Au> {
444        self.map(|value| value.to_used_value(basis))
445    }
446}
447
448impl LogicalSides<LengthPercentageOrAuto<'_>> {
449    pub fn percentages_relative_to(&self, basis: Au) -> LogicalSides<AuOrAuto> {
450        self.map(|value| value.map(|value| value.to_used_value(basis)))
451    }
452}
453
454impl<T: Clone> LogicalSides<AutoOr<T>> {
455    pub fn auto_is(&self, f: impl Fn() -> T) -> LogicalSides<T> {
456        self.map(|s| s.auto_is(&f))
457    }
458}
459
460impl<T: Add<Output = T> + Copy> Add<LogicalSides<T>> for LogicalSides<T> {
461    type Output = LogicalSides<T>;
462
463    fn add(self, other: Self) -> Self::Output {
464        LogicalSides {
465            inline_start: self.inline_start + other.inline_start,
466            inline_end: self.inline_end + other.inline_end,
467            block_start: self.block_start + other.block_start,
468            block_end: self.block_end + other.block_end,
469        }
470    }
471}
472
473impl<T: Sub<Output = T> + Copy> Sub<LogicalSides<T>> for LogicalSides<T> {
474    type Output = LogicalSides<T>;
475
476    fn sub(self, other: Self) -> Self::Output {
477        LogicalSides {
478            inline_start: self.inline_start - other.inline_start,
479            inline_end: self.inline_end - other.inline_end,
480            block_start: self.block_start - other.block_start,
481            block_end: self.block_end - other.block_end,
482        }
483    }
484}
485
486impl<T: Neg<Output = T> + Copy> Neg for LogicalSides<T> {
487    type Output = LogicalSides<T>;
488    fn neg(self) -> Self::Output {
489        Self {
490            inline_start: -self.inline_start,
491            inline_end: -self.inline_end,
492            block_start: -self.block_start,
493            block_end: -self.block_end,
494        }
495    }
496}
497
498impl<T: Zero> LogicalSides<T> {
499    pub(crate) fn zero() -> LogicalSides<T> {
500        Self {
501            inline_start: T::zero(),
502            inline_end: T::zero(),
503            block_start: T::zero(),
504            block_end: T::zero(),
505        }
506    }
507}
508
509impl From<LogicalSides<CSSPixelLength>> for LogicalSides<Au> {
510    fn from(value: LogicalSides<CSSPixelLength>) -> Self {
511        Self {
512            inline_start: value.inline_start.into(),
513            inline_end: value.inline_end.into(),
514            block_start: value.block_start.into(),
515            block_end: value.block_end.into(),
516        }
517    }
518}
519
520impl From<LogicalSides<Au>> for LogicalSides<CSSPixelLength> {
521    fn from(value: LogicalSides<Au>) -> Self {
522        Self {
523            inline_start: value.inline_start.into(),
524            inline_end: value.inline_end.into(),
525            block_start: value.block_start.into(),
526            block_end: value.block_end.into(),
527        }
528    }
529}
530
531impl<T> LogicalSides1D<T> {
532    #[inline]
533    pub(crate) fn new(start: T, end: T) -> Self {
534        Self { start, end }
535    }
536}
537
538impl<T> LogicalSides1D<AutoOr<T>> {
539    #[inline]
540    pub(crate) fn either_specified(&self) -> bool {
541        !self.start.is_auto() || !self.end.is_auto()
542    }
543
544    #[inline]
545    pub(crate) fn either_auto(&self) -> bool {
546        self.start.is_auto() || self.end.is_auto()
547    }
548}
549
550impl<T> LogicalRect<T> {
551    pub fn max_inline_position(&self) -> T
552    where
553        T: Add<Output = T> + Copy,
554    {
555        self.start_corner.inline + self.size.inline
556    }
557
558    pub fn max_block_position(&self) -> T
559    where
560        T: Add<Output = T> + Copy,
561    {
562        self.start_corner.block + self.size.block
563    }
564
565    pub fn inflate(&self, sides: &LogicalSides<T>) -> Self
566    where
567        T: Add<Output = T> + Copy,
568        T: Sub<Output = T> + Copy,
569    {
570        Self {
571            start_corner: LogicalVec2 {
572                inline: self.start_corner.inline - sides.inline_start,
573                block: self.start_corner.block - sides.block_start,
574            },
575            size: LogicalVec2 {
576                inline: self.size.inline + sides.inline_sum(),
577                block: self.size.block + sides.block_sum(),
578            },
579        }
580    }
581
582    pub fn deflate(&self, sides: &LogicalSides<T>) -> Self
583    where
584        T: Add<Output = T> + Copy,
585        T: Sub<Output = T> + Copy,
586    {
587        LogicalRect {
588            start_corner: LogicalVec2 {
589                inline: self.start_corner.inline + sides.inline_start,
590                block: self.start_corner.block + sides.block_start,
591            },
592            size: LogicalVec2 {
593                inline: self.size.inline - sides.inline_sum(),
594                block: self.size.block - sides.block_sum(),
595            },
596        }
597    }
598}
599
600fn flip(start: Au, size: Au, container_size: Au, flipped: bool) -> Au {
601    if flipped {
602        container_size - (start + size)
603    } else {
604        start
605    }
606}
607
608impl LogicalRect<Au> {
609    fn from_physical_inner(
610        rect: PhysicalRect<Au>,
611        writing_mode: WritingMode,
612        container_inline_size: Au,
613        container_block_size: Option<Au>,
614    ) -> LogicalRect<Au> {
615        let inline_start;
616        let mut block_start;
617        let inline_size;
618        let block_size;
619        if writing_mode.is_vertical() {
620            inline_start = rect.origin.y;
621            block_start = rect.origin.x;
622            inline_size = rect.size.height;
623            block_size = rect.size.width;
624        } else {
625            inline_start = rect.origin.x;
626            block_start = rect.origin.y;
627            inline_size = rect.size.width;
628            block_size = rect.size.height;
629        }
630
631        let inline_start = flip(
632            inline_start,
633            inline_size,
634            container_inline_size,
635            writing_mode.is_inline_flipped(),
636        );
637        if writing_mode.is_block_flipped() &&
638            let Some(container_block_size) = container_block_size
639        {
640            block_start = flip(block_start, block_size, container_block_size, true);
641        }
642
643        Self {
644            start_corner: LogicalVec2 {
645                inline: inline_start,
646                block: block_start,
647            },
648            size: LogicalVec2 {
649                inline: inline_size,
650                block: block_size,
651            },
652        }
653    }
654
655    #[cfg_attr(not(test), expect(dead_code))]
656    pub(crate) fn from_physical(
657        rect: PhysicalRect<Au>,
658        writing_mode: WritingMode,
659        container_size: LogicalVec2<Au>,
660    ) -> Self {
661        Self::from_physical_inner(
662            rect,
663            writing_mode,
664            container_size.inline,
665            Some(container_size.block),
666        )
667    }
668
669    pub(crate) fn from_physical_deprecated(
670        rect: PhysicalRect<Au>,
671        containing_block: &ContainingBlock,
672    ) -> Self {
673        Self::from_physical_inner(
674            rect,
675            containing_block.style.writing_mode,
676            containing_block.size.inline,
677            None,
678        )
679    }
680
681    fn as_physical_inner(
682        &self,
683        writing_mode: WritingMode,
684        container_inline_size: Au,
685        container_block_size: Option<Au>,
686    ) -> PhysicalRect<Au> {
687        let inline_offset = flip(
688            self.start_corner.inline,
689            self.size.inline,
690            container_inline_size,
691            writing_mode.is_inline_flipped(),
692        );
693        let block_offset = container_block_size
694            .map(|container_block_size| {
695                flip(
696                    self.start_corner.block,
697                    self.size.block,
698                    container_block_size,
699                    writing_mode.is_block_flipped(),
700                )
701            })
702            .unwrap_or(self.start_corner.block);
703
704        if writing_mode.is_vertical() {
705            PhysicalRect::new(
706                PhysicalPoint::new(block_offset, inline_offset),
707                PhysicalSize::new(self.size.block, self.size.inline),
708            )
709        } else {
710            PhysicalRect::new(
711                PhysicalPoint::new(inline_offset, block_offset),
712                PhysicalSize::new(self.size.inline, self.size.block),
713            )
714        }
715    }
716
717    pub(crate) fn as_physical(
718        &self,
719        writing_mode: WritingMode,
720        container_size: LogicalVec2<Au>,
721    ) -> PhysicalRect<Au> {
722        self.as_physical_inner(
723            writing_mode,
724            container_size.inline,
725            Some(container_size.block),
726        )
727    }
728
729    pub(crate) fn as_physical_deprecated(
730        &self,
731        containing_block: &ContainingBlock<'_>,
732    ) -> PhysicalRect<Au> {
733        self.as_physical_inner(
734            containing_block.style.writing_mode,
735            containing_block.size.inline,
736            None,
737        )
738    }
739}
740
741impl From<LogicalVec2<CSSPixelLength>> for LogicalVec2<Au> {
742    fn from(value: LogicalVec2<CSSPixelLength>) -> Self {
743        LogicalVec2 {
744            inline: value.inline.into(),
745            block: value.block.into(),
746        }
747    }
748}
749
750impl From<LogicalVec2<Au>> for LogicalVec2<CSSPixelLength> {
751    fn from(value: LogicalVec2<Au>) -> Self {
752        LogicalVec2 {
753            inline: value.inline.into(),
754            block: value.block.into(),
755        }
756    }
757}
758
759impl From<LogicalRect<Au>> for LogicalRect<CSSPixelLength> {
760    fn from(value: LogicalRect<Au>) -> Self {
761        LogicalRect {
762            start_corner: value.start_corner.into(),
763            size: value.size.into(),
764        }
765    }
766}
767
768impl From<LogicalRect<CSSPixelLength>> for LogicalRect<Au> {
769    fn from(value: LogicalRect<CSSPixelLength>) -> Self {
770        LogicalRect {
771            start_corner: value.start_corner.into(),
772            size: value.size.into(),
773        }
774    }
775}
776
777/// A `PhysicalRect<Au>` with shared mutablitiy
778///
779/// It is based on `AtomicI32` but is not atomic itself: there is no protection against tearing:
780/// If multiple threads are calling `set()`, the rectangle may end up with some fields from one call
781/// and some fields from another call.
782///
783/// Compared to `AtomicRefCell<PhysicalRect<Au>>`:
784///
785/// * Both are meant for uses where despite shared ownership, no concurrency is expected in practice.
786/// * If concurrent access does unexpectedly happen `AtomicRefCell` will panic,
787///   whereas `SyncPhysicalRectAu` can tear and result in invalid/inconsistent data.
788/// * `SyncPhysicalRectAu` has no space overhead, `AtomicRefCell` stores an `AtomicUsize` borrow flag
789/// * `SyncPhysicalRectAu` uses relaxed atomic access for each field separately
790#[derive(MallocSizeOf, Default)]
791pub(crate) struct SyncPhysicalRectAu(PhysicalRect<AtomicI32>);
792
793impl SyncPhysicalRectAu {
794    #[inline]
795    pub(crate) fn new(rect: PhysicalRect<Au>) -> Self {
796        Self(PhysicalRect::new(
797            PhysicalPoint::new(rect.origin.x.0.into(), rect.origin.y.0.into()),
798            PhysicalSize::new(rect.size.width.0.into(), rect.size.height.0.into()),
799        ))
800    }
801
802    pub(crate) fn get(&self) -> PhysicalRect<Au> {
803        PhysicalRect::new(self.origin(), self.size())
804    }
805
806    pub(crate) fn set(&self, new_rect: PhysicalRect<Au>) {
807        self.set_origin(new_rect.origin);
808        self.set_size(new_rect.size);
809    }
810
811    #[inline]
812    pub(crate) fn origin(&self) -> PhysicalPoint<Au> {
813        Point2D::new(
814            // Bypass clamping in `Au::new`: the value originally came from another `Au`
815            // so it’s expected to already be in range
816            Au(self.0.origin.x.load(Ordering::Relaxed)),
817            Au(self.0.origin.y.load(Ordering::Relaxed)),
818        )
819    }
820
821    #[inline]
822    pub(crate) fn size(&self) -> PhysicalSize<Au> {
823        Size2D::new(
824            // Bypass clamping in `Au::new`: the value originally came from another `Au`
825            // so it’s expected to already be in range
826            Au(self.0.size.width.load(Ordering::Relaxed)),
827            Au(self.0.size.height.load(Ordering::Relaxed)),
828        )
829    }
830
831    #[inline]
832    pub(crate) fn set_origin(&self, new_origin: PhysicalPoint<Au>) {
833        let origin = &self.0.origin;
834        origin.x.store(new_origin.x.0, Ordering::Relaxed);
835        origin.y.store(new_origin.y.0, Ordering::Relaxed);
836    }
837
838    #[inline]
839    pub(crate) fn set_size(&self, new_size: PhysicalSize<Au>) {
840        let size = &self.0.size;
841        size.width.store(new_size.width.0, Ordering::Relaxed);
842        size.height.store(new_size.height.0, Ordering::Relaxed);
843    }
844
845    #[inline]
846    pub(crate) fn translate(&self, offset: PhysicalSize<Au>) {
847        // This code explicitly does not use `AtomicI32::fetch_add`, as we rely on Au's
848        // overflow detection to clamp the resulting value between `MAX_AU` and `MIN_AU`.
849        let new_origin = self.origin() + offset;
850        self.set_origin(new_origin);
851    }
852}
853
854impl fmt::Debug for SyncPhysicalRectAu {
855    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
856        self.get().fmt(f)
857    }
858}
859
860#[test]
861fn test_rectangle_logical_physical_conversion() {
862    let make_logical_rect =
863        |inline_origin: i32, block_origin: i32, inline_size: i32, block_size: i32| LogicalRect {
864            start_corner: LogicalVec2 {
865                inline: Au::from_px(inline_origin),
866                block: Au::from_px(block_origin),
867            },
868            size: LogicalVec2 {
869                inline: Au::from_px(inline_size),
870                block: Au::from_px(block_size),
871            },
872        };
873
874    let make_physical_rect = |x: i32, y: i32, width: i32, height: i32| {
875        PhysicalRect::new(
876            Point2D::new(Au::from_px(x), Au::from_px(y)),
877            Size2D::new(Au::from_px(width), Au::from_px(height)),
878        )
879    };
880
881    let test_rectangle = make_logical_rect(10, 20, 30, 40);
882    let container_size = LogicalVec2 {
883        inline: Au::from_px(100),
884        block: Au::from_px(200),
885    };
886
887    let assert_conversion = |expected_rect: PhysicalRect<Au>, writing_mode| {
888        let converted = test_rectangle.as_physical(writing_mode, container_size);
889        assert_eq!(converted, expected_rect);
890        let converted_back = LogicalRect::from_physical(converted, writing_mode, container_size);
891        assert_eq!(converted_back, test_rectangle);
892    };
893
894    // `writing-mode: horizontal-tb` `direction: ltr`
895    assert_conversion(
896        make_physical_rect(10, 20, 30, 40),
897        WritingMode::horizontal_tb(),
898    );
899    // `writing-mode: horizontal-tb` `direction: rtl`
900    assert_conversion(
901        make_physical_rect(60, 20, 30, 40),
902        WritingMode::RTL | WritingMode::INLINE_REVERSED,
903    );
904    // `writing-mode: vertical-lr` `direction: ltr`
905    assert_conversion(
906        make_physical_rect(20, 10, 40, 30),
907        WritingMode::WRITING_MODE_VERTICAL_LR,
908    );
909    // `writing-mode: vertical-lr` `direction: rtl`
910    assert_conversion(
911        make_physical_rect(20, 60, 40, 30),
912        WritingMode::WRITING_MODE_VERTICAL_LR | WritingMode::RTL | WritingMode::INLINE_REVERSED,
913    );
914    // `writing-mode: vertical-rl` `direction: ltr`
915    assert_conversion(
916        make_physical_rect(140, 10, 40, 30),
917        WritingMode::WRITING_MODE_VERTICAL_RL,
918    );
919    // `writing-mode: vertical-rl` `direction: rtl`
920    assert_conversion(
921        make_physical_rect(140, 60, 40, 30),
922        WritingMode::WRITING_MODE_VERTICAL_RL | WritingMode::RTL | WritingMode::INLINE_REVERSED,
923    );
924    // `writing-mode: sideways-lr` `direction: ltr`
925    assert_conversion(
926        make_physical_rect(20, 60, 40, 30),
927        WritingMode::WRITING_MODE_SIDEWAYS_LR | WritingMode::INLINE_REVERSED,
928    );
929    // `writing-mode: sideways-lr` `direction: rtl`
930    assert_conversion(
931        make_physical_rect(20, 10, 40, 30),
932        WritingMode::WRITING_MODE_SIDEWAYS_LR | WritingMode::RTL,
933    );
934    // `writing-mode: sideways-rl` `direction: ltr`
935    assert_conversion(
936        make_physical_rect(140, 10, 40, 30),
937        WritingMode::WRITING_MODE_SIDEWAYS_RL,
938    );
939    // `writing-mode: sideways-rl` `direction: rtl`
940    assert_conversion(
941        make_physical_rect(140, 60, 40, 30),
942        WritingMode::WRITING_MODE_SIDEWAYS_RL | WritingMode::RTL | WritingMode::INLINE_REVERSED,
943    );
944    // `writing-mode: sideways-rl` `direction: rtl` `text-orientation: upright`
945    assert_conversion(
946        make_physical_rect(140, 10, 40, 30),
947        WritingMode::WRITING_MODE_VERTICAL_RL | WritingMode::UPRIGHT,
948    );
949}