tectonic_xetex_layout 0.3.3

XeTeX's font loading and layout interface encapsulation, as a crate.
Documentation
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
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
//! Font handling - specific fonts used by an engine while shaping text.

use crate::c_api::{Fixed, GlyphBBox, GlyphID, PlatformFontRef};
use crate::utils::fix_to_d;
use std::ffi::{CStr, CString};
use std::path::Path;
use std::str::FromStr;
use std::sync::{Arc, Mutex, OnceLock};
use tectonic_bridge_core::{CoreBridgeState, FileFormat};
#[cfg(not(target_os = "macos"))]
use tectonic_bridge_fontconfig as fc;
use tectonic_bridge_freetype2 as ft;
use tectonic_bridge_harfbuzz as hb;
#[cfg(target_os = "macos")]
use tectonic_mac_core::{
    CFArray, CFDictionary, CFType, CFUrl, CTFont, CTFontDescriptor, FontAttribute, FontNameKey,
};

fn get_glyph_advance(face: &ft::Face, gid: libc::c_uint, vertical: bool) -> ft::Fixed {
    let flags = if vertical {
        ft::LoadFlags::NO_SCALE | ft::LoadFlags::VERTICAL_LAYOUT
    } else {
        ft::LoadFlags::NO_SCALE
    };
    let out = match face.get_advance(gid, flags) {
        Ok(advance) => {
            if vertical {
                -advance
            } else {
                advance
            }
        }
        Err(_) => 0,
    };
    out as ft::Fixed
}

fn get_font_funcs() -> hb::FontFuncsRef<'static, Arc<Mutex<ft::Face>>> {
    static FONTS: OnceLock<hb::ImmutFontFuncs<Arc<Mutex<ft::Face>>>> = OnceLock::new();

    FONTS
        .get_or_init(|| {
            let mut funcs = hb::FontFuncs::<Arc<Mutex<ft::Face>>>::new();

            let mut f = funcs.as_mut();
            f.nominal_glyph_func(|_, face, ch| {
                face.lock().unwrap().get_char_index(ch).map(|cc| cc.get())
            });
            f.variation_glyph_func(|_, face, ch, vs| {
                face.lock()
                    .unwrap()
                    .get_char_variant_index(ch, vs)
                    .map(|cc| cc.get())
            });
            f.glyph_h_advance(|_, face, gid| {
                get_glyph_advance(&face.lock().unwrap(), gid, false) as hb::Position
            });
            f.glyph_v_advance(|_, face, gid| {
                get_glyph_advance(&face.lock().unwrap(), gid, true) as hb::Position
            });
            f.glyph_h_origin(|_, _, _| Some((0, 0)));
            f.glyph_v_origin(|_, _, _| {
                Some((0, 0))

                // TODO
                // Keep the code below for reference, for now we want to keep vertical
                // origin at (0, 0) for compatibility with pre-0.9999.
                // Reconsider this (e.g. using BASE table) when we get around overhauling
                // the text directionality model and implementing real vertical typesetting.

                /*
                FT_Face face = (FT_Face) font_data;
                FT_Error error;

                error = FT_Load_Glyph (face, gid, FT_LOAD_NO_SCALE);
                if (!error) {
                    *x = face->glyph->metrics.horiBearingX -   face->glyph->metrics.vertBearingX;
                    *y = face->glyph->metrics.horiBearingY - (-face->glyph->metrics.vertBearingY);
                }

                return !error;
                 */
            });
            f.glyph_h_kerning(|_, face, gid1, gid2| {
                match face
                    .lock()
                    .unwrap()
                    .get_kerning(gid1, gid2, ft::KerningMode::Unscaled)
                {
                    Ok(vec) => vec.x as hb::Position,
                    Err(_) => 0,
                }
            });
            f.glyph_v_kerning(|_, _, _, _| 0);
            f.glyph_extents(|_, face, gid| {
                let mut face = face.lock().unwrap();
                if let Ok(glyph) = face.load_glyph(gid, ft::LoadFlags::NO_SCALE) {
                    Some(hb::GlyphExtents {
                        x_bearing: glyph.metrics().horiBearingX as hb::Position,
                        y_bearing: glyph.metrics().horiBearingY as hb::Position,
                        width: glyph.metrics().width as hb::Position,
                        height: -glyph.metrics().height as hb::Position,
                    })
                } else {
                    None
                }
            });
            f.glyph_contour_point(|_, face, gid, point_index| {
                let mut face = face.lock().unwrap();

                if let Ok(glyph) = face.load_glyph(gid, ft::LoadFlags::NO_SCALE) {
                    if let Some(outline) = glyph.outline() {
                        if point_index < (outline.n_points as u32) {
                            let x = outline.points()[point_index as usize].x as hb::Position;
                            let y = outline.points()[point_index as usize].y as hb::Position;
                            return Some((x, y));
                        }
                    }
                }
                None
            });
            f.glyph_name(
                |_, face, gid, buf| match face.lock().unwrap().get_glyph_name(gid, buf) {
                    Ok(str) if !str.to_bytes().is_empty() && str.to_bytes()[0] == 0 => 0,
                    Err(_) => 0,
                    Ok(str) => str.to_bytes().len(),
                },
            );

            funcs.make_immutable()
        })
        .as_ref()
}

pub(crate) fn get_larger_script_list_table_ot(font: &Font) -> hb::ot::Table<'_> {
    let layout = font.hb_font().face().ot_layout();

    let sl_sub = layout.table(hb::GTag::GSub);
    let sl_pos = layout.table(hb::GTag::GPos);

    if sl_sub.script_tags_len() > sl_pos.script_tags_len() {
        sl_sub
    } else {
        sl_pos
    }
}

enum FontKind {
    FtFont,
    #[cfg(target_os = "macos")]
    Mac(CTFontDescriptor, Option<CTFont>),
}

/// A font, with all the information needed by TeX to shape it for typesetting.
pub struct Font {
    units_per_em: libc::c_ushort,
    point_size: f32,
    ascent: f32,
    descent: f32,
    cap_height: f32,
    x_height: f32,
    italic_angle: f32,

    vertical: bool,

    filename: CString,
    index: u32,

    ft_face: Option<Arc<Mutex<ft::Face>>>,
    hb_font: Option<hb::Font>,

    // Currently only used on MacOS
    #[allow(dead_code)]
    kind: FontKind,
}

impl Font {
    #[cfg(not(target_os = "macos"))]
    pub(crate) fn new(font: PlatformFontRef, point_size: f32) -> Result<Font, ()> {
        let path = font
            .as_ref()
            .get::<fc::pat::File>(0)
            .and_then(|s| s.to_str().map_err(|_| fc::FcErr::NoMatch))
            .ok();
        let index = font.as_ref().get::<fc::pat::Index>(0).unwrap_or(0);

        Font::new_path_index(path, index as usize, point_size)
    }

    #[cfg(target_os = "macos")]
    pub(crate) fn new(descriptor: PlatformFontRef, point_size: f32) -> Result<Font, ()> {
        let mut out = Font {
            units_per_em: 0,
            point_size,
            ascent: 0.0,
            descent: 0.0,
            cap_height: 0.0,
            x_height: 0.0,
            italic_angle: 0.0,
            vertical: false,
            filename: CString::new("").unwrap(),
            index: 0,
            ft_face: None,
            hb_font: None,
            kind: FontKind::Mac(descriptor, None),
        };
        out.initialize_mac()?;
        Ok(out)
    }

    pub(crate) fn new_path_index(
        path: Option<&str>,
        index: usize,
        point_size: f32,
    ) -> Result<Font, ()> {
        let mut out = Font {
            units_per_em: 0,
            point_size,
            ascent: 0.0,
            descent: 0.0,
            cap_height: 0.0,
            x_height: 0.0,
            italic_angle: 0.0,
            vertical: false,
            filename: CString::new("").unwrap(),
            index: 0,
            ft_face: None,
            hb_font: None,
            kind: FontKind::FtFont,
        };
        if let Some(path) = path {
            out.initialize_ft(path, index)?;
        }
        Ok(out)
    }

    fn initialize_ft(&mut self, pathname: &str, index: usize) -> Result<(), ()> {
        CoreBridgeState::with_global_state(|engine| {
            let handle = engine
                .input_open(pathname, FileFormat::OpenType, false)
                .or_else(|| engine.input_open(pathname, FileFormat::TrueType, false))
                .or_else(|| engine.input_open(pathname, FileFormat::Type1, false));
            let Some(handle) = handle else {
                return Err(());
            };

            let sz = engine.input_get_size(handle);
            let mut backing_data = vec![0; sz];
            engine
                .input_read(handle, &mut backing_data)
                .expect("failed to read font file");

            engine.input_close(handle);

            self.ft_face = match ft::Face::new_memory(backing_data, index) {
                Ok(face) => Some(Arc::new(Mutex::new(face))),
                Err(_) => return Err(()),
            };

            if !self.ft_face().is_scalable() {
                return Err(());
            }

            if index == 0 && !self.ft_face().is_sfnt() {
                let afm = Path::new(pathname)
                    .file_name()
                    .map(Path::new)
                    .unwrap_or(Path::new(pathname));
                let afm = afm.with_extension("afm");

                let afm_handle = engine.input_open(afm.to_str().unwrap(), FileFormat::Afm, false);

                if let Some(afm_handle) = afm_handle {
                    let sz = engine.input_get_size(afm_handle);
                    let mut backing_data2 = vec![0; sz];
                    engine
                        .input_read(afm_handle, &mut backing_data2)
                        .expect("failed to read AFM file");

                    self.ft_face().attach_stream_mem(backing_data2).unwrap();
                    engine.input_close(afm_handle);
                }
            }
            Ok(())
        })?;

        self.filename = CString::from_str(pathname).unwrap();
        self.index = index as u32;
        let upe = { self.ft_face().units_per_em() };
        self.units_per_em = upe;
        let a = { self.ft_face().ascender() } as f64;
        self.ascent = self.units_to_points(a) as f32;
        let d = { self.ft_face().descender() } as f64;
        self.descent = self.units_to_points(d) as f32;

        let ft_face = self.ft_face();
        let post_table = ft_face.get_sfnt_table::<ft::tables::Postscript>();
        let ia = if let Some(table) = post_table {
            fix_to_d(table.italic_angle as Fixed) as f32
        } else {
            self.italic_angle
        };
        drop(ft_face);
        self.italic_angle = ia;

        let ft_face = self.ft_face();
        let os2_table = ft_face.get_sfnt_table::<ft::tables::Os2>();
        let (ch, xh) = if let Some(table) = os2_table {
            let ch = self.units_to_points(table.sCapHeight as f64) as f32;
            let xh = self.units_to_points(table.sxHeight as f64) as f32;
            (ch, xh)
        } else {
            (self.cap_height, self.x_height)
        };
        drop(ft_face);
        self.cap_height = ch;
        self.x_height = xh;

        let ft_face = Arc::clone(self.ft_face.as_ref().unwrap());
        let mut hb_face = hb::Face::new_tables(move |_, tag| {
            if let Ok(table) = ft_face
                .lock()
                .unwrap()
                .load_sfnt_table(ft::TableTag::Other(tag.to_raw()))
            {
                Some(hb::Blob::new(table))
            } else {
                None
            }
        });

        hb_face.as_mut().set_index(self.index);
        hb_face.as_mut().set_upem(self.units_per_em as u32);

        let mut hb_font = hb::Font::new(hb_face.as_ref());

        hb_font
            .as_mut()
            .set_funcs(get_font_funcs(), Arc::clone(self.ft_face.as_ref().unwrap()));
        hb_font
            .as_mut()
            .set_scale(self.units_per_em as i32, self.units_per_em as i32);
        hb_font.as_mut().set_ppem(0, 0);

        self.hb_font = Some(hb_font);

        Ok(())
    }

    #[cfg(target_os = "macos")]
    fn initialize_mac(&mut self) -> Result<(), ()> {
        let FontKind::Mac(descriptor, font_ref) = &mut self.kind else {
            return Err(());
        };

        let empty_cascade_list = CFArray::<CFType>::empty();
        let attributes =
            CFDictionary::new([(FontAttribute::CascadeList.to_str(), empty_cascade_list)]);

        *descriptor = descriptor.copy_with_attrs(&attributes);
        *font_ref = Some(CTFont::new_descriptor(
            descriptor,
            self.point_size as f64 * 72.0 / 72.27,
        ));
        let mut index = 0;
        let pathname = get_file_name_from_ct_font(font_ref.as_ref().unwrap(), &mut index).unwrap();
        self.initialize_ft(pathname.to_str().unwrap(), index as usize)
    }

    pub(crate) fn ft_face(&self) -> std::sync::MutexGuard<'_, ft::Face> {
        self.ft_face.as_ref().unwrap().lock().unwrap()
    }

    pub(crate) fn get_glyph_name(&self, gid: u16) -> Option<CString> {
        if self.ft_face().has_glyph_names() {
            let mut buf = vec![0u8; 256];
            self.ft_face().get_glyph_name(gid as u32, &mut buf).unwrap();

            CStr::from_bytes_until_nul(&buf).map(CStr::to_owned).ok()
        } else {
            None
        }
    }

    pub(crate) fn get_glyph_sidebearings(
        &mut self,
        gid: GlyphID,
        lsb: Option<&mut f32>,
        rsb: Option<&mut f32>,
    ) {
        let width = self.get_glyph_width(gid as u32);

        let bbox = self.get_glyph_bounds(gid);

        if let Some(lsb) = lsb {
            *lsb = bbox.x_min;
        }
        if let Some(rsb) = rsb {
            *rsb = width - bbox.x_max;
        }
    }

    pub(crate) fn get_glyph_ital_corr(&mut self, gid: GlyphID) -> f32 {
        let width = self.get_glyph_width(gid as u32);
        let bbox = self.get_glyph_bounds(gid);

        if bbox.x_max > width {
            bbox.x_max - width
        } else {
            0.0
        }
    }

    pub(crate) fn map_char_to_glyph(&self, ch: u32) -> GlyphID {
        match self.ft_face().get_char_index(ch) {
            Some(val) => val.get() as GlyphID,
            None => 0,
        }
    }

    pub(crate) fn first_char_code(&self) -> u32 {
        self.ft_face().get_first_char().0
    }

    pub(crate) fn last_char_code(&self) -> u32 {
        let ft_face = self.ft_face();

        let (mut ch, mut index) = ft_face.get_first_char();
        let mut prev = ch;
        while index != 0 {
            prev = ch;
            (ch, index) = ft_face.get_next_char(ch);
        }
        prev
    }

    pub(crate) fn map_glyph_to_index(&self, glyph_name: &CStr) -> GlyphID {
        match self.ft_face().get_name_index(glyph_name) {
            Some(index) => index.get() as u16,
            None => 0,
        }
    }

    pub(crate) fn load_font_table(&self, tag: ft::TableTag) -> Option<Vec<u8>> {
        self.ft_face().load_sfnt_table(tag).ok()
    }

    pub(crate) fn get_glyph_bounds(&mut self, gid: GlyphID) -> GlyphBBox {
        let mut ft_face = self.ft_face();

        let glyph = ft_face
            .load_glyph(gid as u32, ft::LoadFlags::NO_SCALE)
            .and_then(|slot| slot.get_glyph());

        match glyph {
            Ok(glyph) => {
                let ft::BBox {
                    x_min,
                    y_min,
                    x_max,
                    y_max,
                } = glyph.get_cbox(ft::BBoxMode::Unscaled);
                drop(ft_face);
                GlyphBBox {
                    x_min: self.units_to_points(x_min as f64) as f32,
                    y_min: self.units_to_points(y_min as f64) as f32,
                    x_max: self.units_to_points(x_max as f64) as f32,
                    y_max: self.units_to_points(y_max as f64) as f32,
                }
            }
            Err(_) => GlyphBBox::default(),
        }
    }

    pub(crate) fn get_glyph_height_depth(
        &mut self,
        gid: GlyphID,
        height: Option<&mut f32>,
        depth: Option<&mut f32>,
    ) {
        let bbox = self.get_glyph_bounds(gid);
        if let Some(height) = height {
            *height = bbox.y_max;
        }
        if let Some(depth) = depth {
            *depth = -bbox.y_min;
        }
    }

    pub(crate) fn filename(&self, index: &mut u32) -> &CStr {
        *index = self.index;
        &self.filename
    }

    // pub(crate) fn get_font_table<T: ft::Table>(&self) -> Option<&T::Table> {
    //     self.ft_face().get_sfnt_table::<T>()
    // }

    pub(crate) fn italic_angle(&self) -> f32 {
        self.italic_angle
    }

    pub(crate) fn num_glyphs(&self) -> usize {
        self.ft_face().num_glyphs()
    }

    pub(crate) fn get_glyph_width(&self, gid: u32) -> f32 {
        self.units_to_points(get_glyph_advance(&self.ft_face(), gid, false) as f64) as f32
    }

    pub(crate) fn layout_dir_vertical(&self) -> bool {
        self.vertical
    }

    pub(crate) fn set_layout_dir_vertical(&mut self, vertical: bool) {
        self.vertical = vertical;
    }

    pub(crate) fn point_size(&self) -> f32 {
        self.point_size
    }

    pub(crate) fn ascent(&self) -> f32 {
        self.ascent
    }

    pub(crate) fn descent(&self) -> f32 {
        self.descent
    }

    pub(crate) fn cap_height(&self) -> f32 {
        self.cap_height
    }

    pub(crate) fn x_height(&self) -> f32 {
        self.x_height
    }

    pub(crate) fn hb_font(&self) -> hb::FontRef<'_> {
        self.hb_font.as_ref().unwrap().as_ref()
    }

    pub(crate) fn try_hb_font(&self) -> Option<hb::FontRef<'_>> {
        self.hb_font.as_ref().map(|f| f.as_ref())
    }

    /* Tectonic: these are modified from the base XeTeX code to use doubles;
     * otherwise roundoff errors can accumulate leading to differences in the
     * XDV outputs. */
    pub(crate) fn units_to_points(&self, units: f64) -> f64 {
        (units * self.point_size as f64) / (self.units_per_em as f64)
    }

    pub(crate) fn points_to_units(&self, points: f64) -> f64 {
        (points * (self.units_per_em as f64)) / self.point_size as f64
    }
}

#[cfg(target_os = "macos")]
pub(crate) fn get_file_name_from_ct_font(ct_font: &CTFont, index: &mut u32) -> Option<CString> {
    let url = ct_font
        .attr(FontAttribute::URL)
        // SAFETY: CFUrl has no generic parameters
        .and_then(|t| unsafe { t.downcast::<CFUrl>() }.ok())?;

    let pathname = url.fs_representation()?;
    *index = 0;

    let face = ft::Face::new(&pathname, 0);
    if let Ok(face) = face {
        if face.num_faces() > 1 {
            let num_faces = face.num_faces();
            let ps_name1 = ct_font.name(FontNameKey::PostScript);
            *index = u32::MAX;
            for i in 0..num_faces {
                let face = ft::Face::new(&pathname, i);
                if let Ok(face) = face {
                    let ps_name2 = face.get_postscript_name();
                    match (&ps_name1, ps_name2) {
                        (None, None) => {
                            *index = i as u32;
                            break;
                        }
                        (Some(name1), Some(name2)) if &*name1.as_cstr() == name2 => {
                            *index = i as u32;
                            break;
                        }
                        _ => (),
                    }
                }
            }
        }
    }

    if *index != u32::MAX {
        Some(pathname)
    } else {
        None
    }
}