Skip to main content

parley/layout/
alignment.rs

1// Copyright 2024 the Parley Authors
2// SPDX-License-Identifier: Apache-2.0 OR MIT
3
4use super::BreakReason;
5use crate::data::LayoutData;
6use crate::style::Brush;
7
8/// Alignment of a layout.
9#[derive(Copy, Clone, Default, PartialEq, Eq, Debug)]
10#[repr(u8)]
11pub enum Alignment {
12    /// This is [`Alignment::Left`] for LTR text and [`Alignment::Right`] for RTL text.
13    #[default]
14    Start,
15    /// This is [`Alignment::Right`] for LTR text and [`Alignment::Left`] for RTL text.
16    End,
17    /// Align content to the left edge.
18    ///
19    /// For alignment that should be aware of text direction, use [`Alignment::Start`] or
20    /// [`Alignment::End`] instead.
21    Left,
22    /// Align each line centered within the container.
23    Center,
24    /// Align content to the right edge.
25    ///
26    /// For alignment that should be aware of text direction, use [`Alignment::Start`] or
27    /// [`Alignment::End`] instead.
28    Right,
29    /// Justify each line by spacing out content.
30    ///
31    /// The last line of a paragraph is start-aligned instead, unless
32    /// [`AlignmentOptions::last_line_alignment`] is set.
33    Justify,
34}
35
36/// Additional options to fine tune alignment
37#[derive(Debug, Clone, Copy)]
38pub struct AlignmentOptions {
39    /// If set to `true`, "end" and "center" alignment will apply even if the line contents are
40    /// wider than the alignment width. If it is set to `false`, all overflowing lines will be
41    /// [`Alignment::Start`] aligned.
42    pub align_when_overflowing: bool,
43    /// The alignment of the last line of each paragraph: the last line of the layout and every
44    /// line that ends in an explicit line break. This corresponds to the CSS `text-align-last`
45    /// property.
46    ///
47    /// If set to `None`, those lines use the alignment passed to [`Layout::align`], except that
48    /// [`Alignment::Justify`] falls back to [`Alignment::Start`]. This is the behavior of
49    /// `text-align-last: auto`.
50    ///
51    /// [`Layout::align`]: crate::Layout::align
52    pub last_line_alignment: Option<Alignment>,
53}
54
55#[expect(
56    clippy::derivable_impls,
57    reason = "Make default values explicit rather than relying on the implicit default value of bool"
58)]
59impl Default for AlignmentOptions {
60    fn default() -> Self {
61        Self {
62            align_when_overflowing: false,
63            last_line_alignment: None,
64        }
65    }
66}
67
68/// Align the layout.
69pub(crate) fn align<B: Brush>(
70    layout: &mut LayoutData<B>,
71    alignment: Alignment,
72    options: AlignmentOptions,
73) {
74    layout.alignment = Some(alignment);
75
76    let is_rtl = layout.base_level.is_rtl();
77
78    // Apply alignment to line items
79    for line in &mut layout.lines {
80        line.justification.amount_per_opportunity = 0.;
81
82        let indent = line.metrics.indent;
83
84        if is_rtl {
85            // In RTL text, trailing whitespace is on the left. As we hang that whitespace, offset
86            // the line to the left. Note: indent is not subtracted here because `free_space` below
87            // already accounts for it.
88            line.metrics.offset = -line.metrics.hanging_advance;
89        } else {
90            line.metrics.offset = indent;
91        }
92
93        // Compute free space.
94        let line_width = line.metrics.inline_max_coord - line.metrics.inline_min_coord;
95        let free_space = line_width - indent - line.metrics.advance + line.metrics.hanging_advance;
96
97        if !options.align_when_overflowing && free_space <= 0.0 {
98            if is_rtl {
99                // In RTL text, right-align on overflow.
100                line.metrics.offset += free_space;
101            }
102            continue;
103        }
104
105        let is_last_line = matches!(line.break_reason, BreakReason::None | BreakReason::Explicit);
106        let line_alignment = if !is_last_line {
107            alignment
108        } else if let Some(last_line_alignment) = options.last_line_alignment {
109            last_line_alignment
110        } else if alignment == Alignment::Justify {
111            Alignment::Start
112        } else {
113            alignment
114        };
115
116        match (line_alignment, is_rtl) {
117            (Alignment::Left, _) | (Alignment::Start, false) | (Alignment::End, true) => {
118                // Do nothing
119            }
120            (Alignment::Right, _) | (Alignment::Start, true) | (Alignment::End, false) => {
121                line.metrics.offset += free_space;
122            }
123            (Alignment::Center, _) => {
124                line.metrics.offset += free_space * 0.5;
125            }
126            (Alignment::Justify, _) => {
127                // Justified alignment doesn't have any effect if free_space is negative or zero
128                if free_space <= 0.0 {
129                    continue;
130                }
131
132                // Justified alignment doesn't apply if there are no whitespace gaps to adjust. In
133                // that case, start-align, i.e., left-align for LTR text and right-align for RTL
134                // text.
135                if line.num_justification_opportunities == 0 {
136                    if is_rtl {
137                        line.metrics.offset += free_space;
138                    }
139                    continue;
140                }
141
142                line.justification.amount_per_opportunity =
143                    free_space / line.num_justification_opportunities as f32;
144            }
145        }
146    }
147}