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