1use crate::{
2 LabelPlan, Point, Rect, Size, TextAlignment, TextAreaMotion, TextEdit, TextPosition,
3 VisualTextLine,
4};
5use std::{borrow::Cow, ops::Range};
6use unicode_bidi::{BidiInfo, Direction, get_base_direction};
7use xrack_runtime::{LayoutDirection, Node, StyledText, TextHorizontalAlignment, TextStyle};
8
9#[derive(Clone, Debug, PartialEq)]
10struct Piece {
11 range: Option<Range<usize>>,
12 rtl_mark: bool,
13 style: TextStyle,
14 link: Option<usize>,
15}
16
17impl Piece {
18 fn text<'a>(&self, document: &'a StyledText) -> Cow<'a, str> {
19 let Some(range) = &self.range else {
20 return Cow::Borrowed("…");
21 };
22 let text = &document.text()[range.clone()];
23 if self.rtl_mark {
24 Cow::Owned(format!("\u{200f}{text}"))
25 } else {
26 Cow::Borrowed(text)
27 }
28 }
29}
30
31#[derive(Clone, Debug, PartialEq)]
33pub struct StyledFragment {
34 piece: Piece,
35 pub bounds: Rect,
36 visual: Option<VisualTextLine>,
37}
38
39impl StyledFragment {
40 pub fn text<'a>(&self, document: &'a StyledText) -> Cow<'a, str> {
41 self.piece.text(document)
42 }
43
44 pub fn style(&self) -> TextStyle {
45 self.piece.style
46 }
47
48 pub fn link(&self) -> Option<usize> {
49 self.piece.link
50 }
51
52 #[doc(hidden)]
53 pub fn selection_geometry(&self) -> Option<(&VisualTextLine, Range<usize>, usize)> {
54 Some((
55 self.visual.as_ref()?,
56 self.piece.range.clone()?,
57 if self.piece.rtl_mark {
58 '\u{200f}'.len_utf8()
59 } else {
60 0
61 },
62 ))
63 }
64
65 fn position(&self, mut local: TextPosition) -> Option<TextPosition> {
66 let (_, range, prefix) = self.selection_geometry()?;
67 local.offset = range.start + local.offset.saturating_sub(prefix).min(range.len());
68 Some(local)
69 }
70}
71
72#[derive(Clone, Debug, PartialEq)]
74pub struct StyledTextLayout {
75 pub size: Size,
76 pub fragments: Vec<StyledFragment>,
77}
78
79impl StyledTextLayout {
80 #[doc(hidden)]
81 pub fn shape_selection(
82 &mut self,
83 document: &StyledText,
84 mut shape: impl FnMut(&str, TextStyle) -> VisualTextLine,
85 ) {
86 for fragment in &mut self.fragments {
87 if fragment.piece.range.is_some() {
88 fragment.visual = Some(shape(&fragment.text(document), fragment.style()));
89 }
90 }
91 }
92
93 #[doc(hidden)]
94 pub fn selection_hit(&self, point: Point) -> Option<TextPosition> {
95 let distance = |point: f32, start: f32, size: f32| {
96 (start - point).max(point - (start + size)).max(0.0)
97 };
98 let fragment = self
99 .fragments
100 .iter()
101 .filter(|fragment| fragment.visual.is_some())
102 .min_by(|a, b| {
103 let y = |f: &StyledFragment| distance(point.y, f.bounds.y, f.bounds.height);
104 let x = |f: &StyledFragment| distance(point.x, f.bounds.x, f.bounds.width);
105 y(a).total_cmp(&y(b)).then_with(|| x(a).total_cmp(&x(b)))
106 })?;
107 fragment.position(fragment.visual.as_ref()?.hit(point.x - fragment.bounds.x))
108 }
109
110 #[doc(hidden)]
111 pub fn move_selection(
112 &self,
113 text: &str,
114 editor: &mut TextEdit,
115 motion: TextAreaMotion,
116 selecting: bool,
117 ) -> bool {
118 let caret = editor.position(text);
119 let items = self
120 .fragments
121 .iter()
122 .enumerate()
123 .filter_map(|(index, fragment)| {
124 let (visual, range, prefix) = fragment.selection_geometry()?;
125 Some((index, fragment, visual, range, prefix))
126 });
127 let Some((index, fragment, visual, range, prefix)) =
128 items.min_by_key(|(_, _, _, range, _)| {
129 let distance = range.start.saturating_sub(caret.offset)
130 + caret.offset.saturating_sub(range.end);
131 let wrong_edge = if caret.trailing {
132 caret.offset == range.start
133 } else {
134 caret.offset == range.end
135 };
136 (distance, wrong_edge)
137 })
138 else {
139 return false;
140 };
141 let local = TextPosition {
142 offset: caret.offset.clamp(range.start, range.end) - range.start + prefix,
143 trailing: caret.trailing,
144 };
145 let mut preferred = None;
146 let next = match motion {
147 TextAreaMotion::Left | TextAreaMotion::Right => {
148 let right = matches!(motion, TextAreaMotion::Right);
149 visual
150 .step(local, right)
151 .and_then(|position| fragment.position(position))
152 .or_else(|| {
153 let adjacent = if right {
154 self.fragments[index + 1..]
155 .iter()
156 .find(|fragment| fragment.visual.is_some())
157 } else {
158 self.fragments[..index]
159 .iter()
160 .rev()
161 .find(|fragment| fragment.visual.is_some())
162 }?;
163 let visual = adjacent.visual.as_ref()?;
164 let edge = visual.edge(!right);
165 let position = adjacent.position(edge)?;
166 if adjacent.bounds.y == fragment.bounds.y && position.offset == caret.offset
167 {
168 visual
169 .step(edge, right)
170 .and_then(|next| adjacent.position(next))
171 .or(Some(position))
172 } else {
173 Some(position)
174 }
175 })
176 }
177 TextAreaMotion::Up
178 | TextAreaMotion::Down
179 | TextAreaMotion::PageUp
180 | TextAreaMotion::PageDown => {
181 let x = editor
182 .preferred_x()
183 .unwrap_or(fragment.bounds.x + visual.caret_x(local));
184 preferred = Some(x);
185 let delta = match motion {
186 TextAreaMotion::Up => -fragment.bounds.height,
187 TextAreaMotion::Down => fragment.bounds.height,
188 TextAreaMotion::PageUp => -self.size.height,
189 _ => self.size.height,
190 };
191 self.selection_hit(Point {
192 x,
193 y: fragment.bounds.y + fragment.bounds.height * 0.5 + delta,
194 })
195 }
196 _ => return false,
197 };
198 if !selecting
199 && matches!(motion, TextAreaMotion::Left | TextAreaMotion::Right)
200 && !editor.selection(text).is_empty()
201 {
202 let range = editor.selection(text);
204 let end = matches!(motion, TextAreaMotion::Right) != visual.is_rtl();
205 editor.place_caret(
206 text,
207 TextPosition {
208 offset: if end { range.end } else { range.start },
209 trailing: end,
210 },
211 false,
212 );
213 } else if let Some(next) = next {
214 editor.place_caret(text, next, selecting);
215 if let Some(x) = preferred {
216 editor.set_preferred_x(x);
217 }
218 }
219 true
220 }
221
222 pub(crate) fn align_in_direction(
223 &mut self,
224 node: &Node,
225 width: f32,
226 direction: LayoutDirection,
227 ) {
228 let alignment =
229 TextAlignment::from_node(node, Some(direction), TextHorizontalAlignment::Start);
230 for line in self
231 .fragments
232 .chunk_by_mut(|left, right| left.bounds.y == right.bounds.y)
233 {
234 let first = line[0].bounds.x;
235 let last = line[line.len() - 1].bounds;
236 let shift = alignment.offset(width - (last.x + last.width - first), false) - first;
237 for fragment in line {
238 fragment.bounds.x += shift;
239 }
240 }
241 }
242
243 pub fn new(
244 node: &Node,
245 document: &StyledText,
246 available: Size,
247 font_size: f32,
248 mut advance: impl FnMut(&str, TextStyle) -> f32,
249 ) -> Self {
250 let bidi = BidiInfo::new(document.text(), None);
251 let bidi = bidi.has_rtl().then_some(&bidi);
252 let mut width = |piece: &Piece| advance(&piece.text(document), piece.style);
253 let plan = LabelPlan::with_font_size(node, available, font_size, |range, ellipsis| {
254 pieces(document, bidi, range, ellipsis)
255 .iter()
256 .map(&mut width)
257 .sum()
258 });
259 let mut fragments = Vec::new();
260 for line in plan.lines {
261 let mut x = line.origin.x;
262 for piece in pieces(document, bidi, line.range, line.ellipsis) {
263 let advance = width(&piece);
264 let bounds = Rect::new(x, line.origin.y, advance, font_size * 1.4);
265 fragments.push(StyledFragment {
266 piece,
267 bounds,
268 visual: None,
269 });
270 x += advance;
271 }
272 }
273 Self {
274 size: plan.size,
275 fragments,
276 }
277 }
278}
279
280fn pieces(
281 document: &StyledText,
282 bidi: Option<&BidiInfo<'_>>,
283 range: Range<usize>,
284 ellipsis: bool,
285) -> Vec<Piece> {
286 let mut pieces = Vec::new();
287 let mut rtl = false;
288 if let Some(bidi) = bidi {
289 let first = bidi
290 .paragraphs
291 .partition_point(|para| para.range.end <= range.start);
292 for para in &bidi.paragraphs[first..] {
293 let line = para.range.start.max(range.start)..para.range.end.min(range.end);
294 if line.start > range.end {
295 break;
296 }
297 if pieces.is_empty() {
298 rtl = para.level.is_rtl();
299 }
300 if line.is_empty() {
301 continue;
302 }
303 let (levels, runs) = bidi.visual_runs(para, line);
304 for run in runs {
305 let rtl = levels[run.start].is_rtl();
306 split_run(document, run, rtl, &mut pieces);
307 }
308 }
309 } else {
310 split_run(document, range, false, &mut pieces);
311 }
312 if ellipsis {
313 let mark = Piece {
314 range: None,
315 rtl_mark: false,
316 style: TextStyle::default(),
317 link: None,
318 };
319 if rtl {
320 pieces.insert(0, mark);
321 } else {
322 pieces.push(mark);
323 }
324 }
325 pieces
326}
327
328fn split_run(document: &StyledText, range: Range<usize>, rtl: bool, pieces: &mut Vec<Piece>) {
329 let first = pieces.len();
330 let mut start = range.start;
331 let styles = document.runs();
332 let links = document.links();
333 while start < range.end {
334 let style_index = styles.partition_point(|run| run.end <= start);
335 let link_index = links.partition_point(|link| link.end <= start);
336 let (style, style_end) = match styles.get(style_index) {
337 Some(run) if run.start <= start => (run.style, run.end),
338 Some(run) => (TextStyle::default(), run.start),
339 None => (TextStyle::default(), range.end),
340 };
341 let (link, link_end) = match links.get(link_index) {
342 Some(link) if link.start <= start => (Some(link_index), link.end),
343 Some(link) => (None, link.start),
344 None => (None, range.end),
345 };
346 let end = range.end.min(style_end).min(link_end);
347 let text = &document.text()[start..end];
348 let rtl_mark = rtl && get_base_direction(text) != Direction::Rtl;
349 pieces.push(Piece {
350 range: Some(start..end),
351 rtl_mark,
352 style,
353 link,
354 });
355 start = end;
356 }
357 if rtl {
358 pieces[first..].reverse();
359 }
360}