Skip to main content

nativeview_engine/editing/
bidi.rs

1//! Single-line HarfBuzz + Unicode BiDi text layout, grapheme-safe visual hit-testing,
2//! logical-to-visual caret X mapping, visual arrow navigation, and disjoint multi-run
3//! selection geometry powered by `cosmic-text`.
4
5
6
7
8
9
10use crate::editing::grapheme::{
11    clamp_grapheme_boundary, grapheme_boundaries, next_grapheme_boundary, prev_grapheme_boundary,
12};
13
14/// One UAX #29 extended grapheme cluster positioned in visual left-to-right line coordinates.
15#[derive(Debug, Clone, Copy, PartialEq)]
16pub struct VisualGraphemeCluster {
17    /// Logical UTF-8 start byte offset in the source string (always a grapheme boundary).
18    pub byte_start: usize,
19    /// Logical UTF-8 end byte offset in the source string (always a grapheme boundary).
20    pub byte_end: usize,
21    /// Visual left edge in logical pixels relative to line origin.
22    pub x_left: f32,
23    /// Visual right edge in logical pixels relative to line origin.
24    pub x_right: f32,
25    /// `true` when this cluster belongs to an odd BiDi embedding level (RTL run).
26    pub is_rtl: bool,
27}
28
29/// Shaped single-line BiDi layout containing visual left-to-right grapheme cluster geometry.
30#[derive(Debug, Clone, PartialEq)]
31pub struct ShapedLineLayout {
32    /// `true` when the resolved Unicode BiDi paragraph direction is RTL.
33    pub rtl: bool,
34    /// Total visual advance width of the line in logical pixels (including trailing spaces).
35    pub line_width: f32,
36    /// Grapheme clusters ordered left-to-right by visual X coordinate.
37    pub clusters: Vec<VisualGraphemeCluster>,
38}
39
40impl ShapedLineLayout {
41    /// Returns `true` if the paragraph or any shaped cluster is RTL.
42    #[inline]
43    pub fn has_rtl(&self) -> bool {
44        self.rtl || self.clusters.iter().any(|c| c.is_rtl)
45    }
46
47    /// Maps a logical UTF-8 byte offset (clamped to a UAX #29 grapheme boundary) to its visual
48    /// caret X offset in logical pixels relative to line origin.
49    ///
50    /// At LTR/RTL run boundaries, paragraph-direction-matching clusters take precedence so caret
51    /// motion remains monotonic within every run.
52    pub fn caret_x_at(&self, text: &str, byte_index: usize) -> f32 {
53        if text.is_empty() || self.clusters.is_empty() {
54            return 0.0;
55        }
56        let idx = clamp_grapheme_boundary(text, byte_index);
57
58        let mut start_match: Option<&VisualGraphemeCluster> = None;
59        let mut end_match: Option<&VisualGraphemeCluster> = None;
60        for c in &self.clusters {
61            if c.byte_start == idx && start_match.is_none() {
62                start_match = Some(c);
63            }
64            if c.byte_end == idx && end_match.is_none() {
65                end_match = Some(c);
66            }
67        }
68
69        let leading_edge = |c: &VisualGraphemeCluster| if c.is_rtl { c.x_right } else { c.x_left };
70        let trailing_edge = |c: &VisualGraphemeCluster| if c.is_rtl { c.x_left } else { c.x_right };
71
72        match (end_match, start_match) {
73            (Some(end_c), Some(start_c)) => {
74                if end_c.is_rtl == self.rtl && start_c.is_rtl != self.rtl {
75                    trailing_edge(end_c)
76                } else if start_c.is_rtl == self.rtl {
77                    leading_edge(start_c)
78                } else {
79                    trailing_edge(end_c)
80                }
81            }
82            (None, Some(start_c)) => leading_edge(start_c),
83            (Some(end_c), None) => trailing_edge(end_c),
84            (None, None) => {
85                if idx == 0 {
86                    if self.rtl { self.line_width } else { 0.0 }
87                } else if self.rtl {
88                    0.0
89                } else {
90                    self.line_width
91                }
92            }
93        }
94    }
95
96    /// Hit-tests a visual `local_x` (logical pixels from line origin) into the closest valid
97    /// UAX #29 logical grapheme byte boundary.
98    pub fn hit_test_x(&self, text: &str, local_x: f32) -> usize {
99        if text.is_empty() || !local_x.is_finite() || self.clusters.is_empty() {
100            return 0;
101        }
102        let first = &self.clusters[0];
103        if local_x <= first.x_left {
104            return if first.is_rtl {
105                first.byte_end
106            } else {
107                first.byte_start
108            };
109        }
110        let last = &self.clusters[self.clusters.len() - 1];
111        if local_x >= self.line_width.max(last.x_right) {
112            return if last.is_rtl {
113                last.byte_start
114            } else {
115                last.byte_end
116            };
117        }
118
119        let mut best_cluster = first;
120        let mut best_dist = f32::INFINITY;
121        for c in &self.clusters {
122            if local_x >= c.x_left && local_x <= c.x_right {
123                best_cluster = c;
124                break;
125            }
126            let dist = if local_x < c.x_left {
127                c.x_left - local_x
128            } else {
129                local_x - c.x_right
130            };
131            if dist < best_dist {
132                best_dist = dist;
133                best_cluster = c;
134            }
135        }
136
137        let mid = (best_cluster.x_left + best_cluster.x_right) * 0.5;
138        let chosen = if best_cluster.is_rtl {
139            if local_x < mid {
140                best_cluster.byte_end
141            } else {
142                best_cluster.byte_start
143            }
144        } else if local_x <= mid {
145            best_cluster.byte_start
146        } else {
147            best_cluster.byte_end
148        };
149        clamp_grapheme_boundary(text, chosen)
150    }
151
152    /// Computes visual `(x_left, width)` selection spans for logical range `start..end`.
153    ///
154    /// Pure LTR/RTL selections produce one contiguous span; mixed BiDi selections that cross
155    /// an LTR/RTL reversal produce disjoint visual spans ordered left-to-right.
156    pub fn selection_spans_for_range(
157        &self,
158        text: &str,
159        start: usize,
160        end: usize,
161    ) -> Vec<(f32, f32)> {
162        if text.is_empty() || self.clusters.is_empty() {
163            return Vec::new();
164        }
165        let lo = clamp_grapheme_boundary(text, start.min(end));
166        let hi = clamp_grapheme_boundary(text, start.max(end));
167        if lo >= hi {
168            return Vec::new();
169        }
170
171        let mut spans: Vec<(f32, f32)> = Vec::new();
172        let mut active: Option<(f32, f32)> = None;
173
174        for c in &self.clusters {
175            let selected = c.byte_end > lo && c.byte_start < hi;
176            if selected {
177                active = Some(match active {
178                    Some((min_x, max_x)) if c.x_left <= max_x + 0.5 => {
179                        (min_x.min(c.x_left), max_x.max(c.x_right))
180                    }
181                    Some((min_x, max_x)) => {
182                        let w = max_x - min_x;
183                        if w > 0.0 {
184                            spans.push((min_x, w));
185                        }
186                        (c.x_left, c.x_right)
187                    }
188                    None => (c.x_left, c.x_right),
189                });
190            } else if let Some((min_x, max_x)) = active.take() {
191                let w = max_x - min_x;
192                if w > 0.0 {
193                    spans.push((min_x, w));
194                }
195            }
196        }
197
198        if let Some((min_x, max_x)) = active {
199            let w = max_x - min_x;
200            if w > 0.0 {
201                spans.push((min_x, w));
202            }
203        }
204
205        spans
206    }
207
208    /// Steps the caret visually left (`delta < 0`) or right (`delta > 0`) by one grapheme stop
209    /// across mixed LTR/RTL runs without ever landing mid-UTF-8 or mid-grapheme.
210    pub fn move_caret_visual(&self, text: &str, caret: usize, delta: i32) -> usize {
211        let idx = clamp_grapheme_boundary(text, caret);
212        if delta == 0 || text.is_empty() {
213            return idx;
214        }
215        if !self.has_rtl() {
216            return if delta < 0 {
217                prev_grapheme_boundary(text, idx)
218            } else {
219                next_grapheme_boundary(text, idx)
220            };
221        }
222
223        let mut stops: Vec<(f32, usize)> = grapheme_boundaries(text)
224            .into_iter()
225            .map(|b| (self.caret_x_at(text, b), b))
226            .collect();
227        stops.sort_by(|a, b| a.0.total_cmp(&b.0).then_with(|| a.1.cmp(&b.1)));
228
229        let Some(pos) = stops.iter().position(|&(_, b)| b == idx) else {
230            return idx;
231        };
232        let next_pos = if delta < 0 {
233            pos.saturating_sub(1)
234        } else {
235            (pos + 1).min(stops.len() - 1)
236        };
237        stops[next_pos].1
238    }
239}
240