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        if range.start > range.end || range.end > self.len {
100            return Err(ShapeError::InvalidGlyphRange);
101        }
102        let removed = range.end - range.start;
103        let required = self
104            .len
105            .checked_sub(removed)
106            .and_then(|len| len.checked_add(replacements.len()))
107            .ok_or(ShapeError::InsufficientCapacity {
108                required: usize::MAX,
109            })?;
110        if required > self.storage.len() {
111            return Err(ShapeError::InsufficientCapacity { required });
112        }
113        if replacements.len() != removed {
114            self.storage
115                .copy_within(range.end..self.len, range.start + replacements.len());
116        }
117        self.storage[range.start..range.start + replacements.len()].copy_from_slice(replacements);
118        self.len = required;
119        Ok(())
120    }
121
122    fn finish(&mut self) -> usize {
123        for glyph in &mut self.storage[..self.len] {
124            glyph.flags &= OUTPUT_FLAGS;
125        }
126        self.len
127    }
128}
129
130#[derive(Clone, Copy, Debug, Eq, PartialEq)]
131pub enum LookupStatus {
132    NotFound,
133    Applied,
134}
135
136#[derive(Clone, Copy)]
137pub struct LookupRequest<'a, 'text> {
138    shape: &'a ShapeRequest<'text>,
139    feature: [u8; 4],
140    mask: GlyphMask,
141}
142
143impl<'a, 'text> LookupRequest<'a, 'text> {
144    pub const fn new(shape: &'a ShapeRequest<'text>, feature: [u8; 4], mask: GlyphMask) -> Self {
145        Self {
146            shape,
147            feature,
148            mask,
149        }
150    }
151
152    pub const fn shape(self) -> &'a ShapeRequest<'text> {
153        self.shape
154    }
155
156    pub const fn feature(self) -> [u8; 4] {
157        self.feature
158    }
159
160    pub const fn mask(self) -> GlyphMask {
161        self.mask
162    }
163}
164
165pub trait ShapingData {
166    fn substitute(
167        &self,
168        request: LookupRequest<'_, '_>,
169        glyphs: &mut GlyphBuffer<'_>,
170    ) -> Result<LookupStatus, ShapeError>;
171
172    fn position(
173        &self,
174        request: LookupRequest<'_, '_>,
175        glyphs: &mut GlyphBuffer<'_>,
176    ) -> Result<LookupStatus, ShapeError>;
177}
178
179pub trait ScriptProvider {
180    fn script(&self) -> Script;
181
182    fn substitute(
183        &self,
184        request: &ShapeRequest<'_>,
185        font: &dyn ShapingData,
186        glyphs: &mut GlyphBuffer<'_>,
187    ) -> Result<(), ShapeError>;
188
189    fn position(
190        &self,
191        request: &ShapeRequest<'_>,
192        font: &dyn ShapingData,
193        glyphs: &mut GlyphBuffer<'_>,
194    ) -> Result<(), ShapeError>;
195}
196
197pub struct ScriptTypeface<'a> {
198    glyphs: &'a dyn GlyphSource,
199    shaping: &'a dyn ShapingData,
200    scripts: &'a [&'a dyn ScriptProvider],
201}
202
203impl<'a> ScriptTypeface<'a> {
204    pub const fn new(glyphs: &'a dyn GlyphSource, shaping: &'a dyn ShapingData) -> Self {
205        Self {
206            glyphs,
207            shaping,
208            scripts: &[],
209        }
210    }
211
212    pub const fn with_scripts(mut self, scripts: &'a [&'a dyn ScriptProvider]) -> Self {
213        self.scripts = scripts;
214        self
215    }
216
217    fn provider(&self, script: Script) -> Option<&dyn ScriptProvider> {
218        self.scripts
219            .iter()
220            .copied()
221            .find(|provider| provider.script() == script)
222    }
223
224    fn map_into(
225        &self,
226        request: &ShapeRequest<'_>,
227        output: &mut [ShapedGlyph],
228    ) -> Result<usize, ShapeError> {
229        let text = &request.text[request.range.clone()];
230        let required = text.chars().count();
231        if output.len() < required {
232            return Err(ShapeError::InsufficientCapacity { required });
233        }
234        for (slot, (offset, character)) in output.iter_mut().zip(text.char_indices()) {
235            let start = request.range.start + offset;
236            let end = start + character.len_utf8();
237            let glyph = self
238                .glyphs
239                .glyph_for(character)?
240                .or(self.glyphs.notdef_glyph()?)
241                .ok_or(ShapeError::MissingGlyph { offset: start })?;
242            *slot = ShapedGlyph::new(glyph, super::TextRange::new(start as u32, end as u32));
243        }
244        Ok(required)
245    }
246}
247
248impl Typeface for ScriptTypeface<'_> {
249    fn id(&self) -> FontId {
250        self.glyphs.id()
251    }
252
253    fn metrics(&self) -> Result<FontMetrics, FontAccessError> {
254        self.glyphs.metrics()
255    }
256
257    fn covers(&self, grapheme: &str) -> Result<bool, FontAccessError> {
258        for character in grapheme.chars() {
259            if self.glyphs.glyph_for(character)?.is_none() {
260                return Ok(false);
261            }
262        }
263        Ok(!grapheme.is_empty())
264    }
265
266    fn supports_complex_shaping(&self) -> bool {
267        true
268    }
269
270    fn shape_into(
271        &self,
272        request: &ShapeRequest<'_>,
273        output: &mut [ShapedGlyph],
274    ) -> Result<usize, ShapeError> {
275        validate_request(request)?;
276        let Some(provider) = self.provider(request.script) else {
277            return SimpleTypeface::new(self.glyphs).shape_into(request, output);
278        };
279        let count = self.map_into(request, output)?;
280        let mut glyphs = GlyphBuffer::new(output, count)?;
281        provider.substitute(request, self.shaping, &mut glyphs)?;
282        for glyph in glyphs.glyphs_mut() {
283            glyph.advance = self.glyphs.glyph_advance(glyph.glyph_id())?;
284        }
285        provider.position(request, self.shaping, &mut glyphs)?;
286        let count = glyphs.finish();
287        if request.direction == Direction::RightToLeft {
288            output[..count].reverse();
289        }
290        Ok(count)
291    }
292}
293
294#[cfg(test)]
295mod tests {
296    use super::*;
297    use crate::shaping::{FlowPoint, TextRange};
298
299    struct Font;
300
301    impl GlyphSource for Font {
302        fn id(&self) -> FontId {
303            FontId::new(7)
304        }
305
306        fn metrics(&self) -> Result<FontMetrics, FontAccessError> {
307            Ok(FontMetrics::default())
308        }
309
310        fn glyph_for(&self, character: char) -> Result<Option<GlyphId>, FontAccessError> {
311            Ok(Some(GlyphId::new(character as u16)))
312        }
313
314        fn glyph_advance(&self, glyph: GlyphId) -> Result<FlowPoint, FontAccessError> {
315            Ok(FlowPoint {
316                x: i32::from(glyph.value()),
317                y: 0,
318            })
319        }
320    }
321
322    struct Data;
323
324    impl ShapingData for Data {
325        fn substitute(
326            &self,
327            request: LookupRequest<'_, '_>,
328            glyphs: &mut GlyphBuffer<'_>,
329        ) -> Result<LookupStatus, ShapeError> {
330            if request.feature() != *b"test" {
331                return Ok(LookupStatus::NotFound);
332            }
333            glyphs.set_glyph(0, GlyphId::new(9)).unwrap();
334            Ok(LookupStatus::Applied)
335        }
336
337        fn position(
338            &self,
339            request: LookupRequest<'_, '_>,
340            glyphs: &mut GlyphBuffer<'_>,
341        ) -> Result<LookupStatus, ShapeError> {
342            if request.feature() != *b"mark" {
343                return Ok(LookupStatus::NotFound);
344            }
345            glyphs.get_mut(1).unwrap().offset.y = -3;
346            Ok(LookupStatus::Applied)
347        }
348    }
349
350    struct Provider;
351
352    impl ScriptProvider for Provider {
353        fn script(&self) -> Script {
354            Script::Thai
355        }
356
357        fn substitute(
358            &self,
359            request: &ShapeRequest<'_>,
360            font: &dyn ShapingData,
361            glyphs: &mut GlyphBuffer<'_>,
362        ) -> Result<(), ShapeError> {
363            glyphs.set_mask(0, GlyphMask::new(1))?;
364            font.substitute(
365                LookupRequest::new(request, *b"test", GlyphMask::new(1)),
366                glyphs,
367            )?;
368            Ok(())
369        }
370
371        fn position(
372            &self,
373            request: &ShapeRequest<'_>,
374            font: &dyn ShapingData,
375            glyphs: &mut GlyphBuffer<'_>,
376        ) -> Result<(), ShapeError> {
377            font.position(
378                LookupRequest::new(request, *b"mark", GlyphMask::ALL),
379                glyphs,
380            )?;
381            Ok(())
382        }
383    }
384
385    #[test]
386    fn glyph_buffer_replaces_in_place_and_reports_capacity() {
387        let mut storage = [ShapedGlyph::default(); 3];
388        storage[0] = ShapedGlyph::new(GlyphId::new(1), TextRange::new(0, 1));
389        storage[1] = ShapedGlyph::new(GlyphId::new(2), TextRange::new(1, 2));
390        let mut buffer = GlyphBuffer::new(&mut storage, 2).unwrap();
391        let replacements = [
392            ShapedGlyph::new(GlyphId::new(3), TextRange::new(0, 1)),
393            ShapedGlyph::new(GlyphId::new(4), TextRange::new(0, 1)),
394        ];
395        buffer.replace(0..1, &replacements).unwrap();
396        assert_eq!(buffer.len(), 3);
397        assert_eq!(buffer.get(2).unwrap().glyph_id(), GlyphId::new(2));
398
399        let before = *buffer.get(0).unwrap();
400        assert_eq!(
401            buffer.replace(0..1, &replacements),
402            Err(ShapeError::InsufficientCapacity { required: 4 })
403        );
404        assert_eq!(*buffer.get(0).unwrap(), before);
405    }
406
407    #[test]
408    fn script_typeface_runs_provider_without_heap_storage() {
409        let providers: [&dyn ScriptProvider; 1] = [&Provider];
410        let face = ScriptTypeface::new(&Font, &Data).with_scripts(&providers);
411        let text = "กิ";
412        let request = ShapeRequest::new(text, 0..text.len(), Direction::LeftToRight, Script::Thai);
413        let mut output = [ShapedGlyph::default(); 2];
414
415        let count = face.shape_into(&request, &mut output).unwrap();
416
417        assert_eq!(count, 2);
418        assert_eq!(output[0].glyph_id(), GlyphId::new(9));
419        assert_eq!(output[0].advance.x, 9);
420        assert_eq!(output[1].offset.y, -3);
421    }
422}