1// font-kit/src/loader.rs
2//
3// Copyright © 2018 The Pathfinder Project Developers.
4//
5// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
6// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
7// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
8// option. This file may not be copied, modified, or distributed
9// except according to those terms.
10
11//! Provides a common interface to the platform-specific API that loads, parses, and rasterizes
12//! fonts.
13
14use log::warn;
15use pathfinder_geometry::rect::{RectF, RectI};
16use pathfinder_geometry::transform2d::Transform2F;
17use pathfinder_geometry::vector::Vector2F;
18use std::sync::Arc;
19
20use crate::canvas::{Canvas, RasterizationOptions};
21use crate::error::{FontLoadingError, GlyphLoadingError};
22use crate::file_type::FileType;
23use crate::handle::Handle;
24use crate::hinting::HintingOptions;
25use crate::metrics::Metrics;
26use crate::outline::OutlineSink;
27use crate::properties::Properties;
28
29#[cfg(not(target_arch = "wasm32"))]
30use std::fs::File;
31#[cfg(not(target_arch = "wasm32"))]
32use std::path::Path;
33
34/// Provides a common interface to the platform-specific API that loads, parses, and rasterizes
35/// fonts.
36pub trait Loader: Clone + Sized {
37 /// The handle that the API natively uses to represent a font.
38 type NativeFont;
39
40 /// Loads a font from raw font data (the contents of a `.ttf`/`.otf`/etc. file).
41 ///
42 /// If the data represents a collection (`.ttc`/`.otc`/etc.), `font_index` specifies the index
43 /// of the font to load from it. If the data represents a single font, pass 0 for `font_index`.
44 fn from_bytes(font_data: Arc<Vec<u8>>, font_index: u32) -> Result<Self, FontLoadingError>;
45
46 /// Loads a font from a `.ttf`/`.otf`/etc. file.
47 ///
48 /// If the file is a collection (`.ttc`/`.otc`/etc.), `font_index` specifies the index of the
49 /// font to load from it. If the file represents a single font, pass 0 for `font_index`.
50 #[cfg(not(target_arch = "wasm32"))]
51 fn from_file(file: &mut File, font_index: u32) -> Result<Self, FontLoadingError>;
52
53 /// Loads a font from the path to a `.ttf`/`.otf`/etc. file.
54 ///
55 /// If the file is a collection (`.ttc`/`.otc`/etc.), `font_index` specifies the index of the
56 /// font to load from it. If the file represents a single font, pass 0 for `font_index`.
57 #[cfg(not(target_arch = "wasm32"))]
58 fn from_path<P>(path: P, font_index: u32) -> Result<Self, FontLoadingError>
59 where
60 P: AsRef<Path>,
61 {
62 Loader::from_file(&mut File::open(path)?, font_index)
63 }
64
65 /// Creates a font from a native API handle.
66 unsafe fn from_native_font(native_font: Self::NativeFont) -> Self;
67
68 /// Loads the font pointed to by a handle.
69 fn from_handle(handle: &Handle) -> Result<Self, FontLoadingError> {
70 match *handle {
71 Handle::Memory {
72 ref bytes,
73 font_index,
74 } => Self::from_bytes((*bytes).clone(), font_index),
75 #[cfg(not(target_arch = "wasm32"))]
76 Handle::Path {
77 ref path,
78 font_index,
79 } => Self::from_path(path, font_index),
80 #[cfg(target_arch = "wasm32")]
81 Handle::Path { .. } => Err(FontLoadingError::NoFilesystem),
82 }
83 }
84
85 /// Determines whether a blob of raw font data represents a supported font, and, if so, what
86 /// type of font it is.
87 fn analyze_bytes(font_data: Arc<Vec<u8>>) -> Result<FileType, FontLoadingError>;
88
89 /// Determines whether a file represents a supported font, and, if so, what type of font it is.
90 #[cfg(not(target_arch = "wasm32"))]
91 fn analyze_file(file: &mut File) -> Result<FileType, FontLoadingError>;
92
93 /// Determines whether a path points to a supported font, and, if so, what type of font it is.
94 #[inline]
95 #[cfg(not(target_arch = "wasm32"))]
96 fn analyze_path<P>(path: P) -> Result<FileType, FontLoadingError>
97 where
98 P: AsRef<Path>,
99 {
100 <Self as Loader>::analyze_file(&mut File::open(path)?)
101 }
102
103 /// Returns the wrapped native font handle.
104 fn native_font(&self) -> Self::NativeFont;
105
106 /// Returns the PostScript name of the font. This should be globally unique.
107 fn postscript_name(&self) -> Option<String>;
108
109 /// Returns the full name of the font (also known as "display name" on macOS).
110 fn full_name(&self) -> String;
111
112 /// Returns the name of the font family.
113 fn family_name(&self) -> String;
114
115 /// Returns true if and only if the font is monospace (fixed-width).
116 fn is_monospace(&self) -> bool;
117
118 /// Returns the values of various font properties, corresponding to those defined in CSS.
119 fn properties(&self) -> Properties;
120
121 /// Returns the number of glyphs in the font.
122 ///
123 /// Glyph IDs range from 0 inclusive to this value exclusive.
124 fn glyph_count(&self) -> u32;
125
126 /// Returns the usual glyph ID for a Unicode character.
127 ///
128 /// Be careful with this function; typographically correct character-to-glyph mapping must be
129 /// done using a *shaper* such as HarfBuzz. This function is only useful for best-effort simple
130 /// use cases like "what does character X look like on its own".
131 fn glyph_for_char(&self, character: char) -> Option<u32>;
132
133 /// Returns the glyph ID for the specified glyph name.
134 #[inline]
135 fn glyph_by_name(&self, _name: &str) -> Option<u32> {
136 warn!("unimplemented");
137 None
138 }
139
140 /// Sends the vector path for a glyph to a sink.
141 ///
142 /// If `hinting_mode` is not None, this function performs grid-fitting as requested before
143 /// sending the hinding outlines to the builder.
144 ///
145 /// TODO(pcwalton): What should we do for bitmap glyphs?
146 fn outline<S>(
147 &self,
148 glyph_id: u32,
149 hinting_mode: HintingOptions,
150 sink: &mut S,
151 ) -> Result<(), GlyphLoadingError>
152 where
153 S: OutlineSink;
154
155 /// Returns the boundaries of a glyph in font units. The origin of the coordinate
156 /// space is at the bottom left.
157 fn typographic_bounds(&self, glyph_id: u32) -> Result<RectF, GlyphLoadingError>;
158
159 /// Returns the distance from the origin of the glyph with the given ID to the next, in font
160 /// units.
161 fn advance(&self, glyph_id: u32) -> Result<Vector2F, GlyphLoadingError>;
162
163 /// Returns the amount that the given glyph should be displaced from the origin.
164 fn origin(&self, glyph_id: u32) -> Result<Vector2F, GlyphLoadingError>;
165
166 /// Retrieves various metrics that apply to the entire font.
167 fn metrics(&self) -> Metrics;
168
169 /// Returns a handle to this font, if possible.
170 ///
171 /// This is useful if you want to open the font with a different loader.
172 fn handle(&self) -> Option<Handle> {
173 // FIXME(pcwalton): This doesn't handle font collections!
174 self.copy_font_data()
175 .map(|font_data| Handle::from_memory(font_data, 0))
176 }
177
178 /// Attempts to return the raw font data (contents of the font file).
179 ///
180 /// If this font is a member of a collection, this function returns the data for the entire
181 /// collection.
182 fn copy_font_data(&self) -> Option<Arc<Vec<u8>>>;
183
184 /// Returns true if and only if the font loader can perform hinting in the requested way.
185 ///
186 /// Some APIs support only rasterizing glyphs with hinting, not retriving hinted outlines. If
187 /// `for_rasterization` is false, this function returns true if and only if the loader supports
188 /// retrieval of hinted *outlines*. If `for_rasterization` is true, this function returns true
189 /// if and only if the loader supports *rasterizing* hinted glyphs.
190 fn supports_hinting_options(
191 &self,
192 hinting_options: HintingOptions,
193 for_rasterization: bool,
194 ) -> bool;
195
196 /// Returns the pixel boundaries that the glyph will take up when rendered using this loader's
197 /// rasterizer at the given `point_size` and `transform`. The origin of the coordinate space is
198 /// at the top left.
199 fn raster_bounds(
200 &self,
201 glyph_id: u32,
202 point_size: f32,
203 transform: Transform2F,
204 _: HintingOptions,
205 _: RasterizationOptions,
206 ) -> Result<RectI, GlyphLoadingError> {
207 let typographic_bounds = self.typographic_bounds(glyph_id)?;
208 let typographic_raster_bounds =
209 typographic_bounds * (point_size / self.metrics().units_per_em as f32);
210
211 // Translate the origin to "origin is top left" coordinate system.
212 let new_origin = Vector2F::new(
213 typographic_raster_bounds.origin_x(),
214 -typographic_raster_bounds.origin_y() - typographic_raster_bounds.height(),
215 );
216 let typographic_raster_bounds = RectF::new(new_origin, typographic_raster_bounds.size());
217 Ok((transform * typographic_raster_bounds).round_out().to_i32())
218 }
219
220 /// Rasterizes a glyph to a canvas with the given size and transform.
221 ///
222 /// Format conversion will be performed if the canvas format does not match the rasterization
223 /// options. For example, if bilevel (black and white) rendering is requested to an RGBA
224 /// surface, this function will automatically convert the 1-bit raster image to the 32-bit
225 /// format of the canvas. Note that this may result in a performance penalty, depending on the
226 /// loader.
227 ///
228 /// If `hinting_options` is not None, the requested grid fitting is performed.
229 fn rasterize_glyph(
230 &self,
231 canvas: &mut Canvas,
232 glyph_id: u32,
233 point_size: f32,
234 transform: Transform2F,
235 hinting_options: HintingOptions,
236 rasterization_options: RasterizationOptions,
237 ) -> Result<(), GlyphLoadingError>;
238
239 /// Get font fallback results for the given text and locale.
240 ///
241 /// The `locale` argument is a language tag such as `"en-US"` or `"zh-Hans-CN"`.
242 fn get_fallbacks(&self, text: &str, locale: &str) -> FallbackResult<Self>;
243
244 /// Returns the OpenType font table with the given tag, if the table exists.
245 fn load_font_table(&self, table_tag: u32) -> Option<Box<[u8]>>;
246}
247
248/// The result of a fallback query.
249#[derive(Debug)]
250pub struct FallbackResult<Font> {
251 /// A list of fallback fonts.
252 pub fonts: Vec<FallbackFont<Font>>,
253 /// The fallback list is valid for this slice of the given text.
254 pub valid_len: usize,
255}
256
257/// A single font record for a fallback query result.
258#[derive(Debug)]
259pub struct FallbackFont<Font> {
260 /// The font.
261 pub font: Font,
262 /// A scale factor that should be applied to the fallback font.
263 pub scale: f32,
264 // TODO: add font simulation data
265}
266