Skip to main content

f_office_fonts/
bilevel.rs

1//! The advance of a glyph at a size as bi-level rendering gives it, and its device width,
2//! from the face's TrueType instructions (`f-office-truetype`). The format crates decide where a target uses it, such
3//! as a PDF writer that writes these advances as glyph widths.
4
5use std::sync::Mutex;
6
7use f_office_truetype::{Error, Hinter};
8
9use crate::face::Face;
10use crate::{FontBytes, FontDb, FontId};
11
12/// The most hinters that a face keeps for one grid. A document
13/// uses a few sizes of a face; the limit bounds the memory of a database that renders many
14/// documents to 8 kept hinters of 15 to 38 KiB for each face and grid.
15pub(crate) const MOST_KEPT_HINTERS: usize = 8;
16
17/// Makes a hinter for the face `index` of a font file at a size: `Hinter::new` or
18/// `Hinter::device`.
19type Build = fn(FontBytes, u32, u16) -> Result<Hinter, Error>;
20
21/// The hinters that a face keeps for one grid, each with its pixels per em, the one put back
22/// last at the end; `None` for a size whose font program or control value program failed. A
23/// hinter is taken out while it hints a glyph, so that the list's lock is not held through a
24/// glyph program and threads that render with one database do not wait for each other. A
25/// size may have several hinters, one for each thread that hinted it at once, so that such
26/// threads each find one the next time. A hinter is boxed, so that taking it out and putting
27/// it back moves a pointer.
28#[derive(Debug, Default)]
29pub(crate) struct KeptHinters {
30    hinters: Vec<(u16, Option<Box<Hinter>>)>,
31}
32
33/// What a face's list of kept hinters holds for a size.
34enum Kept {
35    /// A hinter, now taken out of the list.
36    Hinter(Box<Hinter>),
37    /// The size's programs failed.
38    Failed,
39    /// Nothing: the size is new, has left the list, or its hinters are out on other threads.
40    Missing,
41}
42
43impl KeptHinters {
44    /// Takes the hinter of `ppem` put back last out of the list, or says that the size failed
45    /// or is missing.
46    fn take(&mut self, ppem: u16) -> Kept {
47        let Some(at) = self.hinters.iter().rposition(|&(size, _)| size == ppem) else {
48            return Kept::Missing;
49        };
50        match self.hinters.remove(at) {
51            (_, Some(hinter)) => Kept::Hinter(hinter),
52            failed @ (_, None) => {
53                self.hinters.insert(at, failed);
54                Kept::Failed
55            }
56        }
57    }
58
59    /// Puts the hinter of `ppem`, or `None` for a size that failed, at the end of the list, and
60    /// gives back the hinter that leaves it, so that the caller drops that one after the lock
61    /// is released: when the list is full, the one put back longest ago leaves it, and a
62    /// failed size that the list holds already is not put twice.
63    fn put(&mut self, ppem: u16, hinter: Option<Box<Hinter>>) -> Option<Box<Hinter>> {
64        if hinter.is_none()
65            && self
66                .hinters
67                .iter()
68                .any(|(size, kept)| *size == ppem && kept.is_none())
69        {
70            return None;
71        }
72        self.hinters.push((ppem, hinter));
73        if self.hinters.len() > MOST_KEPT_HINTERS {
74            return self.hinters.remove(0).1;
75        }
76        None
77    }
78
79    /// The size of each hinter in the list, the one put back last at the end.
80    #[cfg(test)]
81    pub(crate) fn sizes(&self) -> Vec<u16> {
82        self.hinters.iter().map(|&(size, _)| size).collect()
83    }
84}
85
86impl FontDb {
87    /// The advance of `glyph` of face `id` in whole pixels at `ppem` pixels per em, as bi-level
88    /// rendering gives it: the linear advance where the face says that the glyph's advance
89    /// scales linearly at that size, else the advance that the glyph's instructions hint.
90    ///
91    /// Returns `None` for an unknown face or glyph, a face without TrueType outlines, or
92    /// instructions that fail. The database keeps each answer, and a hinter for each size.
93    #[must_use]
94    pub fn bi_level_advance(&self, id: FontId, glyph: u32, ppem: u16) -> Option<i32> {
95        let face = self.face(id)?;
96        let key = (ppem, u16::try_from(glyph).ok()?);
97        if let Some(&known) = face.bi_level.lock().ok()?.get(&key) {
98            return known;
99        }
100        let advance = hint(face, &face.bi_level_hinters, Hinter::new, ppem, |hinter| {
101            hinter.advance(key.1)
102        });
103        face.bi_level.lock().ok()?.insert(key, advance);
104        advance
105    }
106
107    /// The device width of `glyph` of face `id` in whole pixels at `ppem` pixels per em: the
108    /// advance point after the glyph's instructions in the interpreter's device-width mode,
109    /// rounded, which is the width that Word's device steps a glyph by.
110    ///
111    /// Returns `None` for an unknown face or glyph, a face without TrueType outlines, or
112    /// instructions that fail. The database keeps each answer, and a hinter for each size.
113    #[must_use]
114    pub fn device_width(&self, id: FontId, glyph: u32, ppem: u16) -> Option<i32> {
115        let face = self.face(id)?;
116        let key = (ppem, u16::try_from(glyph).ok()?);
117        if let Some(&known) = face.device.lock().ok()?.get(&key) {
118            return known;
119        }
120        let width = hint(face, &face.device_hinters, Hinter::device, ppem, |hinter| {
121            hinter.device_width(key.1)
122        });
123        face.device.lock().ok()?.insert(key, width);
124        width
125    }
126}
127
128/// Hints one glyph of the face at `ppem` with `glyph`, by a hinter that `kept` holds for the
129/// size or by a new one from `build`, which runs the face's font program and control value
130/// program, and puts the hinter back. The list's lock is held only to take and to put, and a
131/// hinter that leaves the list is dropped after the lock is released.
132fn hint(
133    face: &Face,
134    kept: &Mutex<KeptHinters>,
135    build: Build,
136    ppem: u16,
137    glyph: impl FnOnce(&mut Hinter) -> Result<i32, Error>,
138) -> Option<i32> {
139    let taken = kept
140        .lock()
141        .map_or(Kept::Missing, |mut list| list.take(ppem));
142    let mut hinter = match taken {
143        Kept::Hinter(hinter) => hinter,
144        Kept::Failed => return None,
145        Kept::Missing => {
146            let made = face
147                .data()
148                .and_then(|data| build(data.clone(), face.index, ppem).ok());
149            let Some(hinter) = made else {
150                let left = kept.lock().ok().and_then(|mut list| list.put(ppem, None));
151                drop(left);
152                return None;
153            };
154            Box::new(hinter)
155        }
156    };
157    let answer = glyph(&mut hinter).ok();
158    let left = kept
159        .lock()
160        .ok()
161        .and_then(|mut list| list.put(ppem, Some(hinter)));
162    drop(left);
163    answer
164}
165
166#[cfg(test)]
167mod tests {
168    use super::{Kept, KeptHinters, MOST_KEPT_HINTERS};
169    use f_office_truetype::Hinter;
170
171    fn hinter() -> Box<Hinter> {
172        Box::new(Hinter::new(crate::tests::CARLITO, 0, 12).unwrap())
173    }
174
175    /// What `take` gave, by name.
176    fn named(kept: &Kept) -> &'static str {
177        match kept {
178            Kept::Hinter(_) => "hinter",
179            Kept::Failed => "failed",
180            Kept::Missing => "missing",
181        }
182    }
183
184    #[test]
185    fn takes_a_hinter_out_and_keeps_a_failed_size_once() {
186        let mut list = KeptHinters::default();
187        let left = [
188            list.put(10, None),
189            list.put(10, None),
190            list.put(12, Some(hinter())),
191        ];
192        assert!(left.iter().all(Option::is_none));
193        // After the hinter is out, a second thread finds none and builds one.
194        let taken = [list.take(10), list.take(12), list.take(12)];
195        assert_eq!(taken.each_ref().map(named), ["failed", "hinter", "missing"]);
196        assert_eq!(list.sizes(), [10]);
197    }
198
199    #[test]
200    fn keeps_a_hinter_for_each_thread_that_hinted_a_size_at_once() {
201        let mut list = KeptHinters::default();
202        let left = [list.put(12, Some(hinter())), list.put(12, Some(hinter()))];
203        assert!(left.iter().all(Option::is_none));
204        assert_eq!(list.sizes(), [12, 12]);
205        let taken = [list.take(12), list.take(12), list.take(12)];
206        assert_eq!(taken.each_ref().map(named), ["hinter", "hinter", "missing"]);
207    }
208
209    #[test]
210    fn gives_back_the_hinter_put_back_longest_ago_when_full() {
211        let mut list = KeptHinters::default();
212        let most = u16::try_from(MOST_KEPT_HINTERS).unwrap();
213        let left: Vec<bool> = (1..=most)
214            .map(|ppem| list.put(ppem, Some(hinter())).is_some())
215            .collect();
216        assert!(!left.contains(&true));
217        // Size 1 is taken out and put back, so size 2 is the one put back longest ago.
218        let Kept::Hinter(one) = list.take(1) else {
219            unreachable!("size 1 is kept");
220        };
221        let left = [list.put(1, Some(one)), list.put(99, Some(hinter()))];
222        assert_eq!(left.each_ref().map(Option::is_some), [false, true]);
223        let mut expected: Vec<u16> = (3..=most).collect();
224        expected.extend([1, 99]);
225        assert_eq!(list.sizes(), expected);
226    }
227}