Skip to main content

textflow/shaping/
complex.rs

1use super::{
2    validate_request, FontAccessError, FontId, FontMetrics, GlyphId, GlyphSource, ShapeError,
3    ShapeRequest, ShapedGlyph, SimpleTypeface, Typeface,
4};
5use crate::bidi::Direction;
6use crate::unicode::Script;
7use core::ops::Range;
8
9const OUTPUT_FLAGS: u16 = ShapedGlyph::UNSAFE_TO_BREAK;
10const MASK_SHIFT: u32 = 1;
11
12#[repr(transparent)]
13#[derive(Clone, Copy, Debug, Default, Eq, PartialEq)]
14pub struct GlyphMask(u16);
15
16impl GlyphMask {
17    pub const NONE: Self = Self(0);
18    pub const ALL: Self = Self(u16::MAX >> MASK_SHIFT);
19
20    pub const fn new(bits: u16) -> Self {
21        Self(bits & Self::ALL.0)
22    }
23
24    pub const fn bits(self) -> u16 {
25        self.0
26    }
27
28    pub const fn intersects(self, other: Self) -> bool {
29        self.0 & other.0 != 0
30    }
31}
32
33pub struct GlyphBuffer<'a> {
34    storage: &'a mut [ShapedGlyph],
35    len: usize,
36}
37
38impl<'a> GlyphBuffer<'a> {
39    pub fn new(storage: &'a mut [ShapedGlyph], len: usize) -> Result<Self, ShapeError> {
40        if len > storage.len() {
41            return Err(ShapeError::InsufficientCapacity { required: len });
42        }
43        Ok(Self { storage, len })
44    }
45
46    pub const fn len(&self) -> usize {
47        self.len
48    }
49
50    pub const fn is_empty(&self) -> bool {
51        self.len == 0
52    }
53
54    pub const fn capacity(&self) -> usize {
55        self.storage.len()
56    }
57
58    pub fn get(&self, index: usize) -> Option<&ShapedGlyph> {
59        self.storage.get(index).filter(|_| index < self.len)
60    }
61
62    pub fn get_mut(&mut self, index: usize) -> Option<&mut ShapedGlyph> {
63        if index >= self.len {
64            return None;
65        }
66        self.storage.get_mut(index)
67    }
68
69    pub fn glyphs(&self) -> &[ShapedGlyph] {
70        &self.storage[..self.len]
71    }
72
73    pub fn glyphs_mut(&mut self) -> &mut [ShapedGlyph] {
74        &mut self.storage[..self.len]
75    }
76
77    pub fn mask(&self, index: usize) -> Option<GlyphMask> {
78        self.get(index)
79            .map(|glyph| GlyphMask::new(glyph.flags >> MASK_SHIFT))
80    }
81
82    pub fn set_mask(&mut self, index: usize, mask: GlyphMask) -> Result<(), ShapeError> {
83        let glyph = self.get_mut(index).ok_or(ShapeError::InvalidGlyphRange)?;
84        glyph.flags = (glyph.flags & OUTPUT_FLAGS) | (mask.bits() << MASK_SHIFT);
85        Ok(())
86    }
87
88    pub fn set_glyph(&mut self, index: usize, glyph_id: GlyphId) -> Result<(), ShapeError> {
89        let glyph = self.get_mut(index).ok_or(ShapeError::InvalidGlyphRange)?;
90        glyph.glyph_id = glyph_id;
91        Ok(())
92    }
93
94    pub fn replace(
95        &mut self,
96        range: Range<usize>,
97        replacements: &[ShapedGlyph],
98    ) -> Result<(), ShapeError> {
99        self.replace_with(range, replacements.len(), |index| replacements[index])
100    }
101
102    pub fn replace_with(
103        &mut self,
104        range: Range<usize>,
105        replacement_len: usize,
106        mut replacement: impl FnMut(usize) -> ShapedGlyph,
107    ) -> Result<(), ShapeError> {
108        if range.start > range.end || range.end > self.len {
109            return Err(ShapeError::InvalidGlyphRange);
110        }
111        let removed = range.end - range.start;
112        let required = self
113            .len
114            .checked_sub(removed)
115            .and_then(|len| len.checked_add(replacement_len))
116            .ok_or(ShapeError::InsufficientCapacity {
117                required: usize::MAX,
118            })?;
119        if required > self.storage.len() {
120            return Err(ShapeError::InsufficientCapacity { required });
121        }
122        if replacement_len != removed {
123            self.storage
124                .copy_within(range.end..self.len, range.start + replacement_len);
125        }
126        for index in 0..replacement_len {
127            self.storage[range.start + index] = replacement(index);
128        }
129        self.len = required;
130        Ok(())
131    }
132
133    fn finish(&mut self) -> usize {
134        for glyph in &mut self.storage[..self.len] {
135            glyph.flags &= OUTPUT_FLAGS;
136        }
137        self.len
138    }
139}
140
141#[derive(Clone, Copy, Debug, Eq, PartialEq)]
142pub enum LookupStatus {
143    NotFound,
144    Applied,
145}
146
147#[derive(Clone, Copy)]
148pub struct LookupRequest<'a, 'text> {
149    shape: &'a ShapeRequest<'text>,
150    feature: [u8; 4],
151    mask: GlyphMask,
152}
153
154impl<'a, 'text> LookupRequest<'a, 'text> {
155    pub const fn new(shape: &'a ShapeRequest<'text>, feature: [u8; 4], mask: GlyphMask) -> Self {
156        Self {
157            shape,
158            feature,
159            mask,
160        }
161    }
162
163    pub const fn shape(self) -> &'a ShapeRequest<'text> {
164        self.shape
165    }
166
167    pub const fn feature(self) -> [u8; 4] {
168        self.feature
169    }
170
171    pub const fn mask(self) -> GlyphMask {
172        self.mask
173    }
174
175    pub const fn selects(self, glyph_mask: GlyphMask) -> bool {
176        self.mask.bits() == GlyphMask::ALL.bits() || self.mask.intersects(glyph_mask)
177    }
178}
179
180pub trait ShapingData {
181    fn substitute(
182        &self,
183        request: LookupRequest<'_, '_>,
184        glyphs: &mut GlyphBuffer<'_>,
185    ) -> Result<LookupStatus, ShapeError>;
186
187    fn position(
188        &self,
189        request: LookupRequest<'_, '_>,
190        glyphs: &mut GlyphBuffer<'_>,
191    ) -> Result<LookupStatus, ShapeError>;
192}
193
194pub trait ScriptProvider {
195    fn script(&self) -> Script;
196
197    fn substitute(
198        &self,
199        request: &ShapeRequest<'_>,
200        font: &dyn ShapingData,
201        glyphs: &mut GlyphBuffer<'_>,
202    ) -> Result<(), ShapeError>;
203
204    fn position(
205        &self,
206        request: &ShapeRequest<'_>,
207        font: &dyn ShapingData,
208        glyphs: &mut GlyphBuffer<'_>,
209    ) -> Result<(), ShapeError>;
210}
211
212pub struct ScriptTypeface<'a> {
213    glyphs: &'a dyn GlyphSource,
214    shaping: &'a dyn ShapingData,
215    scripts: &'a [&'a dyn ScriptProvider],
216}
217
218impl<'a> ScriptTypeface<'a> {
219    pub const fn new(glyphs: &'a dyn GlyphSource, shaping: &'a dyn ShapingData) -> Self {
220        Self {
221            glyphs,
222            shaping,
223            scripts: &[],
224        }
225    }
226
227    pub const fn with_scripts(mut self, scripts: &'a [&'a dyn ScriptProvider]) -> Self {
228        self.scripts = scripts;
229        self
230    }
231
232    fn provider(&self, script: Script) -> Option<&dyn ScriptProvider> {
233        self.scripts
234            .iter()
235            .copied()
236            .find(|provider| provider.script() == script)
237    }
238
239    fn map_into(
240        &self,
241        request: &ShapeRequest<'_>,
242        output: &mut [ShapedGlyph],
243    ) -> Result<usize, ShapeError> {
244        let text = &request.text[request.range.clone()];
245        let required = text.chars().count();
246        if output.len() < required {
247            return Err(ShapeError::InsufficientCapacity { required });
248        }
249        for (slot, (offset, character)) in output.iter_mut().zip(text.char_indices()) {
250            let start = request.range.start + offset;
251            let end = start + character.len_utf8();
252            let glyph = self
253                .glyphs
254                .glyph_for(character)?
255                .or(self.glyphs.notdef_glyph()?)
256                .ok_or(ShapeError::MissingGlyph { offset: start })?;
257            *slot = ShapedGlyph::new(glyph, super::TextRange::new(start as u32, end as u32));
258        }
259        Ok(required)
260    }
261}
262
263impl Typeface for ScriptTypeface<'_> {
264    fn id(&self) -> FontId {
265        self.glyphs.id()
266    }
267
268    fn metrics(&self) -> Result<FontMetrics, FontAccessError> {
269        self.glyphs.metrics()
270    }
271
272    fn covers(&self, grapheme: &str) -> Result<bool, FontAccessError> {
273        for character in grapheme.chars() {
274            if self.glyphs.glyph_for(character)?.is_none() {
275                return Ok(false);
276            }
277        }
278        Ok(!grapheme.is_empty())
279    }
280
281    fn supports_complex_shaping(&self) -> bool {
282        true
283    }
284
285    fn shape_into(
286        &self,
287        request: &ShapeRequest<'_>,
288        output: &mut [ShapedGlyph],
289    ) -> Result<usize, ShapeError> {
290        validate_request(request)?;
291        let Some(provider) = self.provider(request.script) else {
292            return SimpleTypeface::new(self.glyphs).shape_into(request, output);
293        };
294        let count = self.map_into(request, output)?;
295        let mut glyphs = GlyphBuffer::new(output, count)?;
296        provider.substitute(request, self.shaping, &mut glyphs)?;
297        for glyph in glyphs.glyphs_mut() {
298            glyph.advance = self.glyphs.glyph_advance(glyph.glyph_id())?;
299        }
300        provider.position(request, self.shaping, &mut glyphs)?;
301        let count = glyphs.finish();
302        if request.direction == Direction::RightToLeft {
303            output[..count].reverse();
304        }
305        Ok(count)
306    }
307}
308
309#[cfg(test)]
310mod tests {
311    use super::*;
312    use crate::shaping::{FlowPoint, TextRange};
313
314    struct Font;
315
316    impl GlyphSource for Font {
317        fn id(&self) -> FontId {
318            FontId::new(7)
319        }
320
321        fn metrics(&self) -> Result<FontMetrics, FontAccessError> {
322            Ok(FontMetrics::default())
323        }
324
325        fn glyph_for(&self, character: char) -> Result<Option<GlyphId>, FontAccessError> {
326            Ok(Some(GlyphId::new(character as u16)))
327        }
328
329        fn glyph_advance(&self, glyph: GlyphId) -> Result<FlowPoint, FontAccessError> {
330            Ok(FlowPoint {
331                x: i32::from(glyph.value()),
332                y: 0,
333            })
334        }
335    }
336
337    struct Data;
338
339    impl ShapingData for Data {
340        fn substitute(
341            &self,
342            request: LookupRequest<'_, '_>,
343            glyphs: &mut GlyphBuffer<'_>,
344        ) -> Result<LookupStatus, ShapeError> {
345            if request.feature() != *b"test" {
346                return Ok(LookupStatus::NotFound);
347            }
348            glyphs.set_glyph(0, GlyphId::new(9)).unwrap();
349            Ok(LookupStatus::Applied)
350        }
351
352        fn position(
353            &self,
354            request: LookupRequest<'_, '_>,
355            glyphs: &mut GlyphBuffer<'_>,
356        ) -> Result<LookupStatus, ShapeError> {
357            if request.feature() != *b"mark" {
358                return Ok(LookupStatus::NotFound);
359            }
360            glyphs.get_mut(1).unwrap().offset.y = -3;
361            Ok(LookupStatus::Applied)
362        }
363    }
364
365    struct Provider;
366
367    impl ScriptProvider for Provider {
368        fn script(&self) -> Script {
369            Script::Thai
370        }
371
372        fn substitute(
373            &self,
374            request: &ShapeRequest<'_>,
375            font: &dyn ShapingData,
376            glyphs: &mut GlyphBuffer<'_>,
377        ) -> Result<(), ShapeError> {
378            glyphs.set_mask(0, GlyphMask::new(1))?;
379            font.substitute(
380                LookupRequest::new(request, *b"test", GlyphMask::new(1)),
381                glyphs,
382            )?;
383            Ok(())
384        }
385
386        fn position(
387            &self,
388            request: &ShapeRequest<'_>,
389            font: &dyn ShapingData,
390            glyphs: &mut GlyphBuffer<'_>,
391        ) -> Result<(), ShapeError> {
392            font.position(
393                LookupRequest::new(request, *b"mark", GlyphMask::ALL),
394                glyphs,
395            )?;
396            Ok(())
397        }
398    }
399
400    #[test]
401    fn glyph_buffer_replaces_in_place_and_reports_capacity() {
402        let mut storage = [ShapedGlyph::default(); 3];
403        storage[0] = ShapedGlyph::new(GlyphId::new(1), TextRange::new(0, 1));
404        storage[1] = ShapedGlyph::new(GlyphId::new(2), TextRange::new(1, 2));
405        let mut buffer = GlyphBuffer::new(&mut storage, 2).unwrap();
406        let replacements = [
407            ShapedGlyph::new(GlyphId::new(3), TextRange::new(0, 1)),
408            ShapedGlyph::new(GlyphId::new(4), TextRange::new(0, 1)),
409        ];
410        buffer.replace(0..1, &replacements).unwrap();
411        assert_eq!(buffer.len(), 3);
412        assert_eq!(buffer.get(2).unwrap().glyph_id(), GlyphId::new(2));
413
414        let before = *buffer.get(0).unwrap();
415        assert_eq!(
416            buffer.replace(0..1, &replacements),
417            Err(ShapeError::InsufficientCapacity { required: 4 })
418        );
419        assert_eq!(*buffer.get(0).unwrap(), before);
420    }
421
422    #[test]
423    fn glyph_buffer_builds_variable_replacements_in_caller_storage() {
424        let mut storage = [ShapedGlyph::default(); 4];
425        storage[0] = ShapedGlyph::new(GlyphId::new(1), TextRange::new(0, 1));
426        storage[1] = ShapedGlyph::new(GlyphId::new(2), TextRange::new(1, 2));
427        let mut buffer = GlyphBuffer::new(&mut storage, 2).unwrap();
428
429        buffer
430            .replace_with(0..1, 3, |index| {
431                ShapedGlyph::new(GlyphId::new(10 + index as u16), TextRange::new(0, 1))
432            })
433            .unwrap();
434
435        assert_eq!(buffer.len(), 4);
436        assert_eq!(buffer.get(0).unwrap().glyph_id(), GlyphId::new(10));
437        assert_eq!(buffer.get(1).unwrap().glyph_id(), GlyphId::new(11));
438        assert_eq!(buffer.get(2).unwrap().glyph_id(), GlyphId::new(12));
439        assert_eq!(buffer.get(3).unwrap().glyph_id(), GlyphId::new(2));
440    }
441
442    #[test]
443    fn all_lookup_mask_selects_unmarked_glyphs() {
444        let shape = ShapeRequest::new("a", 0..1, Direction::LeftToRight, Script::Latin);
445        let all = LookupRequest::new(&shape, *b"ccmp", GlyphMask::ALL);
446        let form = LookupRequest::new(&shape, *b"init", GlyphMask::new(1));
447
448        assert!(all.selects(GlyphMask::NONE));
449        assert!(form.selects(GlyphMask::new(1)));
450        assert!(!form.selects(GlyphMask::NONE));
451    }
452
453    #[test]
454    fn script_typeface_runs_provider_without_heap_storage() {
455        let providers: [&dyn ScriptProvider; 1] = [&Provider];
456        let face = ScriptTypeface::new(&Font, &Data).with_scripts(&providers);
457        let text = "กิ";
458        let request = ShapeRequest::new(text, 0..text.len(), Direction::LeftToRight, Script::Thai);
459        let mut output = [ShapedGlyph::default(); 2];
460
461        let count = face.shape_into(&request, &mut output).unwrap();
462
463        assert_eq!(count, 2);
464        assert_eq!(output[0].glyph_id(), GlyphId::new(9));
465        assert_eq!(output[0].advance.x, 9);
466        assert_eq!(output[1].offset.y, -3);
467    }
468}