Skip to main content

style/
logical_geometry.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
5//! Geometry in flow-relative space.
6
7use crate::derives::*;
8use crate::properties::style_structs;
9use euclid::default::{Point2D, Rect, SideOffsets2D, Size2D};
10use euclid::num::Zero;
11use std::cmp::{max, min};
12use std::fmt::{self, Debug, Error, Formatter};
13use std::ops::{Add, Sub};
14
15pub enum BlockFlowDirection {
16    TopToBottom,
17    RightToLeft,
18    LeftToRight,
19}
20
21pub enum InlineBaseDirection {
22    LeftToRight,
23    RightToLeft,
24}
25
26fn sideways_enabled(_: &crate::parser::ParserContext) -> bool {
27    crate::pref!("layout.css.writing-mode.sideways.enabled", gecko = true)
28}
29
30/// The writing-mode property (different from the WritingMode enum).
31/// https://drafts.csswg.org/css-writing-modes/#block-flow
32/// Aliases come from https://drafts.csswg.org/css-writing-modes-4/#svg-writing-mode
33#[allow(missing_docs)]
34#[derive(
35    Clone,
36    Copy,
37    Debug,
38    Eq,
39    FromPrimitive,
40    MallocSizeOf,
41    Parse,
42    PartialEq,
43    SpecifiedValueInfo,
44    ToComputedValue,
45    ToCss,
46    ToResolvedValue,
47    ToShmem,
48    ToTyped,
49)]
50#[repr(u8)]
51pub enum WritingModeProperty {
52    #[parse(aliases = "lr,lr-tb,rl,rl-tb")]
53    HorizontalTb,
54    #[parse(aliases = "tb,tb-rl")]
55    VerticalRl,
56    VerticalLr,
57    #[parse(condition = "sideways_enabled")]
58    SidewaysRl,
59    #[parse(condition = "sideways_enabled")]
60    SidewaysLr,
61}
62
63// TODO: improve the readability of the WritingMode serialization, refer to the Debug:fmt()
64#[derive(Clone, Copy, Debug, Eq, MallocSizeOf, PartialEq, Serialize)]
65#[repr(C)]
66pub struct WritingMode(u8);
67bitflags!(
68    impl WritingMode: u8 {
69        /// A vertical writing mode; writing-mode is vertical-rl,
70        /// vertical-lr, sideways-lr, or sideways-rl.
71        const VERTICAL = 1 << 0;
72        /// The inline flow direction is reversed against the physical
73        /// direction (i.e. right-to-left or bottom-to-top); writing-mode is
74        /// sideways-lr or direction is rtl (but not both).
75        ///
76        /// (This bit can be derived from the others, but we store it for
77        /// convenience.)
78        const INLINE_REVERSED = 1 << 1;
79        /// A vertical writing mode whose block progression direction is left-
80        /// to-right; writing-mode is vertical-lr or sideways-lr.
81        ///
82        /// Never set without VERTICAL.
83        const VERTICAL_LR = 1 << 2;
84        /// The line-over/line-under sides are inverted with respect to the
85        /// block-start/block-end edge; writing-mode is vertical-lr.
86        ///
87        /// Never set without VERTICAL and VERTICAL_LR.
88        const LINE_INVERTED = 1 << 3;
89        /// direction is rtl.
90        const RTL = 1 << 4;
91        /// All text within a vertical writing mode is displayed sideways
92        /// and runs top-to-bottom or bottom-to-top; set in these cases:
93        ///
94        /// * writing-mode: sideways-rl;
95        /// * writing-mode: sideways-lr;
96        ///
97        /// Never set without VERTICAL.
98        const VERTICAL_SIDEWAYS = 1 << 5;
99        /// Similar to VERTICAL_SIDEWAYS, but is set via text-orientation;
100        /// set in these cases:
101        ///
102        /// * writing-mode: vertical-rl; text-orientation: sideways;
103        /// * writing-mode: vertical-lr; text-orientation: sideways;
104        ///
105        /// Never set without VERTICAL.
106        const TEXT_SIDEWAYS = 1 << 6;
107        /// Horizontal text within a vertical writing mode is displayed with each
108        /// glyph upright; set in these cases:
109        ///
110        /// * writing-mode: vertical-rl; text-orientation: upright;
111        /// * writing-mode: vertical-lr: text-orientation: upright;
112        ///
113        /// Never set without VERTICAL.
114        const UPRIGHT = 1 << 7;
115        /// Writing mode combinations that can be specified in CSS.
116        ///
117        /// * writing-mode: horizontal-tb;
118        const WRITING_MODE_HORIZONTAL_TB = 0;
119        /// * writing-mode: vertical_rl;
120        const WRITING_MODE_VERTICAL_RL = WritingMode::VERTICAL.bits();
121        /// * writing-mode: vertical-lr;
122        const WRITING_MODE_VERTICAL_LR = WritingMode::VERTICAL.bits() |
123                                         WritingMode::VERTICAL_LR.bits() |
124                                         WritingMode::LINE_INVERTED.bits();
125        /// * writing-mode: sideways-rl;
126        const WRITING_MODE_SIDEWAYS_RL = WritingMode::VERTICAL.bits() |
127                                         WritingMode::VERTICAL_SIDEWAYS.bits();
128        /// * writing-mode: sideways-lr;
129        const WRITING_MODE_SIDEWAYS_LR = WritingMode::VERTICAL.bits() |
130                                         WritingMode::VERTICAL_LR.bits() |
131                                         WritingMode::VERTICAL_SIDEWAYS.bits();
132    }
133);
134
135impl WritingMode {
136    /// Return a WritingMode bitflags from the relevant CSS properties.
137    pub fn new(inheritedbox_style: &style_structs::InheritedBox) -> Self {
138        use crate::properties::longhands::direction::computed_value::T as Direction;
139        use crate::properties::longhands::text_orientation::computed_value::T as TextOrientation;
140
141        let mut flags = WritingMode::empty();
142
143        let direction = *inheritedbox_style.get_direction();
144        let writing_mode = *inheritedbox_style.get_writing_mode();
145
146        match direction {
147            Direction::Ltr => {},
148            Direction::Rtl => {
149                flags.insert(WritingMode::RTL);
150            },
151        }
152
153        match writing_mode {
154            WritingModeProperty::HorizontalTb => {
155                if direction == Direction::Rtl {
156                    flags.insert(WritingMode::INLINE_REVERSED);
157                }
158            },
159            WritingModeProperty::VerticalRl => {
160                flags.insert(WritingMode::WRITING_MODE_VERTICAL_RL);
161                if direction == Direction::Rtl {
162                    flags.insert(WritingMode::INLINE_REVERSED);
163                }
164            },
165            WritingModeProperty::VerticalLr => {
166                flags.insert(WritingMode::WRITING_MODE_VERTICAL_LR);
167                if direction == Direction::Rtl {
168                    flags.insert(WritingMode::INLINE_REVERSED);
169                }
170            },
171            WritingModeProperty::SidewaysRl => {
172                flags.insert(WritingMode::WRITING_MODE_SIDEWAYS_RL);
173                if direction == Direction::Rtl {
174                    flags.insert(WritingMode::INLINE_REVERSED);
175                }
176            },
177            WritingModeProperty::SidewaysLr => {
178                flags.insert(WritingMode::WRITING_MODE_SIDEWAYS_LR);
179                if direction == Direction::Ltr {
180                    flags.insert(WritingMode::INLINE_REVERSED);
181                }
182            },
183        }
184
185        // text-orientation only has an effect for vertical-rl and
186        // vertical-lr values of writing-mode.
187        match writing_mode {
188            WritingModeProperty::VerticalRl | WritingModeProperty::VerticalLr => {
189                match *inheritedbox_style.get_text_orientation() {
190                    TextOrientation::Mixed => {},
191                    TextOrientation::Upright => {
192                        flags.insert(WritingMode::UPRIGHT);
193
194                        // https://drafts.csswg.org/css-writing-modes-3/#valdef-text-orientation-upright:
195                        //
196                        // > This value causes the used value of direction
197                        // > to be ltr, and for the purposes of bidi
198                        // > reordering, causes all characters to be treated
199                        // > as strong LTR.
200                        flags.remove(WritingMode::RTL);
201                        flags.remove(WritingMode::INLINE_REVERSED);
202                    },
203                    TextOrientation::Sideways => {
204                        flags.insert(WritingMode::TEXT_SIDEWAYS);
205                    },
206                }
207            },
208            _ => {},
209        }
210
211        flags
212    }
213
214    /// Returns the `horizontal-tb` value.
215    pub fn horizontal_tb() -> Self {
216        Self::empty()
217    }
218
219    #[inline]
220    pub fn is_vertical(&self) -> bool {
221        self.intersects(WritingMode::VERTICAL)
222    }
223
224    #[inline]
225    pub fn is_vertical_rl(&self) -> bool {
226        self.is_vertical() && !self.is_vertical_lr()
227    }
228
229    #[inline]
230    pub fn is_horizontal(&self) -> bool {
231        !self.is_vertical()
232    }
233
234    /// Assuming .is_vertical(), does the block direction go left to right?
235    #[inline]
236    pub fn is_vertical_lr(&self) -> bool {
237        self.intersects(WritingMode::VERTICAL_LR)
238    }
239
240    /// Assuming .is_vertical(), does the inline direction go top to bottom?
241    #[inline]
242    pub fn is_inline_tb(&self) -> bool {
243        // https://drafts.csswg.org/css-writing-modes-3/#logical-to-physical
244        !self.intersects(WritingMode::INLINE_REVERSED)
245    }
246
247    #[inline]
248    pub fn is_bidi_ltr(&self) -> bool {
249        !self.intersects(WritingMode::RTL)
250    }
251
252    #[inline]
253    pub fn is_sideways(&self) -> bool {
254        self.intersects(WritingMode::VERTICAL_SIDEWAYS | WritingMode::TEXT_SIDEWAYS)
255    }
256
257    #[inline]
258    pub fn is_upright(&self) -> bool {
259        self.intersects(WritingMode::UPRIGHT)
260    }
261
262    /// https://drafts.csswg.org/css-writing-modes/#logical-to-physical
263    ///
264    /// | Return  | line-left is… | line-right is… |
265    /// |---------|---------------|----------------|
266    /// | `true`  | inline-start  | inline-end     |
267    /// | `false` | inline-end    | inline-start   |
268    #[inline]
269    pub fn line_left_is_inline_start(&self) -> bool {
270        // https://drafts.csswg.org/css-writing-modes/#inline-start
271        // “For boxes with a used direction value of ltr, this means the line-left side.
272        //  For boxes with a used direction value of rtl, this means the line-right side.”
273        self.is_bidi_ltr()
274    }
275
276    #[inline]
277    pub fn inline_start_physical_side(&self) -> PhysicalSide {
278        match (self.is_vertical(), self.is_inline_tb(), self.is_bidi_ltr()) {
279            (false, _, true) => PhysicalSide::Left,
280            (false, _, false) => PhysicalSide::Right,
281            (true, true, _) => PhysicalSide::Top,
282            (true, false, _) => PhysicalSide::Bottom,
283        }
284    }
285
286    #[inline]
287    pub fn inline_end_physical_side(&self) -> PhysicalSide {
288        match (self.is_vertical(), self.is_inline_tb(), self.is_bidi_ltr()) {
289            (false, _, true) => PhysicalSide::Right,
290            (false, _, false) => PhysicalSide::Left,
291            (true, true, _) => PhysicalSide::Bottom,
292            (true, false, _) => PhysicalSide::Top,
293        }
294    }
295
296    #[inline]
297    pub fn block_start_physical_side(&self) -> PhysicalSide {
298        match (self.is_vertical(), self.is_vertical_lr()) {
299            (false, _) => PhysicalSide::Top,
300            (true, true) => PhysicalSide::Left,
301            (true, false) => PhysicalSide::Right,
302        }
303    }
304
305    #[inline]
306    pub fn block_end_physical_side(&self) -> PhysicalSide {
307        match (self.is_vertical(), self.is_vertical_lr()) {
308            (false, _) => PhysicalSide::Bottom,
309            (true, true) => PhysicalSide::Right,
310            (true, false) => PhysicalSide::Left,
311        }
312    }
313
314    /// Given a physical side, flips the start on that axis, and returns the corresponding
315    /// physical side.
316    #[inline]
317    pub fn flipped_start_side(&self, side: PhysicalSide) -> PhysicalSide {
318        let bs = self.block_start_physical_side();
319        if side == bs {
320            return self.inline_start_physical_side();
321        }
322        let be = self.block_end_physical_side();
323        if side == be {
324            return self.inline_end_physical_side();
325        }
326        if side == self.inline_start_physical_side() {
327            return bs;
328        }
329        debug_assert_eq!(side, self.inline_end_physical_side());
330        be
331    }
332
333    #[inline]
334    pub fn start_start_physical_corner(&self) -> PhysicalCorner {
335        PhysicalCorner::from_sides(
336            self.block_start_physical_side(),
337            self.inline_start_physical_side(),
338        )
339    }
340
341    #[inline]
342    pub fn start_end_physical_corner(&self) -> PhysicalCorner {
343        PhysicalCorner::from_sides(
344            self.block_start_physical_side(),
345            self.inline_end_physical_side(),
346        )
347    }
348
349    #[inline]
350    pub fn end_start_physical_corner(&self) -> PhysicalCorner {
351        PhysicalCorner::from_sides(
352            self.block_end_physical_side(),
353            self.inline_start_physical_side(),
354        )
355    }
356
357    #[inline]
358    pub fn end_end_physical_corner(&self) -> PhysicalCorner {
359        PhysicalCorner::from_sides(
360            self.block_end_physical_side(),
361            self.inline_end_physical_side(),
362        )
363    }
364
365    #[inline]
366    pub fn block_flow_direction(&self) -> BlockFlowDirection {
367        match (self.is_vertical(), self.is_vertical_lr()) {
368            (false, _) => BlockFlowDirection::TopToBottom,
369            (true, true) => BlockFlowDirection::LeftToRight,
370            (true, false) => BlockFlowDirection::RightToLeft,
371        }
372    }
373
374    #[inline]
375    pub fn inline_base_direction(&self) -> InlineBaseDirection {
376        if self.intersects(WritingMode::RTL) {
377            InlineBaseDirection::RightToLeft
378        } else {
379            InlineBaseDirection::LeftToRight
380        }
381    }
382
383    #[inline]
384    /// Is the text layout vertical?
385    pub fn is_text_vertical(&self) -> bool {
386        self.is_vertical() && !self.is_sideways()
387    }
388}
389
390impl fmt::Display for WritingMode {
391    fn fmt(&self, formatter: &mut Formatter) -> Result<(), Error> {
392        if self.is_vertical() {
393            write!(formatter, "V")?;
394            if self.is_vertical_lr() {
395                write!(formatter, " LR")?;
396            } else {
397                write!(formatter, " RL")?;
398            }
399            if self.is_sideways() {
400                write!(formatter, " Sideways")?;
401            }
402            if self.intersects(WritingMode::LINE_INVERTED) {
403                write!(formatter, " Inverted")?;
404            }
405        } else {
406            write!(formatter, "H")?;
407        }
408        if self.is_bidi_ltr() {
409            write!(formatter, " LTR")
410        } else {
411            write!(formatter, " RTL")
412        }
413    }
414}
415
416/// Wherever logical geometry is used, the writing mode is known based on context:
417/// every method takes a `mode` parameter.
418/// However, this context is easy to get wrong.
419/// In debug builds only, logical geometry objects store their writing mode
420/// (in addition to taking it as a parameter to methods) and check it.
421/// In non-debug builds, make this storage zero-size and the checks no-ops.
422#[cfg(not(debug_assertions))]
423#[derive(Clone, Copy, Eq, PartialEq, Serialize)]
424struct DebugWritingMode;
425
426#[cfg(debug_assertions)]
427#[derive(Clone, Copy, Eq, PartialEq, Serialize)]
428struct DebugWritingMode {
429    mode: WritingMode,
430}
431
432#[cfg(not(debug_assertions))]
433impl DebugWritingMode {
434    #[inline]
435    fn check(&self, _other: WritingMode) {}
436
437    #[inline]
438    fn check_debug(&self, _other: DebugWritingMode) {}
439
440    #[inline]
441    fn new(_mode: WritingMode) -> DebugWritingMode {
442        DebugWritingMode
443    }
444}
445
446#[cfg(debug_assertions)]
447impl DebugWritingMode {
448    #[inline]
449    fn check(&self, other: WritingMode) {
450        assert_eq!(self.mode, other)
451    }
452
453    #[inline]
454    fn check_debug(&self, other: DebugWritingMode) {
455        assert_eq!(self.mode, other.mode)
456    }
457
458    #[inline]
459    fn new(mode: WritingMode) -> DebugWritingMode {
460        DebugWritingMode { mode }
461    }
462}
463
464impl Debug for DebugWritingMode {
465    #[cfg(not(debug_assertions))]
466    fn fmt(&self, formatter: &mut Formatter) -> Result<(), Error> {
467        write!(formatter, "?")
468    }
469
470    #[cfg(debug_assertions)]
471    fn fmt(&self, formatter: &mut Formatter) -> Result<(), Error> {
472        write!(formatter, "{}", self.mode)
473    }
474}
475
476/// A 2D size in flow-relative dimensions
477#[derive(Clone, Copy, Eq, PartialEq, Serialize)]
478pub struct LogicalSize<T> {
479    pub inline: T, // inline-size, a.k.a. logical width, a.k.a. measure
480    pub block: T,  // block-size, a.k.a. logical height, a.k.a. extent
481    debug_writing_mode: DebugWritingMode,
482}
483
484impl<T: Debug> Debug for LogicalSize<T> {
485    fn fmt(&self, formatter: &mut Formatter) -> Result<(), Error> {
486        write!(
487            formatter,
488            "LogicalSize({:?}, i{:?}×b{:?})",
489            self.debug_writing_mode, self.inline, self.block
490        )
491    }
492}
493
494// Can not implement the Zero trait: its zero() method does not have the `mode` parameter.
495impl<T: Zero> LogicalSize<T> {
496    #[inline]
497    pub fn zero(mode: WritingMode) -> LogicalSize<T> {
498        LogicalSize {
499            inline: Zero::zero(),
500            block: Zero::zero(),
501            debug_writing_mode: DebugWritingMode::new(mode),
502        }
503    }
504}
505
506impl<T> LogicalSize<T> {
507    #[inline]
508    pub fn new(mode: WritingMode, inline: T, block: T) -> LogicalSize<T> {
509        LogicalSize {
510            inline,
511            block,
512            debug_writing_mode: DebugWritingMode::new(mode),
513        }
514    }
515
516    #[inline]
517    pub fn from_physical(mode: WritingMode, size: Size2D<T>) -> LogicalSize<T> {
518        if mode.is_vertical() {
519            LogicalSize::new(mode, size.height, size.width)
520        } else {
521            LogicalSize::new(mode, size.width, size.height)
522        }
523    }
524}
525
526impl<T: Clone> LogicalSize<T> {
527    #[inline]
528    pub fn width(&self, mode: WritingMode) -> T {
529        self.debug_writing_mode.check(mode);
530        if mode.is_vertical() {
531            self.block.clone()
532        } else {
533            self.inline.clone()
534        }
535    }
536
537    #[inline]
538    pub fn set_width(&mut self, mode: WritingMode, width: T) {
539        self.debug_writing_mode.check(mode);
540        if mode.is_vertical() {
541            self.block = width
542        } else {
543            self.inline = width
544        }
545    }
546
547    #[inline]
548    pub fn height(&self, mode: WritingMode) -> T {
549        self.debug_writing_mode.check(mode);
550        if mode.is_vertical() {
551            self.inline.clone()
552        } else {
553            self.block.clone()
554        }
555    }
556
557    #[inline]
558    pub fn set_height(&mut self, mode: WritingMode, height: T) {
559        self.debug_writing_mode.check(mode);
560        if mode.is_vertical() {
561            self.inline = height
562        } else {
563            self.block = height
564        }
565    }
566
567    #[inline]
568    pub fn to_physical(&self, mode: WritingMode) -> Size2D<T> {
569        self.debug_writing_mode.check(mode);
570        if mode.is_vertical() {
571            Size2D::new(self.block.clone(), self.inline.clone())
572        } else {
573            Size2D::new(self.inline.clone(), self.block.clone())
574        }
575    }
576
577    #[inline]
578    pub fn convert(&self, mode_from: WritingMode, mode_to: WritingMode) -> LogicalSize<T> {
579        if mode_from == mode_to {
580            self.debug_writing_mode.check(mode_from);
581            self.clone()
582        } else {
583            LogicalSize::from_physical(mode_to, self.to_physical(mode_from))
584        }
585    }
586}
587
588impl<T: Add<T, Output = T>> Add for LogicalSize<T> {
589    type Output = LogicalSize<T>;
590
591    #[inline]
592    fn add(self, other: LogicalSize<T>) -> LogicalSize<T> {
593        self.debug_writing_mode
594            .check_debug(other.debug_writing_mode);
595        LogicalSize {
596            debug_writing_mode: self.debug_writing_mode,
597            inline: self.inline + other.inline,
598            block: self.block + other.block,
599        }
600    }
601}
602
603impl<T: Sub<T, Output = T>> Sub for LogicalSize<T> {
604    type Output = LogicalSize<T>;
605
606    #[inline]
607    fn sub(self, other: LogicalSize<T>) -> LogicalSize<T> {
608        self.debug_writing_mode
609            .check_debug(other.debug_writing_mode);
610        LogicalSize {
611            debug_writing_mode: self.debug_writing_mode,
612            inline: self.inline - other.inline,
613            block: self.block - other.block,
614        }
615    }
616}
617
618/// A 2D point in flow-relative dimensions
619#[derive(Clone, Copy, Eq, PartialEq, Serialize)]
620pub struct LogicalPoint<T> {
621    /// inline-axis coordinate
622    pub i: T,
623    /// block-axis coordinate
624    pub b: T,
625    debug_writing_mode: DebugWritingMode,
626}
627
628impl<T: Debug> Debug for LogicalPoint<T> {
629    fn fmt(&self, formatter: &mut Formatter) -> Result<(), Error> {
630        write!(
631            formatter,
632            "LogicalPoint({:?} (i{:?}, b{:?}))",
633            self.debug_writing_mode, self.i, self.b
634        )
635    }
636}
637
638// Can not implement the Zero trait: its zero() method does not have the `mode` parameter.
639impl<T: Zero> LogicalPoint<T> {
640    #[inline]
641    pub fn zero(mode: WritingMode) -> LogicalPoint<T> {
642        LogicalPoint {
643            i: Zero::zero(),
644            b: Zero::zero(),
645            debug_writing_mode: DebugWritingMode::new(mode),
646        }
647    }
648}
649
650impl<T: Copy> LogicalPoint<T> {
651    #[inline]
652    pub fn new(mode: WritingMode, i: T, b: T) -> LogicalPoint<T> {
653        LogicalPoint {
654            i,
655            b,
656            debug_writing_mode: DebugWritingMode::new(mode),
657        }
658    }
659}
660
661impl<T: Copy + Sub<T, Output = T>> LogicalPoint<T> {
662    #[inline]
663    pub fn from_physical(
664        mode: WritingMode,
665        point: Point2D<T>,
666        container_size: Size2D<T>,
667    ) -> LogicalPoint<T> {
668        if mode.is_vertical() {
669            LogicalPoint {
670                i: if mode.is_inline_tb() {
671                    point.y
672                } else {
673                    container_size.height - point.y
674                },
675                b: if mode.is_vertical_lr() {
676                    point.x
677                } else {
678                    container_size.width - point.x
679                },
680                debug_writing_mode: DebugWritingMode::new(mode),
681            }
682        } else {
683            LogicalPoint {
684                i: if mode.is_bidi_ltr() {
685                    point.x
686                } else {
687                    container_size.width - point.x
688                },
689                b: point.y,
690                debug_writing_mode: DebugWritingMode::new(mode),
691            }
692        }
693    }
694
695    #[inline]
696    pub fn x(&self, mode: WritingMode, container_size: Size2D<T>) -> T {
697        self.debug_writing_mode.check(mode);
698        if mode.is_vertical() {
699            if mode.is_vertical_lr() {
700                self.b
701            } else {
702                container_size.width - self.b
703            }
704        } else if mode.is_bidi_ltr() {
705            self.i
706        } else {
707            container_size.width - self.i
708        }
709    }
710
711    #[inline]
712    pub fn set_x(&mut self, mode: WritingMode, x: T, container_size: Size2D<T>) {
713        self.debug_writing_mode.check(mode);
714        if mode.is_vertical() {
715            self.b = if mode.is_vertical_lr() {
716                x
717            } else {
718                container_size.width - x
719            }
720        } else {
721            self.i = if mode.is_bidi_ltr() {
722                x
723            } else {
724                container_size.width - x
725            }
726        }
727    }
728
729    #[inline]
730    pub fn y(&self, mode: WritingMode, container_size: Size2D<T>) -> T {
731        self.debug_writing_mode.check(mode);
732        if mode.is_vertical() {
733            if mode.is_inline_tb() {
734                self.i
735            } else {
736                container_size.height - self.i
737            }
738        } else {
739            self.b
740        }
741    }
742
743    #[inline]
744    pub fn set_y(&mut self, mode: WritingMode, y: T, container_size: Size2D<T>) {
745        self.debug_writing_mode.check(mode);
746        if mode.is_vertical() {
747            self.i = if mode.is_inline_tb() {
748                y
749            } else {
750                container_size.height - y
751            }
752        } else {
753            self.b = y
754        }
755    }
756
757    #[inline]
758    pub fn to_physical(&self, mode: WritingMode, container_size: Size2D<T>) -> Point2D<T> {
759        self.debug_writing_mode.check(mode);
760        if mode.is_vertical() {
761            Point2D::new(
762                if mode.is_vertical_lr() {
763                    self.b
764                } else {
765                    container_size.width - self.b
766                },
767                if mode.is_inline_tb() {
768                    self.i
769                } else {
770                    container_size.height - self.i
771                },
772            )
773        } else {
774            Point2D::new(
775                if mode.is_bidi_ltr() {
776                    self.i
777                } else {
778                    container_size.width - self.i
779                },
780                self.b,
781            )
782        }
783    }
784
785    #[inline]
786    pub fn convert(
787        &self,
788        mode_from: WritingMode,
789        mode_to: WritingMode,
790        container_size: Size2D<T>,
791    ) -> LogicalPoint<T> {
792        if mode_from == mode_to {
793            self.debug_writing_mode.check(mode_from);
794            *self
795        } else {
796            LogicalPoint::from_physical(
797                mode_to,
798                self.to_physical(mode_from, container_size),
799                container_size,
800            )
801        }
802    }
803}
804
805impl<T: Copy + Add<T, Output = T>> LogicalPoint<T> {
806    /// This doesn’t really makes sense,
807    /// but happens when dealing with multiple origins.
808    #[inline]
809    pub fn add_point(&self, other: &LogicalPoint<T>) -> LogicalPoint<T> {
810        self.debug_writing_mode
811            .check_debug(other.debug_writing_mode);
812        LogicalPoint {
813            debug_writing_mode: self.debug_writing_mode,
814            i: self.i + other.i,
815            b: self.b + other.b,
816        }
817    }
818}
819
820impl<T: Copy + Add<T, Output = T>> Add<LogicalSize<T>> for LogicalPoint<T> {
821    type Output = LogicalPoint<T>;
822
823    #[inline]
824    fn add(self, other: LogicalSize<T>) -> LogicalPoint<T> {
825        self.debug_writing_mode
826            .check_debug(other.debug_writing_mode);
827        LogicalPoint {
828            debug_writing_mode: self.debug_writing_mode,
829            i: self.i + other.inline,
830            b: self.b + other.block,
831        }
832    }
833}
834
835impl<T: Copy + Sub<T, Output = T>> Sub<LogicalSize<T>> for LogicalPoint<T> {
836    type Output = LogicalPoint<T>;
837
838    #[inline]
839    fn sub(self, other: LogicalSize<T>) -> LogicalPoint<T> {
840        self.debug_writing_mode
841            .check_debug(other.debug_writing_mode);
842        LogicalPoint {
843            debug_writing_mode: self.debug_writing_mode,
844            i: self.i - other.inline,
845            b: self.b - other.block,
846        }
847    }
848}
849
850/// A "margin" in flow-relative dimensions
851/// Represents the four sides of the margins, borders, or padding of a CSS box,
852/// or a combination of those.
853/// A positive "margin" can be added to a rectangle to obtain a bigger rectangle.
854#[derive(Clone, Copy, Eq, PartialEq, Serialize)]
855pub struct LogicalMargin<T> {
856    pub block_start: T,
857    pub inline_end: T,
858    pub block_end: T,
859    pub inline_start: T,
860    debug_writing_mode: DebugWritingMode,
861}
862
863impl<T: Debug> Debug for LogicalMargin<T> {
864    fn fmt(&self, formatter: &mut Formatter) -> Result<(), Error> {
865        let writing_mode_string = if cfg!(debug_assertions) {
866            format!("{:?}, ", self.debug_writing_mode)
867        } else {
868            "".to_owned()
869        };
870
871        write!(
872            formatter,
873            "LogicalMargin({}i:{:?}..{:?} b:{:?}..{:?})",
874            writing_mode_string,
875            self.inline_start,
876            self.inline_end,
877            self.block_start,
878            self.block_end
879        )
880    }
881}
882
883impl<T: Zero> LogicalMargin<T> {
884    #[inline]
885    pub fn zero(mode: WritingMode) -> LogicalMargin<T> {
886        LogicalMargin {
887            block_start: Zero::zero(),
888            inline_end: Zero::zero(),
889            block_end: Zero::zero(),
890            inline_start: Zero::zero(),
891            debug_writing_mode: DebugWritingMode::new(mode),
892        }
893    }
894}
895
896impl<T> LogicalMargin<T> {
897    #[inline]
898    pub fn new(
899        mode: WritingMode,
900        block_start: T,
901        inline_end: T,
902        block_end: T,
903        inline_start: T,
904    ) -> LogicalMargin<T> {
905        LogicalMargin {
906            block_start,
907            inline_end,
908            block_end,
909            inline_start,
910            debug_writing_mode: DebugWritingMode::new(mode),
911        }
912    }
913
914    #[inline]
915    pub fn from_physical(mode: WritingMode, offsets: SideOffsets2D<T>) -> LogicalMargin<T> {
916        let block_start;
917        let inline_end;
918        let block_end;
919        let inline_start;
920        if mode.is_vertical() {
921            if mode.is_vertical_lr() {
922                block_start = offsets.left;
923                block_end = offsets.right;
924            } else {
925                block_start = offsets.right;
926                block_end = offsets.left;
927            }
928            if mode.is_inline_tb() {
929                inline_start = offsets.top;
930                inline_end = offsets.bottom;
931            } else {
932                inline_start = offsets.bottom;
933                inline_end = offsets.top;
934            }
935        } else {
936            block_start = offsets.top;
937            block_end = offsets.bottom;
938            if mode.is_bidi_ltr() {
939                inline_start = offsets.left;
940                inline_end = offsets.right;
941            } else {
942                inline_start = offsets.right;
943                inline_end = offsets.left;
944            }
945        }
946        LogicalMargin::new(mode, block_start, inline_end, block_end, inline_start)
947    }
948}
949
950impl<T: Clone> LogicalMargin<T> {
951    #[inline]
952    pub fn new_all_same(mode: WritingMode, value: T) -> LogicalMargin<T> {
953        LogicalMargin::new(mode, value.clone(), value.clone(), value.clone(), value)
954    }
955
956    #[inline]
957    pub fn top(&self, mode: WritingMode) -> T {
958        self.debug_writing_mode.check(mode);
959        if mode.is_vertical() {
960            if mode.is_inline_tb() {
961                self.inline_start.clone()
962            } else {
963                self.inline_end.clone()
964            }
965        } else {
966            self.block_start.clone()
967        }
968    }
969
970    #[inline]
971    pub fn set_top(&mut self, mode: WritingMode, top: T) {
972        self.debug_writing_mode.check(mode);
973        if mode.is_vertical() {
974            if mode.is_inline_tb() {
975                self.inline_start = top
976            } else {
977                self.inline_end = top
978            }
979        } else {
980            self.block_start = top
981        }
982    }
983
984    #[inline]
985    pub fn right(&self, mode: WritingMode) -> T {
986        self.debug_writing_mode.check(mode);
987        if mode.is_vertical() {
988            if mode.is_vertical_lr() {
989                self.block_end.clone()
990            } else {
991                self.block_start.clone()
992            }
993        } else if mode.is_bidi_ltr() {
994            self.inline_end.clone()
995        } else {
996            self.inline_start.clone()
997        }
998    }
999
1000    #[inline]
1001    pub fn set_right(&mut self, mode: WritingMode, right: T) {
1002        self.debug_writing_mode.check(mode);
1003        if mode.is_vertical() {
1004            if mode.is_vertical_lr() {
1005                self.block_end = right
1006            } else {
1007                self.block_start = right
1008            }
1009        } else if mode.is_bidi_ltr() {
1010            self.inline_end = right
1011        } else {
1012            self.inline_start = right
1013        }
1014    }
1015
1016    #[inline]
1017    pub fn bottom(&self, mode: WritingMode) -> T {
1018        self.debug_writing_mode.check(mode);
1019        if mode.is_vertical() {
1020            if mode.is_inline_tb() {
1021                self.inline_end.clone()
1022            } else {
1023                self.inline_start.clone()
1024            }
1025        } else {
1026            self.block_end.clone()
1027        }
1028    }
1029
1030    #[inline]
1031    pub fn set_bottom(&mut self, mode: WritingMode, bottom: T) {
1032        self.debug_writing_mode.check(mode);
1033        if mode.is_vertical() {
1034            if mode.is_inline_tb() {
1035                self.inline_end = bottom
1036            } else {
1037                self.inline_start = bottom
1038            }
1039        } else {
1040            self.block_end = bottom
1041        }
1042    }
1043
1044    #[inline]
1045    pub fn left(&self, mode: WritingMode) -> T {
1046        self.debug_writing_mode.check(mode);
1047        if mode.is_vertical() {
1048            if mode.is_vertical_lr() {
1049                self.block_start.clone()
1050            } else {
1051                self.block_end.clone()
1052            }
1053        } else if mode.is_bidi_ltr() {
1054            self.inline_start.clone()
1055        } else {
1056            self.inline_end.clone()
1057        }
1058    }
1059
1060    #[inline]
1061    pub fn set_left(&mut self, mode: WritingMode, left: T) {
1062        self.debug_writing_mode.check(mode);
1063        if mode.is_vertical() {
1064            if mode.is_vertical_lr() {
1065                self.block_start = left
1066            } else {
1067                self.block_end = left
1068            }
1069        } else if mode.is_bidi_ltr() {
1070            self.inline_start = left
1071        } else {
1072            self.inline_end = left
1073        }
1074    }
1075
1076    #[inline]
1077    pub fn to_physical(&self, mode: WritingMode) -> SideOffsets2D<T> {
1078        self.debug_writing_mode.check(mode);
1079        let top;
1080        let right;
1081        let bottom;
1082        let left;
1083        if mode.is_vertical() {
1084            if mode.is_vertical_lr() {
1085                left = self.block_start.clone();
1086                right = self.block_end.clone();
1087            } else {
1088                right = self.block_start.clone();
1089                left = self.block_end.clone();
1090            }
1091            if mode.is_inline_tb() {
1092                top = self.inline_start.clone();
1093                bottom = self.inline_end.clone();
1094            } else {
1095                bottom = self.inline_start.clone();
1096                top = self.inline_end.clone();
1097            }
1098        } else {
1099            top = self.block_start.clone();
1100            bottom = self.block_end.clone();
1101            if mode.is_bidi_ltr() {
1102                left = self.inline_start.clone();
1103                right = self.inline_end.clone();
1104            } else {
1105                right = self.inline_start.clone();
1106                left = self.inline_end.clone();
1107            }
1108        }
1109        SideOffsets2D::new(top, right, bottom, left)
1110    }
1111
1112    #[inline]
1113    pub fn convert(&self, mode_from: WritingMode, mode_to: WritingMode) -> LogicalMargin<T> {
1114        if mode_from == mode_to {
1115            self.debug_writing_mode.check(mode_from);
1116            self.clone()
1117        } else {
1118            LogicalMargin::from_physical(mode_to, self.to_physical(mode_from))
1119        }
1120    }
1121}
1122
1123impl<T: PartialEq + Zero> LogicalMargin<T> {
1124    #[inline]
1125    pub fn is_zero(&self) -> bool {
1126        self.block_start == Zero::zero()
1127            && self.inline_end == Zero::zero()
1128            && self.block_end == Zero::zero()
1129            && self.inline_start == Zero::zero()
1130    }
1131}
1132
1133impl<T: Copy + Add<T, Output = T>> LogicalMargin<T> {
1134    #[inline]
1135    pub fn inline_start_end(&self) -> T {
1136        self.inline_start + self.inline_end
1137    }
1138
1139    #[inline]
1140    pub fn block_start_end(&self) -> T {
1141        self.block_start + self.block_end
1142    }
1143
1144    #[inline]
1145    pub fn start_end(&self, axis: LogicalAxis) -> T {
1146        match axis {
1147            LogicalAxis::Inline => self.inline_start + self.inline_end,
1148            LogicalAxis::Block => self.block_start + self.block_end,
1149        }
1150    }
1151
1152    #[inline]
1153    pub fn top_bottom(&self, mode: WritingMode) -> T {
1154        self.debug_writing_mode.check(mode);
1155        if mode.is_vertical() {
1156            self.inline_start_end()
1157        } else {
1158            self.block_start_end()
1159        }
1160    }
1161
1162    #[inline]
1163    pub fn left_right(&self, mode: WritingMode) -> T {
1164        self.debug_writing_mode.check(mode);
1165        if mode.is_vertical() {
1166            self.block_start_end()
1167        } else {
1168            self.inline_start_end()
1169        }
1170    }
1171}
1172
1173impl<T: Add<T, Output = T>> Add for LogicalMargin<T> {
1174    type Output = LogicalMargin<T>;
1175
1176    #[inline]
1177    fn add(self, other: LogicalMargin<T>) -> LogicalMargin<T> {
1178        self.debug_writing_mode
1179            .check_debug(other.debug_writing_mode);
1180        LogicalMargin {
1181            debug_writing_mode: self.debug_writing_mode,
1182            block_start: self.block_start + other.block_start,
1183            inline_end: self.inline_end + other.inline_end,
1184            block_end: self.block_end + other.block_end,
1185            inline_start: self.inline_start + other.inline_start,
1186        }
1187    }
1188}
1189
1190impl<T: Sub<T, Output = T>> Sub for LogicalMargin<T> {
1191    type Output = LogicalMargin<T>;
1192
1193    #[inline]
1194    fn sub(self, other: LogicalMargin<T>) -> LogicalMargin<T> {
1195        self.debug_writing_mode
1196            .check_debug(other.debug_writing_mode);
1197        LogicalMargin {
1198            debug_writing_mode: self.debug_writing_mode,
1199            block_start: self.block_start - other.block_start,
1200            inline_end: self.inline_end - other.inline_end,
1201            block_end: self.block_end - other.block_end,
1202            inline_start: self.inline_start - other.inline_start,
1203        }
1204    }
1205}
1206
1207/// A rectangle in flow-relative dimensions
1208#[derive(Clone, Copy, Eq, PartialEq, Serialize)]
1209pub struct LogicalRect<T> {
1210    pub start: LogicalPoint<T>,
1211    pub size: LogicalSize<T>,
1212    debug_writing_mode: DebugWritingMode,
1213}
1214
1215impl<T: Debug> Debug for LogicalRect<T> {
1216    fn fmt(&self, formatter: &mut Formatter) -> Result<(), Error> {
1217        let writing_mode_string = if cfg!(debug_assertions) {
1218            format!("{:?}, ", self.debug_writing_mode)
1219        } else {
1220            "".to_owned()
1221        };
1222
1223        write!(
1224            formatter,
1225            "LogicalRect({}i{:?}×b{:?}, @ (i{:?},b{:?}))",
1226            writing_mode_string, self.size.inline, self.size.block, self.start.i, self.start.b
1227        )
1228    }
1229}
1230
1231impl<T: Zero> LogicalRect<T> {
1232    #[inline]
1233    pub fn zero(mode: WritingMode) -> LogicalRect<T> {
1234        LogicalRect {
1235            start: LogicalPoint::zero(mode),
1236            size: LogicalSize::zero(mode),
1237            debug_writing_mode: DebugWritingMode::new(mode),
1238        }
1239    }
1240}
1241
1242impl<T: Copy> LogicalRect<T> {
1243    #[inline]
1244    pub fn new(
1245        mode: WritingMode,
1246        inline_start: T,
1247        block_start: T,
1248        inline: T,
1249        block: T,
1250    ) -> LogicalRect<T> {
1251        LogicalRect {
1252            start: LogicalPoint::new(mode, inline_start, block_start),
1253            size: LogicalSize::new(mode, inline, block),
1254            debug_writing_mode: DebugWritingMode::new(mode),
1255        }
1256    }
1257
1258    #[inline]
1259    pub fn from_point_size(
1260        mode: WritingMode,
1261        start: LogicalPoint<T>,
1262        size: LogicalSize<T>,
1263    ) -> LogicalRect<T> {
1264        start.debug_writing_mode.check(mode);
1265        size.debug_writing_mode.check(mode);
1266        LogicalRect {
1267            start,
1268            size,
1269            debug_writing_mode: DebugWritingMode::new(mode),
1270        }
1271    }
1272}
1273
1274impl<T: Copy + Add<T, Output = T> + Sub<T, Output = T>> LogicalRect<T> {
1275    #[inline]
1276    pub fn from_physical(
1277        mode: WritingMode,
1278        rect: Rect<T>,
1279        container_size: Size2D<T>,
1280    ) -> LogicalRect<T> {
1281        let inline_start;
1282        let block_start;
1283        let inline;
1284        let block;
1285        if mode.is_vertical() {
1286            inline = rect.size.height;
1287            block = rect.size.width;
1288            if mode.is_vertical_lr() {
1289                block_start = rect.origin.x;
1290            } else {
1291                block_start = container_size.width - (rect.origin.x + rect.size.width);
1292            }
1293            if mode.is_inline_tb() {
1294                inline_start = rect.origin.y;
1295            } else {
1296                inline_start = container_size.height - (rect.origin.y + rect.size.height);
1297            }
1298        } else {
1299            inline = rect.size.width;
1300            block = rect.size.height;
1301            block_start = rect.origin.y;
1302            if mode.is_bidi_ltr() {
1303                inline_start = rect.origin.x;
1304            } else {
1305                inline_start = container_size.width - (rect.origin.x + rect.size.width);
1306            }
1307        }
1308        LogicalRect {
1309            start: LogicalPoint::new(mode, inline_start, block_start),
1310            size: LogicalSize::new(mode, inline, block),
1311            debug_writing_mode: DebugWritingMode::new(mode),
1312        }
1313    }
1314
1315    #[inline]
1316    pub fn inline_end(&self) -> T {
1317        self.start.i + self.size.inline
1318    }
1319
1320    #[inline]
1321    pub fn block_end(&self) -> T {
1322        self.start.b + self.size.block
1323    }
1324
1325    #[inline]
1326    pub fn to_physical(&self, mode: WritingMode, container_size: Size2D<T>) -> Rect<T> {
1327        self.debug_writing_mode.check(mode);
1328        let x;
1329        let y;
1330        let width;
1331        let height;
1332        if mode.is_vertical() {
1333            width = self.size.block;
1334            height = self.size.inline;
1335            if mode.is_vertical_lr() {
1336                x = self.start.b;
1337            } else {
1338                x = container_size.width - self.block_end();
1339            }
1340            if mode.is_inline_tb() {
1341                y = self.start.i;
1342            } else {
1343                y = container_size.height - self.inline_end();
1344            }
1345        } else {
1346            width = self.size.inline;
1347            height = self.size.block;
1348            y = self.start.b;
1349            if mode.is_bidi_ltr() {
1350                x = self.start.i;
1351            } else {
1352                x = container_size.width - self.inline_end();
1353            }
1354        }
1355        Rect {
1356            origin: Point2D::new(x, y),
1357            size: Size2D::new(width, height),
1358        }
1359    }
1360
1361    #[inline]
1362    pub fn convert(
1363        &self,
1364        mode_from: WritingMode,
1365        mode_to: WritingMode,
1366        container_size: Size2D<T>,
1367    ) -> LogicalRect<T> {
1368        if mode_from == mode_to {
1369            self.debug_writing_mode.check(mode_from);
1370            *self
1371        } else {
1372            LogicalRect::from_physical(
1373                mode_to,
1374                self.to_physical(mode_from, container_size),
1375                container_size,
1376            )
1377        }
1378    }
1379
1380    pub fn translate_by_size(&self, offset: LogicalSize<T>) -> LogicalRect<T> {
1381        LogicalRect {
1382            start: self.start + offset,
1383            ..*self
1384        }
1385    }
1386
1387    pub fn translate(&self, offset: &LogicalPoint<T>) -> LogicalRect<T> {
1388        LogicalRect {
1389            start: self.start
1390                + LogicalSize {
1391                    inline: offset.i,
1392                    block: offset.b,
1393                    debug_writing_mode: offset.debug_writing_mode,
1394                },
1395            size: self.size,
1396            debug_writing_mode: self.debug_writing_mode,
1397        }
1398    }
1399}
1400
1401impl<T: Copy + Ord + Add<T, Output = T> + Sub<T, Output = T>> LogicalRect<T> {
1402    #[inline]
1403    pub fn union(&self, other: &LogicalRect<T>) -> LogicalRect<T> {
1404        self.debug_writing_mode
1405            .check_debug(other.debug_writing_mode);
1406
1407        let inline_start = min(self.start.i, other.start.i);
1408        let block_start = min(self.start.b, other.start.b);
1409        LogicalRect {
1410            start: LogicalPoint {
1411                i: inline_start,
1412                b: block_start,
1413                debug_writing_mode: self.debug_writing_mode,
1414            },
1415            size: LogicalSize {
1416                inline: max(self.inline_end(), other.inline_end()) - inline_start,
1417                block: max(self.block_end(), other.block_end()) - block_start,
1418                debug_writing_mode: self.debug_writing_mode,
1419            },
1420            debug_writing_mode: self.debug_writing_mode,
1421        }
1422    }
1423}
1424
1425impl<T: Copy + Add<T, Output = T> + Sub<T, Output = T>> Add<LogicalMargin<T>> for LogicalRect<T> {
1426    type Output = LogicalRect<T>;
1427
1428    #[inline]
1429    fn add(self, other: LogicalMargin<T>) -> LogicalRect<T> {
1430        self.debug_writing_mode
1431            .check_debug(other.debug_writing_mode);
1432        LogicalRect {
1433            start: LogicalPoint {
1434                // Growing a rectangle on the start side means pushing its
1435                // start point on the negative direction.
1436                i: self.start.i - other.inline_start,
1437                b: self.start.b - other.block_start,
1438                debug_writing_mode: self.debug_writing_mode,
1439            },
1440            size: LogicalSize {
1441                inline: self.size.inline + other.inline_start_end(),
1442                block: self.size.block + other.block_start_end(),
1443                debug_writing_mode: self.debug_writing_mode,
1444            },
1445            debug_writing_mode: self.debug_writing_mode,
1446        }
1447    }
1448}
1449
1450impl<T: Copy + Add<T, Output = T> + Sub<T, Output = T>> Sub<LogicalMargin<T>> for LogicalRect<T> {
1451    type Output = LogicalRect<T>;
1452
1453    #[inline]
1454    fn sub(self, other: LogicalMargin<T>) -> LogicalRect<T> {
1455        self.debug_writing_mode
1456            .check_debug(other.debug_writing_mode);
1457        LogicalRect {
1458            start: LogicalPoint {
1459                // Shrinking a rectangle on the start side means pushing its
1460                // start point on the positive direction.
1461                i: self.start.i + other.inline_start,
1462                b: self.start.b + other.block_start,
1463                debug_writing_mode: self.debug_writing_mode,
1464            },
1465            size: LogicalSize {
1466                inline: self.size.inline - other.inline_start_end(),
1467                block: self.size.block - other.block_start_end(),
1468                debug_writing_mode: self.debug_writing_mode,
1469            },
1470            debug_writing_mode: self.debug_writing_mode,
1471        }
1472    }
1473}
1474
1475#[derive(Clone, Copy, Debug, PartialEq)]
1476#[repr(u8)]
1477pub enum LogicalAxis {
1478    Block = 0,
1479    Inline,
1480}
1481
1482impl LogicalAxis {
1483    #[inline]
1484    pub fn to_physical(self, wm: WritingMode) -> PhysicalAxis {
1485        if wm.is_horizontal() == (self == Self::Inline) {
1486            PhysicalAxis::Horizontal
1487        } else {
1488            PhysicalAxis::Vertical
1489        }
1490    }
1491}
1492
1493#[derive(Clone, Copy, Debug, PartialEq)]
1494#[repr(u8)]
1495pub enum LogicalSide {
1496    BlockStart = 0,
1497    BlockEnd,
1498    InlineStart,
1499    InlineEnd,
1500}
1501
1502impl LogicalSide {
1503    fn is_block(self) -> bool {
1504        matches!(self, Self::BlockStart | Self::BlockEnd)
1505    }
1506
1507    #[inline]
1508    pub fn to_physical(self, wm: WritingMode) -> PhysicalSide {
1509        // Block mapping depends only on vertical+vertical-lr
1510        static BLOCK_MAPPING: [[PhysicalSide; 2]; 4] = [
1511            [PhysicalSide::Top, PhysicalSide::Bottom], // horizontal-tb
1512            [PhysicalSide::Right, PhysicalSide::Left], // vertical-rl
1513            [PhysicalSide::Bottom, PhysicalSide::Top], // (horizontal-bt)
1514            [PhysicalSide::Left, PhysicalSide::Right], // vertical-lr
1515        ];
1516
1517        if self.is_block() {
1518            let vertical = wm.is_vertical();
1519            let lr = wm.is_vertical_lr();
1520            let index = (vertical as usize) | ((lr as usize) << 1);
1521            return BLOCK_MAPPING[index][self as usize];
1522        }
1523
1524        // start = 0, end = 1
1525        let edge = self as usize - 2;
1526        // Inline axis sides depend on all three of writing-mode, text-orientation and direction,
1527        // which are encoded in the VERTICAL, INLINE_REVERSED, VERTICAL_LR and LINE_INVERTED bits.
1528        //
1529        //   bit 0 = the VERTICAL value
1530        //   bit 1 = the INLINE_REVERSED value
1531        //   bit 2 = the VERTICAL_LR value
1532        //   bit 3 = the LINE_INVERTED value
1533        //
1534        // Note that not all of these combinations can actually be specified via CSS: there is no
1535        // horizontal-bt writing-mode, and no text-orientation value that produces "inverted"
1536        // text. (The former 'sideways-left' value, no longer in the spec, would have produced
1537        // this in vertical-rl mode.)
1538        static INLINE_MAPPING: [[PhysicalSide; 2]; 16] = [
1539            [PhysicalSide::Left, PhysicalSide::Right], // horizontal-tb               ltr
1540            [PhysicalSide::Top, PhysicalSide::Bottom], // vertical-rl                 ltr
1541            [PhysicalSide::Right, PhysicalSide::Left], // horizontal-tb               rtl
1542            [PhysicalSide::Bottom, PhysicalSide::Top], // vertical-rl                 rtl
1543            [PhysicalSide::Right, PhysicalSide::Left], // (horizontal-bt)  (inverted) ltr
1544            [PhysicalSide::Top, PhysicalSide::Bottom], // sideways-lr                 rtl
1545            [PhysicalSide::Left, PhysicalSide::Right], // (horizontal-bt)  (inverted) rtl
1546            [PhysicalSide::Bottom, PhysicalSide::Top], // sideways-lr                 ltr
1547            [PhysicalSide::Left, PhysicalSide::Right], // horizontal-tb    (inverted) rtl
1548            [PhysicalSide::Top, PhysicalSide::Bottom], // vertical-rl      (inverted) rtl
1549            [PhysicalSide::Right, PhysicalSide::Left], // horizontal-tb    (inverted) ltr
1550            [PhysicalSide::Bottom, PhysicalSide::Top], // vertical-rl      (inverted) ltr
1551            [PhysicalSide::Left, PhysicalSide::Right], // (horizontal-bt)             ltr
1552            [PhysicalSide::Top, PhysicalSide::Bottom], // vertical-lr                 ltr
1553            [PhysicalSide::Right, PhysicalSide::Left], // (horizontal-bt)             rtl
1554            [PhysicalSide::Bottom, PhysicalSide::Top], // vertical-lr                 rtl
1555        ];
1556
1557        debug_assert!(
1558            WritingMode::VERTICAL.bits() == 0x01
1559                && WritingMode::INLINE_REVERSED.bits() == 0x02
1560                && WritingMode::VERTICAL_LR.bits() == 0x04
1561                && WritingMode::LINE_INVERTED.bits() == 0x08
1562        );
1563        let index = (wm.bits() & 0xF) as usize;
1564        INLINE_MAPPING[index][edge]
1565    }
1566}
1567
1568#[derive(Clone, Copy, Debug, PartialEq)]
1569#[repr(u8)]
1570pub enum LogicalCorner {
1571    StartStart = 0,
1572    StartEnd,
1573    EndStart,
1574    EndEnd,
1575}
1576
1577impl LogicalCorner {
1578    #[inline]
1579    pub fn to_physical(self, wm: WritingMode) -> PhysicalCorner {
1580        static CORNER_TO_SIDES: [[LogicalSide; 2]; 4] = [
1581            [LogicalSide::BlockStart, LogicalSide::InlineStart],
1582            [LogicalSide::BlockStart, LogicalSide::InlineEnd],
1583            [LogicalSide::BlockEnd, LogicalSide::InlineStart],
1584            [LogicalSide::BlockEnd, LogicalSide::InlineEnd],
1585        ];
1586
1587        let [block, inline] = CORNER_TO_SIDES[self as usize];
1588        let block = block.to_physical(wm);
1589        let inline = inline.to_physical(wm);
1590        PhysicalCorner::from_sides(block, inline)
1591    }
1592}
1593
1594#[derive(Clone, Copy, Debug, PartialEq)]
1595#[repr(u8)]
1596pub enum PhysicalAxis {
1597    Vertical = 0,
1598    Horizontal,
1599}
1600
1601#[derive(Clone, Copy, Debug, PartialEq)]
1602#[repr(u8)]
1603pub enum PhysicalSide {
1604    Top = 0,
1605    Right,
1606    Bottom,
1607    Left,
1608}
1609
1610impl PhysicalSide {
1611    /// Returns whether one physical side is parallel to another.
1612    pub fn parallel_to(self, other: Self) -> bool {
1613        !self.orthogonal_to(other)
1614    }
1615
1616    /// Returns whether one physical side is orthogonal to another.
1617    pub fn orthogonal_to(self, other: Self) -> bool {
1618        matches!(self, Self::Top | Self::Bottom) != matches!(other, Self::Top | Self::Bottom)
1619    }
1620
1621    /// Returns the opposite side.
1622    pub fn opposite_side(self) -> Self {
1623        match self {
1624            Self::Top => Self::Bottom,
1625            Self::Right => Self::Left,
1626            Self::Bottom => Self::Top,
1627            Self::Left => Self::Right,
1628        }
1629    }
1630}
1631
1632#[derive(Clone, Copy, Debug, PartialEq)]
1633#[repr(u8)]
1634pub enum PhysicalCorner {
1635    TopLeft = 0,
1636    TopRight,
1637    BottomRight,
1638    BottomLeft,
1639}
1640
1641impl PhysicalCorner {
1642    fn from_sides(a: PhysicalSide, b: PhysicalSide) -> Self {
1643        debug_assert!(a.orthogonal_to(b), "Sides should be orthogonal");
1644        // Only some of these are possible, since we expect only orthogonal values. If the two
1645        // sides were to be parallel, we fall back to returning TopLeft.
1646        const IMPOSSIBLE: PhysicalCorner = PhysicalCorner::TopLeft;
1647        static SIDES_TO_CORNER: [[PhysicalCorner; 4]; 4] = [
1648            [
1649                IMPOSSIBLE,
1650                PhysicalCorner::TopRight,
1651                IMPOSSIBLE,
1652                PhysicalCorner::TopLeft,
1653            ],
1654            [
1655                PhysicalCorner::TopRight,
1656                IMPOSSIBLE,
1657                PhysicalCorner::BottomRight,
1658                IMPOSSIBLE,
1659            ],
1660            [
1661                IMPOSSIBLE,
1662                PhysicalCorner::BottomRight,
1663                IMPOSSIBLE,
1664                PhysicalCorner::BottomLeft,
1665            ],
1666            [
1667                PhysicalCorner::TopLeft,
1668                IMPOSSIBLE,
1669                PhysicalCorner::BottomLeft,
1670                IMPOSSIBLE,
1671            ],
1672        ];
1673        SIDES_TO_CORNER[a as usize][b as usize]
1674    }
1675}