Skip to main content

gpui_base/
layout_direction.rs

1//! The application's layout direction.
2//!
3//! Right-to-left support is one global setting, not a switch on each
4//! component: [`LayoutDirection::global`] says whether the interface reads
5//! left to right or right to left, and every component that has a
6//! horizontal sense — arrow-key navigation, which side a submenu opens on,
7//! logical paddings and borders — reads it from there.
8//!
9//! `gpui_base::init` derives the direction from the system's preferred
10//! languages (Arabic, Hebrew, Persian, Urdu, … read right to left). An
11//! application that follows its own language setting overrides it with
12//! [`LayoutDirection::set_global`], which redraws every window.
13//!
14//! Layout written with the logical helpers of [`LogicalStyledExt`]
15//! (`ps`/`pe`, `ms`/`me`, `border_s`/`border_e`, `rounded_s`/`rounded_e`,
16//! `inset_s`/`inset_e`, `flex_row_dir`, `justify_flex_start`/`justify_flex_end`)
17//! mirrors with it; physical helpers (`pl`, `left`, `flex_row`, `justify_start`,
18//! …) keep their physical meaning.
19
20use gpui::{AbsoluteLength, App, DefiniteLength, Global, JustifyContent, Length, Styled};
21
22/// The horizontal direction an interface is laid out and navigated in.
23#[derive(Clone, Copy, Debug, Default, Eq, PartialEq, Hash)]
24pub enum LayoutDirection {
25    /// Left to right, the default.
26    #[default]
27    Ltr,
28    /// Right to left, for Arabic, Hebrew, Persian, Urdu and similar scripts.
29    Rtl,
30}
31
32#[derive(Clone, Copy)]
33struct GlobalLayoutDirection(LayoutDirection);
34
35impl Global for GlobalLayoutDirection {}
36
37impl LayoutDirection {
38    /// Whether this is [`LayoutDirection::Rtl`].
39    pub fn is_rtl(self) -> bool {
40        self == Self::Rtl
41    }
42
43    /// The direction the application is laid out in.
44    pub fn global(cx: &App) -> Self {
45        cx.try_global::<GlobalLayoutDirection>()
46            .map(|direction| direction.0)
47            .unwrap_or_default()
48    }
49
50    /// Sets the direction for the whole application and redraws its windows.
51    pub fn set_global(self, cx: &mut App) {
52        if cx.try_global::<GlobalLayoutDirection>().map(|d| d.0) == Some(self) {
53            return;
54        }
55        cx.set_global(GlobalLayoutDirection(self));
56        cx.refresh_windows();
57    }
58
59    /// The direction of a BCP 47 locale such as `ar-EG`, `he` or `en_US`.
60    pub fn from_locale(locale: &str) -> Self {
61        const RTL: [&str; 12] = [
62            "ar", "ckb", "dv", "fa", "he", "iw", "ks", "ps", "sd", "ug", "ur", "yi",
63        ];
64        let language = locale.split(['-', '_', '.']).next().unwrap_or_default();
65        if RTL.iter().any(|rtl| language.eq_ignore_ascii_case(rtl)) {
66            Self::Rtl
67        } else {
68            Self::Ltr
69        }
70    }
71
72    /// The direction of the system's most preferred language.
73    pub fn system() -> Self {
74        sys_locale::get_locale()
75            .map(|locale| Self::from_locale(&locale))
76            .unwrap_or_default()
77    }
78
79    /// Maps a logical edge to the physical one: `start` is left in LTR and
80    /// right in RTL.
81    pub(crate) fn start_is_left(self) -> bool {
82        self == Self::Ltr
83    }
84}
85
86/// Applies the system direction during `gpui_base::init`, unless the
87/// application already chose one or GPUI's test scheduler is running.
88pub(crate) fn init(cx: &mut App) {
89    if cx.has_global::<GlobalLayoutDirection>() {
90        return;
91    }
92    let is_test = cx
93        .background_executor()
94        .scheduler_executor()
95        .scheduler()
96        .as_test()
97        .is_some();
98    let direction = if is_test {
99        LayoutDirection::Ltr
100    } else {
101        LayoutDirection::system()
102    };
103    cx.set_global(GlobalLayoutDirection(direction));
104}
105
106macro_rules! logical_edge {
107    ($(#[$doc:meta])* $name:ident, $start:ident, $end:ident, $len:ty) => {
108        $(#[$doc])*
109        fn $name(self, length: impl Into<$len> + Clone, cx: &App) -> Self {
110            if LayoutDirection::global(cx).start_is_left() {
111                self.$start(length)
112            } else {
113                self.$end(length)
114            }
115        }
116    };
117}
118
119/// Styling helpers that follow [`LayoutDirection::global`]: `s` (start) is
120/// the left edge in LTR and the right edge in RTL, `e` (end) the opposite.
121pub trait LogicalStyledExt: Styled + Sized {
122    logical_edge!(
123        /// Padding on the start edge.
124        ps,
125        pl,
126        pr,
127        DefiniteLength
128    );
129    logical_edge!(
130        /// Padding on the end edge.
131        pe,
132        pr,
133        pl,
134        DefiniteLength
135    );
136    logical_edge!(
137        /// Margin on the start edge.
138        ms,
139        ml,
140        mr,
141        Length
142    );
143    logical_edge!(
144        /// Margin on the end edge.
145        me,
146        mr,
147        ml,
148        Length
149    );
150    logical_edge!(
151        /// Inset from the start edge of the positioned ancestor.
152        inset_s,
153        left,
154        right,
155        Length
156    );
157    logical_edge!(
158        /// Inset from the end edge of the positioned ancestor.
159        inset_e,
160        right,
161        left,
162        Length
163    );
164
165    /// Border width on the start edge.
166    fn border_s(mut self, width: impl Into<AbsoluteLength>, cx: &App) -> Self {
167        let width = Some(width.into());
168        let widths = &mut self.style().border_widths;
169        if LayoutDirection::global(cx).start_is_left() {
170            widths.left = width;
171        } else {
172            widths.right = width;
173        }
174        self
175    }
176
177    /// Border width on the end edge.
178    fn border_e(mut self, width: impl Into<AbsoluteLength>, cx: &App) -> Self {
179        let width = Some(width.into());
180        let widths = &mut self.style().border_widths;
181        if LayoutDirection::global(cx).start_is_left() {
182            widths.right = width;
183        } else {
184            widths.left = width;
185        }
186        self
187    }
188
189    /// Corner radius of both start corners.
190    fn rounded_s(self, radius: impl Into<AbsoluteLength> + Clone, cx: &App) -> Self {
191        if LayoutDirection::global(cx).start_is_left() {
192            self.rounded_l(radius)
193        } else {
194            self.rounded_r(radius)
195        }
196    }
197
198    /// Corner radius of both end corners.
199    fn rounded_e(self, radius: impl Into<AbsoluteLength> + Clone, cx: &App) -> Self {
200        if LayoutDirection::global(cx).start_is_left() {
201            self.rounded_r(radius)
202        } else {
203            self.rounded_l(radius)
204        }
205    }
206
207    /// A horizontal flex row whose first child sits on the start edge:
208    /// `flex_row` in LTR, `flex_row_reverse` in RTL.
209    fn flex_row_dir(self, cx: &App) -> Self {
210        if LayoutDirection::global(cx).is_rtl() {
211            self.flex().flex_row_reverse()
212        } else {
213            self.flex().flex_row()
214        }
215    }
216
217    /// Packs a row's children against the edge its first child sits on — the
218    /// start edge of a [`flex_row_dir`](Self::flex_row_dir) row.
219    ///
220    /// `justify_start` is the physical left edge even in a reversed row, so it
221    /// does not follow the layout direction; this is CSS `flex-start`.
222    fn justify_flex_start(mut self) -> Self {
223        self.style().justify_content = Some(JustifyContent::FlexStart);
224        self
225    }
226
227    /// Packs a row's children against the edge its last child sits on — the
228    /// end edge of a [`flex_row_dir`](Self::flex_row_dir) row. This is CSS
229    /// `flex-end`; `justify_end` stays on the physical right edge.
230    fn justify_flex_end(mut self) -> Self {
231        self.style().justify_content = Some(JustifyContent::FlexEnd);
232        self
233    }
234
235    /// Aligns text to the start edge: `text_left` in LTR, `text_right` in RTL.
236    fn text_start(self, cx: &App) -> Self {
237        if LayoutDirection::global(cx).start_is_left() {
238            self.text_left()
239        } else {
240            self.text_right()
241        }
242    }
243
244    /// Aligns text to the end edge: `text_right` in LTR, `text_left` in RTL.
245    fn text_end(self, cx: &App) -> Self {
246        if LayoutDirection::global(cx).start_is_left() {
247            self.text_right()
248        } else {
249            self.text_left()
250        }
251    }
252}
253
254impl<T: Styled> LogicalStyledExt for T {}
255
256#[cfg(test)]
257mod tests {
258    use super::*;
259    use gpui::{TestAppContext, div, px};
260
261    #[test]
262    fn locale_direction() {
263        for rtl in ["ar", "ar-EG", "he_IL", "fa", "ur-PK", "HE", "yi.UTF-8"] {
264            assert_eq!(
265                LayoutDirection::from_locale(rtl),
266                LayoutDirection::Rtl,
267                "{rtl}"
268            );
269        }
270        for ltr in ["en", "en-US", "zh-CN", "", "C", "arn"] {
271            assert_eq!(
272                LayoutDirection::from_locale(ltr),
273                LayoutDirection::Ltr,
274                "{ltr}"
275            );
276        }
277    }
278
279    #[gpui::test]
280    fn logical_edges_follow_global_direction(cx: &mut TestAppContext) {
281        cx.update(|cx| {
282            crate::init(cx);
283            assert_eq!(LayoutDirection::global(cx), LayoutDirection::Ltr);
284
285            let mut ltr = div().ps(px(4.), cx).me(px(8.), cx).border_s(px(1.), cx);
286            let style = ltr.style();
287            assert_eq!(style.padding.left, Some(px(4.).into()));
288            assert_eq!(style.margin.right, Some(px(8.).into()));
289            assert_eq!(style.border_widths.left, Some(px(1.).into()));
290
291            LayoutDirection::Rtl.set_global(cx);
292            let mut rtl = div().ps(px(4.), cx).me(px(8.), cx).border_s(px(1.), cx);
293            let style = rtl.style();
294            assert_eq!(style.padding.right, Some(px(4.).into()));
295            assert_eq!(style.padding.left, None);
296            assert_eq!(style.margin.left, Some(px(8.).into()));
297            assert_eq!(style.border_widths.right, Some(px(1.).into()));
298        });
299    }
300
301    #[gpui::test]
302    fn flex_justification_follows_row_direction(cx: &mut TestAppContext) {
303        use gpui::{
304            Context, InteractiveElement as _, IntoElement, ParentElement as _, Render, Window,
305        };
306
307        struct Row;
308        impl Render for Row {
309            fn render(&mut self, _: &mut Window, cx: &mut Context<Self>) -> impl IntoElement {
310                div()
311                    .flex_row_dir(cx)
312                    .w(px(100.))
313                    .justify_flex_end()
314                    .child(div().size(px(10.)).debug_selector(|| "item".into()))
315            }
316        }
317
318        cx.update(crate::init);
319        for (direction, expected_left) in [
320            (LayoutDirection::Ltr, px(90.)),
321            (LayoutDirection::Rtl, px(0.)),
322        ] {
323            cx.update(|cx| direction.set_global(cx));
324            let (_, window) = cx.add_window_view(|_, _| Row);
325            window.update(|window, cx| window.draw(cx).clear(cx));
326            let item = window.debug_bounds("item").expect("item not rendered");
327            assert_eq!(item.left(), expected_left, "{direction:?}");
328        }
329    }
330
331    #[gpui::test]
332    fn text_alignment_follows_global_direction(cx: &mut TestAppContext) {
333        use gpui::TextAlign;
334        cx.update(|cx| {
335            crate::init(cx);
336            assert_eq!(
337                div().text_start(cx).style().text.text_align,
338                Some(TextAlign::Left)
339            );
340            assert_eq!(
341                div().text_end(cx).style().text.text_align,
342                Some(TextAlign::Right)
343            );
344
345            LayoutDirection::Rtl.set_global(cx);
346            assert_eq!(
347                div().text_start(cx).style().text.text_align,
348                Some(TextAlign::Right)
349            );
350            assert_eq!(
351                div().text_end(cx).style().text.text_align,
352                Some(TextAlign::Left)
353            );
354        });
355    }
356}