Skip to main content

fontoxide_ttlib/
collection.rs

1//! Port of `fontTools.ttLib.ttCollection`: TrueType / OpenType collections.
2
3use std::sync::Arc;
4
5use fontoxide_misc::xml_writer::{INDENT, XmlWriter};
6
7use crate::binary::WriteBytes;
8use crate::font::{TTLIB_VERSION, TableCache};
9use crate::sfnt::{TTC_V1, TTC_V1_1, TTC_V2, TTC_V2_1, read_ttc_header};
10use crate::{Font, ReadOptions, Result, TtxOptions};
11
12/// A TrueType or OpenType collection (`TTCollection`).
13#[derive(Debug, Clone, Default)]
14pub struct TtCollection {
15	/// The fonts (`fonts`). For version 1.1 and 2.1 collections, the preferred,
16	/// extended list.
17	pub fonts: Vec<Font>,
18	/// For version 1.1 and 2.1 collections, the compatibility list
19	/// (`legacyFonts`). fontoxide does not derive it.
20	pub legacy_fonts: Option<Vec<Font>>,
21	/// The collection's digital signature (`dsig`). `Some(None)` writes a version
22	/// 2 header without a signature; `None` writes version 1.
23	pub dsig: Option<Option<Vec<u8>>>,
24}
25
26impl TtCollection {
27	/// Reads every font of a collection (`TTCollection(file)`). The font number in
28	/// `options` is ignored.
29	pub fn read(data: impl Into<Arc<[u8]>>, options: ReadOptions) -> Result<Self> {
30		let data: Arc<[u8]> = data.into();
31		let header = read_ttc_header(&data)?;
32		let read = |i: usize, use_legacy_ttc: bool| {
33			Font::read(
34				data.clone(),
35				ReadOptions {
36					font_number: Some(i),
37					use_legacy_ttc,
38					..options
39				},
40			)
41		};
42		let mut collection = TtCollection::default();
43		let num_fonts = header
44			.offset_table2
45			.as_ref()
46			.map_or(header.num_fonts as usize, Vec::len);
47		for i in 0..num_fonts {
48			collection.fonts.push(read(i, false)?);
49		}
50		if header.offset_table2.is_some() {
51			let mut legacy = Vec::new();
52			for i in 0..header.num_fonts as usize {
53				legacy.push(read(i, true)?);
54			}
55			collection.legacy_fonts = Some(legacy);
56		}
57		if let Some((_tag, length, offset)) = header.dsig {
58			collection.dsig = Some(None);
59			if offset != 0 {
60				let start = offset as usize;
61				let end = (start + length as usize).min(data.len());
62				collection.dsig = Some(Some(data.get(start..end).unwrap_or_default().to_vec()));
63			}
64		}
65		Ok(collection)
66	}
67
68	/// Compiles the collection (`save`). With `share_tables`, identical tables are
69	/// stored once.
70	pub fn write(&mut self, share_tables: bool) -> Result<Vec<u8>> {
71		let mut cache = TableCache::new();
72		let has_legacy = self.legacy_fonts.is_some();
73		let version = match (self.dsig.is_some(), has_legacy) {
74			(true, true) => TTC_V2_1,
75			(true, false) => TTC_V2,
76			(false, true) => TTC_V1_1,
77			(false, false) => TTC_V1,
78		};
79
80		// Pin one 'modified' timestamp so that the fonts' 'head' tables can be
81		// shared (`_sharedModifiedTimestamp`).
82		let now = fontoxide_misc::time_tools::timestamp_now();
83		let mut restore = Vec::new();
84		for (i, font) in self
85			.legacy_fonts
86			.iter_mut()
87			.flatten()
88			.chain(self.fonts.iter_mut())
89			.enumerate()
90		{
91			if font.recalc_timestamp && font.contains(crate::Tag::new(b"head")) {
92				restore.push(i);
93				let now =
94					now.ok_or_else(|| crate::Error::value(crate::tables::head::NO_TIMESTAMP))?;
95				font.require::<crate::tables::Head>()?.modified =
96					crate::binary::fit(now, "modified")?;
97				font.recalc_timestamp = false;
98			}
99		}
100		let result = self.write_fonts(version, share_tables.then_some(&mut cache));
101		for (i, font) in self
102			.legacy_fonts
103			.iter_mut()
104			.flatten()
105			.chain(self.fonts.iter_mut())
106			.enumerate()
107		{
108			if restore.contains(&i) {
109				font.recalc_timestamp = true;
110			}
111		}
112		result
113	}
114
115	fn write_fonts(&mut self, version: u32, mut cache: Option<&mut TableCache>) -> Result<Vec<u8>> {
116		let has_legacy = self.legacy_fonts.is_some();
117		let num_fonts = self
118			.legacy_fonts
119			.as_ref()
120			.map_or(self.fonts.len(), Vec::len);
121		// writeTTCHeader
122		let mut file = Vec::new();
123		file.extend_from_slice(b"ttcf");
124		file.put_u32(version);
125		file.put_u32(num_fonts as u32);
126		let offsets_offset = file.len();
127		file.resize(file.len() + 4 * num_fonts, 0);
128		if matches!(version, TTC_V2 | TTC_V2_1) {
129			file.resize(file.len() + 12, 0);
130		}
131		let mut offsets2_offset = None;
132		if matches!(version, TTC_V1_1 | TTC_V2_1) {
133			file.put_u32(self.fonts.len() as u32);
134			offsets2_offset = Some(file.len());
135			file.resize(file.len() + 4 * self.fonts.len(), 0);
136		}
137
138		let mut legacy_offsets = Vec::new();
139		for font in self.legacy_fonts.iter_mut().flatten() {
140			legacy_offsets.push(file.len() as u32);
141			file = font.save_into(file, cache.as_deref_mut(), None)?.0;
142		}
143		let mut offsets = Vec::new();
144		for font in &mut self.fonts {
145			offsets.push(file.len() as u32);
146			file = font.save_into(file, cache.as_deref_mut(), None)?.0;
147		}
148
149		let write_u32s = |file: &mut Vec<u8>, at: usize, values: &[u32]| {
150			for (i, v) in values.iter().enumerate() {
151				file[at + 4 * i..at + 4 * i + 4].copy_from_slice(&v.to_be_bytes());
152			}
153		};
154		if has_legacy {
155			write_u32s(&mut file, offsets_offset, &legacy_offsets);
156			if let Some(at) = offsets2_offset {
157				write_u32s(&mut file, at, &offsets);
158			}
159		} else {
160			write_u32s(&mut file, offsets_offset, &offsets);
161		}
162		if let Some(Some(dsig)) = &self.dsig {
163			let header_at = offsets_offset
164				+ 4 * if has_legacy {
165					legacy_offsets.len()
166				} else {
167					offsets.len()
168				};
169			let dsig_offset = file.len() as u32;
170			file.extend_from_slice(dsig);
171			file[header_at..header_at + 4].copy_from_slice(b"DSIG");
172			write_u32s(&mut file, header_at + 4, &[dsig.len() as u32, dsig_offset]);
173		}
174		Ok(file)
175	}
176
177	/// Dumps the collection as TTX (`saveXML`). `options.tables` and the other
178	/// options apply to every font; `write_version` controls the
179	/// `ttCollection` element.
180	pub fn to_ttx(&mut self, options: &TtxOptions) -> Result<String> {
181		let mut writer = XmlWriter::with_options(INDENT, &options.newline);
182		if options.write_version {
183			writer.begintag("ttCollection", &[("ttLibVersion", &TTLIB_VERSION)]);
184		} else {
185			writer.begintag("ttCollection", &[]);
186		}
187		writer.newline();
188		writer.newline();
189		let font_options = TtxOptions {
190			write_version: false,
191			..options.clone()
192		};
193		for font in &mut self.fonts {
194			font.save_xml(&mut writer, &font_options)?;
195			writer.newline();
196		}
197		writer.endtag("ttCollection");
198		writer.newline();
199		Ok(writer.into_string())
200	}
201}