fontoxide_ttlib/
mac_utils.rs1use std::path::Path;
10
11use fontoxide_misc::mac_res::{ResourceError, ResourceReader};
12
13use crate::{Error, Font, ReadOptions, Result};
14
15#[derive(Debug, Clone, PartialEq, Eq)]
17pub enum ResNameOrIndex {
18 Name(String),
20 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
33pub 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
43pub 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
61pub 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
68pub 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 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}