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, pl, pr, DefiniteLength
125    );
126    logical_edge!(
127        /// Padding on the end edge.
128        pe, pr, pl, DefiniteLength
129    );
130    logical_edge!(
131        /// Margin on the start edge.
132        ms, ml, mr, Length
133    );
134    logical_edge!(
135        /// Margin on the end edge.
136        me, mr, ml, Length
137    );
138    logical_edge!(
139        /// Inset from the start edge of the positioned ancestor.
140        inset_s, left, right, Length
141    );
142    logical_edge!(
143        /// Inset from the end edge of the positioned ancestor.
144        inset_e, right, left, Length
145    );
146
147    /// Border width on the start edge.
148    fn border_s(mut self, width: impl Into<AbsoluteLength>, cx: &App) -> Self {
149        let width = Some(width.into());
150        let widths = &mut self.style().border_widths;
151        if LayoutDirection::global(cx).start_is_left() {
152            widths.left = width;
153        } else {
154            widths.right = width;
155        }
156        self
157    }
158
159    /// Border width on the end edge.
160    fn border_e(mut self, width: impl Into<AbsoluteLength>, cx: &App) -> Self {
161        let width = Some(width.into());
162        let widths = &mut self.style().border_widths;
163        if LayoutDirection::global(cx).start_is_left() {
164            widths.right = width;
165        } else {
166            widths.left = width;
167        }
168        self
169    }
170
171    /// Corner radius of both start corners.
172    fn rounded_s(self, radius: impl Into<AbsoluteLength> + Clone, cx: &App) -> Self {
173        if LayoutDirection::global(cx).start_is_left() {
174            self.rounded_l(radius)
175        } else {
176            self.rounded_r(radius)
177        }
178    }
179
180    /// Corner radius of both end corners.
181    fn rounded_e(self, radius: impl Into<AbsoluteLength> + Clone, cx: &App) -> Self {
182        if LayoutDirection::global(cx).start_is_left() {
183            self.rounded_r(radius)
184        } else {
185            self.rounded_l(radius)
186        }
187    }
188
189    /// A horizontal flex row whose first child sits on the start edge:
190    /// `flex_row` in LTR, `flex_row_reverse` in RTL.
191    fn flex_row_dir(self, cx: &App) -> Self {
192        if LayoutDirection::global(cx).is_rtl() {
193            self.flex().flex_row_reverse()
194        } else {
195            self.flex().flex_row()
196        }
197    }
198
199    /// Packs a row's children against the edge its first child sits on — the
200    /// start edge of a [`flex_row_dir`](Self::flex_row_dir) row.
201    ///
202    /// `justify_start` is the physical left edge even in a reversed row, so it
203    /// does not follow the layout direction; this is CSS `flex-start`.
204    fn justify_flex_start(mut self) -> Self {
205        self.style().justify_content = Some(JustifyContent::FlexStart);
206        self
207    }
208
209    /// Packs a row's children against the edge its last child sits on — the
210    /// end edge of a [`flex_row_dir`](Self::flex_row_dir) row. This is CSS
211    /// `flex-end`; `justify_end` stays on the physical right edge.
212    fn justify_flex_end(mut self) -> Self {
213        self.style().justify_content = Some(JustifyContent::FlexEnd);
214        self
215    }
216
217    /// Aligns text to the start edge: `text_left` in LTR, `text_right` in RTL.
218    fn text_start(self, cx: &App) -> Self {
219        if LayoutDirection::global(cx).start_is_left() {
220            self.text_left()
221        } else {
222            self.text_right()
223        }
224    }
225
226    /// Aligns text to the end edge: `text_right` in LTR, `text_left` in RTL.
227    fn text_end(self, cx: &App) -> Self {
228        if LayoutDirection::global(cx).start_is_left() {
229            self.text_right()
230        } else {
231            self.text_left()
232        }
233    }
234}
235
236impl<T: Styled> LogicalStyledExt for T {}
237
238#[cfg(test)]
239mod tests {
240    use super::*;
241    use gpui::{TestAppContext, div, px};
242
243    #[test]
244    fn locale_direction() {
245        for rtl in ["ar", "ar-EG", "he_IL", "fa", "ur-PK", "HE", "yi.UTF-8"] {
246            assert_eq!(
247                LayoutDirection::from_locale(rtl),
248                LayoutDirection::Rtl,
249                "{rtl}"
250            );
251        }
252        for ltr in ["en", "en-US", "zh-CN", "", "C", "arn"] {
253            assert_eq!(
254                LayoutDirection::from_locale(ltr),
255                LayoutDirection::Ltr,
256                "{ltr}"
257            );
258        }
259    }
260
261    #[gpui::test]
262    fn logical_edges_follow_global_direction(cx: &mut TestAppContext) {
263        cx.update(|cx| {
264            crate::init(cx);
265            assert_eq!(LayoutDirection::global(cx), LayoutDirection::Ltr);
266
267            let mut ltr = div().ps(px(4.), cx).me(px(8.), cx).border_s(px(1.), cx);
268            let style = ltr.style();
269            assert_eq!(style.padding.left, Some(px(4.).into()));
270            assert_eq!(style.margin.right, Some(px(8.).into()));
271            assert_eq!(style.border_widths.left, Some(px(1.).into()));
272
273            LayoutDirection::Rtl.set_global(cx);
274            let mut rtl = div().ps(px(4.), cx).me(px(8.), cx).border_s(px(1.), cx);
275            let style = rtl.style();
276            assert_eq!(style.padding.right, Some(px(4.).into()));
277            assert_eq!(style.padding.left, None);
278            assert_eq!(style.margin.left, Some(px(8.).into()));
279            assert_eq!(style.border_widths.right, Some(px(1.).into()));
280        });
281    }
282
283    #[gpui::test]
284    fn flex_justification_follows_row_direction(cx: &mut TestAppContext) {
285        use gpui::{
286            Context, InteractiveElement as _, IntoElement, ParentElement as _, Render, Window,
287        };
288
289        struct Row;
290        impl Render for Row {
291            fn render(&mut self, _: &mut Window, cx: &mut Context<Self>) -> impl IntoElement {
292                div()
293                    .flex_row_dir(cx)
294                    .w(px(100.))
295                    .justify_flex_end()
296                    .child(div().size(px(10.)).debug_selector(|| "item".into()))
297            }
298        }
299
300        cx.update(crate::init);
301        for (direction, expected_left) in [
302            (LayoutDirection::Ltr, px(90.)),
303            (LayoutDirection::Rtl, px(0.)),
304        ] {
305            cx.update(|cx| direction.set_global(cx));
306            let (_, window) = cx.add_window_view(|_, _| Row);
307            window.update(|window, cx| window.draw(cx).clear(cx));
308            let item = window.debug_bounds("item").expect("item not rendered");
309            assert_eq!(item.left(), expected_left, "{direction:?}");
310        }
311    }
312
313    #[gpui::test]
314    fn text_alignment_follows_global_direction(cx: &mut TestAppContext) {
315        use gpui::TextAlign;
316        cx.update(|cx| {
317            crate::init(cx);
318            assert_eq!(
319                div().text_start(cx).style().text.text_align,
320                Some(TextAlign::Left)
321            );
322            assert_eq!(
323                div().text_end(cx).style().text.text_align,
324                Some(TextAlign::Right)
325            );
326
327            LayoutDirection::Rtl.set_global(cx);
328            assert_eq!(
329                div().text_start(cx).style().text.text_align,
330                Some(TextAlign::Right)
331            );
332            assert_eq!(
333                div().text_end(cx).style().text.text_align,
334                Some(TextAlign::Left)
335            );
336        });
337    }
338}