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
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
use std::collections::VecDeque;

use textwrap::Options;
use textwrap::WordSplitter::NoHyphenation;
use unicode_normalization::UnicodeNormalization;

use crate::{FontKey, TextMetrics};

#[derive(Debug, Clone)]
pub struct Line<T> {
    pub spans: Vec<Span<T>>,
    pub hard_break: bool,
}

impl<T> Line<T> {
    pub fn width(&self) -> f32 {
        self.spans
            .iter()
            .fold(0.0, |current, span| current + span.width())
    }

    pub fn height(&self) -> f32 {
        self.spans
            .iter()
            .fold(0.0, |current, span| current.max(span.height()))
    }

    pub fn spans(&self) -> &[Span<T>] {
        &self.spans
    }

    pub fn new(span: Span<T>) -> Self {
        Line {
            spans: vec![span],
            hard_break: true,
        }
    }

    fn is_rtl(&self) -> bool {
        self.spans.iter().all(|span| span.is_rtl())
    }
}

#[derive(Debug, Clone, Default)]
pub struct Span<T> {
    pub font_key: FontKey,
    pub letter_spacing: f32,
    pub line_height: Option<f32>,
    pub size: f32,
    pub broke_from_prev: bool,
    pub metrics: TextMetrics,
    pub swallow_leading_space: bool,
    pub additional: T,
}

impl<T> Span<T> {
    fn width(&self) -> f32 {
        let mut width = self.metrics.width(self.size, self.letter_spacing);
        if self.swallow_leading_space {
            let c = &self.metrics.positions[0];
            width -=
                c.metrics.advanced_x as f32 / c.metrics.units * self.size + self.letter_spacing;
        }
        width
    }

    fn height(&self) -> f32 {
        self.metrics.height(self.size, self.line_height)
    }

    fn is_rtl(&self) -> bool {
        self.metrics
            .positions
            .iter()
            .all(|p| p.level.map(|l| l.is_rtl()).unwrap_or_default())
    }
}

/// Metrics of an area of rich-content text
#[derive(Debug, Clone)]
pub struct Area<T> {
    pub lines: Vec<Line<T>>,
}

impl<T> Area<T>
where
    T: Clone,
{
    pub fn new() -> Area<T> {
        Area { lines: vec![] }
    }

    // The height of a text area
    pub fn height(&self) -> f32 {
        self.lines
            .iter()
            .fold(0.0, |current, line| current + line.height())
    }

    /// The width of a text area
    pub fn width(&self) -> f32 {
        self.lines
            .iter()
            .fold(0.0_f32, |current, line| current.max(line.width()))
    }

    pub fn unwrap_text(&mut self) {
        let has_soft_break = self.lines.iter().any(|line| !line.hard_break);
        if !has_soft_break {
            return;
        }
        let lines = std::mem::replace(&mut self.lines, Vec::new());
        for line in lines {
            if line.hard_break {
                self.lines.push(line);
            } else {
                let last_line = self.lines.last_mut().unwrap();
                let rtl = last_line.is_rtl() && line.is_rtl();
                let last_line = &mut last_line.spans;
                for mut span in line.spans {
                    span.swallow_leading_space = false;
                    if rtl {
                        if span.broke_from_prev {
                            if let Some(first_span) = last_line.first_mut() {
                                span.metrics.value.push_str(&first_span.metrics.value);
                                span.metrics
                                    .positions
                                    .append(&mut first_span.metrics.positions);
                                std::mem::swap(first_span, &mut span);
                            } else {
                                last_line.insert(0, span);
                            }
                        } else {
                            last_line.insert(0, span);
                        }
                    } else {
                        if span.broke_from_prev {
                            if let Some(last_span) = last_line.last_mut() {
                                last_span.metrics.value.push_str(&span.metrics.value);
                                last_span
                                    .metrics
                                    .positions
                                    .append(&mut span.metrics.positions);
                            } else {
                                last_line.push(span);
                            }
                        } else {
                            last_line.push(span);
                        }
                    }
                }
            }
        }
    }

    pub fn wrap_text(&mut self, width: f32) {
        let rtl = self.lines.iter().all(|line| {
            line.spans.iter().all(|span| {
                span.metrics
                    .positions
                    .iter()
                    .all(|p| p.level.map(|l| l.is_rtl()).unwrap_or_default())
            })
        });
        let mut lines = self.lines.clone().into_iter().collect::<VecDeque<_>>();
        if rtl {
            lines.make_contiguous().reverse();
        }
        let mut result = vec![];
        let mut current_line = Line {
            hard_break: true,
            spans: Vec::new(),
        };
        let mut current_line_width = 0.0;
        let mut is_first_line = true;
        let mut failed_with_no_acception = false;
        while let Some(mut line) = lines.pop_front() {
            log::trace!(
                "current line {}",
                line.spans
                    .iter()
                    .map(|span| span.metrics.value.clone())
                    .collect::<Vec<_>>()
                    .join("")
            );
            if line.hard_break && !is_first_line {
                // Start a new line
                result.push(std::mem::replace(
                    &mut current_line,
                    Line {
                        hard_break: true,
                        spans: Vec::new(),
                    },
                ));
                current_line_width = 0.0;
            }
            is_first_line = false;
            let line_width = line.width();
            if width - (line_width + current_line_width) >= -0.01 {
                // Current line fits, push all of its spans into current line
                current_line_width += line_width;
                current_line.spans.append(&mut line.spans);
            } else {
                // Set line letter-spacing to min(zero, letter-spacing)
                for span in &mut line.spans {
                    span.letter_spacing = span.letter_spacing.min(0.0)
                }
                if rtl {
                    line.spans.reverse();
                }
                // Go through spans to get the first not-fitting span
                let index = line.spans.iter().position(|span| {
                    let span_width = span.width();
                    if span_width + current_line_width <= width {
                        current_line_width += span_width;
                        false
                    } else {
                        true
                    }
                });
                let index = match index {
                    Some(index) => index,
                    None => {
                        // after shrinking letter-spacing, the line fits
                        current_line_width += line.width();
                        current_line.spans.append(&mut line.spans);
                        continue;
                    }
                };
                // put all spans before this into the line
                let mut approved_spans = line.spans.split_off(index);
                std::mem::swap(&mut approved_spans, &mut line.spans);
                if approved_spans.is_empty() {
                    if failed_with_no_acception {
                        // Failed to fit a span twice, fail
                        return;
                    } else {
                        failed_with_no_acception = true;
                    }
                } else {
                    failed_with_no_acception = false;
                }
                current_line.spans.append(&mut approved_spans);
                let mut dropped_metrics = vec![];
                let span = &mut line.spans[0];
                let fixed_value = span.metrics.value().to_string();
                // Try to find a naive break point
                let mut naive_break_index = 0;
                let total_count = span.metrics.positions.len();
                if rtl {
                    span.metrics.positions.reverse();
                }
                // Textwrap cannot find a good break point, we directly drop chars
                while let Some(m) = span.metrics.positions.pop() {
                    dropped_metrics.push(m);
                    let span_width = span.width();
                    if span_width + current_line_width <= width {
                        naive_break_index = span.metrics.positions.len();
                        dropped_metrics.reverse();
                        span.metrics.positions.append(&mut dropped_metrics);
                        break;
                    }
                }
                if rtl {
                    naive_break_index = total_count - naive_break_index;
                    span.metrics.positions.reverse();
                }
                // NOTE: str.nfc() & textwrap all handles RTL text well, so we do
                // not take extra effort here
                let display_str = fixed_value
                    .nfc()
                    .take(naive_break_index)
                    .collect::<String>();
                let options = Options::new(textwrap::core::display_width(&display_str))
                    .word_splitter(NoHyphenation);
                let wrapped = textwrap::wrap(&*fixed_value, options);
                log::trace!("{:?}", wrapped);
                let mut real_index = 0;
                log::debug!(
                    "wrapped nfc count {}, metrics {}",
                    wrapped.iter().map(|span| span.nfc().count()).sum::<usize>(),
                    span.metrics.positions.len()
                );
                if rtl {
                    real_index = total_count - 1;
                }
                for seg in wrapped {
                    let count = seg.nfc().count();
                    if count == 0 {
                        continue;
                    }
                    let span_values = seg.nfc().collect::<Vec<_>>();
                    let mut current_real_index = real_index;
                    while span.metrics.positions()[current_real_index].metrics.c == ' '
                        && span_values
                            .get(current_real_index)
                            .map(|c| *c != ' ')
                            .unwrap_or(true)
                    {
                        if rtl {
                            current_real_index -= 1;
                        } else {
                            current_real_index += 1;
                        }
                    }
                    let factor = span.size / span.metrics.units() as f32;
                    let range = if rtl {
                        (current_real_index + 1 - count)..total_count
                    } else {
                        0..(current_real_index + count)
                    };
                    let acc_seg_width = range
                        .map(|index| span.metrics.positions.get(index).unwrap())
                        .fold(0.0, |current, p| {
                            current
                                + p.kerning as f32 * factor
                                + p.metrics.advanced_x as f32 * factor
                                + span.letter_spacing
                        });
                    if current_line_width + acc_seg_width <= width {
                        if rtl {
                            real_index = current_real_index - count;
                        } else {
                            real_index = current_real_index + count;
                        }
                    } else {
                        break;
                    }
                }
                if (real_index == 0 && !rtl)
                    || (rtl && real_index == span.metrics.positions.len() - 1)
                {
                    real_index = naive_break_index
                }

                // Split here, create a new span
                let mut new_span = span.clone();
                new_span.broke_from_prev = true;
                new_span.metrics.positions = span.metrics.positions.split_off(real_index);
                let mut chars = fixed_value.nfc().collect::<Vec<_>>();
                let new_chars = chars.split_off(real_index);
                log::trace!(
                    "real_index {} index {}, {:?}, {:?}",
                    real_index,
                    index,
                    chars,
                    new_chars
                );
                span.metrics.value = chars.into_iter().collect::<String>();
                new_span.metrics.value = new_chars.into_iter().collect::<String>();
                if rtl {
                    std::mem::swap(span, &mut new_span);
                }
                if !span.metrics.value.is_empty() {
                    current_line.spans.push(span.clone());
                }
                assert_eq!(
                    span.metrics.value.nfc().count(),
                    span.metrics.positions.len()
                );
                assert_eq!(
                    new_span.metrics.value.nfc().count(),
                    new_span.metrics.positions.len()
                );
                // Create a new line
                result.push(std::mem::replace(
                    &mut current_line,
                    Line {
                        hard_break: false,
                        spans: Vec::new(),
                    },
                ));
                // Add new_span to next line
                let mut new_line = Line {
                    hard_break: false,
                    spans: vec![new_span],
                };
                // Check for swallowed leading space
                if new_line.spans[0].metrics.value.starts_with(" ") {
                    new_line.spans[0].swallow_leading_space = true;
                }
                for span in line.spans.into_iter().skip(1) {
                    new_line.spans.push(span);
                }
                lines.push_front(new_line);
                current_line_width = 0.0;
                if real_index != 0 {
                    failed_with_no_acception = false;
                }
            }
        }
        if !current_line.spans.is_empty() {
            result.push(current_line);
        }
        if result.is_empty() || result[0].spans.is_empty() {
            return;
        }
        self.lines = result;
        log::trace!("adjust result: {}", self.value_string());
    }

    pub fn valid(&self) -> bool {
        !self.lines.iter().any(|line| {
            line.spans
                .iter()
                .any(|span| span.metrics.positions.is_empty() && !span.metrics.value.is_empty())
        })
    }

    pub fn value_string(&self) -> String {
        self.lines
            .iter()
            .map(|line| {
                line.spans
                    .iter()
                    .map(|span| span.metrics.value.clone())
                    .collect::<Vec<_>>()
                    .join("")
            })
            .collect::<Vec<_>>()
            .join("\n")
    }

    pub fn span_count(&self) -> usize {
        self.lines
            .iter()
            .fold(0, |current, line| line.spans.len() + current)
    }

    pub fn ellipsis(&mut self, width: f32, height: f32, postfix: TextMetrics) {
        // No need to do ellipsis
        if height - self.height() >= -0.01 && width - self.width() >= -0.01 {
            return;
        }
        let mut ellipsis_span = self.lines[0].spans[0].clone();
        let mut lines_height = 0.0;
        self.lines = self
            .lines
            .clone()
            .drain_filter(|line| {
                lines_height += line.height();
                height - lines_height >= -0.01
            })
            .collect();

        for line in &mut self.lines {
            line.hard_break = true;
            if let Some(ref mut first) = line.spans.first_mut() {
                first.metrics.trim_start();
            }
        }

        if let Some(ref mut line) = self.lines.last_mut() {
            while line.width() + postfix.width(ellipsis_span.size, ellipsis_span.letter_spacing)
                - width
                >= 0.01
                && line.width() > 0.0
            {
                let span = line.spans.last_mut().unwrap();
                span.metrics.pop();
                if span.metrics.positions.is_empty() {
                    line.spans.pop();
                }
            }
            ellipsis_span.metrics = postfix;
            line.spans.push(ellipsis_span);
        }
    }
}