1use crate::{px, FontId, FontRun, Pixels, PlatformTextSystem};
2use collections::HashMap;
3use std::{iter, sync::Arc};
4
5pub struct LineWrapper {
6 platform_text_system: Arc<dyn PlatformTextSystem>,
7 pub(crate) font_id: FontId,
8 pub(crate) font_size: Pixels,
9 cached_ascii_char_widths: [Option<Pixels>; 128],
10 cached_other_char_widths: HashMap<char, Pixels>,
11}
12
13impl LineWrapper {
14 pub const MAX_INDENT: u32 = 256;
15
16 pub fn new(
17 font_id: FontId,
18 font_size: Pixels,
19 text_system: Arc<dyn PlatformTextSystem>,
20 ) -> Self {
21 Self {
22 platform_text_system: text_system,
23 font_id,
24 font_size,
25 cached_ascii_char_widths: [None; 128],
26 cached_other_char_widths: HashMap::default(),
27 }
28 }
29
30 pub fn wrap_line<'a>(
31 &'a mut self,
32 line: &'a str,
33 wrap_width: Pixels,
34 ) -> impl Iterator<Item = Boundary> + 'a {
35 let mut width = px(0.);
36 let mut first_non_whitespace_ix = None;
37 let mut indent = None;
38 let mut last_candidate_ix = 0;
39 let mut last_candidate_width = px(0.);
40 let mut last_wrap_ix = 0;
41 let mut prev_c = '\0';
42 let mut char_indices = line.char_indices();
43 iter::from_fn(move || {
44 for (ix, c) in char_indices.by_ref() {
45 if c == '\n' {
46 continue;
47 }
48
49 if prev_c == ' ' && c != ' ' && first_non_whitespace_ix.is_some() {
50 last_candidate_ix = ix;
51 last_candidate_width = width;
52 }
53
54 if c != ' ' && first_non_whitespace_ix.is_none() {
55 first_non_whitespace_ix = Some(ix);
56 }
57
58 let char_width = self.width_for_char(c);
59 width += char_width;
60 if width > wrap_width && ix > last_wrap_ix {
61 if let (None, Some(first_non_whitespace_ix)) = (indent, first_non_whitespace_ix)
62 {
63 indent = Some(
64 Self::MAX_INDENT.min((first_non_whitespace_ix - last_wrap_ix) as u32),
65 );
66 }
67
68 if last_candidate_ix > 0 {
69 last_wrap_ix = last_candidate_ix;
70 width -= last_candidate_width;
71 last_candidate_ix = 0;
72 } else {
73 last_wrap_ix = ix;
74 width = char_width;
75 }
76
77 if let Some(indent) = indent {
78 width += self.width_for_char(' ') * indent as f32;
79 }
80
81 return Some(Boundary::new(last_wrap_ix, indent.unwrap_or(0)));
82 }
83 prev_c = c;
84 }
85
86 None
87 })
88 }
89
90 #[inline(always)]
91 fn width_for_char(&mut self, c: char) -> Pixels {
92 if (c as u32) < 128 {
93 if let Some(cached_width) = self.cached_ascii_char_widths[c as usize] {
94 cached_width
95 } else {
96 let width = self.compute_width_for_char(c);
97 self.cached_ascii_char_widths[c as usize] = Some(width);
98 width
99 }
100 } else if let Some(cached_width) = self.cached_other_char_widths.get(&c) {
101 *cached_width
102 } else {
103 let width = self.compute_width_for_char(c);
104 self.cached_other_char_widths.insert(c, width);
105 width
106 }
107 }
108
109 fn compute_width_for_char(&self, c: char) -> Pixels {
110 let mut buffer = [0; 4];
111 let buffer = c.encode_utf8(&mut buffer);
112 self.platform_text_system
113 .layout_line(
114 buffer,
115 self.font_size,
116 &[FontRun {
117 len: 1,
118 font_id: self.font_id,
119 }],
120 )
121 .width
122 }
123}
124
125#[derive(Copy, Clone, Debug, PartialEq, Eq)]
126pub struct Boundary {
127 pub ix: usize,
128 pub next_indent: u32,
129}
130
131impl Boundary {
132 fn new(ix: usize, next_indent: u32) -> Self {
133 Self { ix, next_indent }
134 }
135}
136
137#[cfg(test)]
138mod tests {
139 use super::*;
140 use crate::{font, TestAppContext, TestDispatcher};
141 use rand::prelude::*;
142
143 #[test]
144 fn test_wrap_line() {
145 let dispatcher = TestDispatcher::new(StdRng::seed_from_u64(0));
146 let cx = TestAppContext::new(dispatcher);
147
148 cx.update(|cx| {
149 let text_system = cx.text_system().clone();
150 let mut wrapper = LineWrapper::new(
151 text_system.font_id(&font("Courier")).unwrap(),
152 px(16.),
153 text_system.platform_text_system.clone(),
154 );
155 assert_eq!(
156 wrapper
157 .wrap_line("aa bbb cccc ddddd eeee", px(72.))
158 .collect::<Vec<_>>(),
159 &[
160 Boundary::new(7, 0),
161 Boundary::new(12, 0),
162 Boundary::new(18, 0)
163 ],
164 );
165 assert_eq!(
166 wrapper
167 .wrap_line("aaa aaaaaaaaaaaaaaaaaa", px(72.0))
168 .collect::<Vec<_>>(),
169 &[
170 Boundary::new(4, 0),
171 Boundary::new(11, 0),
172 Boundary::new(18, 0)
173 ],
174 );
175 assert_eq!(
176 wrapper
177 .wrap_line(" aaaaaaa", px(72.))
178 .collect::<Vec<_>>(),
179 &[
180 Boundary::new(7, 5),
181 Boundary::new(9, 5),
182 Boundary::new(11, 5),
183 ]
184 );
185 assert_eq!(
186 wrapper
187 .wrap_line(" ", px(72.))
188 .collect::<Vec<_>>(),
189 &[
190 Boundary::new(7, 0),
191 Boundary::new(14, 0),
192 Boundary::new(21, 0)
193 ]
194 );
195 assert_eq!(
196 wrapper
197 .wrap_line(" aaaaaaaaaaaaaa", px(72.))
198 .collect::<Vec<_>>(),
199 &[
200 Boundary::new(7, 0),
201 Boundary::new(14, 3),
202 Boundary::new(18, 3),
203 Boundary::new(22, 3),
204 ]
205 );
206 });
207 }
208
209 // todo!("move this to a test on TextSystem::layout_text")
210 // todo! repeat this test
211 // #[test]
212 // fn test_wrap_shaped_line() {
213 // App::test().run(|cx| {
214 // let text_system = cx.text_system().clone();
215
216 // let normal = TextRun {
217 // len: 0,
218 // font: font("Helvetica"),
219 // color: Default::default(),
220 // underline: Default::default(),
221 // };
222 // let bold = TextRun {
223 // len: 0,
224 // font: font("Helvetica").bold(),
225 // color: Default::default(),
226 // underline: Default::default(),
227 // };
228
229 // impl TextRun {
230 // fn with_len(&self, len: usize) -> Self {
231 // let mut this = self.clone();
232 // this.len = len;
233 // this
234 // }
235 // }
236
237 // let text = "aa bbb cccc ddddd eeee".into();
238 // let lines = text_system
239 // .layout_text(
240 // &text,
241 // px(16.),
242 // &[
243 // normal.with_len(4),
244 // bold.with_len(5),
245 // normal.with_len(6),
246 // bold.with_len(1),
247 // normal.with_len(7),
248 // ],
249 // None,
250 // )
251 // .unwrap();
252 // let line = &lines[0];
253
254 // let mut wrapper = LineWrapper::new(
255 // text_system.font_id(&normal.font).unwrap(),
256 // px(16.),
257 // text_system.platform_text_system.clone(),
258 // );
259 // assert_eq!(
260 // wrapper
261 // .wrap_shaped_line(&text, &line, px(72.))
262 // .collect::<Vec<_>>(),
263 // &[
264 // ShapedBoundary {
265 // run_ix: 1,
266 // glyph_ix: 3
267 // },
268 // ShapedBoundary {
269 // run_ix: 2,
270 // glyph_ix: 3
271 // },
272 // ShapedBoundary {
273 // run_ix: 4,
274 // glyph_ix: 2
275 // }
276 // ],
277 // );
278 // });
279 // }
280}