line_wrapper.rs

  1use crate::{px, FontId, 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 {
101            if let Some(cached_width) = self.cached_other_char_widths.get(&c) {
102                *cached_width
103            } else {
104                let width = self.compute_width_for_char(c);
105                self.cached_other_char_widths.insert(c, width);
106                width
107            }
108        }
109    }
110
111    fn compute_width_for_char(&self, c: char) -> Pixels {
112        let mut buffer = [0; 4];
113        let buffer = c.encode_utf8(&mut buffer);
114        self.platform_text_system
115            .layout_line(buffer, self.font_size, &[(1, self.font_id)])
116            .width
117    }
118}
119
120#[derive(Copy, Clone, Debug, PartialEq, Eq)]
121pub struct Boundary {
122    pub ix: usize,
123    pub next_indent: u32,
124}
125
126impl Boundary {
127    fn new(ix: usize, next_indent: u32) -> Self {
128        Self { ix, next_indent }
129    }
130}
131
132#[cfg(test)]
133mod tests {
134    use super::*;
135    use crate::{font, App};
136
137    #[test]
138    fn test_wrap_line() {
139        App::test().run(|cx| {
140            let text_system = cx.text_system().clone();
141            let mut wrapper = LineWrapper::new(
142                text_system.font_id(&font("Courier")).unwrap(),
143                px(16.),
144                text_system.platform_text_system.clone(),
145            );
146            assert_eq!(
147                wrapper
148                    .wrap_line("aa bbb cccc ddddd eeee", px(72.))
149                    .collect::<Vec<_>>(),
150                &[
151                    Boundary::new(7, 0),
152                    Boundary::new(12, 0),
153                    Boundary::new(18, 0)
154                ],
155            );
156            assert_eq!(
157                wrapper
158                    .wrap_line("aaa aaaaaaaaaaaaaaaaaa", px(72.0))
159                    .collect::<Vec<_>>(),
160                &[
161                    Boundary::new(4, 0),
162                    Boundary::new(11, 0),
163                    Boundary::new(18, 0)
164                ],
165            );
166            assert_eq!(
167                wrapper
168                    .wrap_line("     aaaaaaa", px(72.))
169                    .collect::<Vec<_>>(),
170                &[
171                    Boundary::new(7, 5),
172                    Boundary::new(9, 5),
173                    Boundary::new(11, 5),
174                ]
175            );
176            assert_eq!(
177                wrapper
178                    .wrap_line("                            ", px(72.))
179                    .collect::<Vec<_>>(),
180                &[
181                    Boundary::new(7, 0),
182                    Boundary::new(14, 0),
183                    Boundary::new(21, 0)
184                ]
185            );
186            assert_eq!(
187                wrapper
188                    .wrap_line("          aaaaaaaaaaaaaa", px(72.))
189                    .collect::<Vec<_>>(),
190                &[
191                    Boundary::new(7, 0),
192                    Boundary::new(14, 3),
193                    Boundary::new(18, 3),
194                    Boundary::new(22, 3),
195                ]
196            );
197        });
198    }
199
200    // todo!("move this to a test on TextSystem::layout_text")
201    // todo! repeat this test
202    // #[test]
203    // fn test_wrap_shaped_line() {
204    //     App::test().run(|cx| {
205    //         let text_system = cx.text_system().clone();
206
207    //         let normal = TextRun {
208    //             len: 0,
209    //             font: font("Helvetica"),
210    //             color: Default::default(),
211    //             underline: Default::default(),
212    //         };
213    //         let bold = TextRun {
214    //             len: 0,
215    //             font: font("Helvetica").bold(),
216    //             color: Default::default(),
217    //             underline: Default::default(),
218    //         };
219
220    //         impl TextRun {
221    //             fn with_len(&self, len: usize) -> Self {
222    //                 let mut this = self.clone();
223    //                 this.len = len;
224    //                 this
225    //             }
226    //         }
227
228    //         let text = "aa bbb cccc ddddd eeee".into();
229    //         let lines = text_system
230    //             .layout_text(
231    //                 &text,
232    //                 px(16.),
233    //                 &[
234    //                     normal.with_len(4),
235    //                     bold.with_len(5),
236    //                     normal.with_len(6),
237    //                     bold.with_len(1),
238    //                     normal.with_len(7),
239    //                 ],
240    //                 None,
241    //             )
242    //             .unwrap();
243    //         let line = &lines[0];
244
245    //         let mut wrapper = LineWrapper::new(
246    //             text_system.font_id(&normal.font).unwrap(),
247    //             px(16.),
248    //             text_system.platform_text_system.clone(),
249    //         );
250    //         assert_eq!(
251    //             wrapper
252    //                 .wrap_shaped_line(&text, &line, px(72.))
253    //                 .collect::<Vec<_>>(),
254    //             &[
255    //                 ShapedBoundary {
256    //                     run_ix: 1,
257    //                     glyph_ix: 3
258    //                 },
259    //                 ShapedBoundary {
260    //                     run_ix: 2,
261    //                     glyph_ix: 3
262    //                 },
263    //                 ShapedBoundary {
264    //                     run_ix: 4,
265    //                     glyph_ix: 2
266    //                 }
267    //             ],
268    //         );
269    //     });
270    // }
271}