skia_safe/core/
text_blob.rs

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
use std::{fmt, ptr, slice};

use skia_bindings::{
    self as sb, SkTextBlob, SkTextBlobBuilder, SkTextBlob_Iter, SkTextBlob_Iter_Run, SkTypeface,
};

use crate::{
    prelude::*, scalar, EncodedText, Font, GlyphId, Paint, Point, RSXform, Rect, Typeface,
};

pub type TextBlob = RCHandle<SkTextBlob>;
unsafe_send_sync!(TextBlob);
require_base_type!(SkTextBlob, sb::SkNVRefCnt);

impl NativeRefCounted for SkTextBlob {
    fn _ref(&self) {
        unsafe { sb::C_SkTextBlob_ref(self) };
    }

    fn _unref(&self) {
        unsafe { sb::C_SkTextBlob_unref(self) }
    }

    fn unique(&self) -> bool {
        unsafe { sb::C_SkTextBlob_unique(self) }
    }
}

impl fmt::Debug for TextBlob {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.debug_struct("TextBlob")
            .field("bounds", &self.bounds())
            .field("unique_id", &self.unique_id())
            .finish()
    }
}

impl TextBlob {
    pub fn new(str: impl AsRef<str>, font: &Font) -> Option<Self> {
        Self::from_str(str, font)
    }

    pub fn bounds(&self) -> &Rect {
        Rect::from_native_ref(&self.native().fBounds)
    }

    pub fn unique_id(&self) -> u32 {
        self.native().fUniqueID
    }

    // TODO: consider to provide an inplace variant.
    pub fn get_intercepts(&self, bounds: [scalar; 2], paint: Option<&Paint>) -> Vec<scalar> {
        unsafe {
            let count = self.native().getIntercepts(
                bounds.as_ptr(),
                ptr::null_mut(),
                paint.native_ptr_or_null(),
            );
            let mut intervals = vec![Default::default(); count.try_into().unwrap()];
            let count_2 = self.native().getIntercepts(
                bounds.as_ptr(),
                intervals.as_mut_ptr(),
                paint.native_ptr_or_null(),
            );
            assert_eq!(count, count_2);
            intervals
        }
    }

    pub fn from_str(str: impl AsRef<str>, font: &Font) -> Option<TextBlob> {
        Self::from_text(str.as_ref(), font)
    }

    pub fn from_text(text: impl EncodedText, font: &Font) -> Option<TextBlob> {
        let (ptr, size, encoding) = text.as_raw();
        TextBlob::from_ptr(unsafe {
            sb::C_SkTextBlob_MakeFromText(ptr, size, font.native(), encoding.into_native())
        })
    }

    pub fn from_pos_text_h(
        text: impl EncodedText,
        x_pos: &[scalar],
        const_y: scalar,
        font: &Font,
    ) -> Option<TextBlob> {
        // TODO: avoid that somehow.
        assert_eq!(x_pos.len(), font.count_text(&text));
        let (ptr, size, encoding) = text.as_raw();
        TextBlob::from_ptr(unsafe {
            sb::C_SkTextBlob_MakeFromPosTextH(
                ptr,
                size,
                x_pos.as_ptr(),
                const_y,
                font.native(),
                encoding.into_native(),
            )
        })
    }

    pub fn from_pos_text(text: impl EncodedText, pos: &[Point], font: &Font) -> Option<TextBlob> {
        assert_eq!(pos.len(), font.count_text(&text));
        let (ptr, size, encoding) = text.as_raw();
        TextBlob::from_ptr(unsafe {
            sb::C_SkTextBlob_MakeFromPosText(
                ptr,
                size,
                pos.native().as_ptr(),
                font.native(),
                encoding.into_native(),
            )
        })
    }

    pub fn from_rsxform(
        text: impl EncodedText,
        xform: &[RSXform],
        font: &Font,
    ) -> Option<TextBlob> {
        assert_eq!(xform.len(), font.count_text(&text));
        let (ptr, size, encoding) = text.as_raw();
        TextBlob::from_ptr(unsafe {
            sb::C_SkTextBlob_MakeFromRSXform(
                ptr,
                size,
                xform.native().as_ptr(),
                font.native(),
                encoding.into_native(),
            )
        })
    }
}

pub type TextBlobBuilder = Handle<SkTextBlobBuilder>;
unsafe_send_sync!(TextBlobBuilder);

impl NativeDrop for SkTextBlobBuilder {
    fn drop(&mut self) {
        unsafe { sb::C_SkTextBlobBuilder_destruct(self) }
    }
}

impl fmt::Debug for TextBlobBuilder {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.debug_struct("TextBlobBuilder").finish()
    }
}

impl TextBlobBuilder {
    pub fn new() -> Self {
        Self::from_native_c(unsafe { SkTextBlobBuilder::new() })
    }

    pub fn make(&mut self) -> Option<TextBlob> {
        TextBlob::from_ptr(unsafe { sb::C_SkTextBlobBuilder_make(self.native_mut()) })
    }

    pub fn alloc_run(
        &mut self,
        font: &Font,
        count: usize,
        offset: impl Into<Point>,
        bounds: Option<&Rect>,
    ) -> &mut [GlyphId] {
        let offset = offset.into();
        unsafe {
            let buffer = &*self.native_mut().allocRun(
                font.native(),
                count.try_into().unwrap(),
                offset.x,
                offset.y,
                bounds.native_ptr_or_null(),
            );
            safer::from_raw_parts_mut(buffer.glyphs, count)
        }
    }

    pub fn alloc_run_pos_h(
        &mut self,
        font: &Font,
        count: usize,
        y: scalar,
        bounds: Option<&Rect>,
    ) -> (&mut [GlyphId], &mut [scalar]) {
        unsafe {
            let buffer = &*self.native_mut().allocRunPosH(
                font.native(),
                count.try_into().unwrap(),
                y,
                bounds.native_ptr_or_null(),
            );
            (
                safer::from_raw_parts_mut(buffer.glyphs, count),
                safer::from_raw_parts_mut(buffer.pos, count),
            )
        }
    }

    pub fn alloc_run_pos(
        &mut self,
        font: &Font,
        count: usize,
        bounds: Option<&Rect>,
    ) -> (&mut [GlyphId], &mut [Point]) {
        unsafe {
            let buffer = &*self.native_mut().allocRunPos(
                font.native(),
                count.try_into().unwrap(),
                bounds.native_ptr_or_null(),
            );
            (
                safer::from_raw_parts_mut(buffer.glyphs, count),
                safer::from_raw_parts_mut(buffer.pos as *mut Point, count),
            )
        }
    }

    pub fn alloc_run_rsxform(
        &mut self,
        font: &Font,
        count: usize,
    ) -> (&mut [GlyphId], &mut [RSXform]) {
        unsafe {
            let buffer = &*self
                .native_mut()
                .allocRunRSXform(font.native(), count.try_into().unwrap());
            (
                safer::from_raw_parts_mut(buffer.glyphs, count),
                safer::from_raw_parts_mut(buffer.pos as *mut RSXform, count),
            )
        }
    }

    pub fn alloc_run_text(
        &mut self,
        font: &Font,
        count: usize,
        offset: impl Into<Point>,
        text_byte_count: usize,
        bounds: Option<&Rect>,
    ) -> (&mut [GlyphId], &mut [u8], &mut [u32]) {
        let offset = offset.into();
        unsafe {
            let buffer = &*self.native_mut().allocRunText(
                font.native(),
                count.try_into().unwrap(),
                offset.x,
                offset.y,
                text_byte_count.try_into().unwrap(),
                bounds.native_ptr_or_null(),
            );
            (
                safer::from_raw_parts_mut(buffer.glyphs, count),
                safer::from_raw_parts_mut(buffer.utf8text as *mut u8, text_byte_count),
                safer::from_raw_parts_mut(buffer.clusters, count),
            )
        }
    }

    pub fn alloc_run_text_pos_h(
        &mut self,
        font: &Font,
        count: usize,
        y: scalar,
        text_byte_count: usize,
        bounds: Option<&Rect>,
    ) -> (&mut [GlyphId], &mut [scalar], &mut [u8], &mut [u32]) {
        unsafe {
            let buffer = &*self.native_mut().allocRunTextPosH(
                font.native(),
                count.try_into().unwrap(),
                y,
                text_byte_count.try_into().unwrap(),
                bounds.native_ptr_or_null(),
            );
            (
                safer::from_raw_parts_mut(buffer.glyphs, count),
                safer::from_raw_parts_mut(buffer.pos, count),
                safer::from_raw_parts_mut(buffer.utf8text as *mut u8, text_byte_count),
                safer::from_raw_parts_mut(buffer.clusters, count),
            )
        }
    }

    pub fn alloc_run_text_pos(
        &mut self,
        font: &Font,
        count: usize,
        text_byte_count: usize,
        bounds: Option<&Rect>,
    ) -> (&mut [GlyphId], &mut [Point], &mut [u8], &mut [u32]) {
        unsafe {
            let buffer = &*self.native_mut().allocRunTextPos(
                font.native(),
                count.try_into().unwrap(),
                text_byte_count.try_into().unwrap(),
                bounds.native_ptr_or_null(),
            );
            (
                safer::from_raw_parts_mut(buffer.glyphs, count),
                safer::from_raw_parts_mut(buffer.pos as *mut Point, count),
                safer::from_raw_parts_mut(buffer.utf8text as *mut u8, text_byte_count),
                safer::from_raw_parts_mut(buffer.clusters, count),
            )
        }
    }

    pub fn alloc_run_text_rsxform(
        &mut self,
        font: &Font,
        count: usize,
        text_byte_count: usize,
        bounds: Option<&Rect>,
    ) -> (&mut [GlyphId], &mut [RSXform], &mut [u8], &mut [u32]) {
        unsafe {
            let buffer = &*self.native_mut().allocRunTextPos(
                font.native(),
                count.try_into().unwrap(),
                text_byte_count.try_into().unwrap(),
                bounds.native_ptr_or_null(),
            );
            (
                safer::from_raw_parts_mut(buffer.glyphs, count),
                safer::from_raw_parts_mut(buffer.pos as *mut RSXform, count),
                safer::from_raw_parts_mut(buffer.utf8text as *mut u8, text_byte_count),
                safer::from_raw_parts_mut(buffer.clusters, count),
            )
        }
    }
}

pub type TextBlobIter<'a> = Borrows<'a, Handle<SkTextBlob_Iter>>;

pub struct TextBlobRun<'a> {
    typeface: *mut SkTypeface,
    pub glyph_indices: &'a [u16],
}

impl fmt::Debug for TextBlobRun<'_> {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.debug_struct("TextBlobRun")
            .field("typeface", self.typeface())
            .field("glyph_indices", &self.glyph_indices)
            .finish()
    }
}

impl TextBlobRun<'_> {
    pub fn typeface(&self) -> &Option<Typeface> {
        Typeface::from_unshared_ptr_ref(&self.typeface)
    }
}

impl<'a> Borrows<'a, Handle<SkTextBlob_Iter>> {
    pub fn new(text_blob: &'a TextBlob) -> Self {
        Handle::from_native_c(unsafe { SkTextBlob_Iter::new(text_blob.native()) })
            .borrows(text_blob)
    }
}

impl NativeDrop for SkTextBlob_Iter {
    fn drop(&mut self) {
        unsafe { sb::C_SkTextBlob_Iter_destruct(self) }
    }
}

impl<'a> Iterator for Borrows<'a, Handle<SkTextBlob_Iter>> {
    type Item = TextBlobRun<'a>;
    fn next(&mut self) -> Option<Self::Item> {
        let mut run = SkTextBlob_Iter_Run {
            fTypeface: ptr::null_mut(),
            fGlyphCount: 0,
            fGlyphIndices: ptr::null_mut(),
        };
        unsafe {
            if self.native_mut().next(&mut run) {
                let indices = if !run.fGlyphIndices.is_null() && run.fGlyphCount != 0 {
                    slice::from_raw_parts(run.fGlyphIndices, run.fGlyphCount.try_into().unwrap())
                } else {
                    &[]
                };

                Some(TextBlobRun {
                    typeface: run.fTypeface,
                    glyph_indices: indices,
                })
            } else {
                None
            }
        }
    }
}

#[test]
fn test_point_size_and_alignment_equals_size_of_two_scalars_used_in_alloc_run_pos() {
    use std::mem;
    assert_eq!(mem::size_of::<Point>(), mem::size_of::<[scalar; 2]>());
    assert_eq!(mem::align_of::<Point>(), mem::align_of::<[scalar; 2]>());
}