fontir 0.5.0

Intermediate Representation used by fontc, a font compiler.
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
//! Helps coordinate the graph execution for IR

use std::{
    collections::HashMap,
    fmt::Debug,
    fs::File,
    hash::Hash,
    io::{self, BufReader, BufWriter, Read, Write},
    sync::Arc,
};

use crate::{error::Error, ir, paths::Paths};
use bitflags::bitflags;
use fontdrasil::{
    coords::NormalizedLocation,
    orchestration::{Access, AccessControlList, Identifier, IdentifierDiscriminant, Work},
    types::GlyphName,
};
use parking_lot::RwLock;
use write_fonts::{FontWrite, read::FontRead, validate::Validate};

bitflags! {
    #[derive(Clone, Copy, Debug)]
    pub struct Flags: u32 {
        // If set IR will be emitted to disk when written into Context
        const EMIT_IR = 0b00000001;
        // If set additional debug files will be emitted to disk
        const EMIT_DEBUG = 0b00000010;
        // If set, a glyph with contours and components will be converted to a simple (contour) glyph
        const PREFER_SIMPLE_GLYPHS = 0b00000100;
        // If set, a composite that references another composite will replace that composite with the
        // glyph(s) it references until only simple (contour) glyphs are referenced
        const FLATTEN_COMPONENTS = 0b00001000;
        const DECOMPOSE_TRANSFORMED_COMPONENTS = 0b00010000;
        // If set a files reporting on timing will be emitted to disk
        const EMIT_TIMING = 0b00100000;
        // If set, the direction of contours will NOT be reversed
        const KEEP_DIRECTION = 0b01000000;
        // If set, production names are read & used
        const PRODUCTION_NAMES = 0b10000000;
        // If set, all the composite glyphs will be decomposed to simple glyphs
        const DECOMPOSE_COMPONENTS = 0b100000000;
        // If set, open corners will be erased (Glyphs-native feature)
        const ERASE_OPEN_CORNERS = 0b1000000000;
    }
}

impl Default for Flags {
    fn default() -> Self {
        Flags::PREFER_SIMPLE_GLYPHS | Flags::PRODUCTION_NAMES
    }
}

/// Clones are cheap and reference the same wrapped item courtesy of Arc
///
/// Courtesy of Arc this is Clone even if T isn't
#[derive(Default)]
pub struct ContextItem<I, T, P>
where
    I: Identifier,
{
    id: I,
    acl: Arc<AccessControlList<I>>,
    persistent_storage: Arc<P>,
    value: Arc<RwLock<Option<Arc<T>>>>,
}

impl<I, T, P> ContextItem<I, T, P>
where
    I: Identifier,
    P: PersistentStorage<I>,
    T: Persistable,
{
    pub fn new(id: I, acl: Arc<AccessControlList<I>>, persistent_storage: Arc<P>) -> Self {
        ContextItem {
            id,
            acl,
            persistent_storage,
            value: Default::default(),
        }
    }

    pub fn clone_with_acl(&self, acl: Arc<AccessControlList<I>>) -> Self {
        ContextItem {
            id: self.id.clone(),
            acl,
            persistent_storage: self.persistent_storage.clone(),
            value: self.value.clone(),
        }
    }

    /// Read item that you are sure must exist. Panic if not.
    ///
    /// Intended for use in [Work] to access items present in
    /// [Work::read_access]. If these are missing something is horribly
    /// wrong and we should kerplode.
    pub fn get(&self) -> Arc<T> {
        if let Some(in_memory) = self.try_get() {
            return in_memory;
        }

        // it's *not* in memory but perhaps it's written down?
        if self.persistent_storage.active()
            && let Some(mut reader) = self.persistent_storage.reader(&self.id)
        {
            let restored = T::read(&mut reader);
            *self.value.write() = Some(Arc::from(restored));
        }

        // if we still don't have an answer just give up
        self.try_get()
            .unwrap_or_else(|| panic!("{:?} is not available", self.id))
    }

    /// Read an item that might not exist
    pub fn try_get(&self) -> Option<Arc<T>> {
        self.acl.assert_read_access(&self.id);
        self.value.read().as_ref().cloned()
    }
}

impl<I, T, P> ContextItem<I, T, P>
where
    I: Identifier,
    T: PartialEq + Persistable,
    P: PersistentStorage<I>,
{
    /// Update the value if it has changed.
    ///
    /// Change logging and dependent task execution will only fire if the value changed.
    pub fn set(&self, value: T) {
        self.acl.assert_write_access(&self.id);

        // nop?
        if self
            .value
            .read()
            .as_ref()
            .map(|arc| **arc == value)
            .unwrap_or(false)
        {
            return;
        }

        if self.persistent_storage.active() {
            let mut writer = self.persistent_storage.writer(&self.id);
            value.write(&mut writer);
        }

        *self.value.write() = Some(Arc::from(value));
    }
}

/// Clones are cheap and reference the same wrapped item courtesy of Arc
///
/// Courtesy of Arc this is Clone even if T isn't
#[derive(Default)]
pub struct ContextMap<I, T, P>
where
    I: Identifier,
    T: IdAware<I>,
    P: PersistentStorage<I>,
{
    acl: Arc<AccessControlList<I>>,
    persistent_storage: Arc<P>,
    value: Arc<RwLock<HashMap<I, Arc<T>>>>,
}

impl<I, T, P> ContextMap<I, T, P>
where
    I: Identifier,
    T: IdAware<I> + Persistable,
    P: PersistentStorage<I>,
{
    pub fn new(acl: Arc<AccessControlList<I>>, persistent_storage: Arc<P>) -> Self {
        ContextMap {
            acl,
            persistent_storage,
            value: Default::default(),
        }
    }

    pub fn clone_with_acl(&self, acl: Arc<AccessControlList<I>>) -> Self {
        ContextMap {
            acl,
            persistent_storage: self.persistent_storage.clone(),
            value: self.value.clone(),
        }
    }

    /// Read an item that might not exist
    pub fn try_get(&self, id: &I) -> Option<Arc<T>> {
        self.acl.assert_read_access(id);
        self.value.read().get(id).cloned()
    }

    /// A copy of all the entries in the map. Values are arc'd so they are cheap, though not free, copies.
    pub fn all(&self) -> Vec<(I, Arc<T>)> {
        self.value
            .read()
            .iter()
            .map(|(id, v)| {
                self.acl.assert_read_access(id);
                (id.clone(), v.clone())
            })
            .collect()
    }

    /// Read item that you are sure must exist. Panic if not.
    ///
    /// Intended for use in [Work] to access items present in
    /// [Work::read_access]. If these are missing something is horribly
    /// wrong and we should kerplode.
    pub fn get(&self, id: &I) -> Arc<T> {
        if let Some(in_memory) = self.try_get(id) {
            return in_memory;
        }

        // it's *not* in memory but perhaps it's written down?
        if self.persistent_storage.active()
            && let Some(mut reader) = self.persistent_storage.reader(id)
        {
            let restored = T::read(&mut reader);
            self.value.write().insert(id.clone(), Arc::from(restored));
        }

        // if we still don't have an answer just give up
        self.try_get(id)
            .unwrap_or_else(|| panic!("{id:?} is not available"))
    }
}

impl<I, T, Ir> ContextMap<I, T, Ir>
where
    I: Identifier,
    T: IdAware<I> + Persistable,
    Ir: PersistentStorage<I>,
{
    pub fn set_unconditionally(&self, value: T) {
        let key = value.id();
        self.acl.assert_write_access(&key);

        if self.persistent_storage.active() {
            let mut writer = self.persistent_storage.writer(&key);
            value.write(&mut writer);
        }

        self.value.write().insert(key, Arc::from(value));
    }
}

impl<I, T, Ir> ContextMap<I, T, Ir>
where
    I: Identifier,
    T: IdAware<I> + PartialEq + Persistable,
    Ir: PersistentStorage<I>,
{
    pub fn set(&self, value: T) {
        let key = value.id();
        self.acl.assert_write_access(&key);

        // nop?
        if self
            .value
            .read()
            .get(&key)
            .map(|arc| **arc == value)
            .unwrap_or(false)
        {
            return;
        }

        self.set_unconditionally(value);
    }
}

pub trait IdAware<I> {
    fn id(&self) -> I;
}

pub trait Persistable {
    fn read(from: &mut dyn Read) -> Self;
    fn write(&self, to: &mut dyn Write);
}

/// Reads and writes to somewhere that lives longer than processes.
///
/// This enables the compiler to restore state from prior executions which is
/// crucial to incremental operation.
pub trait PersistentStorage<I> {
    fn active(&self) -> bool;
    /// None if there is nothing written down for id
    fn reader(&self, id: &I) -> Option<Box<dyn Read>>;
    fn writer(&self, id: &I) -> Box<dyn Write>;
}

// Unique identifier of work. If there are no fields work is unique.
// Meant to be small and cheap to copy around.
#[derive(Clone, Debug, PartialEq, Eq, Hash, PartialOrd, Ord)]
pub enum WorkId {
    /// Build the initial static metadata.
    ///
    /// Contains all names, axes, etc. Does NOT contain the final glyph order.
    StaticMetadata,
    /// Build potentially variable font-wide metrics.
    GlobalMetrics,
    Glyph(GlyphName),
    /// Glyph order from source, prior to adjustment
    ///
    /// Typically whatever2ir would populate this and then
    /// it would be used to produce GlyphOrder.
    ///
    /// Most things should use GlyphOrder not this.
    PreliminaryGlyphOrder,
    /// The final glyph order. Most things that need glyph order should rely on this.
    GlyphOrder,
    Features,
    KerningGroups,
    KernInstance(NormalizedLocation),
    Anchor(GlyphName),
    /// CPAL data
    ColorPalettes,
    /// COLR data
    PaintGraph,
}

impl WorkId {
    /// An id representing access to all glyphs
    pub const ALL_GLYPHS: Self = WorkId::Glyph(GlyphName::NOTDEF);
    /// an id representing access to all anchors
    pub const ALL_ANCHORS: Self = WorkId::Anchor(GlyphName::NOTDEF);
}

impl Identifier for WorkId {
    fn discriminant(&self) -> IdentifierDiscriminant {
        match self {
            WorkId::StaticMetadata => "IrStaticMetadata",
            WorkId::GlobalMetrics => "IrGlobalMetrics",
            WorkId::Glyph(..) => "IrGlyph",
            WorkId::PreliminaryGlyphOrder => "IrPreliminaryGlyphOrder",
            WorkId::GlyphOrder => "IrGlyphOrder",
            WorkId::Features => "IrFeatures",
            WorkId::KerningGroups => "IrKerningGroups",
            WorkId::KernInstance(..) => "IrKernInstance",
            WorkId::Anchor(..) => "IrAnchor",
            WorkId::ColorPalettes => "IrPalettes",
            WorkId::PaintGraph => "IrPaints",
        }
    }
}

pub type IrWork = dyn Work<Context, WorkId, Error> + Send;

pub struct IrPersistentStorage {
    active: bool,
    pub(crate) paths: Paths,
}

impl PersistentStorage<WorkId> for IrPersistentStorage {
    fn active(&self) -> bool {
        self.active
    }

    fn reader(&self, id: &WorkId) -> Option<Box<dyn Read>> {
        let file = self.paths.target_file(id);
        if !file.exists() {
            return None;
        }
        let raw_file = File::open(file.clone())
            .map_err(|e| panic!("Unable to write {file:?} {e}"))
            .unwrap();
        Some(Box::from(BufReader::new(raw_file)))
    }

    fn writer(&self, id: &WorkId) -> Box<dyn Write> {
        let file = self.paths.target_file(id);
        let raw_file = File::create(file.clone())
            .map_err(|e| panic!("Unable to write {file:?} {e}"))
            .unwrap();
        Box::from(BufWriter::new(raw_file))
    }
}

impl<T> Persistable for T
where
    for<'a> T: FontRead<'a> + FontWrite + Validate,
{
    fn read(from: &mut dyn Read) -> Self {
        let mut buf = Vec::new();
        from.read_to_end(&mut buf).unwrap();
        T::read(buf.as_slice().into()).expect("if we wrote it we can read it")
    }

    fn write(&self, to: &mut dyn io::Write) {
        let bytes = write_fonts::dump_table(self).unwrap();
        to.write_all(&bytes).unwrap();
    }
}

type FeContextItem<T> = ContextItem<WorkId, T, IrPersistentStorage>;
type FeContextMap<T> = ContextMap<WorkId, T, IrPersistentStorage>;

/// Read/write access to data for async work.
///
/// Intent is a root orchestrator creates a context and share copies with restricted
/// access with spawned tasks. Copies with access control are created to detect bad
/// execution order / mistakes, not to block actual bad actors.
pub struct Context {
    pub flags: Flags,

    pub(crate) persistent_storage: Arc<IrPersistentStorage>,

    // work results we've completed or restored from disk
    // We create individual caches so we can return typed results from get fns
    pub static_metadata: FeContextItem<ir::StaticMetadata>,
    pub preliminary_glyph_order: FeContextItem<ir::GlyphOrder>,
    pub glyph_order: FeContextItem<ir::GlyphOrder>,
    pub global_metrics: FeContextItem<ir::GlobalMetrics>,
    pub glyphs: FeContextMap<ir::Glyph>,
    pub features: FeContextItem<ir::FeaturesSource>,
    pub kerning_groups: FeContextItem<ir::KerningGroups>,
    pub kerning_at: FeContextMap<ir::KerningInstance>,
    pub anchors: FeContextMap<ir::GlyphAnchors>,
    pub colors: FeContextItem<ir::ColorPalettes>,
    pub paint_graph: FeContextItem<ir::ColorGlyphs>,
}

pub fn set_cached<T>(lock: &Arc<RwLock<Option<Arc<T>>>>, value: T) {
    let mut wl = lock.write();
    *wl = Some(Arc::from(value));
}

impl Context {
    fn copy(&self, acl: AccessControlList<WorkId>) -> Context {
        let acl = Arc::from(acl);
        Context {
            flags: self.flags,
            persistent_storage: self.persistent_storage.clone(),
            static_metadata: self.static_metadata.clone_with_acl(acl.clone()),
            preliminary_glyph_order: self.preliminary_glyph_order.clone_with_acl(acl.clone()),
            glyph_order: self.glyph_order.clone_with_acl(acl.clone()),
            global_metrics: self.global_metrics.clone_with_acl(acl.clone()),
            glyphs: self.glyphs.clone_with_acl(acl.clone()),
            features: self.features.clone_with_acl(acl.clone()),
            kerning_groups: self.kerning_groups.clone_with_acl(acl.clone()),
            kerning_at: self.kerning_at.clone_with_acl(acl.clone()),
            anchors: self.anchors.clone_with_acl(acl.clone()),
            colors: self.colors.clone_with_acl(acl.clone()),
            paint_graph: self.paint_graph.clone_with_acl(acl),
        }
    }

    pub fn new_root(flags: Flags, paths: Paths) -> Context {
        let acl = Arc::from(AccessControlList::read_only());
        let persistent_storage = Arc::from(IrPersistentStorage {
            active: flags.contains(Flags::EMIT_IR),
            paths,
        });
        Context {
            flags,
            persistent_storage: persistent_storage.clone(),
            static_metadata: ContextItem::new(
                WorkId::StaticMetadata,
                acl.clone(),
                persistent_storage.clone(),
            ),
            preliminary_glyph_order: ContextItem::new(
                WorkId::PreliminaryGlyphOrder,
                acl.clone(),
                persistent_storage.clone(),
            ),
            glyph_order: ContextItem::new(
                WorkId::GlyphOrder,
                acl.clone(),
                persistent_storage.clone(),
            ),
            global_metrics: ContextItem::new(
                WorkId::GlobalMetrics,
                acl.clone(),
                persistent_storage.clone(),
            ),
            glyphs: ContextMap::new(acl.clone(), persistent_storage.clone()),
            features: ContextItem::new(WorkId::Features, acl.clone(), persistent_storage.clone()),
            kerning_groups: ContextItem::new(
                WorkId::KerningGroups,
                acl.clone(),
                persistent_storage.clone(),
            ),
            kerning_at: ContextMap::new(acl.clone(), persistent_storage.clone()),
            anchors: ContextMap::new(acl.clone(), persistent_storage.clone()),
            colors: ContextItem::new(
                WorkId::ColorPalettes,
                acl.clone(),
                persistent_storage.clone(),
            ),
            paint_graph: ContextItem::new(WorkId::PaintGraph, acl, persistent_storage),
        }
    }

    pub fn copy_for_work(
        &self,
        read_access: Access<WorkId>,
        write_access: Access<WorkId>,
    ) -> Context {
        self.copy(AccessControlList::read_write(read_access, write_access))
    }

    pub fn read_only(&self) -> Context {
        self.copy(AccessControlList::read_only())
    }

    pub fn get_glyph(&self, name: impl Into<GlyphName>) -> Arc<ir::Glyph> {
        let id = WorkId::Glyph(name.into());
        self.glyphs.get(&id)
    }

    pub fn try_get_glyph(&self, name: impl Into<GlyphName>) -> Option<Arc<ir::Glyph>> {
        let id = WorkId::Glyph(name.into());
        self.glyphs.try_get(&id)
    }

    pub fn get_anchor(&self, name: impl Into<GlyphName>) -> Arc<ir::GlyphAnchors> {
        let id = WorkId::Anchor(name.into());
        self.anchors.get(&id)
    }
}