Skip to main content

fontoxide_misc/
ps_operators.rs

1//! Port of `fontTools.misc.psOperators`: the objects of the minimal PostScript
2//! interpreter of [`ps_lib`](crate::ps_lib), and the key orders of Type 1 font
3//! dictionaries.
4//!
5//! The operators themselves (`PSOperators`) are methods of
6//! [`PsInterpreter`](crate::ps_lib::PsInterpreter).
7
8use std::cell::RefCell;
9use std::fmt;
10use std::rc::Rc;
11
12use indexmap::IndexMap;
13
14/// A shared, mutable PostScript object: Python objects are references, and
15/// operators like `cvx`, `readonly` and `readstring` change them in place.
16pub type ObjRef = Rc<RefCell<PsObject>>;
17
18/// A shared dictionary (`ps_dict.value`, `ps_font.value`, the dictionaries of
19/// the dictionary stack).
20pub type DictRef = Rc<RefCell<IndexMap<Key, ObjRef>>>;
21
22/// A dictionary key: the hashable Python values that PostScript objects carry.
23///
24/// Numbers that compare equal in Python are the same key (`1 == 1.0 == True`).
25#[derive(Debug, Clone, PartialEq, Eq, Hash, PartialOrd, Ord)]
26pub enum Key {
27	/// `None` (the value of operators and `null`).
28	None,
29	/// An integer, a boolean, or a float with an integral value.
30	Int(i64),
31	/// A float without an integral value, by its bits.
32	Float(u64),
33	/// A string: names, literals and text strings.
34	Str(String),
35	/// A byte string, as `readstring` makes them.
36	Bytes(Vec<u8>),
37	/// The file object of a tokenizer, by identity.
38	File(u64),
39}
40
41impl Key {
42	/// The name, for string keys.
43	pub fn as_str(&self) -> Option<&str> {
44		match self {
45			Key::Str(s) => Some(s),
46			_ => None,
47		}
48	}
49}
50
51impl fmt::Display for Key {
52	/// `str(key)`.
53	fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
54		match self {
55			Key::None => f.write_str("None"),
56			Key::Int(i) => write!(f, "{i}"),
57			Key::Float(bits) => f.write_str(&crate::py::float_repr(f64::from_bits(*bits))),
58			Key::Str(s) => f.write_str(s),
59			Key::Bytes(b) => f.write_str(&crate::py::bytes_repr(b)),
60			Key::File(_) => f.write_str("<fontTools.misc.psLib.PSTokenizer object>"),
61		}
62	}
63}
64
65impl From<&str> for Key {
66	fn from(s: &str) -> Self {
67		Key::Str(s.to_owned())
68	}
69}
70
71/// The value of a string object (`ps_string.value`): text, or the bytes that
72/// `readstring` reads.
73#[derive(Debug, Clone, PartialEq, Eq)]
74pub enum PsString {
75	/// A `str`; characters of hexadecimal strings are in `0..=255`.
76	Text(String),
77	/// A `bytes`.
78	Bytes(Vec<u8>),
79}
80
81impl PsString {
82	/// `len(value)`: characters or bytes.
83	pub fn len(&self) -> usize {
84		match self {
85			PsString::Text(s) => s.chars().count(),
86			PsString::Bytes(b) => b.len(),
87		}
88	}
89
90	/// Whether it is empty.
91	pub fn is_empty(&self) -> bool {
92		self.len() == 0
93	}
94}
95
96/// What a PostScript object is, with its value.
97#[derive(Clone)]
98pub enum Kind {
99	/// `ps_operator`, by name; the interpreter runs it.
100	Operator(&'static str),
101	/// `ps_procedure`.
102	Procedure(Vec<ObjRef>),
103	/// `ps_name`.
104	Name(String),
105	/// `ps_literal`.
106	Literal(String),
107	/// `ps_array`; `None` for the elements `array` leaves unset.
108	Array(Vec<Option<ObjRef>>),
109	/// `ps_dict`.
110	Dict(DictRef),
111	/// `ps_font`.
112	Font(DictRef),
113	/// `ps_mark`.
114	Mark,
115	/// `ps_procmark`.
116	ProcMark,
117	/// `ps_null`.
118	Null,
119	/// `ps_file`: the tokenizer of the interpreter, by identity.
120	File(u64),
121	/// `ps_boolean`. `true` and `false` of `systemdict` hold the integers 1 and 0
122	/// in fontTools (`py_bool` false); the comparison operators hold Python
123	/// booleans.
124	Boolean {
125		/// The truth value.
126		value: bool,
127		/// Whether the value is a Python `bool` rather than an `int`.
128		py_bool: bool,
129	},
130	/// `ps_string`.
131	String(PsString),
132	/// `ps_integer`.
133	Integer(i64),
134	/// `ps_real`.
135	Real(f64),
136}
137
138impl fmt::Debug for Kind {
139	fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
140		match self {
141			Kind::Operator(n) => write!(f, "<operator {n}>"),
142			Kind::Procedure(_) => f.write_str("<procedure>"),
143			Kind::Name(n) => write!(f, "<name {}>", crate::py::str_repr(n)),
144			Kind::Literal(n) => write!(f, "<literal {}>", crate::py::str_repr(n)),
145			Kind::Array(_) => f.write_str("<array>"),
146			Kind::Dict(_) => f.write_str("<dict>"),
147			Kind::Font(_) => f.write_str("<font>"),
148			Kind::Mark => f.write_str("<mark 'mark'>"),
149			Kind::ProcMark => f.write_str("<procmark 'procmark'>"),
150			Kind::Null => f.write_str("<null None>"),
151			Kind::File(_) => f.write_str("<file>"),
152			Kind::Boolean { value, .. } => write!(f, "<boolean {value}>"),
153			Kind::String(s) => write!(f, "<string {s:?}>"),
154			Kind::Integer(i) => write!(f, "<integer {i}>"),
155			Kind::Real(r) => write!(f, "<real {}>", crate::py::float_repr(*r)),
156		}
157	}
158}
159
160/// A PostScript object (`ps_object`).
161#[derive(Debug, Clone)]
162pub struct PsObject {
163	/// The kind and value.
164	pub kind: Kind,
165	/// Whether it is literal rather than executable (`literal`).
166	pub literal: bool,
167	/// The access level: 0 unlimited, 1 `readonly`, 2 `executeonly`, 3
168	/// `noaccess` (`access`).
169	pub access: u8,
170}
171
172impl PsObject {
173	/// A new object, literal or executable as its class is in fontTools.
174	pub fn new(kind: Kind) -> ObjRef {
175		let literal = !matches!(kind, Kind::Operator(_) | Kind::Procedure(_) | Kind::Name(_));
176		Rc::new(RefCell::new(PsObject {
177			kind,
178			literal,
179			access: 0,
180		}))
181	}
182
183	/// The type name (`type`), e.g. `"integertype"`.
184	pub fn type_name(&self) -> &'static str {
185		match self.kind {
186			Kind::Operator(_) => "operatortype",
187			Kind::Procedure(_) => "proceduretype",
188			Kind::Name(_) => "nametype",
189			Kind::Literal(_) => "literaltype",
190			Kind::Array(_) => "arraytype",
191			Kind::Dict(_) => "dicttype",
192			Kind::Font(_) => "fonttype",
193			Kind::Mark => "marktype",
194			Kind::ProcMark => "procmarktype",
195			Kind::Null => "nulltype",
196			Kind::File(_) => "filetype",
197			Kind::Boolean { .. } => "booleantype",
198			Kind::String(_) => "stringtype",
199			Kind::Integer(_) => "integertype",
200			Kind::Real(_) => "realtype",
201		}
202	}
203}
204
205/// The access names (`_accessstrings`).
206pub const ACCESS_STRINGS: [&str; 4] = ["", "readonly", "executeonly", "noaccess"];
207
208/// The keys of a Type 1 font dictionary before the `eexec` part, in order
209/// (`_type1_pre_eexec_order`).
210pub const TYPE1_PRE_EEXEC_ORDER: [&str; 10] = [
211	"FontInfo",
212	"FontName",
213	"Encoding",
214	"PaintType",
215	"FontType",
216	"FontMatrix",
217	"FontBBox",
218	"UniqueID",
219	"Metrics",
220	"StrokeWidth",
221];
222
223/// The keys of a Type 1 `FontInfo` dictionary, in order (`_type1_fontinfo_order`).
224pub const TYPE1_FONTINFO_ORDER: [&str; 9] = [
225	"version",
226	"Notice",
227	"FullName",
228	"FamilyName",
229	"Weight",
230	"ItalicAngle",
231	"isFixedPitch",
232	"UnderlinePosition",
233	"UnderlineThickness",
234];
235
236/// The keys of a Type 1 font dictionary in the `eexec` part, in order
237/// (`_type1_post_eexec_order`).
238pub const TYPE1_POST_EEXEC_ORDER: [&str; 3] = ["Private", "CharStrings", "FID"];