1use std::collections::BTreeMap;
7
8use fontoxide_misc::Tag;
9use fontoxide_misc::xml_reader::Element;
10use fontoxide_misc::xml_writer::XmlWriter;
11
12use crate::binary::{Reader, WriteBytes, fit};
13use crate::sstruct::eval;
14use crate::table::{Table, TableType, TableXml};
15use crate::{Error, Font, Result};
16
17#[derive(Debug, Clone, PartialEq, Default)]
19pub struct RatRange {
20 pub b_char_set: i64,
22 pub x_ratio: i64,
24 pub y_start_ratio: i64,
26 pub y_end_ratio: i64,
28 pub group_index: Option<i64>,
30}
31
32pub type VdmxGroup = BTreeMap<i64, (i64, i64)>;
34
35#[derive(Debug, Clone, PartialEq, Default)]
37pub struct Vdmx {
38 pub version: i64,
40 pub num_recs: usize,
42 pub num_ratios: usize,
44 pub rat_ranges: Vec<RatRange>,
46 pub groups: Vec<VdmxGroup>,
48}
49
50fn struct_error(size: usize) -> Error {
51 Error::Struct(format!("unpack requires a buffer of {size} bytes"))
52}
53
54fn empty_min() -> Error {
55 Error::value("min() iterable argument is empty")
56}
57
58fn take<'a>(r: &mut Reader<'a>, n: usize) -> Result<Reader<'a>> {
60 let bytes = r.bytes(n).map_err(|_| struct_error(n))?;
61 Ok(Reader::new(bytes))
62}
63
64impl TableType for Vdmx {
65 const TAG: Tag = Tag::new(b"VDMX");
66
67 fn decompile(data: &[u8], _font: &mut Font) -> Result<Self> {
68 let mut r = Reader::new(data);
69 let mut h = take(&mut r, 6)?;
70 let mut table = Vdmx {
71 version: i64::from(h.u16()?),
72 num_recs: usize::from(h.u16()?),
73 num_ratios: usize::from(h.u16()?),
74 ..Default::default()
75 };
76 let mut pos = 6;
77 for _ in 0..table.num_ratios {
78 let mut b = take(&mut r, 4)?;
79 table.rat_ranges.push(RatRange {
80 b_char_set: i64::from(b.u8()?),
81 x_ratio: i64::from(b.u8()?),
82 y_start_ratio: i64::from(b.u8()?),
83 y_end_ratio: i64::from(b.u8()?),
84 group_index: None,
85 });
86 pos += 4;
87 }
88 let mut offsets = Vec::with_capacity(table.num_ratios);
89 for _ in 0..table.num_ratios {
90 offsets.push(usize::from(take(&mut r, 2)?.u16()?));
91 pos += 2;
92 }
93 for group_index in 0..table.num_recs {
94 let curr_offset = pos;
95 let mut g = take(&mut r, 4)?;
96 let recs = g.u16()?;
97 let startsz = i64::from(g.u8()?);
98 let endsz = i64::from(g.u8()?);
99 pos += 4;
100 let mut group = VdmxGroup::new();
101 for _ in 0..recs {
102 let mut v = take(&mut r, 6)?;
103 let y_pel_height = i64::from(v.u16()?);
104 let y_max = i64::from(v.i16()?);
105 let y_min = i64::from(v.i16()?);
106 pos += 6;
107 group.insert(y_pel_height, (y_max, y_min));
108 }
109 let min_size = *group.keys().next().ok_or_else(empty_min)?;
110 let max_size = *group.keys().next_back().ok_or_else(empty_min)?;
111 if startsz != min_size || endsz != max_size {
114 let name = if startsz != min_size {
115 "startsz"
116 } else {
117 "endsz"
118 };
119 return Err(Error::ttlib(format!(
120 "AttributeError: 'dict' object has no attribute '{name}'"
121 )));
122 }
123 table.groups.push(group);
124 for (offset_index, &offset) in offsets.iter().enumerate() {
125 if curr_offset == offset {
127 table.rat_ranges[offset_index].group_index = Some(group_index as i64);
128 }
129 }
130 }
131 for (i, ratio) in table.rat_ranges.iter().enumerate() {
132 if ratio.group_index.is_none() {
133 return Err(Error::ttlib(format!("no group defined for ratRange {i}")));
134 }
135 }
136 Ok(table)
137 }
138}
139
140impl Vdmx {
141 fn offsets(&self) -> Result<Vec<usize>> {
143 let mut pos = 6 + self.rat_ranges.len() * 4 + self.rat_ranges.len() * 2;
144 let mut group_offsets = Vec::with_capacity(self.groups.len());
145 for group in &self.groups {
146 group_offsets.push(pos);
147 pos += 4 + group.len() * 6;
148 }
149 self.rat_ranges
150 .iter()
151 .map(|ratio| {
152 let index = ratio.group_index.ok_or_else(|| {
153 Error::value("list indices must be integers or slices, not NoneType")
154 })?;
155 let index = if index < 0 {
156 index + group_offsets.len() as i64
157 } else {
158 index
159 };
160 usize::try_from(index)
161 .ok()
162 .and_then(|i| group_offsets.get(i).copied())
163 .ok_or_else(|| Error::ttlib("IndexError: list index out of range"))
164 })
165 .collect()
166 }
167}
168
169impl Table for Vdmx {
170 fn tag(&self) -> Tag {
171 Self::TAG
172 }
173
174 fn compile(&mut self, _font: &mut Font) -> Result<Vec<u8>> {
175 if self.version != 0 && self.version != 1 {
176 return Err(Error::ttlib(format!(
177 "unknown format for VDMX table: version {}",
178 self.version
179 )));
180 }
181 self.num_ratios = self.rat_ranges.len();
182 self.num_recs = self.groups.len();
183 let mut out = Vec::new();
184 out.put_u16(fit(self.version, "version")?);
185 out.put_u16(fit(self.num_recs, "numRecs")?);
186 out.put_u16(fit(self.num_ratios, "numRatios")?);
187 for ratio in &self.rat_ranges {
188 out.put_u8(fit(ratio.b_char_set, "bCharSet")?);
189 out.put_u8(fit(ratio.x_ratio, "xRatio")?);
190 out.put_u8(fit(ratio.y_start_ratio, "yStartRatio")?);
191 out.put_u8(fit(ratio.y_end_ratio, "yEndRatio")?);
192 }
193 for offset in self.offsets()? {
194 out.put_u16(fit(offset, "offset")?);
195 }
196 for group in &self.groups {
197 let startsz = *group.keys().next().ok_or_else(empty_min)?;
198 let endsz = *group.keys().next_back().ok_or_else(empty_min)?;
199 out.put_u16(fit(group.len(), "recs")?);
200 out.put_u8(fit(startsz, "startsz")?);
201 out.put_u8(fit(endsz, "endsz")?);
202 for (&y_pel_height, &(y_max, y_min)) in group {
203 out.put_u16(fit(y_pel_height, "yPelHeight")?);
204 out.put_i16(fit(y_max, "yMax")?);
205 out.put_i16(fit(y_min, "yMin")?);
206 }
207 }
208 Ok(out)
209 }
210
211 fn clone_table(&self) -> Box<dyn Table> {
212 Box::new(self.clone())
213 }
214
215 fn remap_glyphs(&mut self, f: &mut dyn FnMut(u32) -> Result<u32>) -> Result<()> {
216 let _ = f;
217 Ok(())
218 }
219}
220
221impl TableXml for Vdmx {
222 fn to_xml(&self, writer: &mut XmlWriter, _font: &mut Font) -> Result<()> {
223 writer.simpletag("version", &[("value", &self.version)]);
224 writer.newline();
225 writer.begintag("ratRanges", &[]);
226 writer.newline();
227 for ratio in &self.rat_ranges {
228 let group_index = match ratio.group_index {
229 Some(i) => i.to_string(),
230 None => "None".to_owned(),
231 };
232 writer.simpletag(
233 "ratRange",
234 &[
235 ("bCharSet", &ratio.b_char_set),
236 ("xRatio", &ratio.x_ratio),
237 ("yStartRatio", &ratio.y_start_ratio),
238 ("yEndRatio", &ratio.y_end_ratio),
239 ("groupIndex", &group_index),
240 ],
241 );
242 writer.newline();
243 }
244 writer.endtag("ratRanges");
245 writer.newline();
246 writer.begintag("groups", &[]);
247 writer.newline();
248 for (index, group) in self.groups.iter().enumerate() {
249 let startsz = *group.keys().next().ok_or_else(empty_min)?;
250 let endsz = *group.keys().next_back().ok_or_else(empty_min)?;
251 writer.begintag("group", &[("index", &index)]);
252 writer.newline();
253 writer.comment(&format!(
254 "recs={}, startsz={startsz}, endsz={endsz}",
255 group.len()
256 ));
257 writer.newline();
258 for (y_pel_height, (y_max, y_min)) in group {
259 writer.simpletag_ordered(
260 "record",
261 &[
262 ("yPelHeight", y_pel_height),
263 ("yMax", y_max),
264 ("yMin", y_min),
265 ],
266 );
267 writer.newline();
268 }
269 writer.endtag("group");
270 writer.newline();
271 }
272 writer.endtag("groups");
273 writer.newline();
274 Ok(())
275 }
276
277 fn from_xml(&mut self, element: &Element, _font: &mut Font) -> Result<()> {
278 let int = |e: &Element, name: &str| -> Result<i64> {
279 let text = e
280 .attr(name)
281 .ok_or_else(|| Error::ttx(format!("missing '{name}' on <{}>", e.name)))?;
282 let v = eval(text)?
283 .as_int()
284 .ok_or_else(|| Error::value(format!("invalid value for {name}")))?;
285 fit(v, name)
286 };
287 match element.name.as_str() {
288 "version" => self.version = int(element, "value")?,
289 "ratRanges" => {
290 for child in element.elements().filter(|e| e.name == "ratRange") {
291 self.num_ratios += 1;
292 let group_index = match child.attr("groupIndex") {
293 Some("None") => None,
294 _ => Some(int(child, "groupIndex")?),
295 };
296 self.rat_ranges.push(RatRange {
297 b_char_set: int(child, "bCharSet")?,
298 x_ratio: int(child, "xRatio")?,
299 y_start_ratio: int(child, "yStartRatio")?,
300 y_end_ratio: int(child, "yEndRatio")?,
301 group_index,
302 });
303 }
304 }
305 "groups" => {
306 for child in element.elements().filter(|e| e.name == "group") {
307 self.num_recs += 1;
308 let mut group = VdmxGroup::new();
309 for record in child.elements().filter(|e| e.name == "record") {
310 let y_pel_height = int(record, "yPelHeight")?;
311 let y_max = int(record, "yMax")?;
312 let y_min = int(record, "yMin")?;
313 group.insert(y_pel_height, (y_max, y_min));
314 }
315 self.groups.push(group);
316 }
317 }
318 _ => {}
319 }
320 Ok(())
321 }
322}