zed_font_kit/loader.rs
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: 'static;
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 { bytes, font_index } => Self::from_bytes((*bytes).clone(), *font_index),
72 #[cfg(not(target_arch = "wasm32"))]
73 Handle::Path { path, font_index } => Self::from_path(path, *font_index),
74 #[cfg(target_arch = "wasm32")]
75 Handle::Path { .. } => Err(FontLoadingError::NoFilesystem),
76 Handle::Native { .. } => {
77 if let Some(native) = handle.native_as::<Self::NativeFont>() {
78 unsafe { Ok(Self::from_native_font(native)) }
79 } else {
80 Err(FontLoadingError::UnknownFormat)
81 }
82 }
83 }
84 }
85
86 /// Determines whether a blob of raw font data represents a supported font, and, if so, what
87 /// type of font it is.
88 fn analyze_bytes(font_data: Arc<Vec<u8>>) -> Result<FileType, FontLoadingError>;
89
90 /// Determines whether a file represents a supported font, and, if so, what type of font it is.
91 #[cfg(not(target_arch = "wasm32"))]
92 fn analyze_file(file: &mut File) -> Result<FileType, FontLoadingError>;
93
94 /// Determines whether a path points to a supported font, and, if so, what type of font it is.
95 #[inline]
96 #[cfg(not(target_arch = "wasm32"))]
97 fn analyze_path<P>(path: P) -> Result<FileType, FontLoadingError>
98 where
99 P: AsRef<Path>,
100 {
101 <Self as Loader>::analyze_file(&mut File::open(path)?)
102 }
103
104 /// Returns the wrapped native font handle.
105 fn native_font(&self) -> Self::NativeFont;
106
107 /// Returns the PostScript name of the font. This should be globally unique.
108 fn postscript_name(&self) -> Option<String>;
109
110 /// Returns the full name of the font (also known as "display name" on macOS).
111 fn full_name(&self) -> String;
112
113 /// Returns the name of the font family.
114 fn family_name(&self) -> String;
115
116 /// Returns true if and only if the font is monospace (fixed-width).
117 fn is_monospace(&self) -> bool;
118
119 /// Returns the values of various font properties, corresponding to those defined in CSS.
120 fn properties(&self) -> Properties;
121
122 /// Returns the number of glyphs in the font.
123 ///
124 /// Glyph IDs range from 0 inclusive to this value exclusive.
125 fn glyph_count(&self) -> u32;
126
127 /// Returns the usual glyph ID for a Unicode character.
128 ///
129 /// Be careful with this function; typographically correct character-to-glyph mapping must be
130 /// done using a *shaper* such as HarfBuzz. This function is only useful for best-effort simple
131 /// use cases like "what does character X look like on its own".
132 fn glyph_for_char(&self, character: char) -> Option<u32>;
133
134 /// Returns the glyph ID for the specified glyph name.
135 #[inline]
136 fn glyph_by_name(&self, _name: &str) -> Option<u32> {
137 warn!("unimplemented");
138 None
139 }
140
141 /// Sends the vector path for a glyph to a sink.
142 ///
143 /// If `hinting_mode` is not None, this function performs grid-fitting as requested before
144 /// sending the hinding outlines to the builder.
145 ///
146 /// TODO(pcwalton): What should we do for bitmap glyphs?
147 fn outline<S>(
148 &self,
149 glyph_id: u32,
150 hinting_mode: HintingOptions,
151 sink: &mut S,
152 ) -> Result<(), GlyphLoadingError>
153 where
154 S: OutlineSink;
155
156 /// Returns the boundaries of a glyph in font units. The origin of the coordinate
157 /// space is at the bottom left.
158 fn typographic_bounds(&self, glyph_id: u32) -> Result<RectF, GlyphLoadingError>;
159
160 /// Returns the distance from the origin of the glyph with the given ID to the next, in font
161 /// units.
162 fn advance(&self, glyph_id: u32) -> Result<Vector2F, GlyphLoadingError>;
163
164 /// Returns the amount that the given glyph should be displaced from the origin.
165 fn origin(&self, glyph_id: u32) -> Result<Vector2F, GlyphLoadingError>;
166
167 /// Retrieves various metrics that apply to the entire font.
168 fn metrics(&self) -> Metrics;
169
170 /// Returns a handle to this font, if possible.
171 ///
172 /// This is useful if you want to open the font with a different loader.
173 fn handle(&self) -> Option<Handle> {
174 // FIXME(pcwalton): This doesn't handle font collections!
175 self.copy_font_data()
176 .map(|font_data| Handle::from_memory(font_data, 0))
177 }
178
179 /// Attempts to return the raw font data (contents of the font file).
180 ///
181 /// If this font is a member of a collection, this function returns the data for the entire
182 /// collection.
183 fn copy_font_data(&self) -> Option<Arc<Vec<u8>>>;
184
185 /// Returns true if and only if the font loader can perform hinting in the requested way.
186 ///
187 /// Some APIs support only rasterizing glyphs with hinting, not retrieving hinted outlines. If
188 /// `for_rasterization` is false, this function returns true if and only if the loader supports
189 /// retrieval of hinted *outlines*. If `for_rasterization` is true, this function returns true
190 /// if and only if the loader supports *rasterizing* hinted glyphs.
191 fn supports_hinting_options(
192 &self,
193 hinting_options: HintingOptions,
194 for_rasterization: bool,
195 ) -> bool;
196
197 /// Returns the pixel boundaries that the glyph will take up when rendered using this loader's
198 /// rasterizer at the given `point_size` and `transform`. The origin of the coordinate space is
199 /// at the top left.
200 fn raster_bounds(
201 &self,
202 glyph_id: u32,
203 point_size: f32,
204 transform: Transform2F,
205 _: HintingOptions,
206 _: RasterizationOptions,
207 ) -> Result<RectI, GlyphLoadingError> {
208 let typographic_bounds = self.typographic_bounds(glyph_id)?;
209 let typographic_raster_bounds =
210 typographic_bounds * (point_size / self.metrics().units_per_em as f32);
211
212 // Translate the origin to "origin is top left" coordinate system.
213 let new_origin = Vector2F::new(
214 typographic_raster_bounds.origin_x(),
215 -typographic_raster_bounds.origin_y() - typographic_raster_bounds.height(),
216 );
217 let typographic_raster_bounds = RectF::new(new_origin, typographic_raster_bounds.size());
218 Ok((transform * typographic_raster_bounds).round_out().to_i32())
219 }
220
221 /// Rasterizes a glyph to a canvas with the given size and transform.
222 ///
223 /// Format conversion will be performed if the canvas format does not match the rasterization
224 /// options. For example, if bilevel (black and white) rendering is requested to an RGBA
225 /// surface, this function will automatically convert the 1-bit raster image to the 32-bit
226 /// format of the canvas. Note that this may result in a performance penalty, depending on the
227 /// loader.
228 ///
229 /// If `hinting_options` is not None, the requested grid fitting is performed.
230 fn rasterize_glyph(
231 &self,
232 canvas: &mut Canvas,
233 glyph_id: u32,
234 point_size: f32,
235 transform: Transform2F,
236 hinting_options: HintingOptions,
237 rasterization_options: RasterizationOptions,
238 ) -> Result<(), GlyphLoadingError>;
239
240 /// Get font fallback results for the given text and locale.
241 ///
242 /// The `locale` argument is a language tag such as `"en-US"` or `"zh-Hans-CN"`.
243 fn get_fallbacks(&self, text: &str, locale: &str) -> FallbackResult<Self>;
244
245 /// Returns the OpenType font table with the given tag, if the table exists.
246 fn load_font_table(&self, table_tag: u32) -> Option<Box<[u8]>>;
247}
248
249/// The result of a fallback query.
250#[derive(Debug)]
251pub struct FallbackResult<Font> {
252 /// A list of fallback fonts.
253 pub fonts: Vec<FallbackFont<Font>>,
254 /// The fallback list is valid for this slice of the given text.
255 pub valid_len: usize,
256}
257
258/// A single font record for a fallback query result.
259#[derive(Debug)]
260pub struct FallbackFont<Font> {
261 /// The font.
262 pub font: Font,
263 /// A scale factor that should be applied to the fallback font.
264 pub scale: f32,
265 // TODO: add font simulation data
266}