Skip to main content

fontoxide_ttlib/
mac_utils.rs

1//! Port of `fontTools.ttLib.macUtils`: fonts in the `sfnt` resources of Mac
2//! resource forks (`.dfont` files and font suitcases), and the
3//! `res_name_or_index` argument of `TTFont` ([`Font::open`]).
4//!
5//! As in fontTools, a file's resource fork is read where the file system has
6//! them (macOS); elsewhere, the data fork is read as a resource fork, which is
7//! how `.dfont` files store their resources.
8
9use std::path::Path;
10
11use fontoxide_misc::mac_res::{ResourceError, ResourceReader};
12
13use crate::{Error, Font, ReadOptions, Result};
14
15/// Which `sfnt` resource to read (`res_name_or_index`).
16#[derive(Debug, Clone, PartialEq, Eq)]
17pub enum ResNameOrIndex {
18	/// The resource with this name.
19	Name(String),
20	/// The resource at this index, from 1. With [`Font::open`], 0 reads the
21	/// first `sfnt` resource if the file has any, else the file itself.
22	Index(i64),
23}
24
25fn resource_error(e: ResourceError) -> Error {
26	match e {
27		ResourceError::Io(e) => Error::Io(e),
28		ResourceError::Resource(m) => Error::ttlib(format!("ResourceError: {m}")),
29		ResourceError::Other(m) => Error::value(m),
30	}
31}
32
33/// The indices, from 1, of the `sfnt` resources of a file, or none if it is
34/// not a resource fork (`getSFNTResIndices`).
35pub fn get_sfnt_res_indices(path: impl AsRef<Path>) -> Result<Vec<usize>> {
36	match ResourceReader::open(path) {
37		Ok(reader) => Ok(reader.get_indices("sfnt")),
38		Err(ResourceError::Resource(_)) => Ok(Vec::new()),
39		Err(e) => Err(resource_error(e)),
40	}
41}
42
43/// The data of an `sfnt` resource of a resource fork.
44pub fn sfnt_resource_data(reader: &ResourceReader, res: &ResNameOrIndex) -> Result<Vec<u8>> {
45	let rsrc = match res {
46		ResNameOrIndex::Name(name) => reader.get_named_resource("sfnt", name),
47		ResNameOrIndex::Index(index) => reader.get_ind_resource("sfnt", *index),
48	};
49	match rsrc {
50		Some(rsrc) => Ok(rsrc.data.clone()),
51		None => Err(Error::ttlib(format!(
52			"sfnt resource not found: {}",
53			match res {
54				ResNameOrIndex::Name(name) => name.clone(),
55				ResNameOrIndex::Index(index) => index.to_string(),
56			}
57		))),
58	}
59}
60
61/// The data of an `sfnt` resource of a file (`SFNTResourceReader(path,
62/// res_name_or_index)`).
63pub fn sfnt_resource(path: impl AsRef<Path>, res: &ResNameOrIndex) -> Result<Vec<u8>> {
64	let reader = ResourceReader::open(path).map_err(resource_error)?;
65	sfnt_resource_data(&reader, res)
66}
67
68/// The fonts of a file (`openTTFonts`): the file itself if it has no `sfnt`
69/// resources, else one font per resource.
70pub fn open_tt_fonts(path: impl AsRef<Path>) -> Result<Vec<Font>> {
71	let path = path.as_ref();
72	let sfnts = get_sfnt_res_indices(path)?;
73	if sfnts.is_empty() {
74		return Ok(vec![Font::open(path, None, ReadOptions::default())?]);
75	}
76	sfnts
77		.into_iter()
78		.map(|index| {
79			Font::open(
80				path,
81				Some(&ResNameOrIndex::Index(index as i64)),
82				ReadOptions::default(),
83			)
84		})
85		.collect()
86}
87
88impl Font {
89	/// Reads a font file (`TTFont(path, res_name_or_index)`). With
90	/// `res_name_or_index`, the font is the `sfnt` resource of the file's
91	/// resource fork that it names; [`ResNameOrIndex::Index`] 0 reads the first
92	/// one if there is any, else the file as an ordinary font file, as `ttx` does.
93	/// Without it, this is [`Font::read`] on the file's data.
94	pub fn open(
95		path: impl AsRef<Path>,
96		res_name_or_index: Option<&ResNameOrIndex>,
97		options: ReadOptions,
98	) -> Result<Font> {
99		let path = path.as_ref();
100		let data = match res_name_or_index {
101			None => std::fs::read(path)?,
102			Some(ResNameOrIndex::Index(0)) => {
103				if get_sfnt_res_indices(path)?.is_empty() {
104					std::fs::read(path)?
105				} else {
106					sfnt_resource(path, &ResNameOrIndex::Index(1))?
107				}
108			}
109			Some(res) => sfnt_resource(path, res)?,
110		};
111		Font::read(data, options)
112	}
113}