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, TextRun, WrapBoundary};
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, None);
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 // For compatibility with the test macro
210 use crate as gpui;
211
212 #[crate::test]
213 fn test_wrap_shaped_line(cx: &mut TestAppContext) {
214 cx.update(|cx| {
215 let text_system = cx.text_system().clone();
216
217 let normal = TextRun {
218 len: 0,
219 font: font("Helvetica"),
220 color: Default::default(),
221 underline: Default::default(),
222 background_color: None,
223 };
224 let bold = TextRun {
225 len: 0,
226 font: font("Helvetica").bold(),
227 color: Default::default(),
228 underline: Default::default(),
229 background_color: None,
230 };
231
232 impl TextRun {
233 fn with_len(&self, len: usize) -> Self {
234 let mut this = self.clone();
235 this.len = len;
236 this
237 }
238 }
239
240 let text = "aa bbb cccc ddddd eeee".into();
241 let lines = text_system
242 .shape_text(
243 text,
244 px(16.),
245 &[
246 normal.with_len(4),
247 bold.with_len(5),
248 normal.with_len(6),
249 bold.with_len(1),
250 normal.with_len(7),
251 ],
252 Some(px(72.)),
253 )
254 .unwrap();
255
256 assert_eq!(
257 lines[0].layout.wrap_boundaries(),
258 &[
259 WrapBoundary {
260 run_ix: 1,
261 glyph_ix: 3
262 },
263 WrapBoundary {
264 run_ix: 2,
265 glyph_ix: 3
266 },
267 WrapBoundary {
268 run_ix: 4,
269 glyph_ix: 2
270 }
271 ],
272 );
273 });
274 }
275}