Skip to main content

fontoxide_ttlib/
cli.rs

1//! The command line (`fontTools.ttLib.__main__`): opens fonts and collections,
2//! and saves them as one font or a collection.
3
4use crate::{Error, Flavor, Font, ReadOptions, Result, Tag, TtCollection, WriteOptions};
5
6const HELP: &str = "\
7usage: fonttools ttLib [-h] [-t table] [-o FILE] [-y NUMBER] [--lazy]
8                       [--no-lazy] [--flavor FLAVOR] [--no-recalc-timestamp]
9                       [-b] [--optimize-font-speed]
10                       [font ...]
11
12Open/save fonts with TTFont() or TTCollection()
13
14positional arguments:
15  font                  Font file.
16
17options:
18  -h, --help            show this help message and exit
19  -t, --table table     Tables to decompile.
20  -o, --output FILE     Output file.
21  -y NUMBER             Font number to load from collections.
22  --lazy                Load fonts lazily.
23  --no-lazy             Load fonts immediately.
24  --flavor FLAVOR       Flavor of output font. 'woff' or 'woff2'.
25  --no-recalc-timestamp
26                        Keep the original font 'modified' timestamp.
27  -b                    Don't recalc glyph bounding boxes: use the values in
28                        the original font.
29  --optimize-font-speed
30                        Enable optimizations that prioritize speed over file
31                        size. This mainly affects how glyf table and gvar /
32                        VARC tables are compiled.
33
34If multiple files are given on the command-line, they are each opened (as a
35font or collection), and added to the font list. The above, when combined with
36-o / --output, allows for extracting a single font from a collection, or
37combining multiple fonts into a collection.
38";
39
40/// The help text of the command line.
41pub fn help() -> &'static str {
42	HELP
43}
44
45/// `argparse` errors.
46fn usage(message: String) -> Error {
47	Error::value(format!("error: {message}"))
48}
49
50/// The command line `fonttools ttLib` (`main`): opens each file as a font, or as
51/// a collection whose fonts are all added, decompiles the requested tables
52/// (`-t`, or all of them with `--no-lazy`), and with `-o` saves the fonts: one
53/// font as a font, several as a collection. Returns the exit code.
54///
55/// fontoxide always reads fonts completely, so `--lazy` only changes which
56/// tables are decompiled, as in fontTools. `--optimize-font-speed` sets
57/// [`Font::optimize_font_speed`] on every font, including the fonts in
58/// collections, and, without `-t` or `--no-lazy`, decompiles each font's `glyf`,
59/// `GLYF`, `gvar`, `GVAR` and `VARC` so that they are recompiled.
60pub fn main(args: &[&str]) -> Result<i32> {
61	let mut fonts_args: Vec<&str> = Vec::new();
62	let mut tables: Option<Vec<&str>> = None;
63	let mut output: Option<&str> = None;
64	let mut font_number: &str = "-1";
65	let mut lazy: Option<bool> = None;
66	let mut flavor: Option<&str> = None;
67	let mut recalc_timestamp = true;
68	let mut recalc_bboxes = true;
69	let mut optimize_font_speed = false;
70	let mut it = args.iter().copied();
71	let mut only_positional = false;
72	while let Some(arg) = it.next() {
73		if only_positional || arg == "-" || !arg.starts_with('-') {
74			fonts_args.push(arg);
75			continue;
76		}
77		let (name, inline) = match arg.split_once('=') {
78			Some((name, value)) if name.starts_with("--") => (name, Some(value)),
79			// `-oFILE`, `-yNUMBER`, `-ttable`.
80			_ if !arg.starts_with("--") && arg.len() > 2 => (&arg[..2], Some(&arg[2..])),
81			_ => (arg, None),
82		};
83		let mut value = |option: &str| -> Result<&str> {
84			match inline {
85				Some(v) => Ok(v),
86				None => it
87					.next()
88					.ok_or_else(|| usage(format!("argument {option}: expected one argument"))),
89			}
90		};
91		match name {
92			"--" => only_positional = true,
93			"-h" | "--help" => {
94				print!(
95					"{}",
96					fontoxide_misc::cli_tools::program_text(HELP, "fonttools ttLib", "ttLib")
97				);
98				return Ok(0);
99			}
100			"-t" | "--table" => tables
101				.get_or_insert_with(Vec::new)
102				.push(value("-t/--table")?),
103			"-o" | "--output" => output = Some(value("-o/--output")?),
104			"-y" => font_number = value("-y")?,
105			"--flavor" => flavor = Some(value("--flavor")?),
106			"--lazy" if inline.is_none() => lazy = Some(true),
107			"--no-lazy" if inline.is_none() => lazy = Some(false),
108			"--no-recalc-timestamp" if inline.is_none() => recalc_timestamp = false,
109			"-b" if inline.is_none() => recalc_bboxes = false,
110			"--optimize-font-speed" if inline.is_none() => optimize_font_speed = true,
111			_ => return Err(usage(format!("unrecognized arguments: {arg}"))),
112		}
113	}
114	let font_number = fontoxide_misc::py::parse_int(font_number).ok_or_else(|| {
115		Error::value(format!(
116			"invalid literal for int() with base 10: {}",
117			fontoxide_misc::py::str_repr(font_number)
118		))
119	})?;
120	let flavor = match flavor {
121		None => None,
122		Some("woff") => Some(Flavor::Woff),
123		Some("woff2") => Some(Flavor::Woff2),
124		Some(other) => return Err(Error::ttlib(format!("Unknown flavor '{other}'"))),
125	};
126
127	let mut fonts = Vec::new();
128	for path in fonts_args {
129		let data: std::sync::Arc<[u8]> = std::fs::read(path)?.into();
130		let options = ReadOptions {
131			font_number: usize::try_from(font_number).ok(),
132			recalc_bboxes,
133			recalc_timestamp,
134			..Default::default()
135		};
136		match Font::read(data.clone(), options) {
137			Ok(font) => fonts.push(font),
138			Err(Error::FileIsCollection(_)) => {
139				fonts.extend(TtCollection::read(data, ReadOptions::default())?.fonts);
140			}
141			Err(e) => return Err(e),
142		}
143	}
144
145	for font in &mut fonts {
146		if optimize_font_speed {
147			font.optimize_font_speed = true;
148		}
149		let font_tables: Vec<&str> = match &tables {
150			Some(tables) => tables.clone(),
151			None if lazy == Some(false) => vec!["*"],
152			// `{"glyf", "GLYF", "gvar", "GVAR", "VARC"}.intersection(font.keys())`:
153			// the order does not matter.
154			None if optimize_font_speed => {
155				let tags = font.tags();
156				["glyf", "GLYF", "gvar", "GVAR", "VARC"]
157					.into_iter()
158					.filter(|t| Tag::from_str_exact(t).is_some_and(|tag| tags.contains(&tag)))
159					.collect()
160			}
161			None => Vec::new(),
162		};
163		if font_tables.contains(&"GlyphOrder") {
164			font.glyph_order()?;
165		}
166		let tags: Vec<Tag> = if font_tables.contains(&"*") {
167			font.tags()
168		} else {
169			font_tables
170				.iter()
171				.filter(|t| **t != "GlyphOrder")
172				.map(|t| {
173					Tag::from_str_exact(t).ok_or_else(|| {
174						Error::ttlib(format!("KeyError: {}", fontoxide_misc::py::str_repr(t)))
175					})
176				})
177				.collect::<Result<_>>()?
178		};
179		for tag in tags {
180			// `font[table]`.
181			if !font.load(tag)? {
182				return Err(Error::TableNotFound(tag));
183			}
184		}
185	}
186
187	if let Some(output) = output {
188		let data = if let [font] = fonts.as_mut_slice() {
189			font.flavor = flavor;
190			font.write(&WriteOptions::default())?
191		} else {
192			if flavor.is_some() {
193				return Err(Error::ttlib("Cannot set flavor for collections."));
194			}
195			let mut collection = TtCollection {
196				fonts,
197				..Default::default()
198			};
199			collection.write(true)?
200		};
201		std::fs::write(output, data)?;
202	}
203	Ok(0)
204}