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
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,
}
}
}
#[derive(Debug, Clone, Default)]
pub struct Span<T> {
pub value: String,
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)
}
}
#[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![] }
}
pub fn height(&self) -> f32 {
self.lines
.iter()
.fold(0.0, |current, line| current + line.height())
}
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 = &mut self.lines.last_mut().unwrap().spans;
for mut span in line.spans {
span.swallow_leading_space = false;
if span.broke_from_prev {
if let Some(last_span) = last_line.last_mut() {
last_span.value.push_str(&span.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 lines = std::mem::replace(&mut self.lines, Vec::new());
let mut lines = lines.into_iter().collect::<VecDeque<_>>();
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;
while let Some(mut line) = lines.pop_front() {
if line.hard_break && !is_first_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 line_width + current_line_width <= width {
current_line_width += line_width;
current_line.spans.append(&mut line.spans);
} else {
for span in &mut line.spans {
span.letter_spacing = span.letter_spacing.min(0.0)
}
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 => {
current_line_width += line.width();
current_line.spans.append(&mut line.spans);
continue;
}
};
let mut approved_spans = line.spans.split_off(index);
std::mem::swap(&mut approved_spans, &mut line.spans);
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();
let mut naive_break_index = 0;
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;
}
}
let options = Options::new(textwrap::core::display_width(
&fixed_value
.nfc()
.take(naive_break_index)
.collect::<String>(),
))
.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()
);
for seg in wrapped {
let count = seg.nfc().count();
if count == 0 {
continue;
}
while span.metrics.positions.get(real_index).unwrap().metrics.c == ' ' {
real_index += 1;
}
let seg_last_metric =
&span.metrics.positions.get(real_index + count - 1).unwrap();
let factor = span.size / span.metrics.units() as f32;
let acc_seg_width = (0..(real_index + count))
.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
})
+ seg_last_metric.metrics.advanced_x as f32 * span.size
/ seg_last_metric.metrics.units as f32
+ span.letter_spacing;
if current_line_width + acc_seg_width <= width {
real_index += count;
} else {
break;
}
}
if real_index == 0 {
real_index = naive_break_index
}
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<_>>();
log::trace!("real_index {} index {}, {:?}", real_index, index, chars);
let new_chars = chars.split_off(real_index);
span.value = chars.into_iter().collect::<String>();
new_span.value = new_chars.into_iter().collect::<String>();
if !span.value.is_empty() {
current_line.spans.push(span.clone());
}
assert_eq!(span.value.nfc().count(), span.metrics.positions.len());
assert_eq!(
new_span.value.nfc().count(),
new_span.metrics.positions.len()
);
result.push(std::mem::replace(
&mut current_line,
Line {
hard_break: false,
spans: Vec::new(),
},
));
let mut new_line = Line {
hard_break: false,
spans: vec![new_span],
};
if new_line.spans[0].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 !current_line.spans.is_empty() {
result.push(current_line);
}
self.lines = result;
}
pub fn valid(&self) -> bool {
!self.lines.iter().any(|line| {
line.spans
.iter()
.any(|span| span.metrics.positions.is_empty())
})
}
pub fn value_string(&self) -> String {
self.lines
.iter()
.map(|line| {
line.spans
.iter()
.map(|span| span.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)
}
}