1use crate::{
2 Point, Size, TextMeasurer, font_size,
3 text_area::{fitting_prefix, grapheme_boundaries, paragraphs},
4};
5use std::{borrow::Cow, ops::Range};
6use unicode_bidi::{Direction, get_base_direction};
7use unicode_segmentation::UnicodeSegmentation;
8use xrack_runtime::{
9 LayoutDirection, Node, TextHorizontalAlignment, TextOverflow, TextVerticalAlignment, TextWrap,
10 Value,
11};
12
13#[derive(Clone, Copy, Debug, PartialEq, Eq)]
15#[doc(hidden)]
16pub struct TextAlignment {
17 mode: TextHorizontalAlignment,
18 direction: Option<LayoutDirection>,
19}
20
21impl TextAlignment {
22 pub(crate) fn from_node(
23 node: &Node,
24 direction: Option<LayoutDirection>,
25 default: TextHorizontalAlignment,
26 ) -> Self {
27 let mode = match node.properties.get("horizontal-alignment") {
28 Some(Value::TextHorizontalAlignment(alignment)) => *alignment,
29 _ => default,
30 };
31 Self { mode, direction }
32 }
33
34 pub fn editor(node: &Node, direction: Option<LayoutDirection>) -> Self {
35 let default = if direction.is_some() {
36 TextHorizontalAlignment::Start
37 } else {
38 TextHorizontalAlignment::Left
39 };
40 Self::from_node(node, direction, default)
41 }
42
43 pub(crate) fn has_offset(self) -> bool {
44 self.mode != TextHorizontalAlignment::Left
45 }
46
47 pub fn offset(self, space: f32, natural_rtl: bool) -> f32 {
48 use TextHorizontalAlignment as Horizontal;
49 let rtl = self.direction.map_or(natural_rtl, |direction| {
50 direction == LayoutDirection::RightToLeft
51 });
52 match self.mode {
53 Horizontal::Center => space * 0.5,
54 Horizontal::Right => space,
55 Horizontal::Start if rtl => space,
56 Horizontal::End if !rtl => space,
57 _ => 0.0,
58 }
59 }
60
61 pub fn single_line_offset(
63 self,
64 width: f32,
65 advance: f32,
66 rtl: bool,
67 caret: Option<f32>,
68 ) -> f32 {
69 let free = width - advance - 1.0;
70 if free < 0.0
71 && let Some(caret) = caret
72 {
73 -(caret + 1.0 - width).max(0.0)
74 } else {
75 self.offset(free, rtl)
76 }
77 }
78
79 #[doc(hidden)]
80 pub fn single_line_view_offset(
81 self,
82 width: f32,
83 advance: f32,
84 rtl: bool,
85 caret: Option<f32>,
86 drag_scroll: Option<f32>,
87 ) -> f32 {
88 let overflow = advance + 1.0 - width;
89 if let Some(scroll) = drag_scroll
90 && overflow > 0.0
91 {
92 -scroll.clamp(0.0, overflow)
93 } else {
94 self.single_line_offset(width, advance, rtl, caret)
95 }
96 }
97}
98
99pub fn uses_label_layout(node: &Node) -> bool {
100 matches!(node.kind, "Label" | "StyledText")
101 || node.kind == "Text"
102 && [
103 "horizontal-alignment",
104 "vertical-alignment",
105 "overflow",
106 "max-lines",
107 "wrap",
108 ]
109 .iter()
110 .any(|key| node.properties.contains_key(key))
111}
112
113fn wrap(node: &Node) -> TextWrap {
114 match node.properties.get("wrap") {
115 Some(Value::TextWrap(wrap)) => *wrap,
116 _ if node.kind == "Label" => TextWrap::NoWrap,
117 _ => TextWrap::WordWrap,
118 }
119}
120
121pub(crate) fn reflows_at_width(node: &Node) -> bool {
122 uses_label_layout(node) && wrap(node) != TextWrap::NoWrap
123}
124
125pub(crate) fn flexible_width(node: &Node) -> bool {
126 reflows_at_width(node)
127 || uses_label_layout(node)
128 && node.properties.get("overflow") == Some(&Value::TextOverflow(TextOverflow::Elide))
129}
130
131pub struct LabelLine<'a> {
132 pub text: Cow<'a, str>,
133 pub origin: Point,
134}
135
136pub struct LabelLayout<'a> {
138 pub size: Size,
139 pub lines: Vec<LabelLine<'a>>,
140}
141
142impl<'a> LabelLayout<'a> {
143 pub fn new(node: &'a Node, available: Size, advance: impl FnMut(&str) -> f32) -> Self {
144 Self::with_font_size(node, available, font_size(node), advance)
145 }
146
147 pub fn with_font_size(
148 node: &'a Node,
149 available: Size,
150 size: f32,
151 advance: impl FnMut(&str) -> f32,
152 ) -> Self {
153 Self::in_direction(node, available, size, node.layout_direction(), advance)
154 }
155
156 pub fn in_direction(
157 node: &'a Node,
158 available: Size,
159 size: f32,
160 direction: Option<LayoutDirection>,
161 mut advance: impl FnMut(&str) -> f32,
162 ) -> Self {
163 let text = node.text("text").unwrap_or("");
164 let plan = LabelPlan::in_direction(node, available, size, direction, |range, ellipsis| {
165 advance(&line_text(text, range, ellipsis))
166 });
167 Self {
168 size: plan.size,
169 lines: plan
170 .lines
171 .into_iter()
172 .map(|line| LabelLine {
173 text: line_text(text, line.range, line.ellipsis),
174 origin: line.origin,
175 })
176 .collect(),
177 }
178 }
179}
180
181fn line_text(text: &str, range: Range<usize>, ellipsis: bool) -> Cow<'_, str> {
182 if ellipsis {
183 let mut shown = text[range].to_owned();
184 shown.push('…');
185 Cow::Owned(shown)
186 } else {
187 Cow::Borrowed(&text[range])
188 }
189}
190
191#[derive(Clone, Debug, PartialEq)]
192pub struct PlannedLabelLine {
193 pub range: Range<usize>,
194 pub ellipsis: bool,
195 pub origin: Point,
196}
197
198#[derive(Clone, Debug, PartialEq)]
199pub(crate) struct TitleLayout {
200 pub height: f32,
201 pub font_size: f32,
202 pub lines: Vec<PlannedLabelLine>,
203}
204
205impl PlannedLabelLine {
206 pub fn text<'a>(&self, source: &'a str) -> Cow<'a, str> {
207 line_text(source, self.range.clone(), self.ellipsis)
208 }
209}
210
211struct LabelStyle {
212 horizontal: TextAlignment,
213 vertical: TextVerticalAlignment,
214 wrap: TextWrap,
215 elide: bool,
216 max_lines: usize,
217}
218
219pub struct LabelPlan {
221 pub size: Size,
222 pub lines: Vec<PlannedLabelLine>,
223}
224
225impl LabelPlan {
226 pub fn with_font_size(
227 node: &Node,
228 available: Size,
229 size: f32,
230 advance: impl FnMut(Range<usize>, bool) -> f32,
231 ) -> Self {
232 Self::in_direction(node, available, size, node.layout_direction(), advance)
233 }
234
235 fn in_direction(
236 node: &Node,
237 available: Size,
238 size: f32,
239 direction: Option<LayoutDirection>,
240 advance: impl FnMut(Range<usize>, bool) -> f32,
241 ) -> Self {
242 use TextHorizontalAlignment as Horizontal;
243 use TextVerticalAlignment as Vertical;
244
245 let text = node.text("text").unwrap_or("");
246 let elide =
247 node.properties.get("overflow") == Some(&Value::TextOverflow(TextOverflow::Elide));
248 let default = if matches!(node.kind, "Label" | "StyledText") {
249 Horizontal::Start
250 } else {
251 Horizontal::Left
252 };
253 let horizontal = TextAlignment::from_node(node, direction, default);
254 let vertical = match node.properties.get("vertical-alignment") {
255 Some(Value::TextVerticalAlignment(alignment)) => *alignment,
256 _ => Vertical::Top,
257 };
258 let max_lines = node
259 .int("max-lines")
260 .and_then(|count| usize::try_from(count).ok())
261 .filter(|&count| count > 0)
262 .unwrap_or(usize::MAX);
263 Self::plan(
264 text,
265 available,
266 size,
267 LabelStyle {
268 horizontal,
269 vertical,
270 wrap: wrap(node),
271 elide,
272 max_lines,
273 },
274 advance,
275 )
276 }
277
278 pub(crate) fn leading_title(
279 node: &Node,
280 title: &str,
281 width: f32,
282 size: f32,
283 direction: LayoutDirection,
284 max_lines: usize,
285 text: &mut impl TextMeasurer,
286 ) -> Self {
287 let preferred_size = text.font_size(node);
288 Self::plan(
289 title,
290 Size::new(width, f32::INFINITY),
291 size,
292 LabelStyle {
293 horizontal: TextAlignment {
294 mode: TextHorizontalAlignment::Start,
295 direction: Some(direction),
296 },
297 vertical: TextVerticalAlignment::Top,
298 wrap: TextWrap::WordWrap,
299 elide: true,
300 max_lines,
301 },
302 |range, ellipsis| {
303 let value = line_text(title, range, ellipsis);
304 if size == preferred_size {
305 text.measure_node(node, &value, f32::MAX).width
306 } else {
307 text.measure_node_at_size(node, &value, size, f32::MAX)
308 .width
309 }
310 },
311 )
312 }
313
314 fn plan(
315 text: &str,
316 available: Size,
317 size: f32,
318 style: LabelStyle,
319 mut advance: impl FnMut(Range<usize>, bool) -> f32,
320 ) -> Self {
321 use TextHorizontalAlignment as Horizontal;
322 use TextVerticalAlignment as Vertical;
323
324 let LabelStyle {
325 horizontal,
326 vertical,
327 wrap,
328 elide,
329 max_lines,
330 } = style;
331 let line_height = size * 1.4;
332 let by_height = available.height / line_height;
333 let by_height = if elide {
334 by_height.next_up().floor()
336 } else {
337 by_height.ceil()
338 } as usize;
339 let limit = max_lines.min(by_height);
340 if limit == 0 || available.width <= 0.0 {
341 return Self {
342 size: Size::default(),
343 lines: Vec::new(),
344 };
345 }
346
347 let mut raw = Vec::new();
348 'paragraphs: for range in paragraphs(text) {
349 let content = &text[range.clone()];
350 let rtl = horizontal.direction.is_none()
351 && matches!(horizontal.mode, Horizontal::Start | Horizontal::End)
352 && get_base_direction(content) == Direction::Rtl;
353 if wrap == TextWrap::NoWrap || content.is_empty() {
354 raw.push((range, rtl));
355 if raw.len() > limit {
356 break;
357 }
358 continue;
359 }
360 let graphemes = grapheme_boundaries(content);
361 let words = if wrap == TextWrap::WordWrap {
362 content
363 .split_word_bound_indices()
364 .map(|(start, word)| start + word.len())
365 .collect::<Vec<_>>()
366 } else {
367 Vec::new()
368 };
369 let last = graphemes.len() - 1;
370 let mut start = 0;
371 while start < last {
372 let fit = fitting_prefix(start, last, |index| {
373 let from = range.start + graphemes[start];
374 let to = range.start + graphemes[index];
375 advance(from..to, false) <= available.width
376 })
377 .max(start + 1);
378 let word_end = words.partition_point(|&byte| byte <= graphemes[fit]);
379 let next = word_end
380 .checked_sub(1)
381 .and_then(|index| graphemes.binary_search(&words[index]).ok())
382 .filter(|&index| index > start)
383 .unwrap_or(fit);
384 let from = range.start + graphemes[start];
385 let to = range.start + graphemes[next];
386 raw.push((trim_trailing_space(text, from..to), rtl));
387 if raw.len() > limit {
388 break 'paragraphs;
389 }
390 start = next;
391 while start < last
392 && content[graphemes[start]..graphemes[start + 1]]
393 .chars()
394 .all(char::is_whitespace)
395 {
396 start += 1;
397 }
398 }
399 }
400
401 let truncated = raw.len() > limit;
402 raw.truncate(limit);
403 let last = raw.len().saturating_sub(1);
404 let height = raw.len() as f32 * line_height;
405 let free = if available.height.is_finite() {
406 (available.height - height).max(0.0)
407 } else {
408 0.0
409 };
410 let top = match vertical {
411 Vertical::Top => 0.0,
412 Vertical::Center => free * 0.5,
413 Vertical::Bottom => free,
414 };
415 let mut width = 0.0_f32;
416 let lines = raw
417 .into_iter()
418 .enumerate()
419 .map(|(index, (mut range, rtl))| {
420 let mut span = advance(range.clone(), false);
421 let mut ellipsis = false;
422 if elide && (span > available.width || truncated && index == last) {
423 (range, ellipsis) = elided(text, range, available.width, &mut advance);
424 span = advance(range.clone(), ellipsis);
425 }
426 width = width.max(span);
427 let free = available.width - span;
428 let x = horizontal.offset(free, rtl);
429 PlannedLabelLine {
430 range,
431 ellipsis,
432 origin: Point {
433 x,
434 y: top + index as f32 * line_height,
435 },
436 }
437 })
438 .collect();
439 Self {
440 size: Size::new(width.min(available.width), height),
441 lines,
442 }
443 }
444}
445
446fn trim_trailing_space(text: &str, range: Range<usize>) -> Range<usize> {
447 range.start..range.start + text[range.clone()].trim_end().len()
448}
449
450#[doc(hidden)]
452pub fn elide_to_width(
453 text: &str,
454 width: f32,
455 mut advance: impl FnMut(&str) -> f32,
456) -> Cow<'_, str> {
457 if advance(text) <= width {
458 return Cow::Borrowed(text);
459 }
460 let (range, ellipsis) = elided(text, 0..text.len(), width, &mut |range, ellipsis| {
461 advance(&line_text(text, range, ellipsis))
462 });
463 line_text(text, range, ellipsis)
464}
465
466fn elided(
467 text: &str,
468 range: Range<usize>,
469 width: f32,
470 advance: &mut impl FnMut(Range<usize>, bool) -> f32,
471) -> (Range<usize>, bool) {
472 let start = range.start;
473 if advance(start..start, true) > width {
474 return (start..start, false);
475 }
476 let boundaries = grapheme_boundaries(&text[range]);
477 let end = fitting_prefix(0, boundaries.len() - 1, |index| {
478 advance(
479 trim_trailing_space(text, start..start + boundaries[index]),
480 true,
481 ) <= width
482 });
483 (
484 trim_trailing_space(text, start..start + boundaries[end]),
485 true,
486 )
487}