1use std::collections::{BTreeMap, BTreeSet, HashMap, HashSet};
8use std::ffi::OsStr;
9use std::hash::Hash;
10use std::num::ParseIntError;
11use std::ops::RangeInclusive;
12use std::str::FromStr;
13use std::sync::{LazyLock, Mutex};
14use std::{fs, path};
15
16use crate::glyphdata::{Category, GlyphData, Subcategory};
17use ascii_plist_derive::FromPlist;
18use fontdrasil::types::WidthClass;
19use indexmap::{IndexMap, IndexSet};
20use kurbo::{Affine, CubicBez, Line, PathSeg, Point, QuadBez};
21use log::{debug, warn};
22use ordered_float::OrderedFloat;
23use smol_str::SmolStr;
24
25use crate::error::Error;
26use crate::plist::{FromPlist, Plist, Token, Tokenizer, VecDelimiters};
27
28static LOGGED_WARNINGS: LazyLock<Mutex<HashSet<String>>> =
30 LazyLock::new(|| Mutex::new(HashSet::new()));
31
32macro_rules! log_once_warn {
34 ($($arg:tt)*) => {{
35 if log::log_enabled!(log::Level::Warn) {
36 let msg = format!($($arg)*);
37 let mut logged = LOGGED_WARNINGS.lock().unwrap();
38 if !logged.contains(&msg) {
39 log::warn!("{}", msg);
40 logged.insert(msg);
41 }
42 }
43 }};
44}
45
46const V3_METRIC_NAMES: [&str; 6] = [
47 "ascender",
48 "baseline",
49 "descender",
50 "cap height",
51 "x-height",
52 "italic angle",
53];
54
55#[derive(Clone, Debug, Default, PartialEq, Hash)]
56pub struct UserToDesignMapping(BTreeMap<String, AxisUserToDesignMap>);
57
58#[derive(Clone, Debug, Default, PartialEq, Hash)]
59pub struct AxisUserToDesignMap(Vec<(OrderedFloat<f64>, OrderedFloat<f64>)>);
60
61#[derive(Clone, Debug, Default, PartialEq, Hash)]
65pub struct Font {
66 pub units_per_em: u16,
67 pub axes: Vec<Axis>,
68 pub masters: Vec<FontMaster>,
69 pub default_master_idx: usize,
70 pub glyphs: BTreeMap<SmolStr, Glyph>,
71 pub glyph_order: Vec<SmolStr>,
72 pub axis_mappings: UserToDesignMapping,
74 pub virtual_masters: Vec<BTreeMap<String, OrderedFloat<f64>>>,
75 pub features: Vec<FeatureSnippet>,
76 pub all_names: BTreeMap<String, Vec<(String, String)>>,
79 pub instances: Vec<Instance>,
80 pub version_major: i32,
81 pub version_minor: u32,
82 pub date: Option<String>,
83
84 pub kerning_ltr: Kerning,
86 pub kerning_rtl: Kerning,
87
88 pub custom_parameters: CustomParameters,
89 pub user_data: BTreeMap<SmolStr, Plist>,
90}
91
92#[derive(Clone, Debug, PartialEq, Hash, Default)]
94pub struct CustomParameters {
95 pub propagate_anchors: Option<bool>,
96 pub vendor_id: Option<String>,
99 pub version_string: Option<String>,
100 pub use_typo_metrics: Option<bool>,
101 pub export_stat_table: Option<bool>,
102 pub elidable_stat_axis_value_names: Vec<SmolStr>,
103 pub style_names_as_stat_entries: Vec<SmolStr>,
104 pub is_fixed_pitch: Option<bool>,
105 pub fs_type: Option<u16>,
106 pub has_wws_names: Option<bool>,
107 pub typo_ascender: Option<i64>,
108 pub typo_descender: Option<i64>,
109 pub typo_line_gap: Option<i64>,
110 pub win_ascent: Option<i64>,
111 pub win_descent: Option<i64>,
112 pub hhea_ascender: Option<i64>,
113 pub hhea_descender: Option<i64>,
114 pub hhea_line_gap: Option<i64>,
115 pub vhea_ascender: Option<i64>,
116 pub vhea_descender: Option<i64>,
117 pub vhea_line_gap: Option<i64>,
118 pub underline_thickness: Option<OrderedFloat<f64>>,
119 pub underline_position: Option<OrderedFloat<f64>>,
120 pub strikeout_position: Option<i64>,
121 pub strikeout_size: Option<i64>,
122 pub subscript_x_offset: Option<i64>,
123 pub subscript_x_size: Option<i64>,
124 pub subscript_y_offset: Option<i64>,
125 pub subscript_y_size: Option<i64>,
126 pub superscript_x_offset: Option<i64>,
127 pub superscript_x_size: Option<i64>,
128 pub superscript_y_offset: Option<i64>,
129 pub superscript_y_size: Option<i64>,
130 pub unicode_range_bits: Option<BTreeSet<u32>>,
131 pub codepage_range_bits: Option<BTreeSet<u32>>,
132 pub panose: Option<Vec<i64>>,
133
134 pub head_flags: Option<Vec<i64>>,
135 pub lowest_rec_ppem: Option<i64>,
136 pub hhea_caret_slope_run: Option<i64>,
137 pub hhea_caret_slope_rise: Option<i64>,
138 pub hhea_caret_offset: Option<i64>,
139 pub vhea_caret_slope_run: Option<i64>,
140 pub vhea_caret_slope_rise: Option<i64>,
141 pub vhea_caret_offset: Option<i64>,
142 pub meta_table: Option<MetaTableValues>,
143 pub dont_use_production_names: Option<bool>,
144 pub link_metrics_with_first_master: Option<bool>,
146 pub link_metrics_with_master: Option<SmolStr>,
147 pub virtual_masters: Option<Vec<BTreeMap<String, OrderedFloat<f64>>>>,
150 pub glyph_order: Option<Vec<SmolStr>>,
151 pub gasp_table: Option<BTreeMap<i64, i64>>,
152 pub feature_for_feature_variations: Option<SmolStr>,
153 pub color_palettes: Option<Vec<Vec<Color>>>,
154 pub name_table_entries: Vec<NameTableEntry>,
155}
156
157#[derive(Clone, Debug, PartialEq, Hash, Default)]
159pub struct MetaTableValues {
160 pub dlng: Vec<SmolStr>,
161 pub slng: Vec<SmolStr>,
162}
163
164impl MetaTableValues {
165 fn from_plist(plist: &Plist) -> Option<Self> {
166 let mut ret = MetaTableValues::default();
167 let as_array = plist.as_array()?;
168 for item in as_array {
169 let tag = item.get("tag").and_then(Plist::as_str)?;
170 let data = item.get("data").and_then(Plist::as_str)?;
171 let data = data
172 .split(',')
173 .map(str::trim)
174 .filter(|s| !s.is_empty())
175 .map(SmolStr::new)
176 .collect();
177
178 match tag {
179 "dlng" => ret.dlng = data,
180 "slng" => ret.slng = data,
181 _ => log_once_warn!("Unknown meta table tag '{tag}'"),
182 }
183 }
184
185 if ret.dlng.len() + ret.slng.len() > 0 {
186 Some(ret)
187 } else {
188 None
189 }
190 }
191}
192
193#[derive(Clone, Debug, Default, PartialEq, Hash)]
195pub struct Kerning(BTreeMap<String, BTreeMap<(SmolStr, SmolStr), OrderedFloat<f64>>>);
196
197impl Kerning {
198 pub fn get(&self, master_id: &str) -> Option<&BTreeMap<(SmolStr, SmolStr), OrderedFloat<f64>>> {
199 self.0.get(master_id)
200 }
201
202 pub fn keys(&self) -> impl Iterator<Item = &String> {
203 self.0.keys()
204 }
205
206 pub fn iter(
207 &self,
208 ) -> impl Iterator<Item = (&String, &BTreeMap<(SmolStr, SmolStr), OrderedFloat<f64>>)> {
209 self.0.iter()
210 }
211
212 fn retain_masters(&mut self, keep: impl Fn(&str) -> bool) {
213 self.0.retain(|master_id, _| keep(master_id));
214 }
215
216 fn insert(
217 &mut self,
218 master_id: String,
219 lhs_class_or_group: SmolStr,
220 rhs_class_or_group: SmolStr,
221 kern: f64,
222 ) {
223 *self
224 .0
225 .entry(master_id)
226 .or_default()
227 .entry((lhs_class_or_group, rhs_class_or_group))
228 .or_default() = kern.into();
229 }
230}
231
232impl FromPlist for Kerning {
234 fn parse(tokenizer: &mut Tokenizer<'_>) -> Result<Self, crate::plist::Error> {
235 let mut kerning = Kerning::default();
236
237 tokenizer.eat(b'{')?;
238
239 loop {
240 if tokenizer.eat(b'}').is_ok() {
241 break;
242 }
243
244 let master_id: String = tokenizer.parse()?;
246 tokenizer.eat(b'=')?;
247
248 tokenizer.eat(b'{')?;
250 loop {
251 if tokenizer.eat(b'}').is_ok() {
252 break;
253 }
254 let lhs_name_or_class: SmolStr = tokenizer.parse()?;
255 tokenizer.eat(b'=')?;
256 tokenizer.eat(b'{')?;
257
258 loop {
260 if tokenizer.eat(b'}').is_ok() {
261 break;
262 }
263
264 let rhs_name_or_class: SmolStr = tokenizer.parse()?;
265 tokenizer.eat(b'=')?;
266 let value: f64 = tokenizer.parse()?;
267 tokenizer.eat(b';')?;
268
269 kerning.insert(
270 master_id.clone(),
271 lhs_name_or_class.clone(),
272 rhs_name_or_class,
273 value,
274 );
275 }
276 tokenizer.eat(b';')?;
277 }
278
279 tokenizer.eat(b';')?;
280 }
281
282 Ok(kerning)
283 }
284}
285
286#[derive(Clone, Debug, PartialEq, Eq, Hash)]
288pub struct FeatureSnippet {
289 pub content: String,
290 pub disabled: bool,
292}
293
294impl FeatureSnippet {
295 pub fn new(content: String, disabled: bool) -> Self {
296 FeatureSnippet { content, disabled }
297 }
298
299 pub fn str_if_enabled(&self) -> Option<&str> {
300 (!self.disabled).then_some(&self.content)
301 }
302}
303
304#[derive(Clone, Default, Debug, PartialEq, Hash)]
305pub struct Glyph {
306 pub name: SmolStr,
307 pub export: bool,
308 pub layers: Vec<Layer>,
309 pub bracket_layers: Vec<Layer>,
310 pub unicode: Vec<u32>,
312 pub left_kern: Option<SmolStr>,
314 pub right_kern: Option<SmolStr>,
316 pub category: Option<Category>,
317 pub sub_category: Option<Subcategory>,
318 pub production_name: Option<SmolStr>,
319 pub smart_component_axes: BTreeMap<SmolStr, RangeInclusive<i64>>,
321}
322
323impl Glyph {
324 pub fn is_nonspacing_mark(&self) -> bool {
325 matches!(
326 (self.category, self.sub_category),
327 (Some(Category::Mark), Some(Subcategory::Nonspacing))
328 )
329 }
330
331 pub fn has_components(&self) -> bool {
332 self.layers
333 .iter()
334 .chain(self.bracket_layers.iter())
335 .flat_map(Layer::components)
336 .next()
337 .is_some()
338 }
339}
340
341impl fontdrasil::util::CompositeLike for Glyph {
342 fn name(&self) -> SmolStr {
343 self.name.clone()
344 }
345
346 fn has_components(&self) -> bool {
347 Glyph::has_components(self)
348 }
349
350 fn component_names(&self) -> impl Iterator<Item = SmolStr> {
351 self.layers
352 .iter()
353 .chain(self.bracket_layers.iter())
354 .flat_map(|layer| layer.shapes.iter())
355 .filter_map(|shape| match shape {
356 Shape::Path(..) => None,
357 Shape::Component(c) => Some(c.name.clone()),
358 })
359 }
360}
361
362#[derive(Clone, Debug, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)]
364pub enum AxisPole {
365 Min,
367 Max,
369}
370
371#[derive(Clone, Debug, Default, PartialEq, FromPlist)]
373pub struct RawHint {
374 #[fromplist(alt_name = "type")]
375 hint_type: SmolStr,
376 name: SmolStr,
377 origin: RawHint2Tuple, scale: Option<RawHint2Tuple>,
379 options: i64, }
381
382#[derive(Clone, Copy, Debug, Default, PartialEq)]
385pub struct RawHint2Tuple {
386 x: f64,
387 y: f64,
388}
389
390impl FromPlist for RawHint2Tuple {
391 fn parse(tokenizer: &mut Tokenizer) -> Result<Self, crate::plist::Error> {
392 if matches!(tokenizer.peek(), Ok(Token::String(_))) {
393 let s = tokenizer.parse::<SmolStr>().unwrap();
394 let s = s.trim_matches(['{', '}']);
396 let Some((x, y)) = s.split_once(',') else {
397 return Err(crate::plist::Error::ExpectedComma);
398 };
399 let x = x
400 .trim()
401 .parse()
402 .map_err(|_| crate::plist::Error::ExpectedNumber)?;
403 let y = y
404 .trim()
405 .parse()
406 .map_err(|_| crate::plist::Error::ExpectedNumber)?;
407 return Ok(RawHint2Tuple { x, y });
408 }
409
410 let origin: Vec<f64> = tokenizer.parse()?;
411 Ok(RawHint2Tuple {
412 x: origin.first().copied().unwrap_or_default(),
413 y: origin.get(1).copied().unwrap_or_default(),
414 })
415 }
416}
417
418impl RawHint {
419 fn to_hint(&self) -> Result<Hint, Error> {
420 let type_ = match self.hint_type.as_str() {
421 "Corner" => HintType::Corner,
422 "Cap" => HintType::Cap,
423 "Stem" => HintType::Stem,
424 "TTStem" => HintType::TTStem,
425 _other => {
426 log::info!("unhandled hint type '{_other}'");
427 HintType::Unknown
428 }
429 };
430
431 let shape_index = self.origin.x as usize;
432 let node_index = self.origin.y as usize;
433
434 let scale = self
435 .scale
436 .map(|RawHint2Tuple { x, y }| Scale::new(x, y))
437 .unwrap_or_default();
438
439 let alignment = match self.options {
440 0 => Alignment::OutStroke,
441 1 => Alignment::InStroke,
442 2 => Alignment::Middle,
443 3 => Alignment::Unused,
444 4 => Alignment::Unaligned,
445 _other => {
446 log::info!("unexpected hint option '{_other}'");
449 Default::default()
450 }
451 };
452
453 Ok(Hint {
454 type_,
455 name: self.name.clone(),
456 shape_index,
457 node_index,
458 scale,
459 alignment,
460 })
461 }
462}
463
464#[derive(Debug, Clone, PartialEq, Hash)]
465pub struct Hint {
466 pub type_: HintType,
467 pub name: SmolStr,
468 pub shape_index: usize,
469 pub node_index: usize,
470 pub scale: Scale,
471 pub alignment: Alignment,
472}
473
474#[derive(Debug, Clone, PartialEq, Hash)]
475pub struct Scale {
476 pub x: OrderedFloat<f64>,
477 pub y: OrderedFloat<f64>,
478}
479
480impl Default for Scale {
481 fn default() -> Self {
482 Self {
483 x: 1.0.into(),
484 y: 1.0.into(),
485 }
486 }
487}
488
489impl Scale {
490 fn new(x: f64, y: f64) -> Self {
491 Self {
492 x: x.into(),
493 y: y.into(),
494 }
495 }
496}
497
498#[derive(Debug, Clone, Copy, PartialEq, Hash)]
499#[non_exhaustive]
500pub enum HintType {
501 Corner,
502 Stem,
504 Cap,
505 TTStem,
506 Unknown,
508}
509
510#[derive(Debug, Clone, Copy, Default, PartialEq, Hash)]
512#[non_exhaustive]
513pub enum Alignment {
514 #[default]
516 OutStroke,
517 InStroke,
519 Middle,
520 Unused,
521 Unaligned,
522}
523
524#[derive(Debug, Default, Clone, PartialEq, Hash)]
525pub struct Layer {
526 pub layer_id: String,
527 pub associated_master_id: Option<String>,
528 pub width: OrderedFloat<f64>,
529 pub vert_width: Option<OrderedFloat<f64>>,
530 pub vert_origin: Option<OrderedFloat<f64>>,
531 pub shapes: Vec<Shape>,
532 pub anchors: Vec<Anchor>,
533 pub attributes: LayerAttributes,
534 pub smart_component_positions: BTreeMap<SmolStr, AxisPole>,
539 pub hints: Vec<Hint>,
541 pub open_corners_erased: bool,
545}
546
547impl Layer {
548 pub fn is_master(&self) -> bool {
549 self.associated_master_id.is_none()
550 }
551
552 pub fn master_id(&self) -> &str {
554 self.associated_master_id
555 .as_deref()
556 .unwrap_or(&self.layer_id)
557 }
558
559 pub fn is_intermediate(&self) -> bool {
560 self.associated_master_id.is_some() && !self.attributes.coordinates.is_empty()
561 }
562
563 pub fn is_color(&self) -> bool {
564 self.attributes.color || self.attributes.color_palette.is_some()
565 }
566
567 pub(crate) fn components(&self) -> impl Iterator<Item = &Component> + '_ {
568 self.shapes.iter().filter_map(|shape| match shape {
569 Shape::Path(_) => None,
570 Shape::Component(comp) => Some(comp),
571 })
572 }
573
574 fn bracket_info(&self, axes: &[Axis]) -> BTreeMap<String, AxisRule> {
576 assert!(
577 !self.attributes.axis_rules.is_empty(),
578 "all bracket layers have axis rules"
579 );
580 axes.iter()
581 .zip(&self.attributes.axis_rules)
582 .map(|(axis, rule)| (axis.tag.clone(), rule.clone()))
583 .collect()
584 }
585
586 fn axis_rules_sort_key(&self) -> Vec<(OrderedFloat<f64>, OrderedFloat<f64>)> {
587 self.attributes
588 .axis_rules
589 .iter()
590 .map(|ax| {
591 (
592 ax.min.unwrap_or(f64::NEG_INFINITY.into()),
593 ax.max.unwrap_or(f64::INFINITY.into()),
594 )
595 })
596 .collect()
597 }
598
599 pub(crate) fn get_anchor_pt(&self, anchor_name: &str) -> Option<Point> {
600 self.anchors
601 .iter()
602 .find(|a| a.name == anchor_name)
603 .map(|a| a.pos)
604 }
605 }
607
608#[derive(Clone, Default, Debug, PartialEq, Hash)]
609pub struct LayerAttributes {
610 pub coordinates: Vec<OrderedFloat<f64>>,
611 pub color: bool,
612 pub axis_rules: Vec<AxisRule>,
614 pub color_palette: Option<i64>,
615}
616
617#[derive(Clone, Default, FromPlist, Debug, PartialEq, Eq, Hash)]
618pub struct AxisRule {
619 pub min: Option<OrderedFloat<f64>>,
621 pub max: Option<OrderedFloat<f64>>,
622}
623
624impl AxisRule {
625 fn from_layer_name(name: &str) -> Option<Self> {
630 let idx = name.find([']', '['])?;
634 let reversed = name.as_bytes()[idx] == b']';
635 let tail = name.get(idx + 1..)?;
636 let (value, _) = tail.split_once(']')?;
637 let value = str::parse::<u32>(value.trim()).ok()?;
638 let value = OrderedFloat(value as f64);
639 let (min, max) = if reversed {
640 (None, Some(value))
641 } else {
642 (Some(value), None)
643 };
644 Some(AxisRule { min, max })
645 }
646}
647
648impl FromPlist for LayerAttributes {
650 fn parse(tokenizer: &mut Tokenizer<'_>) -> Result<Self, crate::plist::Error> {
651 let mut coordinates = Vec::new();
652 let mut color = false;
653 let mut axis_rules = Vec::new();
654 let mut color_palette = None;
655
656 tokenizer.eat(b'{')?;
657
658 loop {
659 if tokenizer.eat(b'}').is_ok() {
660 break;
661 }
662
663 let key: String = tokenizer.parse()?;
664 tokenizer.eat(b'=')?;
665 match key.as_str() {
666 "coordinates" => coordinates = tokenizer.parse()?,
667 "color" => color = tokenizer.parse()?,
668 "axisRules" => axis_rules = tokenizer.parse()?,
669 "colorPalette" => {
670 let value = match tokenizer.peek()?.as_str() {
674 Some("*") => {
675 tokenizer.lex()?;
676 0xFFFF
677 }
678 _ => tokenizer.parse()?,
679 };
680 color_palette = Some(value);
681 }
682 _ => tokenizer.skip_rec()?,
685 }
686 tokenizer.eat(b';')?;
687 }
688
689 Ok(LayerAttributes {
690 coordinates,
691 color,
692 axis_rules,
693 color_palette,
694 })
695 }
696}
697
698#[derive(Clone, Default, Debug, PartialEq, Eq, Hash, FromPlist)]
699pub struct ShapeAttributes {
700 pub gradient: Option<Gradient>,
701 pub fill_color: Option<Color>,
702}
703
704impl ShapeAttributes {
705 pub fn colors(&self) -> impl Iterator<Item = &Color> {
706 self.gradient
707 .iter()
708 .flat_map(|g| g.colors())
709 .chain(self.fill_color.iter())
710 }
711}
712
713#[derive(Clone, Default, Debug, PartialEq, Eq, Hash, FromPlist)]
714pub struct Gradient {
715 pub start: Vec<OrderedFloat<f64>>,
716 pub end: Vec<OrderedFloat<f64>>,
717 pub colors: Vec<ColorStop>,
718 #[fromplist(key = "type")]
719 pub style: String,
720}
721
722impl Gradient {
723 fn colors(&self) -> impl Iterator<Item = &Color> {
724 self.colors.iter().map(|c| &c.color)
725 }
726}
727
728#[derive(Clone, Copy, Default, Debug, PartialEq, Eq, Hash)]
729pub struct Color {
730 pub r: i64,
731 pub g: i64,
732 pub b: i64,
733 pub a: i64,
734}
735
736#[derive(Clone, Copy, Default, Debug, PartialEq, Eq, Hash)]
737pub struct ColorStop {
738 pub color: Color,
739 pub stop_offset: OrderedFloat<f64>,
741}
742
743impl Color {
744 pub fn rgba(r: i64, g: i64, b: i64, a: i64) -> Self {
745 Self { r, g, b, a }
746 }
747
748 pub(crate) fn from_glyphs_color(colors: &[i64]) -> Result<Self, crate::plist::Error> {
749 match *colors {
751 [black, alpha] => Ok(Color::rgba(black, black, black, alpha)),
753 [r, g, b, a] => Ok(Color::rgba(r, g, b, a)),
755 _ => Err(crate::plist::Error::UnexpectedNumberOfValues {
757 value_type: "grayscale (2) or rgba (4)",
758 actual: colors.len(),
759 }),
760 }
761 }
762}
763
764impl FromPlist for Color {
766 fn parse(tokenizer: &mut Tokenizer<'_>) -> Result<Self, crate::plist::Error> {
767 let colors = tokenizer.parse::<Vec<i64>>()?;
768 Color::from_glyphs_color(&colors)
769 }
770}
771
772impl FromPlist for ColorStop {
774 fn parse(tokenizer: &mut Tokenizer<'_>) -> Result<Self, crate::plist::Error> {
775 tokenizer.eat(b'(')?;
776
777 let color = Color::parse(tokenizer)?;
778 tokenizer.eat(b',')?;
779 let stop_offset = tokenizer.parse::<f64>()?;
780 tokenizer.eat(b')')?;
781
782 Ok(ColorStop {
783 color,
784 stop_offset: stop_offset.into(),
785 })
786 }
787}
788
789#[derive(Debug, Clone, PartialEq, Hash)]
790pub enum Shape {
791 Path(Path),
792 Component(Component),
793}
794
795impl Shape {
796 pub fn attributes(&self) -> &ShapeAttributes {
797 match self {
798 Shape::Path(p) => &p.attributes,
799 Shape::Component(c) => &c.attributes,
800 }
801 }
802
803 pub(crate) fn as_path(&self) -> Option<&Path> {
804 match self {
805 Shape::Path(path) => Some(path),
806 _ => None,
807 }
808 }
809
810 pub(crate) fn as_component(&self) -> Option<&Component> {
811 match self {
812 Shape::Component(component) => Some(component),
813 _ => None,
814 }
815 }
816
817 pub(crate) fn reverse(&mut self) {
836 if let Shape::Path(path) = self {
837 path.reverse();
838 if path.closed && !path.nodes.is_empty() {
839 path.nodes.rotate_left(1);
840 }
841 }
842 }
843}
844
845#[derive(Clone, Copy, Debug, Default, PartialEq, PartialOrd)]
846enum FormatVersion {
847 #[default]
848 V2,
849 V3,
850}
851
852#[derive(Default, Debug, PartialEq, FromPlist)]
855#[allow(non_snake_case)]
856struct RawFont {
857 #[fromplist(key = ".formatVersion")]
858 format_version: FormatVersion,
859 units_per_em: Option<i64>,
860 metrics: Vec<RawMetric>,
861 family_name: String,
862 date: Option<String>,
863 copyright: Option<String>,
864 designer: Option<String>,
865 designerURL: Option<String>,
866 manufacturer: Option<String>,
867 manufacturerURL: Option<String>,
868 versionMajor: Option<i64>,
869 versionMinor: Option<i64>,
870 axes: Vec<Axis>,
871 glyphs: Vec<RawGlyph>,
872 font_master: Vec<RawFontMaster>,
873 instances: Vec<RawInstance>,
874 feature_prefixes: Vec<RawFeature>,
875 features: Vec<RawFeature>,
876 classes: Vec<RawFeature>,
877 properties: Vec<RawName>,
878 #[fromplist(alt_name = "kerning")]
879 kerning_LTR: Kerning,
880 kerning_RTL: Kerning,
881 custom_parameters: RawCustomParameters,
882 numbers: Vec<NumberName>,
883 user_data: BTreeMap<SmolStr, Plist>,
884}
885
886#[derive(Default, Debug, PartialEq, FromPlist)]
887struct NumberName {
888 name: SmolStr,
889}
890
891#[derive(Clone, Default, Debug, PartialEq, Eq, Hash)]
894pub(crate) struct RawCustomParameters(Vec<RawCustomParameterValue>);
895
896#[derive(Clone, Default, Debug, PartialEq, Eq, Hash, FromPlist)]
897struct RawCustomParameterValue {
898 name: SmolStr,
899 value: Plist,
900 disabled: Option<bool>,
901}
902
903impl RawCustomParameterValue {
904 fn taken(&self) -> bool {
909 self == &Self::default()
910 }
911}
912
913impl FromPlist for FormatVersion {
914 fn parse(tokenizer: &mut Tokenizer) -> Result<Self, crate::plist::Error> {
915 let raw: i64 = FromPlist::parse(tokenizer)?;
916 if raw == 3 {
917 Ok(FormatVersion::V3)
918 } else {
919 Err(crate::plist::Error::Parse(
921 "'3' is the only known format version".into(),
922 ))
923 }
924 }
925}
926
927impl FormatVersion {
928 fn is_v2(self) -> bool {
929 self == FormatVersion::V2
930 }
931
932 fn codepoint_radix(self) -> u32 {
933 match self {
934 FormatVersion::V2 => 16,
935 FormatVersion::V3 => 10,
936 }
937 }
938}
939
940impl FromPlist for RawCustomParameters {
941 fn parse(tokenizer: &mut Tokenizer) -> Result<Self, crate::plist::Error> {
942 Vec::parse(tokenizer).map(RawCustomParameters)
943 }
944}
945
946trait PlistParamsExt {
948 fn as_codepage_bits(&self) -> Option<BTreeSet<u32>>;
949 fn as_unicode_code_ranges(&self) -> Option<BTreeSet<u32>>;
950 fn as_fs_type(&self) -> Option<u16>;
951 fn as_mapping_values(&self) -> Option<Vec<(OrderedFloat<f64>, OrderedFloat<f64>)>>;
952 fn as_axis_location(&self) -> Option<AxisLocation>;
953 fn as_axis(&self) -> Option<Axis>;
954 fn as_bool(&self) -> Option<bool>;
955 fn as_ordered_f64(&self) -> Option<OrderedFloat<f64>>;
956 fn as_vec_of_ints(&self) -> Option<Vec<i64>>;
957 fn as_axis_locations(&self) -> Option<Vec<AxisLocation>>;
958 fn as_vec_of_string(&self) -> Option<Vec<SmolStr>>;
959 fn as_axes(&self) -> Option<Vec<Axis>>;
960 fn as_axis_mappings(&self) -> Option<Vec<AxisMapping>>;
961 fn as_virtual_master(&self) -> Option<BTreeMap<String, OrderedFloat<f64>>>;
962 fn as_gasp_table(&self) -> Option<BTreeMap<i64, i64>>;
963 fn as_color_palettes(&self) -> Option<Vec<Vec<Color>>>;
964}
965
966impl PlistParamsExt for Plist {
967 fn as_bool(&self) -> Option<bool> {
968 self.as_i64().map(|val| val == 1)
969 }
970
971 fn as_ordered_f64(&self) -> Option<OrderedFloat<f64>> {
972 self.as_f64().map(OrderedFloat)
973 }
974
975 fn as_vec_of_ints(&self) -> Option<Vec<i64>> {
976 if let Some(thing_that_makes_sense) = self.as_array()?.iter().map(Plist::as_i64).collect() {
979 return Some(thing_that_makes_sense);
980 }
981
982 self.as_array()?
983 .iter()
984 .map(|val| val.as_str().and_then(|s| s.parse::<i64>().ok()))
985 .collect()
986 }
987
988 fn as_axis_location(&self) -> Option<AxisLocation> {
989 let plist = self.as_dict()?;
990 let name = plist.get("Axis").and_then(Plist::as_str)?;
991 let location = plist.get("Location").and_then(Plist::as_f64)?;
992 Some(AxisLocation {
993 axis_name: name.into(),
994 location: location.into(),
995 })
996 }
997
998 fn as_axis_locations(&self) -> Option<Vec<AxisLocation>> {
999 let array = self.as_array()?;
1000 array.iter().map(Plist::as_axis_location).collect()
1001 }
1002
1003 fn as_vec_of_string(&self) -> Option<Vec<SmolStr>> {
1004 self.as_array()?
1005 .iter()
1006 .map(|plist| plist.as_str().map(SmolStr::from))
1007 .collect()
1008 }
1009
1010 fn as_axis(&self) -> Option<Axis> {
1011 let plist = self.as_dict()?;
1012 let name = plist.get("Name").and_then(Plist::as_str)?;
1013 let tag = plist.get("Tag").and_then(Plist::as_str)?;
1014 let hidden = plist
1015 .get("Hidden")
1016 .or_else(|| plist.get("hidden"))
1017 .and_then(Plist::as_bool);
1018 Some(Axis {
1019 name: name.into(),
1020 tag: tag.into(),
1021 hidden,
1022 })
1023 }
1024
1025 fn as_axes(&self) -> Option<Vec<Axis>> {
1026 self.as_array()?.iter().map(Plist::as_axis).collect()
1027 }
1028
1029 fn as_mapping_values(&self) -> Option<Vec<(OrderedFloat<f64>, OrderedFloat<f64>)>> {
1030 let plist = self.as_dict()?;
1031 plist
1032 .iter()
1033 .map(|(key, value)| {
1034 let key = key
1036 .parse::<f64>()
1037 .or_else(|_| key.parse::<i64>().map(|i| i as f64))
1038 .ok()?;
1039 let val = value.as_f64()?;
1040 Some((key.into(), val.into()))
1041 })
1042 .collect()
1043 }
1044
1045 fn as_axis_mappings(&self) -> Option<Vec<AxisMapping>> {
1046 self.as_dict()?
1047 .iter()
1048 .map(|(tag, mappings)| {
1049 let user_to_design = mappings.as_mapping_values()?;
1050 Some(AxisMapping {
1051 tag: tag.to_string(),
1052 user_to_design,
1053 })
1054 })
1055 .collect()
1056 }
1057
1058 fn as_virtual_master(&self) -> Option<BTreeMap<String, OrderedFloat<f64>>> {
1059 self.as_array()?
1060 .iter()
1061 .map(Plist::as_axis_location)
1062 .map(|loc| loc.map(|loc| (loc.axis_name, loc.location)))
1063 .collect()
1064 }
1065
1066 fn as_fs_type(&self) -> Option<u16> {
1067 Some(self.as_vec_of_ints()?.iter().map(|bit| 1 << bit).sum())
1068 }
1069
1070 fn as_unicode_code_ranges(&self) -> Option<BTreeSet<u32>> {
1071 let bits = self.as_vec_of_ints()?;
1072 Some(bits.iter().map(|bit| *bit as u32).collect())
1073 }
1074
1075 fn as_codepage_bits(&self) -> Option<BTreeSet<u32>> {
1076 self.as_array()?
1080 .iter()
1081 .map(|val| {
1082 if let Some(n) = val.as_i64() {
1083 return codepage_range_bit(n as u32);
1084 }
1085 if let Some(s) = val.as_str() {
1086 if let Ok(n) = s.parse::<u32>() {
1087 return codepage_range_bit(n);
1088 }
1089 if let Some(rest) = s.strip_prefix("bit ")
1090 && let Ok(bit) = rest.parse::<u32>()
1091 {
1092 return codepage_range_bit(bit);
1093 }
1094 }
1095 Err(Error::InvalidCodePage(0))
1096 })
1097 .collect::<Result<_, _>>()
1098 .ok()
1099 }
1100
1101 fn as_gasp_table(&self) -> Option<BTreeMap<i64, i64>> {
1102 Some(
1103 self.as_dict()?
1104 .iter()
1105 .filter_map(|(k, v)| k.parse::<i64>().ok().zip(v.as_i64()))
1106 .collect(),
1107 )
1108 }
1109
1110 fn as_color_palettes(&self) -> Option<Vec<Vec<Color>>> {
1111 let raw_palettes = self.as_array()?;
1112 let mut palettes = Vec::with_capacity(raw_palettes.len());
1113 for raw_palette in raw_palettes {
1114 let Some(raw_palette) = raw_palette.as_array() else {
1115 warn!("Non-array color palette, ignored");
1116 continue;
1117 };
1118
1119 let mut palette = Vec::with_capacity(raw_palette.len());
1120 for raw_color in raw_palette {
1121 let Some(raw_color) = raw_color.as_vec_of_ints() else {
1122 warn!("Non-int-array color palette entry, ignored");
1123 continue;
1124 };
1125 let Ok(color) = Color::from_glyphs_color(&raw_color) else {
1126 warn!("Invalid color palette entry, ignored");
1127 continue;
1128 };
1129 palette.push(color);
1130 }
1131
1132 palettes.push(palette);
1133 }
1134 Some(palettes)
1135 }
1136}
1137
1138const LONG_PARAM_NAMES: &[&str] = &[
1144 "openTypeOS2VendorID",
1145 "openTypeNameVersion",
1146 "postscriptIsFixedPitch",
1147 "openTypeOS2TypoAscender",
1148 "openTypeOS2TypoDescender",
1149 "openTypeOS2TypoLineGap",
1150 "openTypeOS2WinAscent",
1151 "openTypeOS2WinDescent",
1152 "openTypeHheaAscender",
1153 "openTypeHheaDescender",
1154 "openTypeHheaLineGap",
1155 "openTypeVheaVertTypoAscender",
1156 "openTypeVheaVertTypoDescender",
1157 "openTypeVheaVertTypoLineGap",
1158 "postscriptUnderlineThickness",
1159 "postscriptUnderlinePosition",
1160 "openTypeOS2StrikeoutPosition",
1161 "openTypeOS2StrikeoutSize",
1162 "openTypeOS2SubscriptXOffset",
1163 "openTypeOS2SubscriptXSize",
1164 "openTypeOS2SubscriptYOffset",
1165 "openTypeOS2SubscriptYSize",
1166 "openTypeOS2SuperscriptXOffset",
1167 "openTypeOS2SuperscriptXSize",
1168 "openTypeOS2SuperscriptYOffset",
1169 "openTypeOS2SuperscriptYSize",
1170 "openTypeOS2Type",
1171 "openTypeOS2UnicodeRanges",
1172 "openTypeOS2Panose",
1173];
1174
1175impl RawCustomParameters {
1176 fn to_custom_params(&self) -> Result<CustomParameters, Error> {
1178 let mut params = CustomParameters::default();
1179 let mut virtual_masters = Vec::<BTreeMap<String, OrderedFloat<f64>>>::new();
1180 let (long, others): (Vec<_>, Vec<_>) = self
1185 .0
1186 .iter()
1187 .partition(|param| LONG_PARAM_NAMES.contains(¶m.name.as_str()));
1188
1189 for param in others.into_iter().chain(long) {
1190 if param.taken() {
1192 continue;
1193 }
1194
1195 let name = ¶m.name;
1196 let value = ¶m.value;
1197 let disabled = ¶m.disabled;
1198
1199 macro_rules! add_and_report_issues {
1202 ($field:ident, $converter:path) => {{ add_and_report_issues!($field, $converter(value)) }};
1203
1204 ($field:ident, $converter:path, into) => {{ add_and_report_issues!($field, $converter(value).map(Into::into)) }};
1205
1206 ($field:ident, $value_expr:expr_2021) => {{
1207 let value = $value_expr;
1208
1209 if value.is_none() {
1210 log::warn!("failed to parse param for '{}'", stringify!($field));
1211 }
1212 if params.$field.is_none() {
1216 params.$field = value;
1217 } else {
1218 log::warn!(
1219 "ignoring duplicate param value for field '{}'",
1220 stringify!($field)
1221 );
1222 }
1223 }};
1224 }
1225
1226 if *disabled == Some(true) {
1227 log::debug!("skipping disabled custom param '{name}'");
1228 continue;
1229 }
1230 match name.as_str() {
1231 "Propagate Anchors" => add_and_report_issues!(propagate_anchors, Plist::as_bool),
1232 "vendorID" | "openTypeOS2VendorID" => {
1233 add_and_report_issues!(vendor_id, Plist::as_str, into)
1234 }
1235 "versionString" | "openTypeNameVersion" => {
1236 add_and_report_issues!(version_string, Plist::as_str, into)
1237 }
1238 "Use Typo Metrics" => add_and_report_issues!(use_typo_metrics, Plist::as_bool),
1239 "Has WWS Names" => add_and_report_issues!(has_wws_names, Plist::as_bool),
1240 "Export STAT Table" => {
1241 add_and_report_issues!(export_stat_table, Plist::as_bool)
1242 }
1243 "Elidable STAT Axis Value Name" => match value.as_str() {
1244 Some(value) => params.elidable_stat_axis_value_names.push(value.into()),
1245 None => {
1246 log::warn!("failed to parse param for 'elidable_stat_axis_value_names'")
1247 }
1248 },
1249 "Style Name as STAT entry" => match value.as_str() {
1250 Some(value) => params.style_names_as_stat_entries.push(value.into()),
1251 None => log::warn!("failed to parse param for 'style_names_as_stat_entries'"),
1252 },
1253 "postscriptIsFixedPitch" | "isFixedPitch" => {
1257 add_and_report_issues!(is_fixed_pitch, Plist::as_bool)
1258 }
1259 "typoAscender" | "openTypeOS2TypoAscender" => {
1260 add_and_report_issues!(typo_ascender, Plist::as_i64)
1261 }
1262 "typoDescender" | "openTypeOS2TypoDescender" => {
1263 add_and_report_issues!(typo_descender, Plist::as_i64)
1264 }
1265 "typoLineGap" | "openTypeOS2TypoLineGap" => {
1266 add_and_report_issues!(typo_line_gap, Plist::as_i64)
1267 }
1268 "winAscent" | "openTypeOS2WinAscent" => {
1269 add_and_report_issues!(win_ascent, Plist::as_i64)
1270 }
1271 "winDescent" | "openTypeOS2WinDescent" => {
1272 add_and_report_issues!(win_descent, Plist::as_i64)
1273 }
1274 "hheaAscender" | "openTypeHheaAscender" => {
1275 add_and_report_issues!(hhea_ascender, Plist::as_i64)
1276 }
1277 "hheaDescender" | "openTypeHheaDescender" => {
1278 add_and_report_issues!(hhea_descender, Plist::as_i64)
1279 }
1280 "hheaLineGap" | "openTypeHheaLineGap" => {
1281 add_and_report_issues!(hhea_line_gap, Plist::as_i64)
1282 }
1283 "vheaVertAscender" | "vheaVertTypoAscender" | "openTypeVheaVertTypoAscender" => {
1284 add_and_report_issues!(vhea_ascender, Plist::as_i64)
1285 }
1286 "vheaVertDescender" | "vheaVertTypoDescender" | "openTypeVheaVertTypoDescender" => {
1287 add_and_report_issues!(vhea_descender, Plist::as_i64)
1288 }
1289 "vheaVertLineGap" | "vheaVertTypoLineGap" | "openTypeVheaVertTypoLineGap" => {
1290 add_and_report_issues!(vhea_line_gap, Plist::as_i64)
1291 }
1292 "underlineThickness" | "postscriptUnderlineThickness" => {
1293 add_and_report_issues!(underline_thickness, Plist::as_ordered_f64)
1294 }
1295 "underlinePosition" | "postscriptUnderlinePosition" => {
1296 add_and_report_issues!(underline_position, Plist::as_ordered_f64)
1297 }
1298 "strikeoutPosition" | "openTypeOS2StrikeoutPosition" => {
1299 add_and_report_issues!(strikeout_position, Plist::as_i64)
1300 }
1301 "strikeoutSize" | "openTypeOS2StrikeoutSize" => {
1302 add_and_report_issues!(strikeout_size, Plist::as_i64)
1303 }
1304 "subscriptXOffset" | "openTypeOS2SubscriptXOffset" => {
1305 add_and_report_issues!(subscript_x_offset, Plist::as_i64)
1306 }
1307 "subscriptXSize" | "openTypeOS2SubscriptXSize" => {
1308 add_and_report_issues!(subscript_x_size, Plist::as_i64)
1309 }
1310 "subscriptYOffset" | "openTypeOS2SubscriptYOffset" => {
1311 add_and_report_issues!(subscript_y_offset, Plist::as_i64)
1312 }
1313 "subscriptYSize" | "openTypeOS2SubscriptYSize" => {
1314 add_and_report_issues!(subscript_y_size, Plist::as_i64)
1315 }
1316 "superscriptXOffset" | "openTypeOS2SuperscriptXOffset" => {
1317 add_and_report_issues!(superscript_x_offset, Plist::as_i64)
1318 }
1319 "superscriptXSize" | "openTypeOS2SuperscriptXSize" => {
1320 add_and_report_issues!(superscript_x_size, Plist::as_i64)
1321 }
1322 "superscriptYOffset" | "openTypeOS2SuperscriptYOffset" => {
1323 add_and_report_issues!(superscript_y_offset, Plist::as_i64)
1324 }
1325 "superscriptYSize" | "openTypeOS2SuperscriptYSize" => {
1326 add_and_report_issues!(superscript_y_size, Plist::as_i64)
1327 }
1328 "fsType" | "openTypeOS2Type" => add_and_report_issues!(fs_type, Plist::as_fs_type),
1329 "unicodeRanges" | "openTypeOS2UnicodeRanges" => {
1330 add_and_report_issues!(unicode_range_bits, Plist::as_unicode_code_ranges)
1331 }
1332 "codePageRanges" => {
1333 add_and_report_issues!(codepage_range_bits, Plist::as_codepage_bits)
1334 }
1335 "openTypeHeadLowestRecPPEM" => {
1339 add_and_report_issues!(lowest_rec_ppem, Plist::as_i64)
1340 }
1341 "openTypeHheaCaretSlopeRun" => {
1342 add_and_report_issues!(hhea_caret_slope_run, Plist::as_i64)
1343 }
1344 "openTypeHheaCaretSlopeRise" => {
1345 add_and_report_issues!(hhea_caret_slope_rise, Plist::as_i64)
1346 }
1347 "openTypeHheaCaretOffset" => {
1348 add_and_report_issues!(hhea_caret_offset, Plist::as_i64)
1349 }
1350 "openTypeVheaCaretSlopeRun" => {
1351 add_and_report_issues!(vhea_caret_slope_run, Plist::as_i64)
1352 }
1353 "openTypeVheaCaretSlopeRise" => {
1354 add_and_report_issues!(vhea_caret_slope_rise, Plist::as_i64)
1355 }
1356 "openTypeVheaCaretOffset" => {
1357 add_and_report_issues!(vhea_caret_offset, Plist::as_i64)
1358 }
1359 "meta Table" => {
1360 add_and_report_issues!(meta_table, MetaTableValues::from_plist)
1361 }
1362 "Don't use Production Names" => {
1363 add_and_report_issues!(dont_use_production_names, Plist::as_bool)
1364 }
1365 "Link Metrics With First Master" => {
1366 add_and_report_issues!(link_metrics_with_first_master, Plist::as_bool)
1367 }
1368 "Link Metrics With Master" => {
1369 add_and_report_issues!(link_metrics_with_master, Plist::as_str, into)
1370 }
1371 "openTypeHeadFlags" => {
1372 add_and_report_issues!(head_flags, Plist::as_vec_of_ints)
1373 }
1374 "openTypeOS2FamilyClass" => {
1378 log_once_warn!("unhandled custom param '{name}'")
1379 }
1380
1381 "Virtual Master" => match value.as_virtual_master() {
1382 Some(val) => virtual_masters.push(val),
1383 None => log::warn!("failed to parse virtual master '{value:?}'"),
1384 },
1385 "panose" | "openTypeOS2Panose" => {
1386 add_and_report_issues!(panose, Plist::as_vec_of_ints)
1387 }
1388 "glyphOrder" => add_and_report_issues!(glyph_order, Plist::as_vec_of_string),
1389 "gasp Table" | "GASP Table" => {
1393 add_and_report_issues!(gasp_table, Plist::as_gasp_table)
1394 }
1395 "Feature for Feature Variations" => {
1396 add_and_report_issues!(feature_for_feature_variations, Plist::as_str, into)
1397 }
1398 "Color Palettes" => {
1399 add_and_report_issues!(color_palettes, Plist::as_color_palettes)
1400 }
1401 "Name Table Entry" => match value
1402 .as_str()
1403 .ok_or_else(|| "should be a string".into())
1404 .and_then(NameTableEntry::from_str)
1405 {
1406 Ok(s) => params.name_table_entries.push(s),
1407 Err(e) => log::warn!("bad 'Name Table Entry': {e}"),
1408 },
1409 _ => log_once_warn!("unknown custom parameter '{name}'"),
1410 }
1411 }
1412 params.virtual_masters = Some(virtual_masters).filter(|x| !x.is_empty());
1413 Ok(params)
1414 }
1415
1416 fn contains(&self, name: &str) -> bool {
1417 self.0.iter().any(|val| val.name == name)
1418 }
1419
1420 fn take(&mut self, name: &str) -> Option<Plist> {
1425 let pos = self
1426 .0
1427 .iter()
1428 .position(|val| val.name == name && val.disabled != Some(true))?;
1429
1430 let taken = std::mem::take(&mut self.0[pos]);
1433
1434 Some(taken.value)
1435 }
1436
1437 fn take_string(&mut self, name: &str) -> Option<String> {
1438 self.take(name)
1439 .and_then(|p| p.as_str().map(|s| s.to_owned()))
1440 }
1441
1442 fn take_axes(&mut self) -> Option<Vec<Axis>> {
1443 self.take("Axes").and_then(|p| p.as_axes())
1444 }
1445
1446 fn take_axis_mappings(&mut self) -> Option<Vec<AxisMapping>> {
1447 self.take("Axis Mappings")
1448 .and_then(|p| p.as_axis_mappings())
1449 }
1450
1451 fn take_axis_locations(&mut self) -> Option<Vec<AxisLocation>> {
1452 self.take("Axis Location")
1453 .and_then(|p| p.as_axis_locations())
1454 }
1455}
1456
1457#[derive(Default, Debug, Clone, PartialEq, Eq, Hash)]
1458pub struct AxisLocation {
1459 axis_name: String,
1460 location: OrderedFloat<f64>,
1461}
1462
1463#[derive(Default, Debug, Clone, PartialEq, Eq, Hash)]
1464pub struct AxisMapping {
1465 tag: String,
1467 user_to_design: Vec<(OrderedFloat<f64>, OrderedFloat<f64>)>,
1468}
1469
1470#[derive(Default, Debug, Clone, PartialEq, Eq, Hash, FromPlist)]
1471struct RawMetric {
1472 type_: String,
1474}
1475
1476#[derive(Default, Clone, Debug, PartialEq, Eq, Hash, FromPlist)]
1477struct RawName {
1478 key: String,
1479 value: Option<String>,
1480 values: Vec<RawNameValue>,
1481}
1482
1483#[derive(Clone, Debug, PartialEq, Hash, Default)]
1484pub struct NameTableEntry {
1485 pub name_id: u16,
1486 pub platform_id: u16,
1487 pub encoding_id: u16,
1488 pub lang_id: u16,
1489 pub value: String,
1490}
1491
1492fn parse_maybe_hex_int(s: &str) -> Result<u16, ParseIntError> {
1493 match s.strip_prefix("0x") {
1494 Some(hex) => u16::from_str_radix(hex, 16),
1495 None => s.parse(),
1496 }
1497}
1498
1499impl FromStr for NameTableEntry {
1500 type Err = String;
1501
1502 fn from_str(s: &str) -> Result<Self, Self::Err> {
1503 let Some((head, tail)) = s.split_once(';') else {
1506 return Err(format!("expected ';', found '{s}'"));
1507 };
1508 let mut iter = head.split(" ").flat_map(parse_maybe_hex_int);
1509 let value = tail.trim().into();
1510 match (iter.next(), iter.next(), iter.next(), iter.next()) {
1511 (Some(name_id), None | Some(3), None, None) => Ok(NameTableEntry {
1512 name_id,
1513 platform_id: 3,
1514 encoding_id: 1,
1515 lang_id: 0x409,
1516 value,
1517 }),
1518 (Some(name_id), Some(1), None, None) => Ok(NameTableEntry {
1522 name_id,
1523 platform_id: 1,
1524 encoding_id: 0,
1525 lang_id: 0,
1526 value,
1527 }),
1528 (Some(name_id), Some(platform_id), Some(encoding_id), None) => Ok(NameTableEntry {
1529 name_id,
1530 platform_id,
1531 encoding_id,
1532 lang_id: 0,
1533 value,
1534 }),
1535
1536 (Some(a), Some(b), Some(c), Some(d)) => Ok(NameTableEntry {
1537 name_id: a,
1538 platform_id: b,
1539 encoding_id: c,
1540 lang_id: d,
1541 value,
1542 }),
1543 _ => Err(format!("expected four numerical ids, found '{s}'")),
1544 }
1545 }
1546}
1547
1548fn default_language_score(lang: &str, index: usize, scale: i32) -> i32 {
1553 match lang {
1554 "dflt" => -scale * 3 - index as i32,
1555 "default" => -scale * 2 - index as i32,
1556 "ENG" => -scale - index as i32,
1557 _ => index as i32,
1558 }
1559}
1560
1561impl RawName {
1562 fn is_empty(&self) -> bool {
1563 self.value.is_none() && self.values.is_empty()
1564 }
1565
1566 fn get_value(&self) -> Option<&str> {
1567 if let Some(value) = &self.value {
1568 return Some(value.as_str());
1569 }
1570
1571 let scale = self.values.len() as i32;
1578 self.values
1579 .iter()
1580 .enumerate()
1581 .map(|(i, raw)| {
1582 (
1583 default_language_score(raw.language.as_str(), i, scale),
1584 raw.value.as_str(),
1585 )
1586 })
1587 .min()
1588 .map(|(_, raw)| raw)
1589 }
1590
1591 fn localized_values(&self) -> impl Iterator<Item = (&str, &str)> {
1592 self.values
1593 .iter()
1594 .map(|raw| (raw.language.as_str(), raw.value.as_str()))
1595 }
1596}
1597
1598#[derive(Default, Clone, Debug, PartialEq, Eq, Hash, FromPlist)]
1599struct RawNameValue {
1600 language: String,
1601 value: String,
1602}
1603
1604#[derive(Default, Clone, Debug, PartialEq, Eq, Hash, FromPlist)]
1605struct RawFeature {
1606 automatic: Option<i64>,
1607 disabled: Option<i64>,
1608 name: Option<String>,
1609 tag: Option<String>,
1610 notes: Option<String>,
1611 code: String,
1612 labels: Vec<RawNameValue>,
1613
1614 #[fromplist(ignore)]
1615 other_stuff: BTreeMap<String, Plist>,
1616}
1617
1618#[derive(Default, Clone, Debug, PartialEq, Eq, Hash, FromPlist)]
1619pub struct Axis {
1620 #[fromplist(alt_name = "Name")]
1621 pub name: String,
1622 #[fromplist(alt_name = "Tag")]
1623 pub tag: String,
1624 pub hidden: Option<bool>,
1625}
1626
1627#[derive(Default, Clone, Debug, PartialEq, FromPlist)]
1628struct RawGlyph {
1629 layers: Vec<RawLayer>,
1630 glyphname: SmolStr,
1631 export: Option<bool>,
1632 #[fromplist(alt_name = "leftKerningGroup")]
1633 kern_left: Option<SmolStr>,
1634 #[fromplist(alt_name = "rightKerningGroup")]
1635 kern_right: Option<SmolStr>,
1636 unicode: Option<RawCodepoints>,
1637 category: Option<SmolStr>,
1638 sub_category: Option<SmolStr>,
1639 #[fromplist(alt_name = "production")]
1640 production_name: Option<SmolStr>,
1641 parts_settings: Vec<RawPartSetting>,
1642 #[fromplist(ignore)]
1643 other_stuff: BTreeMap<String, Plist>,
1644}
1645
1646#[derive(Default, Clone, Debug, PartialEq)]
1653struct RawCodepoints(String);
1654
1655impl FromPlist for RawCodepoints {
1656 fn parse(tokenizer: &mut Tokenizer) -> Result<Self, crate::plist::Error> {
1657 if matches!(tokenizer.peek(), Ok(Token::OpenParen)) {
1658 let values: Vec<String> = tokenizer.parse()?;
1659 return Ok(RawCodepoints(values.join(",")));
1660 }
1661 tokenizer.parse().map(RawCodepoints)
1662 }
1663}
1664
1665#[derive(Default, Clone, Debug, PartialEq, FromPlist)]
1666struct RawPartSetting {
1667 name: SmolStr,
1668 bottom_name: Option<SmolStr>,
1669 bottom_value: i64,
1670 top_name: Option<SmolStr>,
1671 top_value: i64,
1672}
1673
1674#[derive(Default, Clone, Debug, PartialEq, FromPlist)]
1675struct RawLayer {
1676 name: String,
1677 layer_id: String,
1678 associated_master_id: Option<String>,
1679 width: Option<OrderedFloat<f64>>,
1680 vert_width: Option<OrderedFloat<f64>>,
1681 vert_origin: Option<OrderedFloat<f64>>,
1682 shapes: Vec<RawShape>,
1683 paths: Vec<Path>,
1684 components: Vec<Component>,
1685 anchors: Vec<RawAnchor>,
1686 hints: Vec<RawHint>,
1687 #[fromplist(alt_name = "attr")]
1688 attributes: LayerAttributes,
1689 part_selection: BTreeMap<SmolStr, i64>,
1692 user_data: LayerUserData,
1694 #[fromplist(ignore)]
1695 other_stuff: BTreeMap<String, Plist>,
1696}
1697
1698#[derive(Default, Clone, Debug, PartialEq, FromPlist)]
1699struct LayerUserData {
1700 #[fromplist(alt_name = "PartSelection")]
1701 part_selection: BTreeMap<SmolStr, i64>,
1702}
1703
1704impl RawLayer {
1705 fn is_draft(&self) -> bool {
1711 self.associated_master_id.is_some()
1712 && self.attributes == Default::default()
1713 && self.part_selection.is_empty() && self.user_data.part_selection.is_empty() }
1716
1717 fn is_bracket_layer(&self, format_version: FormatVersion) -> bool {
1722 self.associated_master_id.is_some()
1725 && self.associated_master_id.as_ref() != Some(&self.layer_id)
1726 && match format_version {
1728 FormatVersion::V2 => AxisRule::from_layer_name(&self.name).is_some(),
1729 FormatVersion::V3 => !self.attributes.axis_rules.is_empty(),
1730 }
1731 }
1732
1733 fn has_bounded_axis_rules(&self) -> bool {
1735 self.attributes
1736 .axis_rules
1737 .iter()
1738 .any(|rule| rule.min.is_some() || rule.max.is_some())
1739 }
1740
1741 fn is_blank_alternate(&self) -> bool {
1747 self.is_bracket_layer(FormatVersion::V3)
1748 && !self.has_bounded_axis_rules()
1749 && self.attributes
1750 == LayerAttributes {
1751 axis_rules: self.attributes.axis_rules.clone(),
1752 ..Default::default()
1753 }
1754 && self.part_selection.is_empty()
1755 }
1756
1757 fn v2_to_v3_attributes(&mut self) {
1758 let mut brace_coordinates = Vec::new();
1761 if let (Some(start), Some(end)) = (self.name.find('{'), self.name.find('}')) {
1762 let mut tokenizer = Tokenizer::new(&self.name[start..=end]);
1763 brace_coordinates = tokenizer
1767 .parse_delimited_vec(VecDelimiters::CSV_IN_BRACES)
1768 .unwrap_or_default();
1769 }
1770 if !brace_coordinates.is_empty() {
1771 self.attributes.coordinates = brace_coordinates;
1772 }
1773 }
1775}
1776
1777#[derive(Default, Clone, Debug, PartialEq, FromPlist)]
1781struct RawShape {
1782 closed: Option<bool>,
1786 nodes: Vec<Node>,
1787
1788 #[fromplist(alt_name = "ref", alt_name = "name")]
1792 glyph_name: Option<SmolStr>,
1793 piece: BTreeMap<SmolStr, f64>,
1796
1797 anchor: Option<SmolStr>,
1800 transform: Option<String>, pos: Vec<f64>, angle: Option<f64>, scale: Vec<f64>, slant: Vec<f64>,
1806
1807 #[fromplist(alt_name = "attr")]
1808 attributes: ShapeAttributes,
1809}
1810
1811#[derive(Default, Clone, Debug, PartialEq, Eq, Hash, FromPlist)]
1813pub struct Path {
1814 pub closed: bool,
1815 pub nodes: Vec<Node>,
1816 pub attributes: ShapeAttributes,
1817}
1818
1819#[derive(Default, Clone, Debug, FromPlist)]
1821pub struct Component {
1822 pub name: SmolStr,
1824 pub transform: Affine,
1826 pub anchor: Option<SmolStr>,
1831 #[fromplist(alt_name = "piece")]
1836 pub smart_component_values: BTreeMap<SmolStr, f64>,
1837 pub attributes: ShapeAttributes,
1838}
1839
1840impl PartialEq for Component {
1841 fn eq(&self, other: &Self) -> bool {
1842 self.name == other.name
1843 && Into::<AffineForEqAndHash>::into(self.transform) == other.transform.into()
1844 }
1845}
1846
1847impl Eq for Component {}
1848
1849impl Hash for Component {
1850 fn hash<H: std::hash::Hasher>(&self, state: &mut H) {
1851 self.name.hash(state);
1852 Into::<AffineForEqAndHash>::into(self.transform).hash(state);
1853 }
1854}
1855
1856#[derive(Clone, Copy, Debug)]
1857pub struct Node {
1858 pub pt: Point,
1859 pub node_type: NodeType,
1860}
1861
1862impl Node {
1863 pub fn is_on_curve(&self) -> bool {
1864 !matches!(self.node_type, NodeType::OffCurve)
1865 }
1866}
1867
1868impl PartialEq for Node {
1869 fn eq(&self, other: &Self) -> bool {
1870 Into::<PointForEqAndHash>::into(self.pt) == other.pt.into()
1871 && self.node_type == other.node_type
1872 }
1873}
1874
1875impl Eq for Node {}
1876
1877impl Hash for Node {
1878 fn hash<H: std::hash::Hasher>(&self, state: &mut H) {
1879 PointForEqAndHash::new(self.pt).hash(state);
1880 self.node_type.hash(state);
1881 }
1882}
1883
1884#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
1885pub enum NodeType {
1886 Line,
1887 LineSmooth,
1888 OffCurve,
1889 Curve,
1890 CurveSmooth,
1891 QCurve,
1892 QCurveSmooth,
1893}
1894
1895#[derive(Default, Clone, Debug, PartialEq, FromPlist)]
1896struct RawAnchor {
1897 name: SmolStr,
1898 pos: Option<Point>, position: Option<String>, }
1901
1902#[derive(Clone, Debug, PartialEq)]
1903pub struct Anchor {
1904 pub name: SmolStr,
1905 pub pos: Point,
1906}
1907
1908impl Hash for Anchor {
1909 fn hash<H: std::hash::Hasher>(&self, state: &mut H) {
1910 self.name.hash(state);
1911 PointForEqAndHash::new(self.pos).hash(state);
1912 }
1913}
1914
1915#[derive(Clone, Debug, PartialEq, Hash)]
1916pub struct FontMaster {
1917 pub id: String,
1918 pub name: String,
1919 pub axes_values: Vec<OrderedFloat<f64>>,
1920 metric_values: BTreeMap<String, MetricValue>,
1921 pub number_values: BTreeMap<SmolStr, OrderedFloat<f64>>,
1922 pub custom_parameters: CustomParameters,
1923 pub user_data: BTreeMap<SmolStr, Plist>,
1924 pub metrics_source_id: Option<String>,
1925}
1926
1927impl FontMaster {
1928 fn read_metric(&self, metric_name: &str) -> Option<f64> {
1929 self.metric_values
1930 .get(metric_name)
1931 .map(|metric| metric.pos.into_inner())
1932 }
1933
1934 pub fn ascender(&self) -> Option<f64> {
1935 self.read_metric("ascender")
1936 }
1937
1938 pub fn descender(&self) -> Option<f64> {
1939 self.read_metric("descender")
1940 }
1941
1942 pub fn x_height(&self) -> Option<f64> {
1943 self.read_metric("x-height")
1944 }
1945
1946 pub fn cap_height(&self) -> Option<f64> {
1947 self.read_metric("cap height")
1948 }
1949
1950 pub fn italic_angle(&self) -> Option<f64> {
1951 self.read_metric("italic angle")
1952 }
1953}
1954
1955fn resolve_metrics_source_id(
1959 custom_params: &CustomParameters,
1960 master_ids_to_names: &IndexMap<String, Option<String>>,
1961) -> Option<String> {
1962 if custom_params.link_metrics_with_first_master == Some(true) {
1964 return master_ids_to_names.first().map(|(id, _)| id.clone());
1965 }
1966
1967 if let Some(ref source_ref) = custom_params.link_metrics_with_master {
1968 if master_ids_to_names.contains_key(source_ref.as_str()) {
1970 return Some(source_ref.to_string());
1971 }
1972 if let Some((id, _)) = master_ids_to_names
1974 .iter()
1975 .find(|(_, name)| name.as_deref() == Some(source_ref.as_str()))
1976 {
1977 return Some(id.clone());
1978 }
1979 log::warn!("Source master for metrics not found: '{source_ref}'");
1980 }
1981
1982 None
1983}
1984
1985#[derive(Default, Debug, Clone, PartialEq, Eq, Hash, FromPlist)]
1986struct RawFontMaster {
1987 id: String,
1988 name: Option<String>,
1989
1990 weight: Option<String>,
1991 width: Option<String>,
1992 custom: Option<String>,
1993
1994 weight_value: Option<OrderedFloat<f64>>,
1995 interpolation_weight: Option<OrderedFloat<f64>>,
1996
1997 width_value: Option<OrderedFloat<f64>>,
1998 interpolation_width: Option<OrderedFloat<f64>>,
1999
2000 custom_value: Option<OrderedFloat<f64>>,
2001
2002 typo_ascender: Option<i64>,
2003 typo_descender: Option<OrderedFloat<f64>>,
2004 typo_line_gap: Option<OrderedFloat<f64>>,
2005 win_ascender: Option<OrderedFloat<f64>>,
2006 win_descender: Option<OrderedFloat<f64>>,
2007
2008 axes_values: Vec<OrderedFloat<f64>>,
2009 metric_values: Vec<RawMetricValue>, ascender: Option<OrderedFloat<f64>>, baseline: Option<OrderedFloat<f64>>, descender: Option<OrderedFloat<f64>>, cap_height: Option<OrderedFloat<f64>>, x_height: Option<OrderedFloat<f64>>, #[fromplist(alt_name = "italic angle")]
2017 italic_angle: Option<OrderedFloat<f64>>, alignment_zones: Vec<String>, custom_parameters: RawCustomParameters,
2022 number_values: Vec<OrderedFloat<f64>>,
2023 user_data: BTreeMap<SmolStr, Plist>,
2024
2025 #[fromplist(ignore)]
2026 other_stuff: BTreeMap<String, Plist>,
2027}
2028
2029#[derive(Default, Debug, Clone, PartialEq, Eq, Hash, FromPlist)]
2030struct RawMetricValue {
2031 pos: Option<OrderedFloat<f64>>,
2032 over: Option<OrderedFloat<f64>>,
2033}
2034
2035#[derive(Default, Debug, Clone, PartialEq, Eq, Hash)]
2036pub struct MetricValue {
2037 pos: OrderedFloat<f64>,
2038 over: OrderedFloat<f64>,
2039}
2040
2041impl From<RawMetricValue> for MetricValue {
2042 fn from(src: RawMetricValue) -> MetricValue {
2043 MetricValue {
2044 pos: src.pos.unwrap_or_default(),
2045 over: src.over.unwrap_or_default(),
2046 }
2047 }
2048}
2049
2050#[derive(Clone, Debug, PartialEq, Hash)]
2051pub struct Instance {
2052 pub name: String,
2053 pub active: bool,
2054 pub is_bold: bool,
2055 pub is_italic: bool,
2056 pub link_style: Option<String>,
2057 pub weight_class: Option<u16>,
2058 pub width_class: Option<u16>,
2059 pub type_: InstanceType,
2061 pub axis_mappings: BTreeMap<String, AxisUserToDesignMap>,
2062 pub axes_values: Vec<OrderedFloat<f64>>,
2063 pub custom_parameters: CustomParameters,
2064 properties: Vec<RawName>, }
2066
2067#[derive(Clone, Debug, PartialEq, Hash)]
2069pub enum InstanceType {
2070 Single,
2071 Variable,
2072}
2073
2074impl From<&str> for InstanceType {
2075 fn from(value: &str) -> Self {
2076 if value.eq_ignore_ascii_case("variable") {
2077 InstanceType::Variable
2078 } else {
2079 InstanceType::Single
2080 }
2081 }
2082}
2083
2084#[derive(Default, Debug, Clone, PartialEq, Eq, Hash, FromPlist)]
2085struct RawInstance {
2086 name: String,
2087 exports: Option<i64>,
2088 active: Option<i64>,
2089 is_bold: Option<bool>,
2090 is_italic: Option<bool>,
2091 link_style: Option<String>,
2092 type_: Option<String>,
2093 axes_values: Vec<OrderedFloat<f64>>,
2094
2095 weight_value: Option<OrderedFloat<f64>>,
2096 interpolation_weight: Option<OrderedFloat<f64>>,
2097
2098 width_value: Option<OrderedFloat<f64>>,
2099 interpolation_width: Option<OrderedFloat<f64>>,
2100
2101 custom_value: Option<OrderedFloat<f64>>,
2102 interpolation_custom: Option<OrderedFloat<f64>>,
2103
2104 weight_class: Option<String>,
2105 width_class: Option<String>,
2106 properties: Vec<RawName>,
2107 custom_parameters: RawCustomParameters,
2108}
2109
2110impl RawInstance {
2111 fn is_active(&self) -> bool {
2114 self.exports.unwrap_or(1) != 0 && self.active.unwrap_or(1) != 0
2115 }
2116}
2117
2118trait GlyphsV2OrderedAxes {
2119 fn weight_value(&self) -> Option<OrderedFloat<f64>>;
2120 fn interpolation_weight(&self) -> Option<OrderedFloat<f64>>;
2121 fn width_value(&self) -> Option<OrderedFloat<f64>>;
2122 fn interpolation_width(&self) -> Option<OrderedFloat<f64>>;
2123 fn custom_value(&self) -> Option<OrderedFloat<f64>>;
2124 fn interpolation_custom(&self) -> Option<OrderedFloat<f64>>;
2125
2126 fn value_for_nth_axis(&self, nth_axis: usize) -> Result<OrderedFloat<f64>, Error> {
2127 Ok(match nth_axis {
2133 0 => self
2134 .weight_value()
2135 .or(self.interpolation_weight())
2136 .unwrap_or(100.0.into()),
2137 1 => self
2138 .width_value()
2139 .or(self.interpolation_width())
2140 .unwrap_or(100.0.into()),
2141 2 => self
2142 .custom_value()
2143 .or(self.interpolation_custom())
2144 .unwrap_or(0.0.into()),
2145 _ => {
2146 return Err(Error::StructuralError(format!(
2147 "We don't know what field to use for axis {nth_axis}"
2148 )));
2149 }
2150 })
2151 }
2152
2153 fn axis_values(&self, axes: &[Axis]) -> Result<Vec<OrderedFloat<f64>>, Error> {
2154 (0..axes.len())
2155 .map(|nth_axis| self.value_for_nth_axis(nth_axis))
2156 .collect::<Result<Vec<OrderedFloat<f64>>, Error>>()
2157 }
2158}
2159
2160impl GlyphsV2OrderedAxes for RawFontMaster {
2161 fn weight_value(&self) -> Option<OrderedFloat<f64>> {
2162 self.weight_value
2163 }
2164
2165 fn interpolation_weight(&self) -> Option<OrderedFloat<f64>> {
2166 self.interpolation_weight
2167 }
2168
2169 fn width_value(&self) -> Option<OrderedFloat<f64>> {
2170 self.width_value
2171 }
2172
2173 fn interpolation_width(&self) -> Option<OrderedFloat<f64>> {
2174 self.interpolation_width
2175 }
2176
2177 fn custom_value(&self) -> Option<OrderedFloat<f64>> {
2178 self.custom_value
2179 }
2180
2181 fn interpolation_custom(&self) -> Option<OrderedFloat<f64>> {
2182 None
2184 }
2185}
2186
2187impl GlyphsV2OrderedAxes for RawInstance {
2188 fn weight_value(&self) -> Option<OrderedFloat<f64>> {
2189 self.weight_value
2190 }
2191
2192 fn interpolation_weight(&self) -> Option<OrderedFloat<f64>> {
2193 self.interpolation_weight
2194 }
2195
2196 fn width_value(&self) -> Option<OrderedFloat<f64>> {
2197 self.width_value
2198 }
2199
2200 fn interpolation_width(&self) -> Option<OrderedFloat<f64>> {
2201 self.interpolation_width
2202 }
2203
2204 fn custom_value(&self) -> Option<OrderedFloat<f64>> {
2205 self.custom_value
2206 }
2207
2208 fn interpolation_custom(&self) -> Option<OrderedFloat<f64>> {
2209 self.interpolation_custom
2210 }
2211}
2212
2213fn parse_node_from_string(value: &str) -> Node {
2214 let mut spl = value.splitn(3, ' ');
2215 let x = spl.next().unwrap().parse().unwrap();
2216 let y = spl.next().unwrap().parse().unwrap();
2217 let pt = Point::new(x, y);
2218 let mut raw_node_type = spl.next().unwrap();
2219 if raw_node_type.contains('{') {
2221 raw_node_type = raw_node_type.split('{').next().unwrap().trim_end();
2222 }
2223 let node_type = raw_node_type.parse().unwrap();
2224 Node { pt, node_type }
2225}
2226
2227fn parse_node_from_tokenizer(tokenizer: &mut Tokenizer<'_>) -> Result<Node, crate::plist::Error> {
2228 let x: f64 = tokenizer.parse()?;
2230 tokenizer.eat(b',')?;
2231 let y: f64 = tokenizer.parse()?;
2232 tokenizer.eat(b',')?;
2233 let node_type: String = tokenizer.parse()?;
2234 let node_type = NodeType::from_str(&node_type)
2235 .map_err(|_| crate::plist::Error::Parse(format!("unknown node type '{node_type}'")))?;
2236
2237 if tokenizer.eat(b',').is_ok() {
2239 tokenizer.skip_rec()?;
2240 }
2241
2242 Ok(Node {
2243 pt: Point { x, y },
2244 node_type,
2245 })
2246}
2247
2248impl std::str::FromStr for NodeType {
2249 type Err = String;
2250 fn from_str(s: &str) -> Result<Self, Self::Err> {
2251 match s {
2252 "LINE" => Ok(NodeType::Line),
2254 "LINE SMOOTH" => Ok(NodeType::LineSmooth),
2255 "OFFCURVE" => Ok(NodeType::OffCurve),
2256 "CURVE" => Ok(NodeType::Curve),
2257 "CURVE SMOOTH" => Ok(NodeType::CurveSmooth),
2258 "QCURVE" => Ok(NodeType::QCurve),
2259 "QCURVE SMOOTH" => Ok(NodeType::QCurveSmooth),
2260 "l" => Ok(NodeType::Line),
2262 "ls" => Ok(NodeType::LineSmooth),
2263 "o" => Ok(NodeType::OffCurve),
2264 "c" => Ok(NodeType::Curve),
2265 "cs" => Ok(NodeType::CurveSmooth),
2266 "q" => Ok(NodeType::QCurve),
2267 "qs" => Ok(NodeType::QCurveSmooth),
2268 _ => Err(format!("unknown node type {s}")),
2269 }
2270 }
2271}
2272
2273impl FromPlist for Node {
2275 fn parse(tokenizer: &mut Tokenizer<'_>) -> Result<Self, crate::plist::Error> {
2276 use crate::plist::Error;
2277 let tok = tokenizer.lex()?;
2278 let node = match &tok {
2279 Token::Atom(value) => parse_node_from_string(value),
2280 Token::String(value) => parse_node_from_string(value),
2281 Token::OpenParen => {
2282 let node = parse_node_from_tokenizer(tokenizer)?;
2283 tokenizer.eat(b')')?;
2284 node
2285 }
2286 _ => return Err(Error::ExpectedString),
2287 };
2288 Ok(node)
2289 }
2290}
2291
2292impl Path {
2293 pub fn new(closed: bool) -> Path {
2294 Path {
2295 nodes: Vec::new(),
2296 closed,
2297 ..Default::default()
2298 }
2299 }
2300
2301 pub fn add(&mut self, pt: impl Into<Point>, node_type: NodeType) {
2302 let pt = pt.into();
2303 self.nodes.push(Node { pt, node_type });
2304 }
2305
2306 pub fn rotate_left(&mut self, delta: usize) {
2309 self.nodes.rotate_left(delta);
2310 }
2311
2312 pub fn reverse(&mut self) {
2313 self.nodes.reverse();
2314 }
2315
2316 pub(crate) fn get_previous_segment(&self, idx: usize) -> Option<PathSeg> {
2318 if self.nodes.len() < 2 {
2319 return None;
2320 }
2321 let end = self.nodes.get(idx)?.pt;
2322 let mut idx = self.prev_idx(idx);
2323 let prev = self.nodes.get(idx)?;
2324 if prev.node_type == NodeType::OffCurve {
2325 idx = self.prev_idx(idx);
2326 let control1 = self.nodes.get(idx)?;
2327 if control1.node_type != NodeType::OffCurve {
2328 log::info!("path for corner component contains unexpected quadratic");
2330 return Some(QuadBez::new(control1.pt, prev.pt, end).into());
2331 }
2332 let start = self.nodes.get(self.prev_idx(idx))?;
2333 Some(CubicBez::new(start.pt, control1.pt, prev.pt, end).into())
2334 } else {
2335 Some(Line::new(prev.pt, end).into())
2336 }
2337 }
2338
2339 pub(crate) fn get_next_segment(&self, idx: usize) -> Option<PathSeg> {
2341 if self.nodes.len() < 2 {
2342 return None;
2343 }
2344 let start = self.nodes.get(idx)?.pt;
2345 let mut idx = self.next_idx(idx);
2346 let next = self.nodes.get(idx)?;
2347 if next.node_type == NodeType::OffCurve {
2348 idx = self.next_idx(idx);
2349 let control2 = self.nodes.get(idx)?;
2350 if control2.node_type != NodeType::OffCurve {
2351 log::info!("path for corner component contains unexpected quadratic");
2353 return Some(QuadBez::new(start, next.pt, control2.pt).into());
2354 }
2355 let end = self.nodes.get(self.next_idx(idx))?;
2356 Some(CubicBez::new(start, next.pt, control2.pt, end.pt).into())
2357 } else {
2358 Some(Line::new(start, next.pt).into())
2359 }
2360 }
2361
2362 pub(crate) fn prev_idx(&self, idx: usize) -> usize {
2363 if idx == 0 {
2364 self.nodes.len().saturating_sub(1)
2365 } else {
2366 idx - 1
2367 }
2368 }
2369
2370 pub(crate) fn next_idx(&self, idx: usize) -> usize {
2371 (idx + 1) % self.nodes.len()
2372 }
2373
2374 #[cfg(test)]
2375 pub(crate) fn to_points(&self) -> Vec<Point> {
2376 self.nodes.iter().map(|n| n.pt).collect()
2377 }
2378}
2379
2380fn v2_to_v3_name(v2_prop: Option<&str>, v3_name: &str) -> Option<RawName> {
2381 v2_prop.map(|value| {
2384 if v3_name.ends_with('s') {
2385 RawName {
2386 key: v3_name.into(),
2387 value: None,
2388 values: vec![RawNameValue {
2389 language: "dflt".into(),
2390 value: value.to_string(),
2391 }],
2392 }
2393 } else {
2394 RawName {
2395 key: v3_name.into(),
2396 value: Some(value.to_string()),
2397 values: vec![],
2398 }
2399 }
2400 })
2401}
2402
2403impl RawFont {
2404 pub fn load_from_string(raw_content: &str) -> Result<Self, crate::plist::Error> {
2405 Self::parse_plist(raw_content)
2406 }
2407
2408 pub fn load(glyphs_file: &path::Path) -> Result<Self, Error> {
2409 if glyphs_file.extension() == Some(OsStr::new("glyphspackage")) {
2410 return Self::load_package(glyphs_file);
2411 }
2412
2413 debug!("Read glyphs {glyphs_file:?}");
2414 let raw_content = fs::read_to_string(glyphs_file).map_err(Error::IoError)?;
2415 Self::load_from_string(&raw_content)
2416 .map_err(|e| Error::ParseError(glyphs_file.to_path_buf(), e.to_string()))
2417 }
2418
2419 fn load_package(glyphs_package: &path::Path) -> Result<RawFont, Error> {
2421 if !glyphs_package.is_dir() {
2422 return Err(Error::NotAGlyphsPackage(glyphs_package.to_path_buf()));
2423 }
2424 debug!("Read glyphs package {glyphs_package:?}");
2425
2426 let fontinfo_file = glyphs_package.join("fontinfo.plist");
2427 let fontinfo_data = fs::read_to_string(&fontinfo_file).map_err(Error::IoError)?;
2428 let mut raw_font = RawFont::parse_plist(&fontinfo_data)
2429 .map_err(|e| Error::ParseError(fontinfo_file.to_path_buf(), format!("{e}")))?;
2430
2431 let mut glyphs: HashMap<SmolStr, RawGlyph> = HashMap::new();
2432 let glyphs_dir = glyphs_package.join("glyphs");
2433 if glyphs_dir.is_dir() {
2434 for entry in fs::read_dir(glyphs_dir).map_err(Error::IoError)? {
2435 let entry = entry.map_err(Error::IoError)?;
2436 let path = entry.path();
2437 if path.extension() == Some(OsStr::new("glyph")) {
2438 let glyph_data = fs::read_to_string(&path).map_err(Error::IoError)?;
2439 let glyph = RawGlyph::parse_plist(&glyph_data)
2440 .map_err(|e| Error::ParseError(path.clone(), e.to_string()))?;
2441 if glyph.glyphname.is_empty() {
2442 return Err(Error::ParseError(
2443 path.clone(),
2444 "Glyph dict must have a 'glyphname' key".to_string(),
2445 ));
2446 }
2447 let name = glyph.glyphname.clone();
2448 if glyphs.insert(name.clone(), glyph).is_some() {
2449 return Err(Error::DuplicateGlyphName(name));
2450 }
2451 }
2452 }
2453 }
2454
2455 let order_file = glyphs_package.join("order.plist");
2457 let mut ordered_glyphs = Vec::new();
2458 if order_file.exists() {
2459 let order_data = fs::read_to_string(&order_file).map_err(Error::IoError)?;
2460 let order_plist = Plist::parse(&order_data)
2461 .map_err(|e| Error::ParseError(order_file.to_path_buf(), e.to_string()))?;
2462 let order = order_plist
2463 .expect_array()
2464 .map_err(|e| Error::ParseError(order_file.to_path_buf(), e.to_string()))?;
2465 for glyph_name in order {
2466 let glyph_name = glyph_name
2467 .expect_string()
2468 .map_err(|e| Error::ParseError(order_file.to_path_buf(), e.to_string()))?;
2469 if let Some(glyph) = glyphs.remove(glyph_name.as_str()) {
2470 ordered_glyphs.push(glyph);
2471 }
2472 }
2473 }
2474 let mut glyph_names: Vec<_> = glyphs.keys().cloned().collect();
2476 glyph_names.sort();
2477 ordered_glyphs.extend(
2478 glyph_names
2479 .into_iter()
2480 .map(|glyph_name| glyphs.remove(&glyph_name).unwrap()),
2481 );
2482 assert!(glyphs.is_empty());
2483 raw_font.glyphs = ordered_glyphs;
2484
2485 Ok(raw_font)
2488 }
2489
2490 fn v2_to_v3_axes(&mut self) -> Result<Vec<String>, Error> {
2491 let mut tags = Vec::new();
2492 if let Some(v2_axes) = self.custom_parameters.take_axes() {
2493 for v2_axis in v2_axes {
2494 tags.push(v2_axis.tag.clone());
2495 self.axes.push(v2_axis.clone());
2496 }
2497 }
2498
2499 if self.axes.is_empty() {
2502 self.axes.push(Axis {
2503 name: "Weight".into(),
2504 tag: "wght".into(),
2505 hidden: None,
2506 });
2507 self.axes.push(Axis {
2508 name: "Width".into(),
2509 tag: "wdth".into(),
2510 hidden: None,
2511 });
2512 self.axes.push(Axis {
2513 name: "Custom".into(),
2514 tag: "XXXX".into(),
2515 hidden: None,
2516 });
2517 }
2518
2519 if self.axes.len() > 3 {
2520 return Err(Error::StructuralError(
2521 "We only understand 0..3 axes for Glyphs v2".into(),
2522 ));
2523 }
2524
2525 for master in self.font_master.iter_mut() {
2528 master.axes_values = master.axis_values(&self.axes)?;
2529 }
2530 for instance in self.instances.iter_mut() {
2531 instance.axes_values = instance.axis_values(&self.axes)?;
2532 }
2533
2534 Ok(tags)
2535 }
2536
2537 fn v2_to_v3_metrics(&mut self) -> Result<(), Error> {
2538 self.metrics = V3_METRIC_NAMES
2540 .iter()
2541 .map(|n| RawMetric {
2542 type_: n.to_string(),
2543 })
2544 .collect();
2545
2546 let mut used_metrics = [false; 6];
2547 for m in &self.font_master {
2549 for (i, val) in [
2550 m.ascender,
2551 m.baseline,
2552 m.descender,
2553 m.cap_height,
2554 m.x_height,
2555 m.italic_angle,
2556 ]
2557 .iter()
2558 .enumerate()
2559 {
2560 used_metrics[i] |= val.is_some();
2561 }
2562 }
2563
2564 self.metrics = V3_METRIC_NAMES
2566 .into_iter()
2567 .zip(used_metrics)
2568 .filter(|(_, used)| *used)
2569 .map(|(name, _)| RawMetric {
2570 type_: name.to_string(),
2571 })
2572 .collect();
2573
2574 let mut non_metric_alignment_zones = vec![vec![]; self.font_master.len()];
2575
2576 for (i, master) in self.font_master.iter_mut().enumerate() {
2578 let mut metric_values = vec![RawMetricValue::default(); self.metrics.len()];
2582 for (metric_idx, name) in self.metrics.iter().enumerate() {
2583 let value = match name.type_.as_ref() {
2584 "ascender" => master.ascender,
2585 "baseline" => master.baseline,
2586 "descender" => master.descender,
2587 "cap height" => master.cap_height,
2588 "x-height" => master.x_height,
2589 "italic angle" => master.italic_angle,
2590 _ => unreachable!("only these values exist in V3_METRIC_NAMES"),
2591 };
2592 metric_values[metric_idx].pos = value;
2593 }
2594
2595 for alignment_zone in &master.alignment_zones {
2597 let Some((pos, over)) = parse_alignment_zone(alignment_zone) else {
2598 warn!("Confusing alignment zone '{alignment_zone}', skipping");
2599 continue;
2600 };
2601
2602 if over == 0. {
2604 continue;
2605 }
2606
2607 if pos == 0. {
2611 if let Some((idx, _)) = self
2612 .metrics
2613 .iter()
2614 .enumerate()
2615 .find(|(_, name)| name.type_ == "baseline")
2616 {
2617 metric_values[idx].over = Some(over);
2618 }
2619 continue;
2620 }
2621
2622 if let Some(metric) = metric_values.iter_mut().find(|x| x.pos == Some(pos)) {
2625 metric.over = Some(over);
2626 } else {
2627 non_metric_alignment_zones[i].push((pos, over))
2628 }
2629 }
2630 master.metric_values = metric_values;
2631 }
2632
2633 let mut new_metrics = HashMap::new();
2636 for pos in non_metric_alignment_zones
2637 .iter()
2638 .flat_map(|master| master.iter().map(|(pos, _)| *pos))
2639 {
2640 if !new_metrics.contains_key(&pos) {
2641 let next_zone = new_metrics.len() + 1;
2642 let idx = self.metrics.len();
2643 self.metrics.push(RawMetric {
2644 type_: format!("zone {next_zone}"),
2645 });
2646 new_metrics.insert(pos, idx);
2647 }
2648 }
2649
2650 let new_metrics: BTreeMap<_, _> = new_metrics.into_iter().map(|(k, v)| (v, k)).collect();
2652
2653 for (idx, metrics) in non_metric_alignment_zones.into_iter().enumerate() {
2655 for pos_to_add in new_metrics.values().copied() {
2656 let to_add = metrics.iter().copied().find_map(|(pos, over)| {
2657 (pos == pos_to_add).then_some(RawMetricValue {
2658 pos: Some(pos),
2659 over: Some(over),
2660 })
2661 });
2662
2663 self.font_master[idx]
2664 .metric_values
2665 .push(to_add.unwrap_or_default());
2666 }
2667 }
2668 Ok(())
2669 }
2670
2671 fn default_master_names(&mut self) {
2673 let italic_angle_idx = self.metrics.iter().position(|m| m.type_ == "italic angle");
2683 for master in self.font_master.iter_mut() {
2684 if master.name.is_some() {
2685 continue;
2686 }
2687
2688 let mut names = [
2690 master.width.as_deref(),
2691 master.weight.as_deref(),
2692 master.custom.as_deref(),
2693 ]
2694 .iter()
2695 .flatten()
2696 .flat_map(|n| n.split_ascii_whitespace())
2697 .filter(|x| *x != "Regular")
2698 .collect::<Vec<_>>();
2699
2700 let italic = italic_angle_idx
2702 .and_then(|idx| master.metric_values.get(idx))
2703 .and_then(|value| value.pos)
2704 .is_some_and(|angle| angle != 0.0);
2705 if italic
2706 && (names.is_empty()
2707 || !names
2708 .iter()
2709 .any(|name| name.contains("Italic") || name.contains("Oblique")))
2711 {
2712 names.push("Italic");
2713 }
2714 master.name = if names.is_empty() {
2716 Some("Regular".into())
2717 } else {
2718 Some(names.join(" "))
2719 };
2720 }
2721 }
2722
2723 fn v2_to_v3_names(&mut self) -> Result<(), Error> {
2724 let mut properties = std::mem::take(&mut self.properties);
2728
2729 properties.extend(v2_to_v3_name(self.copyright.as_deref(), "copyrights"));
2730 properties.extend(v2_to_v3_name(self.designer.as_deref(), "designers"));
2731 properties.extend(v2_to_v3_name(self.designerURL.as_deref(), "designerURL"));
2732 properties.extend(v2_to_v3_name(self.manufacturer.as_deref(), "manufacturers"));
2733 properties.extend(v2_to_v3_name(
2734 self.manufacturerURL.as_deref(),
2735 "manufacturerURL",
2736 ));
2737
2738 let mut v2_to_v3_param = |v2_names: &[&str], v3_name: &str| {
2741 if properties.iter().any(|n| n.key == v3_name && !n.is_empty()) {
2742 return;
2743 }
2744 for v2_name in v2_names {
2745 if let Some(value) = v2_to_v3_name(
2746 self.custom_parameters.take_string(v2_name).as_deref(),
2747 v3_name,
2748 ) {
2749 properties.push(value);
2750 return;
2751 }
2752 }
2753 };
2754
2755 v2_to_v3_param(&["description", "openTypeNameDescription"], "descriptions");
2756 v2_to_v3_param(&["licenseURL", "openTypeNameLicenseURL"], "licenseURL");
2757 v2_to_v3_param(&["versionString", "openTypeNameVersion"], "versionString");
2758 v2_to_v3_param(&["compatibleFullName"], "compatibleFullNames");
2759 v2_to_v3_param(&["license", "openTypeNameLicense"], "licenses");
2760 v2_to_v3_param(&["uniqueID", "openTypeNameUniqueID"], "uniqueID");
2761 v2_to_v3_param(&["trademark"], "trademarks");
2762 v2_to_v3_param(&["sampleText", "openTypeNameSampleText"], "sampleTexts");
2763 v2_to_v3_param(&["postscriptFullName"], "postscriptFullName");
2764 v2_to_v3_param(&["postscriptFontName"], "postscriptFontName");
2765 v2_to_v3_param(
2766 &["WWSFamilyName", "openTypeNameWWSFamilyName"],
2767 "WWSFamilyName",
2768 );
2769 v2_to_v3_param(&["vendorID", "openTypeOS2VendorID"], "vendorID");
2770
2771 self.properties = properties;
2772
2773 Ok(())
2774 }
2775
2776 fn v2_to_v3_instances(&mut self) -> Result<(), Error> {
2777 for instance in self.instances.iter_mut() {
2778 if let Some(custom_weight_class) = instance.custom_parameters.take("weightClass") {
2779 instance.weight_class = custom_weight_class.to_string().into();
2780 }
2781 if let Some(custom_width_class) = instance.custom_parameters.take("widthClass") {
2782 instance.width_class = custom_width_class.to_string().into();
2783 }
2784
2785 for (keys, property) in [
2790 (&["familyName"][..], "familyNames"),
2791 (&["postscriptFontName"][..], "postscriptFontName"),
2792 (
2793 &["preferredFamilyName", "openTypeNamePreferredFamilyName"][..],
2794 "preferredFamilyNames",
2795 ),
2796 (
2797 &[
2798 "preferredSubfamilyName",
2799 "openTypeNamePreferredSubfamilyName",
2800 ][..],
2801 "preferredSubfamilyNames",
2802 ),
2803 (
2804 &["WWSFamilyName", "openTypeNameWWSFamilyName"][..],
2805 "WWSFamilyName",
2806 ),
2807 (
2808 &["WWSSubfamilyName", "openTypeNameWWSSubfamilyName"][..],
2809 "WWSSubfamilyName",
2810 ),
2811 (&["styleMapFamilyName"][..], "styleMapFamilyNames"),
2812 (&["styleMapStyleName"][..], "styleMapStyleNames"),
2813 (&["postscriptFullName"][..], "postscriptFullName"),
2814 (&["license", "openTypeNameLicense"][..], "licenses"),
2815 (&["licenseURL", "openTypeNameLicenseURL"][..], "licenseURL"),
2816 (&["trademark"][..], "trademarks"),
2817 (
2818 &["description", "openTypeNameDescription"][..],
2819 "descriptions",
2820 ),
2821 (&["sampleText", "openTypeNameSampleText"][..], "sampleTexts"),
2822 (&["uniqueID", "openTypeNameUniqueID"][..], "uniqueID"),
2823 ] {
2824 if let Some(name) = keys
2825 .iter()
2826 .find_map(|key| instance.custom_parameters.take_string(key))
2827 {
2828 instance
2829 .properties
2830 .extend(v2_to_v3_name(Some(&name), property));
2831 }
2832 }
2833 }
2834
2835 Ok(())
2836 }
2837
2838 fn v2_to_v3_layer_attributes(&mut self) {
2839 for raw_glyph in self.glyphs.iter_mut() {
2840 for layer in raw_glyph.layers.iter_mut() {
2841 layer.v2_to_v3_attributes();
2842 }
2843 }
2844 }
2845
2846 fn normalize_instance_classes(&mut self) -> Result<(), Error> {
2852 for instance in self.instances.iter_mut() {
2853 for (tag, opt) in [
2854 ("wght", &mut instance.weight_class),
2855 ("wdth", &mut instance.width_class),
2856 ] {
2857 let Some(value) = opt.as_ref() else {
2858 continue;
2859 };
2860 if f64::from_str(value).is_ok() {
2861 continue;
2862 };
2863 let Some(value) = lookup_class_value(tag, value) else {
2864 return Err(Error::UnknownValueName(value.clone()));
2865 };
2866 let _ = opt.insert(value.to_string());
2867 }
2868 }
2869 Ok(())
2870 }
2871
2872 fn v2_to_v3(&mut self) -> Result<(), Error> {
2874 self.v2_to_v3_axes()?;
2875 self.v2_to_v3_metrics()?;
2876 self.v2_to_v3_instances()?;
2877 self.v2_to_v3_names()?; self.v2_to_v3_layer_attributes();
2879 Ok(())
2880 }
2881}
2882
2883fn parse_alignment_zone(zone: &str) -> Option<(OrderedFloat<f64>, OrderedFloat<f64>)> {
2885 let (one, two) = zone.split_once(',')?;
2886 let one = one.trim_start_matches(['{', ' ']).parse::<i32>().ok()?;
2887 let two = two.trim_start().trim_end_matches('}').parse::<i32>().ok()?;
2888 Some((OrderedFloat(one as f64), OrderedFloat(two as f64)))
2889}
2890
2891fn make_glyph_order(
2892 glyphs: &[RawGlyph],
2893 custom_order: Option<Vec<SmolStr>>,
2894) -> Result<Vec<SmolStr>, Error> {
2895 let mut valid_names = HashSet::new();
2896 for glyph in glyphs {
2897 if !valid_names.insert(&glyph.glyphname) {
2898 return Err(Error::DuplicateGlyphName(glyph.glyphname.clone()));
2899 }
2900 }
2901 let mut glyph_order = Vec::new();
2902
2903 for name in custom_order.into_iter().flatten() {
2906 if valid_names.remove(&name) {
2907 glyph_order.push(name.clone());
2908 }
2909 }
2910
2911 glyph_order.extend(
2913 glyphs
2914 .iter()
2915 .filter(|g| valid_names.contains(&g.glyphname))
2916 .map(|g| g.glyphname.clone()),
2917 );
2918
2919 Ok(glyph_order)
2920}
2921
2922fn parse_codepoint_str(s: &str, radix: u32) -> Vec<u32> {
2924 s.split(',')
2925 .map(|cp| u32::from_str_radix(cp, radix).unwrap())
2926 .collect()
2927}
2928
2929fn default_master_idx(raw_font: &mut RawFont) -> usize {
2931 if let Some(master_idx) = raw_font
2934 .custom_parameters
2935 .take_string("Variable Font Origin")
2936 .and_then(|origin| {
2937 raw_font
2938 .font_master
2939 .iter()
2940 .position(|master| master.id == origin)
2941 })
2942 {
2943 return master_idx;
2944 }
2945
2946 let contenders = raw_font
2950 .font_master
2951 .iter()
2952 .enumerate()
2953 .filter_map(|(i, m)| {
2954 m.name
2955 .as_deref()
2956 .map(|name| (i, whitespace_separated_tokens(name)))
2957 })
2958 .collect::<Vec<_>>();
2959
2960 if contenders.is_empty() {
2962 return 0;
2963 }
2964
2965 let mut common_words = contenders[0].1.clone();
2967 for (_, words) in contenders.iter().skip(1) {
2968 common_words.retain(|w| words.contains(w));
2969 }
2970
2971 let mut best_idx = 0;
2978 for (idx, mut words) in contenders {
2979 if *common_words == words {
2981 best_idx = idx;
2982 break;
2983 }
2984
2985 words.retain(|w| *w != "Regular");
2988 if *common_words == words {
2989 best_idx = idx;
2990 }
2991 }
2992 best_idx
2993}
2994
2995fn whitespace_separated_tokens(s: &str) -> Vec<&str> {
2996 s.split_whitespace().collect()
2997}
2998
2999fn axis_index(axes: &[Axis], pred: impl Fn(&Axis) -> bool) -> Option<usize> {
3000 axes.iter()
3001 .enumerate()
3002 .find_map(|(i, a)| if pred(a) { Some(i) } else { None })
3003}
3004
3005fn user_to_design_from_axis_mapping(
3006 from: &mut RawFont,
3007) -> Option<BTreeMap<String, AxisUserToDesignMap>> {
3008 let mappings = from.custom_parameters.take_axis_mappings()?;
3009 let mut axis_mappings: BTreeMap<String, AxisUserToDesignMap> = BTreeMap::new();
3010 for mapping in mappings {
3011 let Some(axis_index) = axis_index(&from.axes, |a| a.tag == mapping.tag) else {
3012 log::warn!(
3013 "axis mapping includes tag {:?} not included in font",
3014 mapping.tag
3015 );
3016 continue;
3017 };
3018 let axis_name = &from.axes.get(axis_index).unwrap().name;
3019 for (user, design) in mapping.user_to_design.iter() {
3020 axis_mappings
3021 .entry(axis_name.clone())
3022 .or_default()
3023 .add_if_new(*user, *design);
3024 }
3025 }
3026 if axis_mappings.is_empty() {
3027 return None;
3028 }
3029 Some(axis_mappings)
3030}
3031
3032fn user_to_design_from_axis_location(
3033 from: &mut RawFont,
3034) -> Option<BTreeMap<String, AxisUserToDesignMap>> {
3035 let master_locations: Vec<_> = from
3038 .font_master
3039 .iter_mut()
3040 .filter_map(|m| m.custom_parameters.take_axis_locations())
3041 .collect();
3042 if master_locations.len() != from.font_master.len() {
3043 if !master_locations.is_empty() {
3044 warn!(
3045 "{}/{} masters have Axis Location; ignoring",
3046 master_locations.len(),
3047 from.font_master.len()
3048 );
3049 }
3050 return None;
3051 }
3052
3053 let mut axis_mappings: BTreeMap<String, AxisUserToDesignMap> = BTreeMap::new();
3054 for (master, axis_locations) in from.font_master.iter().zip(master_locations) {
3055 for (idx, axis) in from.axes.iter().enumerate() {
3058 let Some(axis_location) = axis_locations.iter().find(|loc| loc.axis_name == axis.name)
3059 else {
3060 continue;
3061 };
3062 let user = axis_location.location;
3063 let design = master.axes_values[idx];
3064 let old = axis_mappings
3067 .entry(axis_location.axis_name.clone())
3068 .or_default()
3069 .add_or_replace(user, design);
3070 if let Some(old) = old {
3071 let name = master.name.as_deref().unwrap_or(&master.id);
3072 warn!(
3073 "Axis {}: master '{}' redefines mapping for user \
3074 location {user} from {old} to {design}",
3075 axis.name, name
3076 );
3077 }
3078 }
3079 }
3080 Some(axis_mappings)
3081}
3082
3083impl AxisUserToDesignMap {
3084 fn add_if_new(&mut self, user: OrderedFloat<f64>, design: OrderedFloat<f64>) {
3085 if self.0.iter().any(|(u, _)| *u == user) {
3087 return;
3088 }
3089 self.0.push((user, design));
3090 }
3091
3092 fn add_or_replace(
3095 &mut self,
3096 user: OrderedFloat<f64>,
3097 design: OrderedFloat<f64>,
3098 ) -> Option<OrderedFloat<f64>> {
3099 if let Some(entry) = self.0.iter_mut().find(|(u, _)| *u == user) {
3100 if entry.1 != design {
3101 let old = entry.1;
3102 entry.1 = design;
3103 return Some(old);
3104 }
3105 } else {
3106 self.0.push((user, design));
3107 }
3108 None
3109 }
3110
3111 fn add_identity_map(&mut self, value: OrderedFloat<f64>) {
3112 if self.0.iter().any(|(u, d)| *u == value || *d == value) {
3114 return;
3115 }
3116 self.0.push((value, value));
3117 }
3118
3119 pub fn iter(&self) -> impl Iterator<Item = &(OrderedFloat<f64>, OrderedFloat<f64>)> {
3120 self.0.iter()
3121 }
3122
3123 pub fn is_identity(&self) -> bool {
3124 self.0.iter().all(|(u, d)| u == d)
3125 }
3126
3127 fn user_at(&self, design: OrderedFloat<f64>) -> Option<OrderedFloat<f64>> {
3130 let mut points: Vec<_> = self.0.iter().map(|(u, d)| (*d, *u)).collect();
3131 points.sort();
3132 let w = points
3133 .windows(2)
3134 .find(|w| w[0].0 <= design && design <= w[1].0)?;
3135 let ((d0, u0), (d1, u1)) = (w[0], w[1]);
3136 let user = if d0 == d1 {
3137 u0.0
3138 } else {
3139 u0.0 + (u1.0 - u0.0) * (design.0 - d0.0) / (d1.0 - d0.0)
3140 };
3141 Some(OrderedFloat(
3142 write_fonts::types::Fixed::from_f64(user).to_f64(),
3143 ))
3144 }
3145
3146 fn extended_to_masters(
3156 &self,
3157 tag: &str,
3158 min: OrderedFloat<f64>,
3159 max: OrderedFloat<f64>,
3160 ) -> Option<Self> {
3161 let mut points: Vec<_> = self.0.iter().map(|(u, d)| (*d, *u)).collect();
3162 points.sort();
3163 if points.len() < 2 || !points.iter().any(|(d, _)| min <= *d && *d <= max) {
3164 return None;
3165 }
3166 let (first, last) = (points[0].0, points[points.len() - 1].0);
3167 let mut extended = self.clone();
3168 for design in [min, max] {
3169 let ((d0, u0), (d1, u1)) = if design < first {
3170 (points[0], points[1])
3171 } else if design > last {
3172 (points[points.len() - 2], points[points.len() - 1])
3173 } else {
3174 continue;
3175 };
3176 if d0 == d1 || u0 == u1 {
3177 return None;
3178 }
3179 let user = u0.0 + (design.0 - d0.0) * (u1.0 - u0.0) / (d1.0 - d0.0);
3180 let user = write_fonts::types::Fixed::from_f64(user).to_f64();
3181 let valid = match tag {
3184 "wght" => (1.0..=1000.0).contains(&user),
3185 "wdth" => user > 0.0,
3186 _ => true,
3187 };
3188 if !valid {
3189 return None;
3190 }
3191 extended.add_if_new(OrderedFloat(user), design);
3192 }
3193 Some(extended)
3194 }
3195}
3196
3197impl UserToDesignMapping {
3198 fn new(from: &mut RawFont, instances: &[Instance], default_master_idx: usize) -> Self {
3202 let from_axis_mapping = user_to_design_from_axis_mapping(from);
3203 let from_axis_location = user_to_design_from_axis_location(from);
3204 let from_instances_only = from_axis_mapping.is_none() && from_axis_location.is_none();
3205 let (result, incomplete_mapping) = match (from_axis_mapping, from_axis_location) {
3206 (Some(from_mapping), Some(..)) => {
3207 warn!("Axis Mapping *and* Axis Location are defined; using Axis Mapping");
3208 (from_mapping, false)
3209 }
3210 (Some(from_mapping), None) => (from_mapping, false),
3211 (None, Some(from_location)) => (from_location, true),
3212 (None, None) => (BTreeMap::new(), true),
3213 };
3214 let mut result = Self(result);
3215 if incomplete_mapping {
3216 result.add_instance_mappings(instances);
3218 if from_instances_only {
3219 result.check_instance_mappings_against_masters(from, default_master_idx);
3220 }
3221 result.trim_to_masters(from);
3222 if result.0.is_empty() || result.0.values().all(|v| v.is_identity()) {
3223 result.add_master_mappings_if_new(from);
3224 }
3225 }
3226 result
3227 }
3228
3229 pub fn contains(&self, axis_name: &str) -> bool {
3230 self.0.contains_key(axis_name)
3231 }
3232
3233 pub fn get(&self, axis_name: &str) -> Option<&AxisUserToDesignMap> {
3234 self.0.get(axis_name)
3235 }
3236
3237 fn add_instance_mappings(&mut self, instances: &[Instance]) {
3240 for instance in instances
3241 .iter()
3242 .filter(|i| i.active && i.type_ == InstanceType::Single)
3243 {
3244 for (axis_name, inst_mapping) in instance.axis_mappings.iter() {
3245 let entry = self.0.entry(axis_name.clone()).or_default();
3246 for (user, design) in inst_mapping.iter() {
3247 if let Some(old) = entry.add_or_replace(*user, *design) {
3248 warn!(
3249 "Axis {axis_name}: instance '{}' redefines mapping for user \
3250 location {user} from {old} to {design}",
3251 instance.name
3252 );
3253 }
3254 }
3255 }
3256 }
3257 }
3258
3259 fn check_instance_mappings_against_masters(
3273 &mut self,
3274 from: &RawFont,
3275 default_master_idx: usize,
3276 ) {
3277 for (idx, axis) in from.axes.iter().enumerate() {
3278 let Some(mapping) = self.0.get_mut(&axis.name) else {
3279 continue;
3280 };
3281 if mapping.is_identity() {
3282 continue;
3283 }
3284 let masters: Vec<_> = from
3285 .font_master
3286 .iter()
3287 .filter_map(|m| m.axes_values.get(idx).copied())
3288 .collect();
3289 let covers = |design: &OrderedFloat<f64>| {
3290 mapping.iter().any(|(_, d)| d <= design) && mapping.iter().any(|(_, d)| d >= design)
3291 };
3292 let (Some(min), Some(max)) =
3294 (masters.iter().min().copied(), masters.iter().max().copied())
3295 else {
3296 continue;
3297 };
3298 if !masters.iter().all(covers) {
3299 let Some(extended) = mapping.extended_to_masters(&axis.tag, min, max) else {
3300 warn!(
3301 "Axis {}: not using the mapping from the instances, as they don't \
3302 span all the masters; add Axis Location parameters to the masters \
3303 to map the axis",
3304 axis.name
3305 );
3306 self.0.remove(&axis.name);
3307 continue;
3308 };
3309 warn!(
3310 "Axis {}: the instances don't span all the masters, extending their \
3311 mapping out to the masters; add Axis Location parameters to the \
3312 masters to map the axis explicitly",
3313 axis.name
3314 );
3315 *mapping = extended;
3316 }
3317 let default = from
3318 .font_master
3319 .get(default_master_idx)
3320 .and_then(|m| m.axes_values.get(idx).copied());
3321 for design in [default, Some(min), Some(max)].into_iter().flatten() {
3322 if mapping.iter().any(|(_, d)| *d == design) {
3323 continue;
3324 }
3325 let Some(user) = mapping.user_at(design) else {
3326 continue;
3327 };
3328 if Some(design) == default {
3329 warn!(
3330 "Axis {}: no instance is at the default master, mapping it to the \
3331 interpolated user location {user}; add an instance or Axis Location \
3332 parameters to map it explicitly",
3333 axis.name
3334 );
3335 }
3336 mapping.add_or_replace(user, design);
3337 }
3338 }
3339 }
3340
3341 fn trim_to_masters(&mut self, from: &RawFont) {
3346 for (idx, axis) in from.axes.iter().enumerate() {
3347 let Some(mapping) = self.0.get_mut(&axis.name) else {
3348 continue;
3349 };
3350 let masters = from
3351 .font_master
3352 .iter()
3353 .filter_map(|m| m.axes_values.get(idx).copied());
3354 let (Some(min), Some(max)) = (masters.clone().min(), masters.max()) else {
3355 continue;
3356 };
3357 let untrimmed = mapping.clone();
3358 mapping.0.retain(|(_, d)| min <= *d && *d <= max);
3359 if mapping.0.len() == untrimmed.0.len() {
3360 continue;
3361 }
3362 for design in [min, max] {
3363 if mapping.iter().any(|(_, d)| *d == design) {
3364 continue;
3365 }
3366 if let Some(user) = untrimmed.user_at(design) {
3367 mapping.add_if_new(user, design);
3368 }
3369 }
3370 }
3371 }
3372
3373 fn add_master_mappings_if_new(&mut self, from: &RawFont) {
3374 for master in from.font_master.iter() {
3375 for (axis, value) in from.axes.iter().zip(&master.axes_values) {
3376 self.0
3377 .entry(axis.name.clone())
3378 .or_default()
3379 .add_identity_map(*value);
3380 }
3381 }
3382 }
3383}
3384
3385impl TryFrom<RawShape> for Shape {
3386 type Error = Error;
3387
3388 fn try_from(from: RawShape) -> Result<Self, Self::Error> {
3389 let shape = if let Some(glyph_name) = from.glyph_name {
3393 assert!(!glyph_name.is_empty(), "A pointless component");
3394
3395 let mut transform = if let Some(transform) = from.transform {
3397 Affine::parse_plist(&transform)?
3398 } else {
3399 Affine::IDENTITY
3400 };
3401
3402 if !from.pos.is_empty() {
3407 if from.pos.len() != 2 {
3408 return Err(Error::StructuralError(format!("Bad pos: {:?}", from.pos)));
3409 }
3410 transform *= Affine::translate((from.pos[0], from.pos[1]));
3411 }
3412 if !from.slant.is_empty() {
3413 if from.slant.len() != 2 {
3414 return Err(Error::StructuralError(format!(
3415 "Bad slant: {:?}",
3416 from.slant
3417 )));
3418 }
3419 transform *= Affine::skew(
3422 from.slant[0].to_radians().tan(),
3423 from.slant[1].to_radians().tan(),
3424 );
3425 }
3426 if let Some(angle) = from.angle {
3427 transform *= normalized_rotation(angle);
3428 }
3429 if !from.scale.is_empty() {
3430 if from.scale.len() != 2 {
3431 return Err(Error::StructuralError(format!(
3432 "Bad scale: {:?}",
3433 from.scale
3434 )));
3435 }
3436 transform *= Affine::scale_non_uniform(from.scale[0], from.scale[1]);
3437 }
3438
3439 Shape::Component(Component {
3440 name: glyph_name,
3441 transform,
3442 anchor: from.anchor,
3443 attributes: from.attributes,
3444 smart_component_values: from.piece,
3445 })
3446 } else {
3447 Shape::Path(Path {
3449 closed: from.closed.unwrap_or_default(),
3450 nodes: from.nodes.clone(),
3451 attributes: from.attributes,
3452 })
3453 };
3454 Ok(shape)
3455 }
3456}
3457
3458fn normalized_rotation(angle_deg: f64) -> Affine {
3468 const ROT_90: Affine = Affine::new([0.0, 1.0, -1.0, 0.0, 0.0, 0.0]);
3469 const ROT_180: Affine = Affine::new([-1.0, 0.0, 0.0, -1.0, 0.0, 0.0]);
3470 const ROT_270: Affine = Affine::new([0.0, -1.0, 1.0, 0.0, 0.0, 0.0]);
3471 let normalized_angle = angle_deg.rem_euclid(360.0);
3473
3474 match normalized_angle {
3475 0.0 => Affine::IDENTITY,
3476 90.0 => ROT_90,
3477 180.0 => ROT_180,
3478 270.0 => ROT_270,
3479 _ => Affine::rotate(angle_deg.to_radians()),
3480 }
3481}
3482
3483fn map_and_push_if_present<T, U>(dest: &mut Vec<T>, src: Vec<U>, map: fn(U) -> T) {
3484 src.into_iter().map(map).for_each(|v| dest.push(v));
3485}
3486
3487impl RawLayer {
3488 fn build(self, format_version: FormatVersion) -> Result<Layer, Error> {
3489 const DEFAULT_LAYER_WIDTH: f64 = 600.;
3495 let mut shapes = Vec::new();
3496
3497 map_and_push_if_present(&mut shapes, self.paths, Shape::Path);
3499 map_and_push_if_present(&mut shapes, self.components, Shape::Component);
3500
3501 for raw_shape in self.shapes {
3503 shapes.push(raw_shape.try_into()?);
3504 }
3505
3506 let anchors = self
3507 .anchors
3508 .into_iter()
3509 .map(|ra| {
3510 let pos = if let Some(pos) = ra.pos {
3511 pos
3512 } else if let Some(raw) = ra.position {
3513 Point::parse_plist(&raw).unwrap()
3514 } else {
3515 Point::ZERO
3516 };
3517 Anchor { name: ra.name, pos }
3518 })
3519 .collect();
3520
3521 let mut attributes = self.attributes;
3522 if let Some(axis_rule) =
3524 AxisRule::from_layer_name(&self.name).filter(|_| format_version.is_v2())
3525 {
3526 assert!(
3527 attributes.axis_rules.is_empty(),
3528 "glyphs v2 does not use axisRules attr"
3529 );
3530 attributes.axis_rules.push(axis_rule);
3531 }
3532 let smart_component_positions = if format_version.is_v2() {
3533 self.user_data.part_selection
3534 } else {
3535 self.part_selection
3536 }
3537 .into_iter()
3538 .map(|(k, v)| match v {
3539 1 => Ok((k, AxisPole::Min)),
3540 2 => Ok((k, AxisPole::Max)),
3541 other => Err(Error::BadValue(format!(
3542 "expected only 1 or 2 in partSelection, found '{other}'"
3543 ))),
3544 })
3545 .collect::<Result<_, _>>()?;
3546 let hints = self
3547 .hints
3548 .iter()
3549 .map(RawHint::to_hint)
3550 .collect::<Result<_, _>>()?;
3551 Ok(Layer {
3552 layer_id: self.layer_id,
3553 associated_master_id: self.associated_master_id,
3554 width: self.width.unwrap_or(DEFAULT_LAYER_WIDTH.into()),
3555 vert_width: self.vert_width,
3556 vert_origin: self.vert_origin,
3557 shapes,
3558 anchors,
3559 attributes,
3560 smart_component_positions,
3561 hints,
3562 open_corners_erased: false,
3563 })
3564 }
3565}
3566
3567fn resolve_reverse_bracket_layers(layers: &mut [RawLayer]) {
3580 let is_master = |layer: &RawLayer| {
3581 layer.associated_master_id.is_none()
3582 || layer.associated_master_id.as_ref() == Some(&layer.layer_id)
3583 };
3584 let mut pairs = Vec::new();
3585 let mut ignored = Vec::new();
3586 for (i, master) in layers.iter().enumerate() {
3587 if !is_master(master) {
3588 continue;
3589 }
3590 let blank = layers
3591 .iter()
3592 .enumerate()
3593 .filter(|(_, layer)| {
3594 layer.is_blank_alternate()
3595 && layer.associated_master_id.as_ref() == Some(&master.layer_id)
3596 })
3597 .map(|(j, _)| j)
3598 .collect::<Vec<_>>();
3599 match blank.as_slice() {
3600 [j] if master.has_bounded_axis_rules() => pairs.push((i, *j)),
3601 _ => ignored.extend(blank),
3602 }
3603 }
3604 for (i, j) in pairs {
3605 log::debug!(
3606 "using blank alternate layer '{}' as master '{}'",
3607 layers[j].layer_id,
3608 layers[i].layer_id
3609 );
3610 let master_id = layers[i].layer_id.clone();
3611 let blank_id = std::mem::replace(&mut layers[j].layer_id, master_id.clone());
3612 layers[j].associated_master_id = None;
3613 layers[j].attributes.axis_rules.clear();
3614 layers[i].layer_id = blank_id;
3616 layers[i].associated_master_id = Some(master_id);
3617 layers.swap(i, j);
3618 }
3619 for j in ignored {
3620 log::debug!("ignoring blank alternate layer '{}'", layers[j].layer_id);
3621 layers[j].attributes.axis_rules.clear();
3622 }
3623}
3624
3625impl RawGlyph {
3626 fn build(
3628 mut self,
3629 format_version: FormatVersion,
3630 glyph_data: &GlyphData,
3631 ) -> Result<Glyph, Error> {
3632 if format_version == FormatVersion::V3 {
3633 resolve_reverse_bracket_layers(&mut self.layers);
3634 }
3635 let mut instances = Vec::new();
3636 let mut bracket_layers = Vec::new();
3637 for mut layer in self.layers {
3638 if layer.is_bracket_layer(format_version) {
3639 bracket_layers.push(layer.build(format_version)?);
3640 } else if !layer.is_draft() {
3641 layer.attributes.axis_rules.clear();
3644 instances.push(layer.build(format_version)?);
3645 }
3646 }
3647 fn parse_category<T>(s: Option<&str>, glyph: &SmolStr) -> Option<T>
3652 where
3653 T: FromStr<Err = SmolStr>,
3654 {
3655 match s.filter(|s| !s.is_empty()).map(T::from_str).transpose() {
3656 Ok(x) => x,
3657 Err(err) => {
3659 log::warn!("Unknown category '{err}' for glyph '{glyph}'");
3660 None
3661 }
3662 }
3663 }
3664
3665 let mut category = parse_category(self.category.as_deref(), &self.glyphname);
3666 let mut sub_category = parse_category(self.sub_category.as_deref(), &self.glyphname);
3667 let mut production_name = self.production_name;
3668
3669 let category_was_set = self.category.as_deref().is_some_and(|s| !s.is_empty());
3678 let sub_category_was_set = self.sub_category.as_deref().is_some_and(|s| !s.is_empty());
3679
3680 let codepoints = self
3681 .unicode
3682 .filter(|RawCodepoints(s)| !s.is_empty())
3683 .map(|RawCodepoints(s)| parse_codepoint_str(&s, format_version.codepoint_radix()))
3684 .unwrap_or_default();
3685
3686 if (category.is_none() || sub_category.is_none() || production_name.is_none())
3687 && let Some(result) = glyph_data.query(&self.glyphname, Some(&codepoints))
3688 {
3689 if !category_was_set {
3692 category = category.or(Some(result.category));
3693 }
3694 if !sub_category_was_set {
3695 sub_category = sub_category.or(result.subcategory);
3696 }
3697 production_name = production_name.or(result.production_name.map(Into::into));
3698 }
3699
3700 let part_settings = self
3701 .parts_settings
3702 .iter()
3703 .map(|raw| (raw.name.clone(), raw.bottom_value..=raw.top_value))
3704 .collect();
3705
3706 Ok(Glyph {
3707 name: self.glyphname,
3708 export: self.export.unwrap_or(true),
3709 layers: instances,
3710 bracket_layers,
3711 left_kern: self.kern_left,
3712 right_kern: self.kern_right,
3713 unicode: codepoints,
3714 category,
3715 sub_category,
3716 production_name,
3717 smart_component_axes: part_settings,
3718 })
3719 }
3720}
3721
3722#[rustfmt::skip]
3724static GLYPHS_TO_OPENTYPE_LANGUAGE_ID: &[(&str, i32)] = &[
3725 ("AFK", 0x0436), ("ARA", 0x0C01), ("ASM", 0x044D), ("AZE", 0x042C), ("BEL", 0x0423),
3726 ("BEN", 0x0845), ("BGR", 0x0402), ("BRE", 0x047E), ("CAT", 0x0403), ("CSY", 0x0405),
3727 ("DAN", 0x0406), ("DEU", 0x0407), ("ELL", 0x0408), ("ENG", 0x0409), ("ESP", 0x0C0A),
3728 ("ETI", 0x0425), ("EUQ", 0x042D), ("FIN", 0x040B), ("FLE", 0x0813), ("FOS", 0x0438),
3729 ("FRA", 0x040C), ("FRI", 0x0462), ("GRN", 0x046F), ("GUJ", 0x0447), ("HAU", 0x0468),
3730 ("HIN", 0x0439), ("HRV", 0x041A), ("HUN", 0x040E), ("HVE", 0x042B), ("IRI", 0x083C),
3731 ("ISL", 0x040F), ("ITA", 0x0410), ("IWR", 0x040D), ("JPN", 0x0411), ("KAN", 0x044B),
3732 ("KAT", 0x0437), ("KAZ", 0x043F), ("KHM", 0x0453), ("KOK", 0x0457), ("KOR", 0x0412), ("LAO", 0x0454),
3733 ("LSB", 0x082E), ("LTH", 0x0427), ("LVI", 0x0426), ("MAR", 0x044E), ("MKD", 0x042F),
3734 ("MLR", 0x044C), ("MLY", 0x043E), ("MNG", 0x0352), ("MOL", 0x0818), ("MTS", 0x043A), ("NEP", 0x0461),
3735 ("NLD", 0x0413), ("NOB", 0x0414), ("ORI", 0x0448), ("PAN", 0x0446), ("PAS", 0x0463),
3736 ("PLK", 0x0415), ("PTG", 0x0816), ("PTG-BR", 0x0416), ("RMS", 0x0417), ("ROM", 0x0418),
3737 ("RUS", 0x0419), ("SAN", 0x044F), ("SKY", 0x041B), ("SLV", 0x0424), ("SQI", 0x041C),
3738 ("SRB", 0x081A), ("SVE", 0x041D), ("TAM", 0x0449), ("TAT", 0x0444), ("TEL", 0x044A),
3739 ("THA", 0x041E), ("TIB", 0x0451), ("TRK", 0x041F), ("UKR", 0x0422), ("URD", 0x0420),
3740 ("USB", 0x042E), ("UYG", 0x0480), ("UZB", 0x0443), ("VIT", 0x042A), ("WEL", 0x0452),
3741 ("ZHH", 0x0C04), ("ZHS", 0x0804), ("ZHT", 0x0404),
3742 ("dflt", 0x0409),
3743];
3744
3745pub fn glyphs_to_opentype_lang_id(lang: &str) -> Option<u16> {
3747 GLYPHS_TO_OPENTYPE_LANGUAGE_ID
3748 .binary_search_by_key(&lang, |entry| entry.0)
3749 .ok()
3750 .map(|idx| GLYPHS_TO_OPENTYPE_LANGUAGE_ID[idx].1 as u16)
3751}
3752
3753impl RawFeature {
3754 fn autostr(&self) -> &str {
3756 match self.automatic {
3757 Some(1) => "# automatic\n",
3758 _ => "",
3759 }
3760 }
3761
3762 fn name(&self) -> Result<&str, Error> {
3763 self.name
3764 .as_deref()
3765 .or(self.tag.as_deref())
3766 .ok_or_else(|| Error::StructuralError(format!("{self:?} missing name and tag")))
3767 }
3768
3769 fn disabled(&self) -> bool {
3770 self.disabled == Some(1)
3771 }
3772
3773 fn legacy_name_record_maybe(&self) -> Option<String> {
3778 let first_line = self.notes.as_deref()?.lines().next()?;
3779 let name = first_line.strip_prefix("Name:")?.trim();
3780 if name.is_empty() {
3781 None
3782 } else {
3783 let name = escape_fea_string(name);
3784 Some(format!("name 3 1 0x409 \"{name}\";"))
3785 }
3786 }
3787
3788 fn feature_names(&self) -> String {
3790 let labels = self
3791 .labels
3792 .iter()
3793 .filter_map(|label| label.to_fea())
3794 .chain(self.legacy_name_record_maybe())
3795 .collect::<Vec<_>>()
3796 .join("\n");
3797 if labels.is_empty() {
3798 Default::default()
3799 } else {
3800 format!("featureNames {{\n{labels}\n}};\n")
3801 }
3802 }
3803
3804 fn prefix_to_feature(&self) -> Result<FeatureSnippet, Error> {
3806 let name = self.name.as_deref().unwrap_or_default();
3807 let code = format!("# Prefix: {}\n{}{}", name, self.autostr(), self.code);
3808 Ok(FeatureSnippet::new(code, self.disabled()))
3809 }
3810
3811 fn class_to_feature(&self) -> Result<FeatureSnippet, Error> {
3813 let name = self.name()?;
3814 let code = format!(
3815 "{}{}{name} = [ {}\n];",
3816 self.autostr(),
3817 if name.starts_with('@') { "" } else { "@" },
3818 self.code
3819 );
3820 Ok(FeatureSnippet::new(code, self.disabled()))
3821 }
3822
3823 fn raw_feature_to_feature(&self) -> Result<FeatureSnippet, Error> {
3825 let name = self.name()?;
3826 let insert_mark = self.insert_mark_if_manual_kern_feature();
3827 let code = format!(
3828 "feature {name} {{\n{}{}{}{insert_mark}\n}} {name};",
3829 self.autostr(),
3830 self.feature_names(),
3831 self.code
3832 );
3833 Ok(FeatureSnippet::new(code, self.disabled()))
3834 }
3835
3836 fn insert_mark_if_manual_kern_feature(&self) -> &str {
3838 if self.name().unwrap_or_default() == "kern"
3839 && self.automatic != Some(1)
3840 && !self.code.contains("# Automatic Code")
3841 {
3842 "# Automatic Code\n"
3843 } else {
3844 ""
3845 }
3846 }
3847}
3848
3849impl RawNameValue {
3850 fn to_fea(&self) -> Option<String> {
3851 if self.value.is_empty() {
3852 return None;
3855 }
3856
3857 let Some(language_id) = glyphs_to_opentype_lang_id(&self.language) else {
3858 warn!("Unknown feature label language: {}", self.language);
3859 return None;
3860 };
3861 let name = escape_fea_string(&self.value);
3862 Some(format!(" name 3 1 0x{language_id:04X} \"{name}\";"))
3863 }
3864}
3865
3866fn escape_fea_string(s: &str) -> String {
3871 s.replace('\\', "\\005c").replace('"', "\\0022")
3872}
3873
3874fn lookup_class_value(axis_tag: &str, user_class: &str) -> Option<u16> {
3876 let user_class = match user_class {
3877 value if !value.is_empty() => {
3878 let mut value = value.to_ascii_lowercase();
3879 value.retain(|c| c != ' ');
3880 value
3881 }
3882 _ => String::from(""),
3883 };
3884 match (axis_tag, user_class.as_str()) {
3885 ("wght", "thin") => Some(100),
3886 ("wght", "extralight" | "ultralight") => Some(200),
3887 ("wght", "light") => Some(300),
3888 ("wght", "" | "normal" | "regular") => Some(400),
3889 ("wght", "medium") => Some(500),
3890 ("wght", "demibold" | "semibold") => Some(600),
3891 ("wght", "bold") => Some(700),
3892 ("wght", "ultrabold" | "extrabold") => Some(800),
3893 ("wght", "black" | "heavy") => Some(900),
3894 ("wdth", "ultracondensed") => Some(1),
3895 ("wdth", "extracondensed") => Some(2),
3896 ("wdth", "condensed") => Some(3),
3897 ("wdth", "semicondensed") => Some(4),
3898 ("wdth", "" | "medium(normal)") => Some(5),
3899 ("wdth", "semiexpanded") => Some(6),
3900 ("wdth", "expanded") => Some(7),
3901 ("wdth", "extraexpanded") => Some(8),
3902 ("wdth", "ultraexpanded") => Some(9),
3903 _ => {
3904 warn!("Unrecognized ('{axis_tag}', '{user_class}')");
3905 None
3906 }
3907 }
3908}
3909
3910fn add_mapping_if_new(
3911 axis_mappings: &mut BTreeMap<String, AxisUserToDesignMap>,
3912 axes: &[Axis],
3913 axis_tag: &str,
3914 axes_values: &[OrderedFloat<f64>],
3915 value: f64,
3916) {
3917 let Some(idx) = axes.iter().position(|a| a.tag == axis_tag) else {
3918 return;
3919 };
3920 let axis = &axes[idx];
3921 let Some(design) = axes_values.get(idx) else {
3922 return;
3923 };
3924
3925 axis_mappings
3926 .entry(axis.name.clone())
3927 .or_default()
3928 .add_if_new(value.into(), *design);
3929}
3930
3931impl Instance {
3932 fn new(
3937 axes: &[Axis],
3938 value: &mut RawInstance,
3939 masters_have_axis_locations: bool,
3940 ) -> Result<Self, Error> {
3941 let active = value.is_active();
3942 let mut axis_mappings: BTreeMap<String, AxisUserToDesignMap> = BTreeMap::new();
3943
3944 let mut tags_done = BTreeSet::new();
3947 for axis_location in value
3948 .custom_parameters
3949 .take_axis_locations()
3950 .unwrap_or_default()
3951 {
3952 let Some(axis_index) = axis_index(axes, |a| a.name == axis_location.axis_name) else {
3953 log_once_warn!(
3954 "{} instance's 'Axis Location' includes axis {:?} not included in font",
3955 value.name,
3956 axis_location.axis_name
3957 );
3958 continue;
3959 };
3960 let user = axis_location.location;
3961 let design = value.axes_values[axis_index];
3962
3963 axis_mappings
3964 .entry(axis_location.axis_name.clone())
3965 .or_default()
3966 .add_if_new(user, design);
3967
3968 tags_done.insert(axes[axis_index].tag.as_str());
3969 }
3970
3971 for (i, axis) in axes.iter().enumerate() {
3978 if tags_done.contains(axis.tag.as_str()) {
3979 continue;
3980 }
3981 if axis.tag == "wght" || axis.tag == "wdth" || masters_have_axis_locations {
3982 continue;
3983 }
3984 if let Some(&design) = value.axes_values.get(i) {
3985 axis_mappings
3986 .entry(axis.name.clone())
3987 .or_default()
3988 .add_if_new(design, design);
3989 }
3990 }
3991
3992 if !masters_have_axis_locations && !tags_done.contains("wght") {
3994 add_mapping_if_new(
3996 &mut axis_mappings,
3997 axes,
3998 "wght",
3999 &value.axes_values,
4000 value
4001 .weight_class
4002 .as_ref()
4003 .map(|v| f64::from_str(v).unwrap())
4004 .unwrap_or(400.0),
4005 );
4006 }
4007
4008 if !masters_have_axis_locations && !tags_done.contains("wdth") {
4009 add_mapping_if_new(
4012 &mut axis_mappings,
4013 axes,
4014 "wdth",
4015 value.axes_values.as_ref(),
4016 value
4017 .width_class
4018 .as_ref()
4019 .map(|v| match WidthClass::try_from(u16::from_str(v).unwrap()) {
4020 Ok(width_class) => width_class.to_percent(),
4021 Err(err) => {
4022 warn!("{err}");
4023 100.0
4024 }
4025 })
4026 .unwrap_or(100.0),
4027 );
4028 }
4029
4030 let weight_class = value
4031 .weight_class
4032 .as_ref()
4033 .and_then(|value| value.parse().ok());
4034 let width_class = value
4035 .width_class
4036 .as_ref()
4037 .and_then(|value| value.parse().ok());
4038
4039 Ok(Instance {
4040 name: value.name.clone(),
4041 active,
4042 link_style: value.link_style.clone(),
4043 weight_class,
4044 width_class,
4045 is_bold: value.is_bold.unwrap_or_default(),
4046 is_italic: value.is_italic.unwrap_or_default(),
4047 type_: value
4048 .type_
4049 .as_ref()
4050 .map(|v| v.as_str().into())
4051 .unwrap_or(InstanceType::Single),
4052 axis_mappings,
4053 axes_values: value.axes_values.clone(),
4054 properties: value.properties.clone(),
4055 custom_parameters: value.custom_parameters.to_custom_params()?,
4056 })
4057 }
4058
4059 pub fn family_name(&self) -> Option<&str> {
4060 self.properties
4061 .iter()
4062 .find(|raw| raw.key == "familyNames")
4063 .and_then(RawName::get_value)
4064 }
4065
4066 pub fn default_names(&self) -> impl Iterator<Item = (&str, &str)> {
4067 self.properties
4068 .iter()
4069 .filter_map(|name| name.get_value().map(|value| (name.key.as_str(), value)))
4070 }
4071
4072 pub fn get_default_name(&self, key: &str) -> Option<&str> {
4073 self.default_names()
4074 .find_map(|(name, value)| (name == key).then_some(value))
4075 }
4076
4077 pub fn has_property(&self, key: &str) -> bool {
4079 self.properties.iter().any(|name| name.key == key)
4080 }
4081
4082 pub fn localized_names(&self) -> impl Iterator<Item = (&str, &str, &str)> {
4086 self.properties.iter().flat_map(|name| {
4087 name.localized_values()
4088 .filter(|(lang, _)| !matches!(*lang, "dflt" | "default" | "ENG"))
4089 .map(move |(lang, value)| (name.key.as_str(), lang, value))
4090 })
4091 }
4092
4093 pub fn postscript_name(&self) -> Option<&str> {
4095 ["variablePostscriptFontName", "postscriptFontName"]
4098 .iter()
4099 .find_map(|key| {
4100 self.properties
4101 .iter()
4102 .find(|raw| raw.key == *key)
4103 .and_then(RawName::get_value)
4104 })
4105 }
4106}
4107
4108fn codepage_range_bit(codepage: u32) -> Result<u32, Error> {
4112 Ok(match codepage {
4113 1252 => 0, 1250 => 1, 1251 => 2, 1253 => 3, 1254 => 4, 1255 => 5, 1256 => 6, 1257 => 7, 1258 => 8, 874 => 16, 932 => 17, 936 => 18, 949 => 19, 950 => 20, 1361 => 21, 869 => 48, 866 => 49, 865 => 50, 864 => 51, 863 => 52, 862 => 53, 861 => 54, 860 => 55, 857 => 56, 855 => 57, 852 => 58, 775 => 59, 737 => 60, 708 => 61, 850 => 62, 437 => 63, v if v < 64 => v, _ => return Err(Error::InvalidCodePage(codepage)),
4147 })
4148}
4149
4150fn update_names(all_names: &mut BTreeMap<String, Vec<(String, String)>>, raw_names: &[RawName]) {
4151 for name in raw_names {
4152 let mut lang_map: IndexMap<String, String> = IndexMap::new();
4158
4159 if let Some(value) = &name.value {
4161 lang_map.insert("dflt".to_string(), value.clone());
4162 }
4163
4164 for (lang, val) in name.localized_values() {
4166 lang_map.insert(lang.to_string(), val.to_string());
4167 }
4168
4169 if !lang_map.is_empty() {
4170 let values: Vec<_> = lang_map.into_iter().collect();
4171 all_names.insert(name.key.clone(), values);
4172 }
4173 }
4174}
4175
4176impl TryFrom<RawFont> for Font {
4177 type Error = Error;
4178
4179 fn try_from(from: RawFont) -> Result<Self, Self::Error> {
4180 Font::from_raw(from, &GlyphData::default())
4181 }
4182}
4183
4184impl Font {
4185 fn from_raw(mut from: RawFont, glyph_data: &GlyphData) -> Result<Self, Error> {
4188 if from.format_version.is_v2() {
4189 from.v2_to_v3()?;
4190 } else {
4191 from.v2_to_v3_names()?;
4193 }
4194 from.default_master_names();
4195 from.normalize_instance_classes()?;
4196
4197 let masters_have_axis_locations = from
4204 .font_master
4205 .iter()
4206 .all(|master| master.custom_parameters.contains("Axis Location"));
4207
4208 let instances: Vec<_> = from
4209 .instances
4210 .iter_mut()
4211 .map(|ri| Instance::new(&from.axes, ri, masters_have_axis_locations))
4212 .collect::<Result<Vec<_>, Error>>()?;
4213
4214 let default_master_idx = default_master_idx(&mut from);
4219 let axis_mappings = UserToDesignMapping::new(&mut from, &instances, default_master_idx);
4220
4221 let mut custom_parameters = from.custom_parameters.to_custom_params()?;
4222
4223 let glyph_order = make_glyph_order(&from.glyphs, custom_parameters.glyph_order.take())?;
4224
4225 let master_ids: HashSet<_> = from.font_master.iter().map(|m| m.id.as_str()).collect();
4226 let mut glyphs = BTreeMap::new();
4227 for mut raw_glyph in from.glyphs.into_iter() {
4228 raw_glyph.layers.retain(|layer| {
4232 master_ids.contains(layer.layer_id.as_str())
4233 || layer
4234 .associated_master_id
4235 .as_deref()
4236 .is_some_and(|id| master_ids.contains(id))
4237 });
4238 let mut glyph = raw_glyph.build(from.format_version, glyph_data)?;
4239 for layer in glyph.bracket_layers.iter_mut() {
4243 layer
4244 .attributes
4245 .axis_rules
4246 .resize(from.axes.len(), Default::default());
4247 }
4248 glyphs.insert(glyph.name.clone(), glyph);
4249 }
4250
4251 let mut features = Vec::new();
4252 for class in from.classes {
4253 features.push(class.class_to_feature()?);
4254 }
4255 for prefix in from.feature_prefixes {
4256 features.push(prefix.prefix_to_feature()?);
4257 }
4258 for feature in from.features {
4259 features.push(feature.raw_feature_to_feature()?);
4260 }
4261
4262 let units_per_em = from.units_per_em.ok_or(Error::NoUnitsPerEm)?;
4263 let units_per_em = units_per_em.try_into().map_err(Error::InvalidUpem)?;
4264
4265 let mut all_names = BTreeMap::new();
4266 update_names(&mut all_names, &from.properties);
4267 for instance in &instances {
4268 if instance.active
4269 && instance.type_ == InstanceType::Variable
4270 && instance.family_name().map(|name| name == from.family_name.as_str()).unwrap_or(true)
4274 {
4275 update_names(&mut all_names, &instance.properties);
4276 }
4277 }
4278 let family_names = all_names
4281 .entry("familyNames".into())
4282 .or_insert_with(Vec::new);
4283 family_names.retain(|(lang, _)| lang != "dflt");
4284 family_names.insert(0, ("dflt".to_string(), from.family_name.clone()));
4285
4286 let metric_names: BTreeMap<usize, String> = from
4287 .metrics
4288 .into_iter()
4289 .enumerate()
4290 .map(|(idx, metric)| (idx, metric.type_))
4291 .collect();
4292
4293 let master_ids_to_names: IndexMap<_, _> = from
4294 .font_master
4295 .iter()
4296 .map(|m| (m.id.clone(), m.name.clone()))
4297 .collect();
4298
4299 let masters = from
4300 .font_master
4301 .into_iter()
4302 .map(|m| {
4303 let custom_parameters = m.custom_parameters.to_custom_params()?;
4304 let metrics_source_id =
4305 resolve_metrics_source_id(&custom_parameters, &master_ids_to_names);
4306 Ok(FontMaster {
4307 id: m.id,
4308 name: m.name.unwrap_or_default(),
4309 axes_values: m.axes_values,
4310 metric_values: m
4311 .metric_values
4312 .into_iter()
4313 .enumerate()
4314 .filter_map(|(idx, value)| {
4315 metric_names.get(&idx).map(|name| (name.clone(), value))
4316 })
4317 .fold(BTreeMap::new(), |mut acc, (name, value)| {
4318 acc.entry(name).or_insert(value.into());
4322 acc
4323 }),
4324 number_values: from
4325 .numbers
4326 .iter()
4327 .zip(m.number_values.iter())
4328 .map(|(k, v)| (k.name.clone(), *v))
4329 .collect(),
4330 custom_parameters,
4331 user_data: m.user_data,
4332 metrics_source_id,
4333 })
4334 })
4335 .collect::<Result<Vec<_>, Error>>()?;
4336
4337 let virtual_masters = custom_parameters.virtual_masters.take().unwrap_or_default();
4338 Ok(Font {
4339 units_per_em,
4340 axes: from.axes,
4341 masters,
4342 default_master_idx,
4343 glyphs,
4344 glyph_order,
4345 axis_mappings,
4346 virtual_masters,
4347 features,
4348 all_names,
4349 instances,
4350 version_major: from.versionMajor.unwrap_or(1) as i32,
4351 version_minor: from.versionMinor.unwrap_or_default() as u32,
4352 date: from.date,
4353 kerning_ltr: from.kerning_LTR,
4354 kerning_rtl: from.kerning_RTL,
4355 custom_parameters,
4356 user_data: from.user_data,
4357 })
4358 }
4359}
4360
4361fn variable_instance_for<'a>(instances: &'a [Instance], name: &str) -> Option<&'a Instance> {
4362 instances
4363 .iter()
4364 .find(|i| i.active && i.type_ == InstanceType::Variable && i.name == name)
4365}
4366
4367impl Font {
4368 pub fn load_from_string(data: &str) -> Result<Font, Error> {
4369 let raw_font = RawFont::load_from_string(data)?;
4370 let mut font = Font::try_from(raw_font)?;
4371 font.preprocess()?;
4372 Ok(font)
4373 }
4374
4375 pub fn load(glyphs_file: &path::Path) -> Result<Font, Error> {
4376 let mut font = Self::load_raw(glyphs_file)?;
4377 font.preprocess()?;
4378 Ok(font)
4379 }
4380
4381 pub fn load_with_glyph_data(
4384 glyphs_file: &path::Path,
4385 glyph_data: &GlyphData,
4386 ) -> Result<Font, Error> {
4387 let raw_font = RawFont::load(glyphs_file)?;
4388 let mut font = Font::from_raw(raw_font, glyph_data)?;
4389 font.preprocess()?;
4390 Ok(font)
4391 }
4392
4393 pub fn color_palettes(&self) -> Option<&Vec<Vec<Color>>> {
4394 self.default_master()
4395 .custom_parameters
4396 .color_palettes
4397 .as_ref()
4398 .or(self.custom_parameters.color_palettes.as_ref())
4399 }
4400
4401 pub fn default_palette(&self) -> Option<&[Color]> {
4402 self.color_palettes().map(|p| p[0].as_slice())
4403 }
4404
4405 fn preprocess(&mut self) -> Result<(), Error> {
4406 self.instantiate_all_smart_components()?;
4417
4418 self.insert_all_corner_components()
4420 }
4421
4422 pub(crate) fn depth_sorted_composite_glyphs(&self) -> Vec<SmolStr> {
4426 fontdrasil::util::depth_sorted_composite_glyphs(&self.glyphs)
4427 }
4428
4429 pub fn align_bracket_layers(&mut self) {
4438 let todo = self.depth_sorted_composite_glyphs();
4440
4441 for name in &todo {
4442 let mut needed = IndexMap::new();
4443 let glyph = self.glyphs.get(name).unwrap();
4444 let my_bracket_layers = glyph
4445 .bracket_layers
4446 .iter()
4447 .map(|l| l.bracket_info(&self.axes))
4448 .collect::<IndexSet<_>>();
4449 for layer in &glyph.layers {
4450 for comp in layer.components() {
4451 let comp_glyph = self.glyphs.get(&comp.name).unwrap();
4452
4453 let comp_bracket_layers = comp_glyph
4454 .bracket_layers
4455 .iter()
4456 .map(|l| l.bracket_info(&self.axes))
4457 .collect::<IndexSet<_>>();
4458 if comp_bracket_layers != my_bracket_layers {
4459 let missing = comp_bracket_layers.difference(&my_bracket_layers);
4460 needed
4461 .entry(layer.layer_id.clone())
4462 .or_insert(IndexSet::new())
4463 .extend(missing.cloned());
4464 }
4465 }
4466 }
4467
4468 if needed.is_empty() {
4469 continue;
4471 }
4472
4473 let mut new_layers = Vec::new();
4474 for (master, needed_brackets) in needed {
4475 let master_name = self
4476 .masters
4477 .iter()
4478 .find_map(|m| (m.id == master).then_some(m.name.as_str()))
4479 .unwrap_or(master.as_str());
4480 if !my_bracket_layers.is_empty() {
4481 log::warn!(
4482 "Glyph {name} in master {master_name} has different bracket layers \
4483 than its components. This is not supported, so some bracket layers \
4484 will not be applied. Consider fixing the source instead."
4485 );
4486 }
4487
4488 let base_layer = glyph.layers.iter().find(|l| l.layer_id == master).unwrap();
4489 for box_ in needed_brackets {
4490 log::debug!("synthesized layer {box_:?} in master {master_name} for '{name}'",);
4491 let new_layer = synthesize_bracket_layer(base_layer, box_, &self.axes);
4492 new_layers.push(new_layer);
4493 }
4494 }
4495
4496 new_layers.sort_by_cached_key(|l| l.axis_rules_sort_key());
4498
4499 self.glyphs
4500 .get_mut(name)
4501 .unwrap()
4502 .bracket_layers
4503 .extend_from_slice(&new_layers);
4504 }
4505 }
4506
4507 fn instantiate_all_smart_components(&mut self) -> Result<(), Error> {
4510 let mut glyphs_with_smart_components = self
4512 .glyphs
4513 .values()
4514 .filter(|glyph| {
4515 glyph
4516 .layers
4517 .iter()
4518 .flat_map(|layer| layer.components())
4519 .any(|comp| {
4520 self.glyphs
4524 .get(&comp.name)
4525 .map(|ref_glyph| !ref_glyph.smart_component_axes.is_empty())
4526 .unwrap_or(false)
4527 })
4528 })
4529 .cloned()
4530 .collect::<Vec<_>>();
4531
4532 if glyphs_with_smart_components.is_empty() {
4533 return Ok(());
4534 }
4535 let depth_ranked = self
4538 .depth_sorted_composite_glyphs()
4539 .into_iter()
4540 .enumerate()
4541 .map(|(rank, name)| (name, rank))
4542 .collect::<HashMap<_, _>>();
4543
4544 glyphs_with_smart_components
4547 .sort_by_key(|g| depth_ranked.get(&g.name).copied().unwrap_or(usize::MAX));
4548
4549 for mut glyph in glyphs_with_smart_components {
4551 for layer in glyph.layers.iter_mut() {
4552 let explicit_anchor_names: HashSet<SmolStr> =
4555 layer.anchors.iter().map(|a| a.name.clone()).collect();
4556 let old_shapes = std::mem::take(&mut layer.shapes);
4557 let mut new_shapes = Vec::new();
4558 let mut new_indices = Vec::with_capacity(old_shapes.len());
4560 for shape in old_shapes {
4561 if let Some(comp) = shape.as_component()
4562 && let Some(ref_glyph) = self
4563 .glyphs
4564 .get(&comp.name)
4565 .filter(|g| !g.smart_component_axes.is_empty())
4566 {
4567 log::debug!(
4568 "instantiating smart component '{}' for '{}'",
4569 comp.name,
4570 glyph.name
4571 );
4572 let instance = crate::smart_components::instantiate_for_layer(
4573 layer.master_id(),
4574 comp,
4575 ref_glyph,
4576 )
4577 .map_err(|issue| Error::BadSmartComponent {
4578 glyph: glyph.name.clone(),
4579 component: comp.name.clone(),
4580 issue,
4581 })?;
4582 new_shapes.extend(instance.shapes);
4583 new_indices.push(None);
4584 let new_anchors: Vec<_> = instance
4587 .anchors
4588 .into_iter()
4589 .filter(|a| !explicit_anchor_names.contains(&a.name))
4590 .collect();
4591 let new_names: HashSet<&SmolStr> =
4594 new_anchors.iter().map(|a| &a.name).collect();
4595 layer.anchors.retain(|a| !new_names.contains(&a.name));
4596 layer.anchors.extend(new_anchors);
4597 } else {
4598 new_indices.push(Some(layer.shapes.len()));
4599 layer.shapes.push(shape);
4600 }
4601 }
4602 layer.shapes.extend(new_shapes);
4603 layer
4604 .hints
4605 .retain_mut(|hint| match new_indices.get(hint.shape_index) {
4606 Some(Some(idx)) => {
4607 hint.shape_index = *idx;
4608 true
4609 }
4610 Some(None) => false,
4611 None => true,
4612 });
4613 }
4614 self.glyphs.insert(glyph.name.clone(), glyph);
4616 }
4617 Ok(())
4618 }
4619
4620 fn insert_all_corner_components(&mut self) -> Result<(), Error> {
4622 let glyphs_with_corners: Vec<_> = self
4624 .glyphs
4625 .values()
4626 .filter(|glyph| {
4627 glyph
4628 .layers
4629 .iter()
4630 .chain(glyph.bracket_layers.iter())
4631 .any(|layer| {
4632 layer
4633 .hints
4634 .iter()
4635 .any(|hint| hint.type_ == HintType::Corner)
4636 })
4637 })
4638 .cloned()
4639 .collect();
4640
4641 if glyphs_with_corners.is_empty() {
4642 return Ok(());
4643 }
4644
4645 for mut glyph in glyphs_with_corners {
4646 for layer in glyph
4647 .layers
4648 .iter_mut()
4649 .chain(glyph.bracket_layers.iter_mut())
4650 {
4651 crate::corner_components::insert_corner_components_for_layer(layer, &self.glyphs)
4652 .map_err(|issue| Error::BadCornerComponent {
4653 glyph: glyph.name.clone(),
4654 issue,
4655 })?;
4656 }
4657
4658 self.glyphs.insert(glyph.name.clone(), glyph);
4659 }
4660
4661 Ok(())
4662 }
4663
4664 pub(crate) fn load_raw(glyphs_file: impl AsRef<path::Path>) -> Result<Font, Error> {
4666 RawFont::load(glyphs_file.as_ref()).and_then(Font::try_from)
4667 }
4668
4669 pub fn default_master(&self) -> &FontMaster {
4670 &self.masters[self.default_master_idx]
4671 }
4672
4673 pub fn apply_alternate_layers(&mut self, location: &[OrderedFloat<f64>]) {
4682 for glyph in self.glyphs.values_mut() {
4683 for bracket in std::mem::take(&mut glyph.bracket_layers) {
4684 let applies =
4685 bracket
4686 .attributes
4687 .axis_rules
4688 .iter()
4689 .zip(location)
4690 .all(|(rule, pos)| {
4691 rule.min.is_none_or(|min| min <= *pos)
4692 && rule.max.is_none_or(|max| *pos <= max)
4693 });
4694 if !applies {
4695 continue;
4696 }
4697 let Some(layer) = glyph
4698 .layers
4699 .iter_mut()
4700 .find(|layer| layer.layer_id == bracket.master_id())
4701 else {
4702 continue;
4703 };
4704 *layer = Layer {
4705 layer_id: std::mem::take(&mut layer.layer_id),
4706 associated_master_id: None,
4707 attributes: std::mem::take(&mut layer.attributes),
4708 smart_component_positions: std::mem::take(&mut layer.smart_component_positions),
4709 ..bracket
4710 };
4711 }
4712 }
4713 }
4714
4715 pub fn retain_master(&mut self, master_id: &str) -> bool {
4735 let Some(index) = self.masters.iter().position(|m| m.id == master_id) else {
4736 return false;
4737 };
4738 let master = self.masters.swap_remove(index);
4739 let metrics_source_id = master.metrics_source_id.clone();
4740 self.masters = vec![master];
4741 self.default_master_idx = 0;
4742 self.virtual_masters.clear();
4743 for glyph in self.glyphs.values_mut() {
4744 if let Some(source_id) = metrics_source_id.as_deref()
4747 && let Some(linked) = glyph.layers.iter().find(|l| l.layer_id == source_id)
4748 {
4749 let (width, vert_width, vert_origin) =
4750 (linked.width, linked.vert_width, linked.vert_origin);
4751 for layer in glyph.layers.iter_mut() {
4752 if layer.layer_id == master_id {
4753 layer.width = width;
4754 layer.vert_width = vert_width.or(layer.vert_width);
4755 layer.vert_origin = vert_origin.or(layer.vert_origin);
4756 }
4757 }
4758 }
4759 glyph
4760 .layers
4761 .retain(|layer| layer.master_id() == master_id && !layer.is_intermediate());
4762 glyph
4763 .bracket_layers
4764 .retain(|layer| layer.master_id() == master_id);
4765 }
4766 let keep_kerning = |id: &str| id == master_id || metrics_source_id.as_deref() == Some(id);
4767 self.kerning_ltr.retain_masters(keep_kerning);
4768 self.kerning_rtl.retain_masters(keep_kerning);
4769 true
4770 }
4771
4772 pub fn is_used_as_component(&self, glyph_name: &str) -> bool {
4774 self.glyphs.values().any(|g| {
4775 g.layers
4776 .iter()
4777 .chain(g.bracket_layers.iter())
4778 .flat_map(|l| l.shapes.iter())
4779 .any(|shape| matches!(shape, Shape::Component(c) if c.name == glyph_name))
4780 })
4781 }
4782
4783 pub fn kerning_source_id<'a>(&'a self, master_id: &'a str) -> &'a str {
4790 self.masters
4791 .iter()
4792 .find(|m| m.id == master_id)
4793 .and_then(|m| m.metrics_source_id.as_deref())
4794 .unwrap_or(master_id)
4795 }
4796
4797 pub fn has_kerns_for_master(&self, master_id: &str) -> bool {
4799 self.kerning_ltr
4800 .get(master_id)
4801 .is_some_and(|k| !k.is_empty())
4802 || self
4803 .kerning_rtl
4804 .get(master_id)
4805 .is_some_and(|k| !k.is_empty())
4806 }
4807
4808 pub fn variable_export_settings(&self, master: &FontMaster) -> Option<&Instance> {
4810 variable_instance_for(&self.instances, &master.name)
4811 }
4812
4813 pub fn get_default_name(&self, key: &str) -> Option<&str> {
4819 let values = self.all_names.get(key)?;
4820 let scale = values.len() as i32;
4821 values
4822 .iter()
4823 .enumerate()
4824 .map(|(i, (lang, val))| {
4825 (
4826 default_language_score(lang.as_str(), i, scale),
4827 val.as_str(),
4828 )
4829 })
4830 .min()
4831 .map(|(_, val)| val)
4832 }
4833
4834 pub fn get_localized_names(&self, key: &str) -> impl Iterator<Item = (&str, &str)> + '_ {
4839 self.all_names
4840 .get(key)
4841 .into_iter()
4842 .flat_map(|v| v.iter())
4843 .filter(|(lang, _)| !matches!(lang.as_str(), "dflt" | "default" | "ENG"))
4844 .map(|(lang, val)| (lang.as_str(), val.as_str()))
4845 }
4846
4847 pub fn default_names(&self) -> impl Iterator<Item = (&str, &str)> + '_ {
4852 self.all_names
4853 .keys()
4854 .filter_map(|key| self.get_default_name(key).map(|val| (key.as_str(), val)))
4855 }
4856
4857 pub fn localized_names(&self) -> impl Iterator<Item = (&str, &str, &str)> + '_ {
4862 self.all_names.iter().flat_map(|(key, values)| {
4863 values
4864 .iter()
4865 .filter(|(lang, _)| !matches!(lang.as_str(), "dflt" | "default" | "ENG"))
4866 .map(move |(lang, val)| (key.as_str(), lang.as_str(), val.as_str()))
4867 })
4868 }
4869
4870 pub fn vendor_id(&self) -> Option<&str> {
4871 self.get_default_name("vendorID")
4872 }
4873}
4874
4875fn synthesize_bracket_layer(
4877 old_layer: &Layer,
4878 box_: BTreeMap<String, AxisRule>,
4879 axes: &[Axis],
4880) -> Layer {
4881 let mut new_layer = old_layer.clone();
4882 new_layer.associated_master_id = Some(std::mem::take(&mut new_layer.layer_id));
4883 new_layer.attributes.axis_rules = axes
4884 .iter()
4885 .map(|axis| box_.get(&axis.tag).cloned().unwrap_or_default())
4886 .collect();
4887
4888 new_layer
4889}
4890
4891#[derive(Clone, Debug, PartialEq, Eq, Hash)]
4893struct PointForEqAndHash {
4894 x: OrderedFloat<f64>,
4895 y: OrderedFloat<f64>,
4896}
4897
4898impl PointForEqAndHash {
4899 fn new(point: Point) -> PointForEqAndHash {
4900 point.into()
4901 }
4902}
4903
4904impl From<Point> for PointForEqAndHash {
4905 fn from(value: Point) -> Self {
4906 PointForEqAndHash {
4907 x: value.x.into(),
4908 y: value.y.into(),
4909 }
4910 }
4911}
4912
4913#[derive(Clone, Debug, PartialEq, Eq, Hash)]
4915struct AffineForEqAndHash([OrderedFloat<f64>; 6]);
4916
4917impl From<Affine> for AffineForEqAndHash {
4918 fn from(value: Affine) -> Self {
4919 Self(value.as_coeffs().map(|coeff| coeff.into()))
4920 }
4921}
4922
4923#[cfg(test)]
4924mod tests {
4925 use super::*;
4926 use crate::{Font, FontMaster, Node, Shape, plist::FromPlist, smart_components};
4927 use std::{
4928 collections::{BTreeMap, BTreeSet, HashSet},
4929 path::{Path, PathBuf},
4930 };
4931
4932 use ordered_float::OrderedFloat;
4933
4934 use pretty_assertions::assert_eq;
4935
4936 use kurbo::{Affine, Point, Rect, Vec2};
4937
4938 use rstest::rstest;
4939 use smol_str::ToSmolStr;
4940
4941 fn testdata_dir() -> PathBuf {
4942 let mut dir = Path::new("../resources/testdata");
4944 if !dir.is_dir() {
4945 dir = Path::new("./resources/testdata");
4946 }
4947 assert!(dir.is_dir());
4948 dir.to_path_buf()
4949 }
4950
4951 fn glyphs2_dir() -> PathBuf {
4952 testdata_dir().join("glyphs2")
4953 }
4954
4955 fn glyphs3_dir() -> PathBuf {
4956 testdata_dir().join("glyphs3")
4957 }
4958
4959 fn round(transform: Affine, digits: u8) -> Affine {
4960 let m = 10f64.powi(digits as i32);
4961 let mut coeffs = transform.as_coeffs();
4962 for c in coeffs.iter_mut() {
4963 *c = (*c * m).round() / m;
4964 }
4965 Affine::new(coeffs)
4966 }
4967
4968 #[test]
4969 fn v2_format_version() {
4970 let v2_font = glyphs2_dir().join("Mono.glyphs");
4971 let as_str = std::fs::read_to_string(&v2_font).unwrap();
4972 assert!(!as_str.contains(".formatVersion"), "only exists in v3");
4973 let font = RawFont::load(&v2_font).unwrap();
4974 assert_eq!(font.format_version, FormatVersion::V2);
4976 }
4977
4978 #[test]
4979 fn skips_layers_without_a_matching_master() {
4980 let font = Font::load_from_string(
4982 r#"{
4983.formatVersion = 3;
4984axes = ({ name = Weight; tag = wght; });
4985fontMaster = ({ id = m01; axesValues = (400); });
4986glyphs = ({ glyphname = zero; layers = (
4987{ layerId = m01; width = 500; },
4988{ layerId = brace; associatedMasterId = m01; attr = { coordinates = (500); }; width = 550; },
4989{ layerId = bracket; associatedMasterId = m01; attr = { axisRules = ({ min = 600; }); }; width = 600; },
4990{ layerId = orphan; width = 700; },
4991{ layerId = orphanBrace; associatedMasterId = deleted; attr = { coordinates = (500); }; width = 750; },
4992{ layerId = orphanBracket; associatedMasterId = deleted; attr = { axisRules = ({ min = 600; }); }; width = 800; }
4993); });
4994unitsPerEm = 1000;
4995}"#,
4996 )
4997 .unwrap();
4998 let glyph = &font.glyphs["zero"];
4999 assert_eq!(
5000 glyph
5001 .layers
5002 .iter()
5003 .map(|l| l.layer_id.as_str())
5004 .collect::<Vec<_>>(),
5005 ["m01", "brace"]
5006 );
5007 assert_eq!(
5008 glyph
5009 .bracket_layers
5010 .iter()
5011 .map(|l| l.layer_id.as_str())
5012 .collect::<Vec<_>>(),
5013 ["bracket"]
5014 );
5015 }
5016
5017 #[test]
5018 fn v3_format_version() {
5019 let v3_font = glyphs3_dir().join("MasterNames.glyphs");
5020 let as_str = std::fs::read_to_string(&v3_font).unwrap();
5021 assert!(as_str.contains(".formatVersion"), "exists in v3");
5022 let font = RawFont::load(&v3_font).unwrap();
5023 assert_eq!(font.format_version, FormatVersion::V3);
5025 }
5026
5027 fn axis_map(points: &[(f64, f64)]) -> AxisUserToDesignMap {
5028 AxisUserToDesignMap(
5029 points
5030 .iter()
5031 .map(|(u, d)| (OrderedFloat(*u), OrderedFloat(*d)))
5032 .collect(),
5033 )
5034 }
5035
5036 #[rstest]
5037 #[case(
5039 &[(400.0, 50.0), (700.0, 100.0), (800.0, 150.0)],
5040 (10.0, 160.0),
5041 Some(&[(400.0, 50.0), (700.0, 100.0), (800.0, 150.0), (160.0, 10.0), (820.0, 160.0)][..])
5042 )]
5043 #[case(
5045 &[(400.0, 50.0), (700.0, 100.0), (800.0, 150.0)],
5046 (10.0, 50.0),
5047 Some(&[(400.0, 50.0), (700.0, 100.0), (800.0, 150.0), (160.0, 10.0)][..])
5048 )]
5049 #[case(&[(400.0, 50.0), (700.0, 100.0), (800.0, 150.0)], (10.0, 20.0), None)]
5051 #[case(&[(400.0, 100.0)], (50.0, 100.0), None)]
5053 #[case(
5055 &[(400.0, 100.0), (300.0, 150.0)],
5056 (50.0, 200.0),
5057 Some(&[(400.0, 100.0), (300.0, 150.0), (500.0, 50.0), (200.0, 200.0)][..])
5058 )]
5059 #[case(&[(400.0, 100.0), (700.0, 100.0)], (50.0, 100.0), None)]
5061 #[case(&[(400.0, 90.0), (900.0, 100.0)], (90.0, 190.0), None)]
5063 #[case(&[(100.0, 50.0), (400.0, 100.0)], (0.0, 100.0), None)]
5064 fn extend_axis_map_to_masters(
5065 #[case] mapping: &[(f64, f64)],
5066 #[case] (min, max): (f64, f64),
5067 #[case] expected: Option<&[(f64, f64)]>,
5068 ) {
5069 assert_eq!(
5070 axis_map(mapping).extended_to_masters("wght", OrderedFloat(min), OrderedFloat(max)),
5071 expected.map(axis_map)
5072 );
5073 }
5074
5075 #[test]
5076 fn meta_table_splits_and_trims_scriptlangtags() {
5077 let font = Font::load(&glyphs3_dir().join("MetaTableSpacedTags.glyphs")).unwrap();
5078 let meta = font
5079 .custom_parameters
5080 .meta_table
5081 .as_ref()
5082 .expect("meta table");
5083 assert_eq!(meta.dlng, ["Latn", "Am", "Tig", "Tir", "sgw"]);
5087 assert_eq!(meta.slng, ["Latn", "Am", "Tig", "Tir", "sgw"]);
5088 }
5089
5090 #[test]
5091 fn meta_table_ignores_empty_segments() {
5092 let plist = Plist::parse(
5093 r#"(
5094 { data = "Latn,, Am ,"; tag = dlng; },
5095 { data = ""; tag = slng; }
5096 )"#,
5097 )
5098 .unwrap();
5099 let meta = MetaTableValues::from_plist(&plist).unwrap();
5100 assert_eq!(meta.dlng, ["Latn", "Am"]);
5101 assert!(meta.slng.is_empty());
5102 }
5103
5104 #[test]
5105 fn glyphs3_named_and_numeric_instance_classes() {
5106 let font = Font::load(&glyphs3_dir().join("InstanceClasses.glyphs")).unwrap();
5107
5108 let user_locations = |axis_name: &str| {
5109 font.instances
5110 .iter()
5111 .map(|i| i.axis_mappings[axis_name].iter().copied().collect())
5112 .collect::<Vec<Vec<_>>>()
5113 };
5114 assert_eq!(
5115 user_locations("Weight"),
5116 [
5117 [(OrderedFloat(600.0), OrderedFloat(60.0))],
5118 [(OrderedFloat(650.0), OrderedFloat(70.0))],
5119 ]
5120 );
5121 assert_eq!(
5122 user_locations("Width"),
5123 [
5124 [(OrderedFloat(75.0), OrderedFloat(80.0))],
5125 [(OrderedFloat(100.0), OrderedFloat(90.0))],
5126 ]
5127 );
5128 }
5129
5130 #[test]
5131 fn loads_stat_instance_metadata() {
5132 let font = Font::load(&glyphs3_dir().join("StatInstanceMetadata.glyphs")).unwrap();
5133
5134 let bold_italic = &font.instances[0];
5135 assert!(bold_italic.is_bold);
5136 assert!(bold_italic.is_italic);
5137 assert_eq!(bold_italic.custom_parameters.export_stat_table, Some(false));
5138 assert_eq!(
5139 bold_italic.custom_parameters.elidable_stat_axis_value_names,
5140 ["Regular", "Regular"]
5141 );
5142 assert_eq!(
5143 bold_italic.custom_parameters.style_names_as_stat_entries,
5144 ["Bold", "Bold Italic"]
5145 );
5146
5147 let upright = &font.instances[1];
5148 assert!(!upright.is_bold);
5149 assert!(!upright.is_italic);
5150 }
5151
5152 #[test]
5153 fn test_glyphs3_node() {
5154 let node: Node = Node::parse_plist("(354, 183, l)").unwrap();
5155 assert_eq!(
5156 Node {
5157 node_type: crate::NodeType::Line,
5158 pt: super::Point { x: 354.0, y: 183.0 }
5159 },
5160 node
5161 );
5162 }
5163
5164 #[test]
5165 fn test_glyphs2_node() {
5166 let node: Node = Node::parse_plist("\"354 183 LINE\"").unwrap();
5167 assert_eq!(
5168 Node {
5169 node_type: crate::NodeType::Line,
5170 pt: super::Point { x: 354.0, y: 183.0 }
5171 },
5172 node
5173 );
5174 }
5175
5176 #[test]
5177 fn test_glyphs3_node_userdata() {
5178 let node = Node::parse_plist("(354, 183, l,{name = hr00;})").unwrap();
5179 assert_eq!(
5180 Node {
5181 node_type: crate::NodeType::Line,
5182 pt: super::Point { x: 354.0, y: 183.0 }
5183 },
5184 node
5185 );
5186 }
5187
5188 #[test]
5189 fn test_glyphs2_node_userdata() {
5190 let node = Node::parse_plist("\"354 183 LINE {name=duck}\"").unwrap();
5191 assert_eq!(
5192 Node {
5193 node_type: crate::NodeType::Line,
5194 pt: super::Point { x: 354.0, y: 183.0 }
5195 },
5196 node
5197 );
5198 }
5199
5200 #[test]
5203 fn survive_unquoted_infinity() {
5204 Font::load(&glyphs3_dir().join("infinity.glyphs")).unwrap();
5206 }
5207
5208 fn assert_wght_var_metrics(font: &Font) {
5209 let default_master = font.default_master();
5210 assert_eq!(737.0, default_master.ascender().unwrap());
5211 assert_eq!(-42.0, default_master.descender().unwrap());
5212 }
5213
5214 #[test]
5215 fn read_wght_var_2_metrics() {
5216 assert_wght_var_metrics(&Font::load(&glyphs2_dir().join("WghtVar.glyphs")).unwrap());
5217 }
5218
5219 #[test]
5220 fn read_wght_var_3_metrics() {
5221 assert_wght_var_metrics(&Font::load(&glyphs3_dir().join("WghtVar.glyphs")).unwrap());
5222 }
5223
5224 enum LoadCompare {
5226 Glyphs,
5227 GlyphsAndPackage,
5228 }
5229
5230 fn assert_fonts_equal_sans_localized_names(f1: &Font, f2: &Font, context: &str) {
5234 let mut f1_clone = f1.clone();
5235 let mut f2_clone = f2.clone();
5236 for all_names in [&mut f1_clone.all_names, &mut f2_clone.all_names] {
5238 for values in all_names.values_mut() {
5239 values.retain(|(lang, _)| matches!(lang.as_str(), "dflt" | "default" | "ENG"));
5240 }
5241 }
5242 assert_eq!(f1_clone, f2_clone, "{context}");
5243 }
5244
5245 fn assert_fonts_equal(f1: &Font, f2: &Font, context: &str) {
5248 assert_eq!(f1, f2, "{context}");
5249 }
5250
5251 fn dump_font(name: &str, font: &Font) {
5253 let path = std::env::temp_dir().join(format!("{name}.txt"));
5254 std::fs::write(path, format!("{font:#?}")).unwrap();
5255 }
5256
5257 fn assert_load_v2_matches_load_v3(name: &str, compare: LoadCompare) {
5258 let has_package = matches!(compare, LoadCompare::GlyphsAndPackage);
5259 let _ = tracing_subscriber::fmt().with_test_writer().try_init();
5260 let filename = format!("{name}.glyphs");
5261 let pkgname = format!("{name}.glyphspackage");
5262 let g2_file = glyphs2_dir().join(filename.clone());
5263 let g3_file = glyphs3_dir().join(filename.clone());
5264 let g2 = Font::load(&g2_file).unwrap();
5265 let g3 = Font::load(&g3_file).unwrap();
5266
5267 dump_font(&format!("{name}-g2.glyphs"), &g2);
5268 dump_font(&format!("{name}-g3.glyphs"), &g3);
5269
5270 assert_fonts_equal_sans_localized_names(
5271 &g2,
5272 &g3,
5273 &format!("g2 vs g3: {g2_file:?} vs {g3_file:?}"),
5274 );
5275
5276 if has_package {
5277 let g2_pkg = Font::load(&glyphs2_dir().join(pkgname.clone())).unwrap();
5278 let g3_pkg = Font::load(&glyphs3_dir().join(pkgname.clone())).unwrap();
5279
5280 dump_font(&format!("{name}-g2.glyphspackage"), &g2_pkg);
5281 dump_font(&format!("{name}-g3.glyphspackage"), &g3_pkg);
5282
5283 assert_fonts_equal_sans_localized_names(&g2_pkg, &g3_pkg, "g2_pkg vs g3_pkg");
5284 assert_fonts_equal(&g3_pkg, &g3, "g3_pkg vs g3");
5285 }
5286 }
5287
5288 #[test]
5289 fn read_wght_var_2_and_3() {
5290 assert_load_v2_matches_load_v3("WghtVar", LoadCompare::GlyphsAndPackage);
5291 }
5292
5293 #[test]
5294 fn read_wght_var_avar_2_and_3() {
5295 assert_load_v2_matches_load_v3("WghtVar_Avar", LoadCompare::GlyphsAndPackage);
5296 }
5297
5298 #[test]
5299 fn read_wght_var_instances_2_and_3() {
5300 assert_load_v2_matches_load_v3("WghtVar_Instances", LoadCompare::GlyphsAndPackage);
5301 }
5302
5303 #[test]
5304 fn read_wght_var_os2_2_and_3() {
5305 assert_load_v2_matches_load_v3("WghtVar_OS2", LoadCompare::GlyphsAndPackage);
5306 }
5307
5308 #[test]
5309 fn read_wght_var_anchors_2_and_3() {
5310 assert_load_v2_matches_load_v3("WghtVar_Anchors", LoadCompare::GlyphsAndPackage);
5311 }
5312
5313 #[test]
5314 fn read_infinity_2_and_3() {
5315 assert_load_v2_matches_load_v3("infinity", LoadCompare::GlyphsAndPackage);
5316 }
5317
5318 #[test]
5319 fn read_wght_var_noexport_2_and_3() {
5320 assert_load_v2_matches_load_v3("WghtVar_NoExport", LoadCompare::Glyphs);
5321 }
5322
5323 #[test]
5324 fn read_master_names_2_and_3() {
5325 assert_load_v2_matches_load_v3("MasterNames", LoadCompare::Glyphs);
5326 }
5327
5328 #[test]
5329 fn read_master_names_with_italic_2_and_3() {
5330 assert_load_v2_matches_load_v3("MasterNames-Italic", LoadCompare::Glyphs);
5331 }
5332
5333 fn only_shape_in_only_layer<'a>(font: &'a Font, glyph_name: &str) -> &'a Shape {
5334 let glyph = font.glyphs.get(glyph_name).unwrap();
5335 assert_eq!(1, glyph.layers.len());
5336 assert_eq!(1, glyph.layers[0].shapes.len());
5337 &glyph.layers[0].shapes[0]
5338 }
5339
5340 fn check_v2_to_v3_transform(glyphs_file: &str, glyph_name: &str, expected: Affine) {
5341 let g2 = Font::load(&glyphs2_dir().join(glyphs_file)).unwrap();
5342 let g3 = Font::load(&glyphs3_dir().join(glyphs_file)).unwrap();
5343
5344 let g2_shape = only_shape_in_only_layer(&g2, glyph_name);
5346 let g3_shape = only_shape_in_only_layer(&g3, glyph_name);
5347
5348 let Shape::Component(g2_shape) = g2_shape else {
5349 panic!("{g2_shape:?} should be a component");
5350 };
5351 let Shape::Component(g3_shape) = g3_shape else {
5352 panic!("{g3_shape:?} should be a component");
5353 };
5354
5355 assert_eq!(expected, round(g2_shape.transform, 4));
5356 assert_eq!(expected, round(g3_shape.transform, 4));
5357 }
5358
5359 #[test]
5360 fn read_transformed_component_2_and_3_uniform_scale() {
5361 let expected = Affine::new([1.6655, 1.1611, -1.1611, 1.6655, -233.0, -129.0]);
5362 check_v2_to_v3_transform("Component.glyphs", "comma", expected);
5363 }
5364
5365 #[test]
5366 fn read_transformed_component_2_and_3_nonuniform_scale() {
5367 let expected = Affine::new([0.8452, 0.5892, -1.1611, 1.6655, -233.0, -129.0]);
5368 check_v2_to_v3_transform("Component.glyphs", "non_uniform_scale", expected);
5369 }
5370
5371 #[test]
5379 fn read_component_slant_2_and_3() {
5380 let expected = Affine::new([0.8, 0.2736, -0.1411, 0.7518, 0.0, 0.0]);
5381 check_v2_to_v3_transform("ComponentSlant.glyphs", "slanted_square", expected);
5382 }
5383
5384 fn component_transform(shape_plist: &str) -> Affine {
5386 let shape: Shape = RawShape::parse_plist(shape_plist)
5387 .unwrap()
5388 .try_into()
5389 .unwrap();
5390 let Shape::Component(component) = shape else {
5391 panic!("{shape:?} should be a component");
5392 };
5393 component.transform
5394 }
5395
5396 #[test]
5397 fn parse_component_slant_key() {
5398 let raw = RawShape::parse_plist(
5399 r#"
5400{
5401ref = A;
5402pos = (5,21);
5403scale = (1,0.94);
5404slant = (-0.7,0);
5405}
5406 "#,
5407 )
5408 .unwrap();
5409 assert_eq!(raw.slant, vec![-0.7, 0.0]);
5410 }
5411
5412 #[test]
5420 fn read_component_slant_x_with_scale() {
5421 let transform = component_transform(
5422 r#"
5423{
5424ref = A;
5425pos = (5,21);
5426scale = (1,0.94);
5427slant = (-0.7,0);
5428}
5429 "#,
5430 );
5431 assert_eq!(
5432 round(transform, 9),
5433 round(
5434 Affine::new([1.0, 0.0, -0.011484837902484654, 0.94, 5.0, 21.0]),
5435 9
5436 )
5437 );
5438 }
5439
5440 #[test]
5441 fn read_component_slant_with_rotation_and_scale() {
5442 let transform = component_transform(
5443 r#"
5444{
5445ref = A;
5446angle = 20;
5447scale = (0.8,0.8);
5448slant = (10,0);
5449}
5450 "#,
5451 );
5452 assert_eq!(
5453 round(transform, 9),
5454 round(
5455 Affine::new([
5456 0.8,
5457 0.273616114660535,
5458 -0.14106158456677195,
5459 0.7517540966287268,
5460 0.0,
5461 0.0
5462 ]),
5463 9
5464 )
5465 );
5466 }
5467
5468 #[test]
5473 fn read_component_slant_y() {
5474 let transform = component_transform(
5475 r#"
5476{
5477ref = A;
5478slant = (0,5);
5479}
5480 "#,
5481 );
5482 assert_eq!(
5483 round(transform, 9),
5484 round(
5485 Affine::new([1.0, 5f64.to_radians().tan(), 0.0, 1.0, 0.0, 0.0]),
5486 9
5487 )
5488 );
5489 }
5490
5491 #[test]
5492 fn reject_malformed_component_slant() {
5493 let raw = RawShape::parse_plist(
5494 r#"
5495{
5496ref = A;
5497slant = (10);
5498}
5499 "#,
5500 )
5501 .unwrap();
5502 let result = Shape::try_from(raw);
5503 assert!(
5504 matches!(&result, Err(Error::StructuralError(msg)) if msg.starts_with("Bad slant")),
5505 "{result:?}"
5506 );
5507 }
5508
5509 #[test]
5510 fn upgrade_2_to_3_with_implicit_axes() {
5511 let font = Font::load(&glyphs2_dir().join("WghtVar_ImplicitAxes.glyphs")).unwrap();
5512 assert_eq!(
5513 font.axes
5514 .iter()
5515 .map(|a| a.tag.as_str())
5516 .collect::<Vec<&str>>(),
5517 vec!["wght", "wdth", "XXXX"]
5518 );
5519 }
5520
5521 #[test]
5522 fn understand_v2_style_unquoted_hex_unicode() {
5523 let font = Font::load(&glyphs2_dir().join("Unicode-UnquotedHex.glyphs")).unwrap();
5524 assert_eq!(vec![0x1234], font.glyphs.get("name").unwrap().unicode);
5525 assert_eq!(1, font.glyphs.len());
5526 }
5527
5528 #[test]
5529 fn understand_v2_style_quoted_hex_unicode_sequence() {
5530 let font = Font::load(&glyphs2_dir().join("Unicode-QuotedHexSequence.glyphs")).unwrap();
5531 assert_eq!(
5532 vec![0x2044, 0x200D, 0x2215],
5533 font.glyphs.get("name").unwrap().unicode,
5534 );
5535 assert_eq!(1, font.glyphs.len());
5536 }
5537
5538 #[test]
5539 fn understand_v3_style_unquoted_decimal_unicode() {
5540 let font = Font::load(&glyphs3_dir().join("Unicode-UnquotedDec.glyphs")).unwrap();
5541 assert_eq!(vec![182], font.glyphs.get("name").unwrap().unicode);
5542 assert_eq!(1, font.glyphs.len());
5543 }
5544
5545 #[test]
5546 fn understand_v3_style_unquoted_decimal_unicode_sequence() {
5547 let font = Font::load(&glyphs3_dir().join("Unicode-UnquotedDecSequence.glyphs")).unwrap();
5548 assert_eq!(vec![1619, 1764], font.glyphs.get("name").unwrap().unicode);
5549 assert_eq!(1, font.glyphs.len());
5550 }
5551
5552 #[rstest]
5555 #[case::spread_over_lines(
5556 |s: String| s.replace("unicode = (1619,1764);", "unicode = (
55571619,
55581764
5559);"),
5560 &[1619, 1764]
5561 )]
5562 #[case::written_by_plist_to_string(
5563 |s: String| Plist::parse(&s).unwrap().to_string(),
5564 &[1619, 1764]
5565 )]
5566 #[case::whole_file_on_one_line(|s: String| s.lines().collect::<Vec<_>>().join(" "), &[1619, 1764])]
5567 #[case::empty_list(|s: String| s.replace("unicode = (1619,1764);", "unicode = ();"), &[])]
5568 #[case::empty_string(|s: String| s.replace("unicode = (1619,1764);", "unicode = \"\";"), &[])]
5569 fn understand_unicode_sequence_layouts(
5570 #[case] rewrite: fn(String) -> String,
5571 #[case] expected: &[u32],
5572 ) {
5573 let raw =
5574 fs::read_to_string(glyphs3_dir().join("Unicode-UnquotedDecSequence.glyphs")).unwrap();
5575 assert!(raw.contains("unicode = (1619,1764);"));
5576 let font = Font::load_from_string(&rewrite(raw)).unwrap();
5577 assert_eq!(expected, font.glyphs.get("name").unwrap().unicode);
5578 }
5579
5580 #[test]
5581 fn axes_not_hidden() {
5582 let font = Font::load(&glyphs3_dir().join("WghtVar.glyphs")).unwrap();
5583 assert_eq!(
5584 font.axes.iter().map(|a| a.hidden).collect::<Vec<_>>(),
5585 vec![None]
5586 );
5587 }
5588
5589 #[test]
5590 fn axis_hidden() {
5591 let font = Font::load(&glyphs3_dir().join("WghtVar_3master_CustomOrigin.glyphs")).unwrap();
5592 assert_eq!(
5593 font.axes.iter().map(|a| a.hidden).collect::<Vec<_>>(),
5594 vec![Some(true)]
5595 );
5596 }
5597
5598 #[test]
5599 fn axis_hidden_v2() {
5600 let font = Font::load(&glyphs2_dir().join("WghtVar_HiddenAxis.glyphs")).unwrap();
5601 assert_eq!(
5602 font.axes.iter().map(|a| a.hidden).collect::<Vec<_>>(),
5603 vec![Some(true)]
5604 );
5605 }
5606
5607 #[test]
5608 fn vf_origin_single_axis_default() {
5609 let font = Font::load(&glyphs3_dir().join("WghtVar.glyphs")).unwrap();
5610 assert_eq!(0, font.default_master_idx);
5611 }
5612
5613 #[test]
5614 fn vf_origin_multi_axis_default() {
5615 let font = Font::load(&glyphs2_dir().join("WghtVar_ImplicitAxes.glyphs")).unwrap();
5616 assert_eq!(0, font.default_master_idx);
5617 }
5618
5619 #[test]
5620 fn vf_origin_multi_axis_custom() {
5621 let font = Font::load(&glyphs3_dir().join("WghtVar_3master_CustomOrigin.glyphs")).unwrap();
5622 assert_eq!(2, font.default_master_idx);
5623 }
5624
5625 #[test]
5626 fn vf_origin_unquoted_string() {
5627 let font = Font::load(&glyphs3_dir().join("CustomOrigin.glyphs")).unwrap();
5634 assert_eq!(1, font.default_master_idx);
5635 }
5636
5637 #[rstest]
5638 #[case::upright("UnnamedMaster.glyphs", "Regular")]
5639 #[case::italic("UnnamedMaster-Italic.glyphs", "Italic")]
5640 fn unnamed_v3_master_is_default(#[case] file: &str, #[case] expected: &str) {
5641 let font = Font::load(&glyphs3_dir().join(file)).unwrap();
5642 assert_eq!(1, font.default_master_idx);
5643 assert_eq!(expected, font.masters[1].name);
5644 }
5645
5646 #[rstest]
5647 #[case::base_style_without_regular(
5648 &[
5649 "Expanded Thin Italic",
5650 "Expanded Italic",
5651 "Expanded Bold Italic",
5652 ],
5653 "Expanded Italic" )]
5655 #[case::base_style_contains_regular(
5656 &[
5657 "Regular Foo Bar",
5658 "Regular Foo Baz",
5659 "Regular Foo",
5660 ],
5661 "Regular Foo" )]
5663 #[case::base_style_with_regular_omitted(
5664 &[
5665 "Condensed Thin",
5666 "Condensed Light",
5667 "Condensed Regular",
5668 ],
5669 "Condensed Regular"
5671 )]
5672 #[case::default_to_regular(
5674 &["Thin", "Light", "Regular", "Medium", "Bold"],
5675 "Regular"
5676 )]
5677 #[case::default_to_first(&["Foo", "Bar", "Baz"], "Foo")]
5679 fn find_default_master(#[case] master_names: &[&str], #[case] expected: &str) {
5680 let mut font = RawFont::default();
5681 for name in master_names {
5682 let master = RawFontMaster {
5683 name: Some(name.to_string()),
5684 ..Default::default()
5685 };
5686 font.font_master.push(master);
5687 }
5688
5689 let idx = default_master_idx(&mut font);
5690
5691 assert_eq!(expected, font.font_master[idx].name.as_deref().unwrap());
5692 }
5693
5694 #[test]
5695 fn glyph_order_default_is_file_order() {
5696 let font = Font::load(&glyphs3_dir().join("WghtVar.glyphs")).unwrap();
5697 assert_eq!(
5698 vec![
5699 "space",
5700 "exclam",
5701 "hyphen",
5702 "bracketleft",
5703 "bracketright",
5704 "manual-component"
5705 ],
5706 font.glyph_order
5707 );
5708 }
5709
5710 #[test]
5711 fn glyph_order_override_obeyed() {
5712 let _ = tracing_subscriber::fmt().with_test_writer().try_init();
5713 let font = Font::load(&glyphs3_dir().join("WghtVar_GlyphOrder.glyphs")).unwrap();
5714 assert_eq!(vec!["hyphen", "space", "exclam"], font.glyph_order);
5715 }
5716
5717 #[test]
5718 fn duplicate_glyph_name_is_error() {
5719 let result = Font::load(&glyphs3_dir().join("DuplicateGlyphName.glyphs"));
5720 assert!(
5721 matches!(&result, Err(Error::DuplicateGlyphName(name)) if name == "a"),
5722 "{result:?}"
5723 );
5724 }
5725
5726 #[test]
5727 fn loads_global_axis_mappings_from_glyphs2() {
5728 let font = Font::load(&glyphs2_dir().join("OpszWghtVar_AxisMappings.glyphs")).unwrap();
5729
5730 assert_eq!(
5732 UserToDesignMapping(BTreeMap::from([
5733 (
5734 "Optical Size".into(),
5735 AxisUserToDesignMap(vec![
5736 (OrderedFloat(12.0), OrderedFloat(12.0)),
5737 (OrderedFloat(72.0), OrderedFloat(72.0))
5738 ])
5739 ),
5740 (
5741 "Weight".into(),
5742 AxisUserToDesignMap(vec![
5743 (OrderedFloat(100.0), OrderedFloat(40.0)),
5744 (OrderedFloat(200.0), OrderedFloat(46.0)),
5745 (OrderedFloat(300.0), OrderedFloat(51.0)),
5746 (OrderedFloat(400.0), OrderedFloat(57.0)),
5747 (OrderedFloat(450.0), OrderedFloat(57.0)), (OrderedFloat(500.0), OrderedFloat(62.0)),
5749 (OrderedFloat(600.0), OrderedFloat(68.0)),
5750 (OrderedFloat(700.0), OrderedFloat(73.0)),
5751 ])
5752 ),
5753 ])),
5754 font.axis_mappings
5755 );
5756 }
5757
5758 #[test]
5759 fn loads_global_axis_locations_from_glyphs3() {
5760 let font = Font::load(&glyphs3_dir().join("WghtVar_AxisLocation.glyphs")).unwrap();
5761
5762 assert_eq!(
5764 UserToDesignMapping(BTreeMap::from([(
5765 "Weight".into(),
5766 AxisUserToDesignMap(vec![
5767 (OrderedFloat(400.0), OrderedFloat(0.0)),
5768 (OrderedFloat(500.0), OrderedFloat(8.0)),
5769 (OrderedFloat(700.0), OrderedFloat(10.0)),
5770 (OrderedFloat(600.0), OrderedFloat(8.5)),
5772 ])
5776 ),])),
5777 font.axis_mappings
5778 );
5779 }
5780
5781 #[test]
5782 fn loads_global_axis_mappings_from_instances_wght_glyphs3() {
5783 let font = Font::load(&glyphs3_dir().join("WghtVar_Avar_From_Instances.glyphs")).unwrap();
5784
5785 let wght_idx = font.axes.iter().position(|a| a.tag == "wght").unwrap();
5786 assert_eq!(
5787 vec![60.0, 80.0, 132.0],
5788 font.masters
5789 .iter()
5790 .map(|m| m.axes_values[wght_idx].into_inner())
5791 .collect::<Vec<_>>()
5792 );
5793 assert_eq!(
5795 (132.0, 2),
5796 (
5797 font.default_master().axes_values[wght_idx].into_inner(),
5798 font.default_master_idx
5799 )
5800 );
5801
5802 assert_eq!(
5804 UserToDesignMapping(BTreeMap::from([(
5805 "Weight".into(),
5806 AxisUserToDesignMap(vec![
5807 (OrderedFloat(300.0), OrderedFloat(60.0)),
5808 (OrderedFloat(400.0), OrderedFloat(80.0)),
5813 (OrderedFloat(500.0), OrderedFloat(100.0)),
5814 (OrderedFloat(700.0), OrderedFloat(132.0)),
5815 ])
5816 ),])),
5817 font.axis_mappings
5818 );
5819 }
5820
5821 #[test]
5822 fn empty_axis_mappings_falls_back_to_instances() {
5823 let base_path = glyphs3_dir().join("WghtVar_Avar_From_Instances.glyphs");
5827 let raw = std::fs::read_to_string(&base_path).unwrap();
5828 let raw = raw.replace(
5830 "customParameters = (\n{",
5831 "customParameters = (\n{\nname = \"Axis Mappings\";\nvalue = {};\n},\n{",
5832 );
5833 let font = Font::load_from_string(&raw).unwrap();
5834
5835 let font_without = Font::load(&base_path).unwrap();
5837 assert_eq!(font_without.axis_mappings, font.axis_mappings);
5838 }
5839
5840 #[test]
5841 fn custom_axis_instance_without_axis_location_gets_identity_mapping() {
5842 let font = Font::load(&glyphs3_dir().join("CustomAxisNoAxisLocation.glyphs")).unwrap();
5846
5847 assert_eq!(
5848 UserToDesignMapping(BTreeMap::from([(
5849 "Year".into(),
5850 AxisUserToDesignMap(vec![
5851 (OrderedFloat(1979.0), OrderedFloat(1979.0)),
5852 (OrderedFloat(2020.0), OrderedFloat(2020.0)),
5853 (OrderedFloat(2050.0), OrderedFloat(2050.0)),
5854 ])
5855 )])),
5856 font.axis_mappings
5857 );
5858 }
5859
5860 #[test]
5861 fn loads_global_axis_mappings_from_instances_wdth_glyphs3() {
5862 let font = Font::load(&glyphs3_dir().join("WdthVar.glyphs")).unwrap();
5863
5864 assert_eq!(font.axes.len(), 1);
5865 assert_eq!(font.axes[0].tag, "wdth");
5866 assert_eq!(
5867 vec![22.0, 62.0],
5868 font.masters
5869 .iter()
5870 .map(|m| m.axes_values[0].into_inner())
5871 .collect::<Vec<_>>()
5872 );
5873 assert_eq!(
5875 (22.0, 0),
5876 (
5877 font.default_master().axes_values[0].into_inner(),
5878 font.default_master_idx
5879 )
5880 );
5881 assert_eq!(
5883 UserToDesignMapping(BTreeMap::from([(
5884 "Width".into(),
5885 AxisUserToDesignMap(vec![
5886 (OrderedFloat(50.0), OrderedFloat(22.0)),
5889 (OrderedFloat(100.0), OrderedFloat(41.0)),
5894 (OrderedFloat(200.0), OrderedFloat(62.0)),
5897 ])
5898 ),])),
5899 font.axis_mappings
5900 );
5901 }
5902
5903 #[test]
5904 fn fea_for_class() {
5905 let font = Font::load(&glyphs2_dir().join("Fea_Class.glyphs")).unwrap();
5906 assert_eq!(
5907 vec![
5908 concat!("# automatic\n", "@Uppercase = [ A B C\n", "];",),
5909 concat!("@Lowercase = [ a b c\n", "];",),
5910 ],
5911 font.features
5912 .iter()
5913 .filter_map(|f| f.str_if_enabled())
5914 .collect::<Vec<_>>()
5915 )
5916 }
5917
5918 #[test]
5919 fn fea_for_prefix() {
5920 let font = Font::load(&glyphs2_dir().join("Fea_Prefix.glyphs")).unwrap();
5921 assert_eq!(
5922 vec![
5923 "\
5924# Prefix: Languagesystems
5925# automatic
5926languagesystem DFLT dflt;
5927
5928languagesystem latn dflt;
5929and more;
5930",
5931 "# Prefix: \n# automatic\nthanks for all the fish;",
5932 ],
5933 font.features
5934 .iter()
5935 .filter_map(|f| f.str_if_enabled())
5936 .collect::<Vec<_>>()
5937 )
5938 }
5939
5940 #[test]
5941 fn fea_for_feature() {
5942 let font = Font::load(&glyphs2_dir().join("Fea_Feature.glyphs")).unwrap();
5943 assert_eq!(
5944 vec![
5945 "\
5946feature aalt {
5947feature locl;
5948feature tnum;
5949} aalt;",
5950 "\
5951feature ccmp {
5952# automatic
5953lookup ccmp_Other_2 {
5954 sub @Markscomb' @MarkscombCase by @MarkscombCase;
5955 sub @MarkscombCase @Markscomb' by @MarkscombCase;
5956} ccmp_Other_2;
5957
5958etc;
5959} ccmp;",
5960 ],
5961 font.features
5962 .iter()
5963 .filter_map(|f| f.str_if_enabled())
5964 .collect::<Vec<_>>()
5965 )
5966 }
5967
5968 #[test]
5969 fn fea_order() {
5970 let font = Font::load(&glyphs2_dir().join("Fea_Order.glyphs")).unwrap();
5971 assert_eq!(
5972 vec![
5973 "@class_first = [ meh\n];",
5974 "# Prefix: second\nmeh",
5975 "feature third {\nmeh\n} third;",
5976 ],
5977 font.features
5978 .iter()
5979 .filter_map(|f| f.str_if_enabled())
5980 .collect::<Vec<_>>()
5981 )
5982 }
5983
5984 #[test]
5985 fn fea_labels() {
5986 let font = Font::load(&glyphs3_dir().join("Fea_Labels.glyphs")).unwrap();
5987 assert_eq!(
5988 vec![
5989 concat!(
5990 "feature ss01 {\n",
5991 "# automatic\n",
5992 "featureNames {\n",
5993 " name 3 1 0x0409 \"Test 1\";\n",
5994 " name 3 1 0x0C01 \"اختبار ١\";\n",
5995 "};\n",
5996 "sub a by a.ss01;\n",
5997 "sub b by b.ss01;\n\n",
5998 "} ss01;",
5999 ),
6000 concat!(
6001 "feature ss02 {\n",
6002 "featureNames {\n",
6003 " name 3 1 0x0409 \"Test 2\";\n",
6004 "};\n",
6005 "sub c by c.alt;\n",
6006 "} ss02;",
6007 ),
6008 ],
6009 font.features
6010 .iter()
6011 .filter_map(|f| f.str_if_enabled())
6012 .collect::<Vec<_>>()
6013 )
6014 }
6015
6016 #[test]
6017 fn tags_make_excellent_names() {
6018 let raw = RawFeature {
6019 tag: Some("aalt".to_string()),
6020 code: "blah".to_string(),
6021 ..Default::default()
6022 };
6023 assert_eq!("aalt", raw.name().unwrap());
6024 }
6025
6026 #[test]
6028 fn legacy_feature_name_is_escaped() {
6029 let raw = RawFeature {
6030 tag: Some("ss05".into()),
6031 notes: Some("Name: a\"b\\c\n".into()),
6032 ..Default::default()
6033 };
6034 assert_eq!(
6035 raw.feature_names(),
6036 "featureNames {\nname 3 1 0x409 \"a\\0022b\\005cc\";\n};\n"
6037 );
6038 }
6039
6040 #[test]
6042 fn legacy_feature_name_is_first_line() {
6043 let raw = RawFeature {
6044 tag: Some("ss04".into()),
6045 notes: Some(
6046 "Name: Dynamic arrows and triangles\nSecond approximation\nArrows 2\n".into(),
6047 ),
6048 ..Default::default()
6049 };
6050 assert_eq!(
6051 raw.feature_names(),
6052 "featureNames {\nname 3 1 0x409 \"Dynamic arrows and triangles\";\n};\n"
6053 );
6054 }
6055
6056 #[test]
6057 fn legacy_feature_name_empty_first_line() {
6058 let raw = RawFeature {
6059 tag: Some("ss01".into()),
6060 notes: Some("Name: \nSecond line\n".into()),
6061 ..Default::default()
6062 };
6063 assert_eq!(raw.feature_names(), "");
6064 }
6065
6066 #[test]
6067 fn manual_kern_always_gets_insert_mark() {
6068 let feature = RawFeature {
6069 tag: Some("kern".into()),
6070 ..Default::default()
6071 };
6072
6073 assert!(
6074 feature
6075 .raw_feature_to_feature()
6076 .unwrap()
6077 .content
6078 .contains("# Automatic Code")
6079 )
6080 }
6081
6082 #[test]
6083 fn but_automatic_does_not() {
6084 let feature = RawFeature {
6085 tag: Some("kern".into()),
6086 automatic: Some(1),
6087 ..Default::default()
6088 };
6089
6090 assert!(
6091 !feature
6092 .raw_feature_to_feature()
6093 .unwrap()
6094 .content
6095 .contains("# Automatic Code")
6096 )
6097 }
6098
6099 #[test]
6100 fn v2_to_v3_simple_names() {
6101 let v2 = Font::load(&glyphs2_dir().join("WghtVar.glyphs")).unwrap();
6102 let v3 = Font::load(&glyphs3_dir().join("WghtVar.glyphs")).unwrap();
6103 let v2_defaults: BTreeMap<_, _> = v2.default_names().collect();
6105 let v3_defaults: BTreeMap<_, _> = v3.default_names().collect();
6106 assert_eq!(v3_defaults, v2_defaults);
6107 }
6108
6109 #[test]
6110 fn v2_to_v3_more_names() {
6111 let v2 = Font::load(&glyphs2_dir().join("TheBestNames.glyphs")).unwrap();
6112 let v3 = Font::load(&glyphs3_dir().join("TheBestNames.glyphs")).unwrap();
6113
6114 let v2_defaults: BTreeMap<_, _> = v2.default_names().collect();
6117 let v3_defaults: BTreeMap<_, _> = v3.default_names().collect();
6118
6119 assert_eq!(v2_defaults, v3_defaults);
6120 }
6121
6122 #[test]
6123 fn v2_long_param_names() {
6124 let v2 = Font::load(&glyphs2_dir().join("LongParamNames.glyphs")).unwrap();
6125 assert_eq!(v2.get_default_name("vendorID"), Some("DERP"));
6126 assert_eq!(
6127 v2.get_default_name("descriptions"),
6128 Some("legacy description")
6129 );
6130 assert_eq!(
6131 v2.get_default_name("licenseURL"),
6132 Some("www.example.com/legacy")
6133 );
6134 assert_eq!(v2.get_default_name("versionString"), Some("legacy version"));
6135 assert_eq!(v2.get_default_name("licenses"), Some("legacy license"));
6136 assert_eq!(v2.get_default_name("uniqueID"), Some("legacy unique id"));
6137 assert_eq!(
6138 v2.get_default_name("sampleTexts"),
6139 Some("legacy sample text")
6140 );
6141 }
6142
6143 #[test]
6144 fn v2_style_names_in_a_v3_file() {
6145 let v3_mixed_with_v2 =
6146 Font::load(&glyphs3_dir().join("TheBestV2NamesInAV3File.glyphs")).unwrap();
6147 let v3 = Font::load(&glyphs3_dir().join("TheBestNames.glyphs")).unwrap();
6148
6149 let v3_mixed_defaults: BTreeMap<_, _> = v3_mixed_with_v2.default_names().collect();
6152 let v3_defaults: BTreeMap<_, _> = v3.default_names().collect();
6153
6154 assert_eq!(v3_mixed_defaults, v3_defaults);
6155 }
6156
6157 #[test]
6158 fn no_english_names_fallback() {
6159 let font = Font::load(&glyphs3_dir().join("NoEnglishNames.glyphs")).unwrap();
6164
6165 assert_eq!(
6167 font.get_default_name("copyrights"),
6168 Some("Droit d'auteur français")
6169 );
6170
6171 assert_eq!(
6173 font.get_default_name("designers"),
6174 Some("Concepteur français")
6175 );
6176
6177 assert_eq!(
6179 font.get_default_name("manufacturers"),
6180 Some("Produttore italiano")
6181 );
6182
6183 let localized: Vec<_> = font.localized_names().collect();
6184
6185 assert!(localized.contains(&("copyrights", "FRA", "Droit d'auteur français")));
6187 assert!(localized.contains(&("copyrights", "DEU", "Deutsches Urheberrecht")));
6189 assert!(localized.contains(&("copyrights", "JPN", "日本の著作権")));
6190 }
6191
6192 fn assert_wghtvar_avar_master_and_axes(glyphs_file: &Path) {
6193 let font = Font::load(glyphs_file).unwrap();
6194 let wght_idx = font.axes.iter().position(|a| a.tag == "wght").unwrap();
6195 assert_eq!(
6196 vec![300.0, 400.0, 700.0],
6197 font.masters
6198 .iter()
6199 .map(|m| m.axes_values[wght_idx].into_inner())
6200 .collect::<Vec<_>>()
6201 );
6202 assert_eq!(
6203 (400.0, 1),
6204 (
6205 font.default_master().axes_values[wght_idx].into_inner(),
6206 font.default_master_idx
6207 )
6208 );
6209 }
6210
6211 #[test]
6212 fn favor_regular_as_origin_glyphs2() {
6213 assert_wghtvar_avar_master_and_axes(&glyphs2_dir().join("WghtVar_Avar.glyphs"));
6214 }
6215
6216 #[test]
6217 fn favor_regular_as_origin_glyphs3() {
6218 assert_wghtvar_avar_master_and_axes(&glyphs3_dir().join("WghtVar_Avar.glyphs"));
6219 }
6220
6221 #[test]
6222 fn have_all_the_best_instances() {
6223 let font = Font::load(&glyphs3_dir().join("WghtVar_Instances.glyphs")).unwrap();
6224 assert_eq!(
6225 vec![
6226 ("Regular", vec![("Weight", 400.0)]),
6227 ("Bold", vec![("Weight", 700.0)])
6228 ],
6229 font.instances
6230 .iter()
6231 .map(|inst| (
6232 inst.name.as_str(),
6233 font.axes
6234 .iter()
6235 .zip(&inst.axes_values)
6236 .map(|(a, v)| (a.name.as_str(), v.0))
6237 .collect::<Vec<_>>()
6238 ))
6239 .collect::<Vec<_>>()
6240 );
6241 }
6242
6243 #[test]
6244 fn read_typo_whatsits() {
6245 let font = Font::load(&glyphs2_dir().join("WghtVar_OS2.glyphs")).unwrap();
6246 let master = font.default_master();
6247 assert_eq!(Some(1193), master.custom_parameters.typo_ascender);
6248 assert_eq!(Some(-289), master.custom_parameters.typo_descender);
6249 }
6250
6251 #[test]
6252 fn read_os2_flags_default_set() {
6253 let font = Font::load(&glyphs2_dir().join("WghtVar.glyphs")).unwrap();
6254 assert_eq!(font.custom_parameters.use_typo_metrics, Some(true));
6255 assert_eq!(font.custom_parameters.has_wws_names, Some(true));
6256 }
6257
6258 #[test]
6259 fn read_os2_flags_default_unset() {
6260 let font = Font::load(&glyphs2_dir().join("WghtVar_OS2.glyphs")).unwrap();
6261 assert_eq!(font.custom_parameters.use_typo_metrics, None);
6262 assert_eq!(font.custom_parameters.has_wws_names, None);
6263 }
6264
6265 #[test]
6266 fn read_os2_longform_param_names() {
6267 let font = Font::load(&glyphs2_dir().join("os2_longform_params.glyphs")).unwrap();
6270 assert_eq!(font.custom_parameters.strikeout_position, Some(300));
6271 assert_eq!(font.custom_parameters.strikeout_size, Some(50));
6272 assert_eq!(font.custom_parameters.subscript_x_offset, Some(-80));
6273 assert_eq!(font.custom_parameters.subscript_x_size, Some(700));
6274 assert_eq!(font.custom_parameters.subscript_y_offset, Some(-75));
6275 assert_eq!(font.custom_parameters.subscript_y_size, Some(650));
6276 assert_eq!(font.custom_parameters.superscript_x_offset, Some(50));
6277 assert_eq!(font.custom_parameters.superscript_x_size, Some(600));
6278 assert_eq!(font.custom_parameters.superscript_y_offset, Some(350));
6279 assert_eq!(font.custom_parameters.superscript_y_size, Some(600));
6280 }
6281
6282 #[test]
6283 fn read_simple_kerning() {
6284 let font = Font::load(&glyphs3_dir().join("WghtVar.glyphs")).unwrap();
6285 assert_eq!(
6286 HashSet::from(["m01", "E09E0C54-128D-4FEA-B209-1B70BEFE300B",]),
6287 font.kerning_ltr
6288 .keys()
6289 .map(|k| k.as_str())
6290 .collect::<HashSet<_>>()
6291 );
6292
6293 let actual_groups: Vec<_> = font
6294 .glyphs
6295 .iter()
6296 .filter_map(|(name, glyph)| {
6297 if glyph.left_kern.is_some() || glyph.right_kern.is_some() {
6298 Some((
6299 name.as_str(),
6300 glyph.left_kern.as_deref(),
6301 glyph.right_kern.as_deref(),
6302 ))
6303 } else {
6304 None
6305 }
6306 })
6307 .collect();
6308
6309 let actual_kerning = font
6310 .kerning_ltr
6311 .get("m01")
6312 .unwrap()
6313 .iter()
6314 .map(|((n1, n2), value)| (n1.as_str(), n2.as_str(), value.0))
6315 .collect::<Vec<_>>();
6316
6317 assert_eq!(
6318 (
6319 vec![
6320 ("bracketleft", Some("bracketleft_L"), Some("bracketleft_R")),
6321 (
6322 "bracketright",
6323 Some("bracketright_L"),
6324 Some("bracketright_R")
6325 ),
6326 ],
6327 vec![
6328 ("@MMK_L_bracketleft_R", "exclam", -165.),
6329 ("bracketleft", "bracketright", -300.),
6330 ("exclam", "@MMK_R_bracketright_L", -160.),
6331 ("exclam", "exclam", -360.),
6332 ("exclam", "hyphen", 20.),
6333 ("hyphen", "hyphen", -150.),
6334 ],
6335 ),
6336 (actual_groups, actual_kerning),
6337 "{:?}",
6338 font.kerning_ltr
6339 );
6340 }
6341
6342 #[test]
6343 fn kern_floats() {
6344 let font = Font::load(&glyphs3_dir().join("KernFloats.glyphs")).unwrap();
6345
6346 let kerns = font.kerning_ltr.get("m01").unwrap();
6347 let key = ("space".to_smolstr(), "space".to_smolstr());
6348 assert_eq!(kerns.get(&key), Some(&OrderedFloat(4.2001)));
6349 }
6350
6351 #[test]
6352 fn read_simple_anchor() {
6353 let font = Font::load(&glyphs3_dir().join("WghtVar_Anchors.glyphs")).unwrap();
6354 assert_eq!(
6355 vec![
6356 ("m01", "top", Point::new(300.0, 700.0)),
6357 ("l2", "top", Point::new(325.0, 725.0))
6358 ],
6359 font.glyphs
6360 .get("A")
6361 .unwrap()
6362 .layers
6363 .iter()
6364 .flat_map(|l| l.anchors.iter().map(|a| (
6365 l.layer_id.as_str(),
6366 a.name.as_str(),
6367 a.pos
6368 )))
6369 .collect::<Vec<_>>()
6370 );
6371 }
6372
6373 #[test]
6374 fn read_export_glyph() {
6375 let font = Font::load(&glyphs3_dir().join("WghtVar_NoExport.glyphs")).unwrap();
6376 assert_eq!(
6377 vec![
6378 ("bracketleft", true),
6379 ("bracketright", true),
6380 ("exclam", true),
6381 ("hyphen", false),
6382 ("manual-component", true),
6383 ("space", true),
6384 ],
6385 font.glyphs
6386 .iter()
6387 .map(|(name, glyph)| (name.as_str(), glyph.export))
6388 .collect::<Vec<_>>()
6389 );
6390 }
6391
6392 #[test]
6393 fn read_fstype_none() {
6394 let font = Font::load(&glyphs3_dir().join("infinity.glyphs")).unwrap();
6395 assert!(font.custom_parameters.fs_type.is_none());
6396 }
6397
6398 #[test]
6399 fn read_fstype_zero() {
6400 let font = Font::load(&glyphs3_dir().join("fstype_0x0000.glyphs")).unwrap();
6401 assert_eq!(Some(0), font.custom_parameters.fs_type);
6402 }
6403
6404 #[test]
6405 fn short_param_names_take_precedence_in_either_order() {
6406 let original = std::fs::read_to_string(glyphs3_dir().join("fstype_0x0000.glyphs")).unwrap();
6407 let placeholder = "{\nname = fsType;\nvalue = (\n);\n}";
6408 assert!(original.contains(placeholder));
6409 let short = [
6410 "{name = fsType; value = ();}",
6411 "{name = typoAscender; value = 800;}",
6412 "{name = underlinePosition; value = -100;}",
6413 "{name = panose; value = (2,0,5,3,0,0,0,0,0,0);}",
6414 ];
6415 let long = [
6416 "{name = openTypeOS2Type; value = (2);}",
6417 "{name = openTypeOS2TypoAscender; value = 900;}",
6418 "{name = postscriptUnderlinePosition; value = -200;}",
6419 "{name = openTypeOS2Panose; value = (2,0,8,3,0,0,0,0,0,0);}",
6420 ];
6421 for params in [[short, long].concat(), [long, short].concat()] {
6422 let source = original.replace(placeholder, ¶ms.join(",\n"));
6423 let params = Font::load_from_string(&source).unwrap().custom_parameters;
6424 assert_eq!(params.fs_type, Some(0));
6425 assert_eq!(params.typo_ascender, Some(800));
6426 assert_eq!(params.underline_position, Some(OrderedFloat(-100.0)));
6427 assert_eq!(params.panose, Some(vec![2, 0, 5, 3, 0, 0, 0, 0, 0, 0]));
6428 }
6429 }
6430
6431 #[test]
6432 fn read_fstype_bits() {
6433 let font = Font::load(&glyphs3_dir().join("fstype_0x0104.glyphs")).unwrap();
6434 assert_eq!(Some(0x104), font.custom_parameters.fs_type);
6435 }
6436
6437 #[test]
6438 fn anchor_components() {
6439 let font = Font::load(&glyphs3_dir().join("ComponentAnchor.glyphs")).unwrap();
6440 let glyph = font.glyphs.get("A_Aacute").unwrap();
6441 let acute_comb = glyph.layers[0]
6442 .shapes
6443 .iter()
6444 .find_map(|shape| match shape {
6445 Shape::Component(c) if c.name == "acutecomb" => Some(c),
6446 _ => None,
6447 })
6448 .unwrap();
6449 assert_eq!(acute_comb.anchor.as_deref(), Some("top_2"));
6450 }
6451
6452 #[test]
6453 fn parse_alignment_zone_smoke_test() {
6454 assert_eq!(
6455 super::parse_alignment_zone("{1, -12}").map(|x| (x.0.0, x.1.0)),
6456 Some((1., -12.))
6457 );
6458 assert_eq!(
6459 super::parse_alignment_zone("{-5001, 12}").map(|x| (x.0.0, x.1.0)),
6460 Some((-5001., 12.))
6461 );
6462 }
6463
6464 impl FontMaster {
6466 fn get_metric(&self, name: &str) -> Option<(f64, f64)> {
6467 self.metric_values
6468 .get(name)
6469 .map(|raw| (raw.pos.0, raw.over.0))
6470 }
6471 }
6472
6473 #[test]
6474 fn v2_alignment_zones_to_metrics() {
6475 let font = Font::load(&glyphs2_dir().join("alignment_zones_v2.glyphs")).unwrap();
6476 let master = font.default_master();
6477
6478 assert_eq!(master.get_metric("ascender"), Some((800., 17.)));
6479 assert_eq!(master.get_metric("cap height"), Some((700., 16.)));
6480 assert_eq!(master.get_metric("baseline"), Some((0., -16.)));
6481 assert_eq!(master.get_metric("descender"), Some((-200., -17.)));
6482 assert_eq!(master.get_metric("x-height"), Some((500., 15.)));
6483 assert_eq!(master.get_metric("italic angle"), None);
6484 }
6485
6486 #[test]
6487 fn v3_duplicate_metrics_first_wins() {
6488 let font = Font::load(&glyphs3_dir().join("WghtVar_OS2.glyphs")).unwrap();
6494 let master = font.default_master();
6495
6496 assert_eq!(master.get_metric("x-height"), Some((501., 0.)));
6497 }
6498
6499 #[test]
6500 fn v2_preserve_custom_alignment_zones() {
6501 let font = Font::load(&glyphs2_dir().join("alignment_zones_v2.glyphs")).unwrap();
6502 let master = font.default_master();
6503 assert_eq!(master.get_metric("zone 1"), Some((1000., 20.)));
6504 assert_eq!(master.get_metric("zone 2"), Some((-100., -15.)));
6505 }
6506
6507 #[test]
6511 fn unknown_glyph_category() {
6512 let raw = super::RawGlyph {
6513 glyphname: "A".into(),
6514 category: Some("Fake".into()),
6515 ..Default::default()
6516 };
6517
6518 let cooked = raw.build(FormatVersion::V2, &GlyphData::default()).unwrap();
6519 assert_eq!((cooked.category, cooked.sub_category), (None, None));
6520 }
6521
6522 #[test]
6527 fn explicit_unknown_subcategory_does_not_revert_to_ligature_guess() {
6528 let raw = super::RawGlyph {
6529 glyphname: "a_a".into(),
6530 category: Some("Letter".into()),
6531 sub_category: Some("Conjunct-but-fontc-doesnt-know-it".into()),
6532 ..Default::default()
6533 };
6534
6535 let cooked = raw.build(FormatVersion::V2, &GlyphData::default()).unwrap();
6536 assert_eq!(cooked.category, Some(Category::Letter));
6537 assert_eq!(cooked.sub_category, None); }
6539
6540 #[test]
6541 fn gasp_table_either_case() {
6542 let expected = BTreeMap::from([(8, 10), (20, 7), (65535, 15), (65536, 1)]);
6546 for file in ["WghtVarGasp.glyphs", "WghtVarGaspUppercase.glyphs"] {
6547 let font = Font::load(&glyphs3_dir().join(file)).unwrap();
6548 assert_eq!(
6549 Some(&expected),
6550 font.custom_parameters.gasp_table.as_ref(),
6551 "{file}"
6552 );
6553 }
6554 }
6555
6556 #[test]
6557 fn custom_params_disable() {
6558 let font = Font::load(&glyphs3_dir().join("custom_param_disable.glyphs")).unwrap();
6559
6560 assert!(font.custom_parameters.fs_type.is_none())
6561 }
6562
6563 #[test]
6564 fn parse_numbers() {
6565 let font = Font::load(&glyphs3_dir().join("number_value.glyphs")).unwrap();
6566 assert_eq!(
6567 font.masters[0].number_values.get("foo"),
6568 Some(&OrderedFloat(12.4f64))
6569 );
6570 assert_eq!(
6571 font.masters[1].number_values.get("foo"),
6572 Some(&OrderedFloat(0f64))
6573 );
6574 }
6575
6576 #[test]
6577 fn read_font_metrics() {
6578 let font =
6579 Font::load(&glyphs3_dir().join("GlobalMetrics_font_customParameters.glyphs")).unwrap();
6580 assert_eq!(Some(950), font.custom_parameters.typo_ascender);
6581 assert_eq!(Some(-350), font.custom_parameters.typo_descender);
6582 assert_eq!(Some(0), font.custom_parameters.typo_line_gap);
6583 assert_eq!(Some(950), font.custom_parameters.hhea_ascender);
6584 assert_eq!(Some(-350), font.custom_parameters.hhea_descender);
6585 assert_eq!(Some(0), font.custom_parameters.hhea_line_gap);
6586 assert_eq!(Some(1185), font.custom_parameters.win_ascent);
6587 assert_eq!(Some(420), font.custom_parameters.win_descent);
6588 assert_eq!(
6589 Some(OrderedFloat(42_f64)),
6590 font.custom_parameters.underline_thickness
6591 );
6592 assert_eq!(
6593 Some(OrderedFloat(-300_f64)),
6594 font.custom_parameters.underline_position
6595 );
6596 }
6597
6598 #[test]
6599 fn read_longform_metric_param_names() {
6600 let font = Font::load_from_string(
6601 r#"{
6602.formatVersion = 3;
6603fontMaster = (
6604{
6605customParameters = (
6606{name = postscriptUnderlineThickness; value = 70;},
6607{name = postscriptUnderlinePosition; value = -120;},
6608{name = openTypeOS2TypoAscender; value = 800;},
6609{name = openTypeOS2TypoDescender; value = -200;},
6610{name = openTypeOS2TypoLineGap; value = 10;},
6611{name = openTypeOS2WinAscent; value = 1000;},
6612{name = openTypeOS2WinDescent; value = 300;},
6613{name = openTypeHheaAscender; value = 900;},
6614{name = openTypeHheaDescender; value = -250;},
6615{name = openTypeHheaLineGap; value = 20;},
6616{name = openTypeVheaVertTypoAscender; value = 500;},
6617{name = openTypeVheaVertTypoDescender; value = -500;},
6618{name = openTypeVheaVertTypoLineGap; value = 30;}
6619);
6620id = "m01";
6621},
6622{
6623customParameters = (
6624{name = vheaVertTypoAscender; value = 510;},
6625{name = vheaVertTypoDescender; value = -510;},
6626{name = vheaVertTypoLineGap; value = 40;}
6627);
6628id = "m02";
6629}
6630);
6631unitsPerEm = 1000;
6632}"#,
6633 )
6634 .unwrap();
6635 let params = &font.masters[0].custom_parameters;
6636 assert_eq!(params.underline_thickness, Some(OrderedFloat(70.0)));
6637 assert_eq!(params.underline_position, Some(OrderedFloat(-120.0)));
6638 assert_eq!(params.typo_ascender, Some(800));
6639 assert_eq!(params.typo_descender, Some(-200));
6640 assert_eq!(params.typo_line_gap, Some(10));
6641 assert_eq!(params.win_ascent, Some(1000));
6642 assert_eq!(params.win_descent, Some(300));
6643 assert_eq!(params.hhea_ascender, Some(900));
6644 assert_eq!(params.hhea_descender, Some(-250));
6645 assert_eq!(params.hhea_line_gap, Some(20));
6646 assert_eq!(params.vhea_ascender, Some(500));
6647 assert_eq!(params.vhea_descender, Some(-500));
6648 assert_eq!(params.vhea_line_gap, Some(30));
6649
6650 let params = &font.masters[1].custom_parameters;
6651 assert_eq!(params.vhea_ascender, Some(510));
6652 assert_eq!(params.vhea_descender, Some(-510));
6653 assert_eq!(params.vhea_line_gap, Some(40));
6654 }
6655
6656 #[test]
6657 fn parse_legacy_stylistic_set_name() {
6658 let font = Font::load(&glyphs2_dir().join("FeaLegacyName.glyphs")).unwrap();
6659 assert_eq!(font.features.len(), 2);
6660 let [ss01, ss02] = font.features.as_slice() else {
6661 panic!("wrong number of features");
6662 };
6663
6664 assert!(
6665 ss01.content
6666 .contains("name 3 1 0x409 \"Alternate placeholder\"")
6667 );
6668 assert!(!ss02.content.contains("name 3 1"))
6669 }
6670
6671 #[test]
6673 fn one_italic_is_enough() {
6674 let font = Font::load(&glyphs2_dir().join("ItalicItalic.glyphs")).unwrap();
6675 for master in font.masters {
6676 let mut fragments = master.name.split_ascii_whitespace().collect::<Vec<_>>();
6677 fragments.sort();
6678 for words in fragments.windows(2) {
6679 assert!(
6680 words[0] != words[1],
6681 "Multiple instances of {} in {}",
6682 words[0],
6683 master.name
6684 );
6685 }
6686 }
6687 }
6688
6689 #[test]
6690 fn master_name_contains_italic() {
6691 let font = Font::load(&glyphs2_dir().join("MasterNameNotExactlyItalic.glyphs")).unwrap();
6695
6696 assert_eq!(font.default_master().name, "ThinItalic");
6697 }
6698
6699 #[test]
6701 fn ignore_masters_if_axis_mapping() {
6702 let font = Font::load(&glyphs2_dir().join("MasterNotMapped.glyphs")).unwrap();
6703 let mapping = &font.axis_mappings.0.get("Weight").unwrap().0;
6704 assert_eq!(
6705 vec![
6706 (OrderedFloat(400_f64), OrderedFloat(40.0)),
6707 (OrderedFloat(700_f64), OrderedFloat(70.0))
6708 ],
6709 *mapping
6710 );
6711 }
6712
6713 #[rstest]
6714 #[case::rotate_0(0.0, Affine::new([1.0, 0.0, 0.0, 1.0, 0.0, 0.0]))]
6715 #[case::rotate_360(360.0, Affine::new([1.0, 0.0, 0.0, 1.0, 0.0, 0.0]))]
6716 #[case::rotate_90(90.0, Affine::new([0.0, 1.0, -1.0, 0.0, 0.0, 0.0]))]
6717 #[case::rotate_minus_90(-90.0, Affine::new([0.0, -1.0, 1.0, 0.0, 0.0, 0.0]))]
6718 #[case::rotate_180(180.0, Affine::new([-1.0, 0.0, 0.0, -1.0, 0.0, 0.0]))]
6719 #[case::rotate_minus_180(-180.0, Affine::new([-1.0, 0.0, 0.0, -1.0, 0.0, 0.0]))]
6720 #[case::rotate_270(270.0, Affine::new([0.0, -1.0, 1.0, 0.0, 0.0, 0.0]))]
6721 #[case::rotate_minus_270(-270.0, Affine::new([0.0, 1.0, -1.0, 0.0, 0.0, 0.0]))]
6722 #[case::rotate_450(450.0, Affine::new([0.0, 1.0, -1.0, 0.0, 0.0, 0.0]))]
6723 #[case::rotate_540(540.0, Affine::new([-1.0, 0.0, 0.0, -1.0, 0.0, 0.0]))]
6724 fn cardinal_rotation_contain_exact_zeros_and_ones(
6725 #[case] angle: f64,
6726 #[case] expected: Affine,
6727 ) {
6728 assert_eq!(expected, normalized_rotation(angle));
6734 }
6735
6736 #[rstest]
6737 #[case::rotate_30(30.0, 4, Affine::new([0.866, 0.5, -0.5, 0.866, 0.0, 0.0]))]
6738 #[case::rotate_minus_30(-30.0, 4, Affine::new([0.866, -0.5, 0.5, 0.866, 0.0, 0.0]))]
6739 #[case::rotate_almost_90(
6740 90.01, 8, Affine::new([-0.00017453, 0.99999998, -0.99999998, -0.00017453, 0.0, 0.0])
6741 )]
6742 fn non_cardinal_rotation_left_untouched(
6743 #[case] angle: f64,
6744 #[case] precision: u8,
6745 #[case] expected: Affine,
6746 ) {
6747 assert_eq!(expected, round(normalized_rotation(angle), precision));
6749 }
6750
6751 #[test]
6752 fn parse_colrv1_identify_colr_glyphs() {
6753 let font = Font::load(&glyphs3_dir().join("COLRv1-gradient.glyphs")).unwrap();
6754 let expected_colr = HashSet::from(["A", "B", "C", "D", "K", "L", "M", "N"]);
6755 assert_eq!(
6756 expected_colr,
6757 font.glyphs
6758 .values()
6759 .filter(|g| g.layers.iter().all(|l| l.attributes.color))
6760 .map(|g| g.name.as_str())
6761 .collect::<HashSet<_>>()
6762 );
6763 }
6764
6765 #[test]
6766 fn parse_colrv1_gradients() {
6767 let font = Font::load(&glyphs3_dir().join("COLRv1-gradient.glyphs")).unwrap();
6768 let expected_colr = HashSet::from([
6769 (
6770 "A",
6771 Gradient {
6772 start: vec![OrderedFloat(0.1), OrderedFloat(0.1)],
6773 end: vec![OrderedFloat(0.9), OrderedFloat(0.9)],
6774 colors: vec![
6775 ColorStop {
6776 color: Color::rgba(255, 0, 0, 255),
6777 stop_offset: 0.into(),
6778 },
6779 ColorStop {
6780 color: Color::rgba(0, 0, 255, 255),
6781 stop_offset: 1.into(),
6782 },
6783 ],
6784 ..Default::default()
6785 },
6786 ),
6787 (
6788 "N",
6789 Gradient {
6790 start: vec![OrderedFloat(1.0), OrderedFloat(1.0)],
6791 end: vec![OrderedFloat(0.0), OrderedFloat(0.0)],
6792 colors: vec![
6793 ColorStop {
6794 color: Color::rgba(255, 0, 0, 255),
6795 stop_offset: 0.into(),
6796 },
6797 ColorStop {
6798 color: Color::rgba(0, 0, 255, 255),
6799 stop_offset: 1.into(),
6800 },
6801 ],
6802 style: "circle".to_string(),
6803 },
6804 ),
6805 ]);
6806 assert_eq!(
6807 expected_colr,
6808 font.glyphs
6809 .values()
6810 .filter(|g| expected_colr.iter().any(|(name, _)| *name == g.name))
6811 .flat_map(|g| g.layers.iter().flat_map(|l| l.shapes.iter()).map(|s| (
6812 g.name.as_str(),
6813 s.attributes().gradient.as_ref().unwrap().clone()
6814 )))
6815 .collect::<HashSet<_>>()
6816 );
6817 }
6818
6819 #[test]
6820 fn parse_grayscale_colors() {
6821 let font = Font::load(&glyphs3_dir().join("COLRv1-grayscale.glyphs")).unwrap();
6822 assert_eq!(
6823 vec![
6824 ColorStop {
6825 color: Color::rgba(64, 64, 64, 255),
6826 stop_offset: 0.into(),
6827 },
6828 ColorStop {
6829 color: Color::rgba(0, 0, 0, 255),
6830 stop_offset: 1.into(),
6831 },
6832 ],
6833 font.glyphs
6834 .values()
6835 .flat_map(
6836 |g| g.layers.iter().flat_map(|l| l.shapes.iter()).flat_map(|s| s
6837 .attributes()
6838 .gradient
6839 .iter()
6840 .flat_map(|g| g.colors.iter())
6841 .cloned())
6842 )
6843 .collect::<Vec<_>>()
6844 );
6845 }
6846
6847 #[test]
6849 fn missing_width_no_problem() {
6850 let font = Font::load(&glyphs3_dir().join("MissingWidth.glyphs")).unwrap();
6851 let glyph = font.glyphs.get("widthless").unwrap();
6852 assert_eq!(glyph.layers[0].width, 600.);
6853 }
6854
6855 #[test]
6856 fn read_preferred_names_from_properties() {
6857 let font = Font::load(&glyphs3_dir().join("PreferableNames.glyphs")).unwrap();
6858 assert_eq!(
6859 vec![
6860 Some("Pref Family Name"),
6861 Some("Pref Regular"),
6862 Some("Name 25?!")
6863 ],
6864 vec![
6865 font.get_default_name("preferredFamilyNames"),
6866 font.get_default_name("preferredSubfamilyNames"),
6867 font.get_default_name("variationsPostScriptNamePrefix"),
6868 ]
6869 );
6870 }
6871
6872 #[test]
6873 fn zero_value_metrics() {
6874 let font = Font::load(&glyphs3_dir().join("ZeroMetrics.glyphs")).unwrap();
6875 let master = font.default_master();
6876 assert_eq!(master.ascender(), Some(789.));
6877 assert_eq!(master.cap_height(), Some(0.));
6879 assert_eq!(master.x_height(), Some(0.));
6882 assert_eq!(master.italic_angle(), None);
6884 }
6885
6886 #[test]
6889 fn names_from_instances() {
6890 let font = Font::load(&glyphs3_dir().join("InstanceNames.glyphs")).unwrap();
6891 assert_eq!(
6892 font.get_default_name("preferredSubfamilyNames").unwrap(),
6893 "Italic"
6894 )
6895 }
6896
6897 #[rstest]
6898 #[case::v2(glyphs2_dir())]
6899 #[case::v3(glyphs3_dir())]
6900 fn glyph_production_names(#[case] glyphs_dir: PathBuf) {
6901 let font = Font::load(&glyphs_dir.join("ProductionNames.glyphs")).unwrap();
6902 let glyphs = font.glyphs;
6903
6904 assert_eq!(glyphs.get("A").unwrap().production_name, None);
6906
6907 assert_eq!(
6909 glyphs.get("idotless").unwrap().production_name,
6910 Some("uni0131".into())
6911 );
6912
6913 assert_eq!(
6916 glyphs.get("nbspace").unwrap().production_name,
6917 Some("uni00A0".into())
6918 );
6919 }
6920
6921 #[test]
6922 fn parse_axis_rules() {
6923 let raw = RawFont::load(&glyphs3_dir().join("AxisRules.glyphs")).unwrap();
6924 let space = &raw.glyphs[0];
6925 let axes = &space.layers[0].attributes.axis_rules;
6926 assert_eq!(
6927 axes,
6928 &[
6929 AxisRule {
6930 min: None,
6931 max: Some(OrderedFloat(400.0))
6932 },
6933 AxisRule {
6934 min: Some(OrderedFloat(100.0)),
6935 max: None,
6936 },
6937 AxisRule {
6938 min: None,
6939 max: None,
6940 },
6941 ]
6942 )
6943 }
6944
6945 #[test]
6946 fn parse_fractional_axis_rules() {
6947 let plist =
6948 r#"{ axisRules = ({ min = 39.6; max = 39.99; }, { min = 20; max = "60.5"; }); }"#;
6949 let attrs = LayerAttributes::parse_plist(plist).unwrap();
6950 assert_eq!(
6951 attrs.axis_rules,
6952 [
6953 AxisRule {
6954 min: Some(OrderedFloat(39.6)),
6955 max: Some(OrderedFloat(39.99)),
6956 },
6957 AxisRule {
6958 min: Some(OrderedFloat(20.0)),
6959 max: Some(OrderedFloat(60.5)),
6960 },
6961 ]
6962 )
6963 }
6964
6965 #[test]
6966 fn drop_axis_rules_if_no_assoc_master() {
6967 let font = Font::load(&glyphs3_dir().join("AxisRules.glyphs")).unwrap();
6969 let space = font.glyphs.get("space").unwrap();
6970 assert!(space.layers[0].attributes.axis_rules.is_empty());
6971 }
6972
6973 #[test]
6974 fn parse_v2_bracket_layers() {
6975 let font = Font::load(&glyphs2_dir().join("AxisRules.glyphs")).unwrap();
6976 let glyph = font.glyphs.get("space").unwrap();
6977 assert_eq!(
6978 glyph.bracket_layers[0].attributes.axis_rules,
6979 [
6980 AxisRule {
6981 min: None,
6982 max: Some(OrderedFloat(141.0))
6983 },
6984 AxisRule::default()
6985 ]
6986 );
6987 }
6988
6989 #[test]
6990 fn parse_layer_normal() {
6991 for name in &["[60]", "Light Extended [ 60 ]"] {
6992 let rule = AxisRule::from_layer_name(name);
6993 assert_eq!(
6994 rule,
6995 Some(AxisRule {
6996 min: Some(OrderedFloat(60.0)),
6997 max: None
6998 }),
6999 "{name}"
7000 )
7001 }
7002 }
7003
7004 #[test]
7005 fn parse_layer_reversed() {
7006 for name in &["]60]", "Light Extended ] 60 ]"] {
7007 let rule = AxisRule::from_layer_name(name);
7008 assert_eq!(
7009 rule,
7010 Some(AxisRule {
7011 min: None,
7012 max: Some(OrderedFloat(60.0))
7013 })
7014 )
7015 }
7016 }
7017
7018 #[test]
7019 fn parse_layer_fails() {
7020 for name in &["[hi]", "[45opsz]", "Medium [499‹wg]", "[39.6]"] {
7021 assert!(AxisRule::from_layer_name(name).is_none(), "{name}")
7022 }
7023 }
7024
7025 #[test]
7026 fn v2_bracket_layers() {
7027 let font = Font::load(&glyphs2_dir().join("WorkSans-minimal-bracketlayer.glyphs")).unwrap();
7028 let glyph = font.glyphs.get("colonsign").unwrap();
7029 assert_eq!(glyph.layers.len(), 3);
7030 assert_eq!(glyph.bracket_layers.len(), 3);
7031
7032 assert!(
7033 glyph
7034 .layers
7035 .iter()
7036 .all(|l| l.attributes.axis_rules.is_empty())
7037 );
7038 assert!(
7039 glyph
7040 .bracket_layers
7041 .iter()
7042 .all(|l| !l.attributes.axis_rules.is_empty())
7043 );
7044 }
7045
7046 fn raw_layer(
7047 layer_id: &str,
7048 master_id: Option<&str>,
7049 rules: &[(Option<f64>, Option<f64>)],
7050 ) -> RawLayer {
7051 RawLayer {
7052 name: format!("name-{layer_id}"),
7053 layer_id: layer_id.into(),
7054 associated_master_id: master_id.map(Into::into),
7055 attributes: LayerAttributes {
7056 axis_rules: rules
7057 .iter()
7058 .map(|(min, max)| AxisRule {
7059 min: min.map(OrderedFloat),
7060 max: max.map(OrderedFloat),
7061 })
7062 .collect(),
7063 ..Default::default()
7064 },
7065 ..Default::default()
7066 }
7067 }
7068
7069 fn layer_summary(layers: &[RawLayer]) -> Vec<(&str, Option<&str>, &str, usize)> {
7070 layers
7071 .iter()
7072 .map(|l| {
7073 (
7074 l.layer_id.as_str(),
7075 l.associated_master_id.as_deref(),
7076 l.name.as_str(),
7077 l.attributes.axis_rules.len(),
7078 )
7079 })
7080 .collect()
7081 }
7082
7083 #[rstest]
7086 #[case(300.0, [601, 500, 500, 607])]
7087 #[case(400.0, [602, 604, 605, 607])]
7088 #[case(500.0, [602, 604, 605, 500])]
7089 fn apply_alternate_layers(#[case] wght: f64, #[case] expected: [i32; 4]) {
7090 let mut font = Font::load_from_string(
7091 r#"{
7092.formatVersion = 3;
7093axes = ({ name = Weight; tag = wght; });
7094fontMaster = ({ id = m01; axesValues = (400); });
7095glyphs = (
7096{ glyphname = a; layers = (
7097{ layerId = m01; width = 500; },
7098{ associatedMasterId = m01; attr = { axisRules = ({ min = 300; max = 400; }); }; layerId = a1; width = 601; },
7099{ associatedMasterId = m01; attr = { axisRules = ({ min = 400; }); }; layerId = a2; width = 602; }
7100); },
7101{ glyphname = b; layers = (
7102{ layerId = m01; width = 500; },
7103{ associatedMasterId = m01; attr = { axisRules = ({ min = 350; }); }; layerId = b1; width = 603; },
7104{ associatedMasterId = m01; attr = { axisRules = ({ min = 380; }); }; layerId = b2; width = 604; }
7105); },
7106{ glyphname = c; layers = (
7107{ layerId = m01; width = 500; },
7108{ associatedMasterId = m01; attr = { axisRules = ({ min = 380; }); }; layerId = c2; width = 606; },
7109{ associatedMasterId = m01; attr = { axisRules = ({ min = 350; }); }; layerId = c1; width = 605; }
7110); },
7111{ glyphname = d; layers = (
7112{ layerId = m01; width = 500; },
7113{ associatedMasterId = m01; attr = { axisRules = ({ max = 400; }); }; layerId = d1; width = 607; }
7114); }
7115);
7116unitsPerEm = 1000;
7117}"#,
7118 )
7119 .unwrap();
7120 font.apply_alternate_layers(&[wght.into()]);
7121 for (name, width) in ["a", "b", "c", "d"].into_iter().zip(expected) {
7122 let glyph = &font.glyphs[name];
7123 assert!(glyph.bracket_layers.is_empty(), "{name}");
7124 assert_eq!(glyph.layers.len(), 1, "{name}");
7125 assert_eq!(glyph.layers[0].layer_id, "m01", "{name}");
7126 assert_eq!(glyph.layers[0].width, width as f64, "{name} at {wght}");
7127 }
7128 }
7129
7130 #[test]
7131 fn resolve_reverse_bracket_layers_swap_in_every_master() {
7132 let min_100 = [(Some(100.0), None)];
7133 let blank = [(None, None)];
7134 let mut layers = vec![
7135 raw_layer("M1", None, &min_100),
7136 raw_layer("B1", Some("M1"), &blank),
7137 raw_layer("X1", Some("M1"), &[(None, Some(50.0))]),
7138 raw_layer("M2", None, &min_100),
7139 raw_layer("B2", Some("M2"), &blank),
7140 ];
7141 resolve_reverse_bracket_layers(&mut layers);
7142 assert_eq!(
7143 layer_summary(&layers),
7144 [
7145 ("M1", None, "name-B1", 0),
7146 ("B1", Some("M1"), "name-M1", 1),
7147 ("X1", Some("M1"), "name-X1", 1),
7148 ("M2", None, "name-B2", 0),
7149 ("B2", Some("M2"), "name-M2", 1),
7150 ]
7151 );
7152 assert_eq!(
7153 layers[1].attributes.axis_rules[0].min,
7154 Some(OrderedFloat(100.0))
7155 );
7156 }
7157
7158 #[test]
7159 fn resolve_reverse_bracket_layers_swap_multiple_axes() {
7160 let mut layers = vec![
7161 raw_layer("M1", None, &[(Some(100.0), None), (None, None)]),
7162 raw_layer("B1", Some("M1"), &[(None, None), (None, None)]),
7163 ];
7164 resolve_reverse_bracket_layers(&mut layers);
7165 assert_eq!(
7166 layer_summary(&layers),
7167 [("M1", None, "name-B1", 0), ("B1", Some("M1"), "name-M1", 2)]
7168 );
7169 }
7170
7171 #[test]
7172 fn resolve_reverse_bracket_layers_ignore() {
7173 let min_100 = [(Some(100.0), None)];
7174 let blank = [(None, None)];
7175 for (mut layers, ignored) in [
7176 (
7178 vec![
7179 raw_layer("M1", None, &[]),
7180 raw_layer("B1", Some("M1"), &blank),
7181 ],
7182 vec!["B1"],
7183 ),
7184 (
7186 vec![
7187 raw_layer("B1", Some("M1"), &blank),
7188 raw_layer("M1", None, &blank),
7189 ],
7190 vec!["B1"],
7191 ),
7192 (
7194 vec![
7195 raw_layer("M1", None, &min_100),
7196 raw_layer("B1", Some("M1"), &blank),
7197 raw_layer("B2", Some("M1"), &blank),
7198 raw_layer("X1", Some("M1"), &[(None, Some(50.0))]),
7199 ],
7200 vec!["B1", "B2"],
7201 ),
7202 ] {
7203 let before = layers.clone();
7204 resolve_reverse_bracket_layers(&mut layers);
7205 for (layer, old) in layers.iter().zip(&before) {
7208 assert_eq!(layer.layer_id, old.layer_id);
7209 if ignored.contains(&layer.layer_id.as_str()) {
7210 assert!(layer.attributes.axis_rules.is_empty());
7211 assert!(layer.is_draft());
7212 } else {
7213 assert_eq!(layer, old);
7214 }
7215 }
7216 }
7217 }
7218
7219 #[test]
7220 fn is_blank_alternate() {
7221 let blank = [(None, None)];
7222 assert!(raw_layer("B1", Some("M1"), &blank).is_blank_alternate());
7223 assert!(raw_layer("B1", Some("M1"), &[(None, None), (None, None)]).is_blank_alternate());
7224
7225 let mut brace = raw_layer("B1", Some("M1"), &blank);
7226 brace.attributes.coordinates = vec![OrderedFloat(75.0)];
7227 let mut color = raw_layer("B1", Some("M1"), &blank);
7228 color.attributes.color = true;
7229 let mut smart = raw_layer("B1", Some("M1"), &blank);
7230 smart.part_selection.insert("Width".into(), 2);
7231 for (layer, why) in [
7232 (raw_layer("M1", None, &blank), "master"),
7233 (raw_layer("M1", Some("M1"), &blank), "master with own id"),
7234 (raw_layer("B1", Some("M1"), &[]), "no axis rules"),
7235 (raw_layer("B1", Some("M1"), &[(Some(100.0), None)]), "min"),
7236 (raw_layer("B1", Some("M1"), &[(None, Some(50.0))]), "max"),
7237 (
7238 raw_layer("B1", Some("M1"), &[(None, None), (Some(1.0), None)]),
7239 "bounded second axis",
7240 ),
7241 (brace, "brace"),
7242 (color, "color"),
7243 (smart, "smart component"),
7244 ] {
7245 assert!(!layer.is_blank_alternate(), "{why}");
7246 }
7247 }
7248
7249 #[test]
7250 fn resolve_reverse_bracket_layers_not_applicable() {
7251 let min_100 = [(Some(100.0), None)];
7252 let mut brace = raw_layer("B1", Some("M1"), &[(None, None)]);
7253 brace.attributes.coordinates = vec![OrderedFloat(75.0)];
7254 for mut layers in [
7255 vec![
7257 raw_layer("M1", None, &min_100),
7258 raw_layer("X1", Some("M1"), &[(None, Some(50.0))]),
7259 ],
7260 vec![
7262 raw_layer("M1", None, &min_100),
7263 raw_layer("X1", Some("M1"), &[]),
7264 ],
7265 vec![raw_layer("M1", None, &min_100), brace.clone()],
7267 ] {
7268 let before = layers.clone();
7269 resolve_reverse_bracket_layers(&mut layers);
7270 assert_eq!(layers, before);
7271 }
7272 }
7273
7274 #[test]
7275 fn v3_bracket_layers() {
7276 let font = Font::load(&glyphs3_dir().join("LibreFranklin-bracketlayer.glyphs")).unwrap();
7277 let glyph = font.glyphs.get("peso").unwrap();
7278 assert_eq!(glyph.layers.len(), 2);
7279 assert_eq!(glyph.bracket_layers.len(), 2);
7280
7281 assert!(
7282 glyph
7283 .layers
7284 .iter()
7285 .all(|l| l.attributes.axis_rules.is_empty())
7286 );
7287 assert!(
7288 glyph
7289 .bracket_layers
7290 .iter()
7291 .all(|l| !l.attributes.axis_rules.is_empty())
7292 );
7293 }
7294
7295 #[test]
7296 fn reads_version_defaults_and_explicit_zero() {
7297 for (version, major, minor) in [
7298 ("", 1, 0),
7299 ("versionMajor = 0;", 0, 0),
7300 ("versionMajor = 2; versionMinor = 15;", 2, 15),
7301 ] {
7302 let source = format!(
7303 "{{ .formatVersion = 3; fontMaster = ({{ id = m01; }}); unitsPerEm = 1000; {version} }}"
7304 );
7305 let font = Font::load_from_string(&source).unwrap();
7306 assert_eq!((font.version_major, font.version_minor), (major, minor));
7307 }
7308 }
7309
7310 #[test]
7311 fn reads_instance_export_metadata() {
7312 let font = Font::load_from_string(
7313 r#"{
7314.formatVersion = 3;
7315fontMaster = ({ id = m01; });
7316unitsPerEm = 1000;
7317instances = (
7318{ name = Regular; },
7319{ name = Bold; weightClass = 700; widthClass = 3; linkStyle = Book;
7320customParameters = (
7321{ name = vendorID; value = IGNR; disabled = 1; },
7322{ name = vendorID; value = EXPO; }
7323);
7324properties = ({ key = preferredFamilyNames; values = ({ language = dflt; value = Preferred; }); });
7325}
7326);
7327}"#,
7328 )
7329 .unwrap();
7330 let absent = &font.instances[0];
7331 assert_eq!(absent.weight_class, None);
7332 assert_eq!(absent.width_class, None);
7333 let export = &font.instances[1];
7334 assert_eq!(export.weight_class, Some(700));
7335 assert_eq!(export.width_class, Some(3));
7336 assert_eq!(export.custom_parameters.vendor_id.as_deref(), Some("EXPO"));
7337 assert_eq!(export.link_style.as_deref(), Some("Book"));
7338 assert!(!export.is_bold);
7339 assert_eq!(
7340 export.get_default_name("preferredFamilyNames"),
7341 Some("Preferred")
7342 );
7343 }
7344
7345 #[test]
7346 fn glyphs2_instance_naming_parameters_become_properties() {
7347 let font = Font::load_from_string(
7350 r#"{
7351familyName = Example;
7352fontMaster = ({ id = m01; });
7353unitsPerEm = 1000;
7354instances = ({ name = Regular; customParameters = (
7355{ name = familyName; value = Other; },
7356{ name = description; value = Described; },
7357{ name = vendorID; value = VNDR; },
7358{ name = versionString; value = "Version 2.0"; }
7359); });
7360}"#,
7361 )
7362 .unwrap();
7363 let instance = &font.instances[0];
7364 assert_eq!(instance.family_name(), Some("Other"));
7365 assert_eq!(instance.get_default_name("descriptions"), Some("Described"));
7366 assert_eq!(
7367 instance.custom_parameters.vendor_id.as_deref(),
7368 Some("VNDR")
7369 );
7370 assert_eq!(
7371 instance.custom_parameters.version_string.as_deref(),
7372 Some("Version 2.0")
7373 );
7374 }
7375
7376 #[test]
7377 fn glyphs2_width_class_custom_instance_parameter() {
7378 let font = Font::load_from_string(
7380 r#"{
7381familyName = Example;
7382fontMaster = ({ id = m01; });
7383unitsPerEm = 1000;
7384instances = ({ name = Condensed; widthClass = Expanded; customParameters = (
7385{ name = widthClass; value = 3; }
7386); });
7387}"#,
7388 )
7389 .unwrap();
7390 assert_eq!(font.instances[0].width_class, Some(3));
7391 }
7392
7393 #[test]
7394 fn glyphs2_weight_class_custom_instance_parameter() {
7395 let font = Font::load(&glyphs2_dir().join("WeightClassCustomParam.glyphs")).unwrap();
7398 let mapping = &font.axis_mappings.0.get("Weight").unwrap().0;
7399 assert_eq!(
7400 mapping.as_slice(),
7401 &[
7402 (OrderedFloat(200f64), OrderedFloat(42f64)),
7403 (OrderedFloat(700.), OrderedFloat(125.)),
7404 (OrderedFloat(1000.), OrderedFloat(208.))
7405 ]
7406 )
7407 }
7408
7409 #[test]
7410 fn glyphs2_avoid_adding_mapping_from_master() {
7411 let font = Font::load(&glyphs2_dir().join("master_missing_from_instances.glyphs")).unwrap();
7416
7417 let mapping = &font.axis_mappings.0.get("Weight").unwrap().0;
7418 assert_eq!(
7419 mapping.as_slice(),
7420 &[
7421 (OrderedFloat(100f64), OrderedFloat(20f64)),
7422 (OrderedFloat(300.), OrderedFloat(50.)),
7423 (OrderedFloat(400.), OrderedFloat(71.)),
7424 (OrderedFloat(700.), OrderedFloat(156.)),
7425 (OrderedFloat(900.), OrderedFloat(226.)),
7426 ]
7427 )
7428 }
7429
7430 #[test]
7431 fn does_not_truncate_axis_location() {
7432 let font = Font::load(&glyphs3_dir().join("WghtVar_AxisLocationFloat.glyphs")).unwrap();
7433 let mapping = &font.axis_mappings.0.get("Weight").unwrap().0;
7434
7435 assert_eq!(
7437 mapping.as_slice(),
7438 &[(OrderedFloat(400.75), OrderedFloat(0f64)),]
7439 )
7440 }
7441
7442 fn make_axis_location_params(values: &[(&str, i64)]) -> RawCustomParameterValue {
7443 RawCustomParameterValue {
7444 name: "Axis Location".into(),
7445 value: Plist::Array(
7446 values
7447 .iter()
7448 .map(|(name, loc)| {
7449 Plist::Dictionary(BTreeMap::from([
7450 ("Axis".into(), Plist::String(name.to_string())),
7451 ("Location".into(), Plist::Integer(*loc)),
7452 ]))
7453 })
7454 .collect(),
7455 ),
7456 disabled: None,
7457 }
7458 }
7459
7460 #[test]
7461 fn user_to_design_with_no_axes() {
7462 let _ = tracing_subscriber::fmt().with_test_writer().try_init();
7463 let mut myfont = RawFont {
7464 font_master: vec![RawFontMaster {
7465 custom_parameters: RawCustomParameters(vec![make_axis_location_params(&[(
7466 "Weight", 400,
7467 )])]),
7468 ..Default::default()
7469 }],
7470 ..Default::default()
7471 };
7472
7473 let _just_dont_crash_plz = user_to_design_from_axis_location(&mut myfont);
7474 }
7475
7476 #[test]
7477 fn user_to_design_with_unknown_axis_location() {
7478 let _ = tracing_subscriber::fmt().with_test_writer().try_init();
7479 let mut myfont = RawFont {
7480 axes: vec![Axis {
7481 name: "Weight".into(),
7482 tag: "wght".into(),
7483 hidden: None,
7484 }],
7485 font_master: vec![RawFontMaster {
7486 custom_parameters: RawCustomParameters(vec![make_axis_location_params(&[
7487 ("Weight", 400),
7488 ("Italic", 0),
7489 ])]),
7490 axes_values: vec![60.0.into()],
7491 ..Default::default()
7492 }],
7493 ..Default::default()
7494 };
7495
7496 let _just_dont_crash_plz = user_to_design_from_axis_location(&mut myfont);
7497 }
7498
7499 #[test]
7500 fn axis_location_string_value() {
7501 let raw = Plist::Dictionary(BTreeMap::from([
7502 ("Axis".into(), Plist::String("Weight".into())),
7503 ("Location".into(), Plist::String("42".into())),
7504 ]));
7505 assert_eq!(
7506 Some(AxisLocation {
7507 axis_name: "Weight".into(),
7508 location: 42.0.into(),
7509 }),
7510 raw.as_axis_location()
7511 );
7512 }
7513
7514 #[test]
7515 fn glyphs2_unicode_ranges() {
7516 let font = Font::load(&glyphs2_dir().join("UnicodeRanges.glyphs")).unwrap();
7517 assert_eq!(
7518 Some(BTreeSet::from([8])),
7519 font.custom_parameters.unicode_range_bits
7520 );
7521 }
7522
7523 #[test]
7524 fn parse_smart_components_v3() {
7525 let font = RawFont::load(&glyphs3_dir().join("SmartComponents.glyphs")).unwrap();
7528 let font = Font::try_from(font).unwrap();
7529 let shoulder = font.glyphs.get("_part.shoulder").unwrap();
7530 assert_eq!(
7531 shoulder.smart_component_axes,
7532 BTreeMap::from([
7533 ("shoulderWidth".into(), 0..=100),
7534 ("crotchDepth".into(), -100..=0)
7535 ])
7536 );
7537
7538 let m = font.glyphs.get("m").unwrap();
7539 let expected = [
7540 Component {
7541 name: "_part.stem".into(),
7542 ..Default::default()
7543 },
7544 Component {
7545 name: "_part.shoulder".into(),
7546 transform: Affine::translate((17., 0.)),
7547 smart_component_values: BTreeMap::from([
7548 ("crotchDepth".into(), -44.28304),
7549 ("shoulderWidth".into(), 28.78011),
7550 ]),
7551 ..Default::default()
7552 },
7553 Component {
7554 name: "_part.shoulder".into(),
7555 transform: Affine::translate((180., 1.)),
7556 smart_component_values: BTreeMap::from([
7557 ("crotchDepth".into(), -81.24796),
7558 ("shoulderWidth".into(), 0.0),
7559 ]),
7560 ..Default::default()
7561 },
7562 ];
7563 assert_eq!(
7564 m.layers[0].components().cloned().collect::<Vec<_>>(),
7565 expected
7566 );
7567 }
7568
7569 fn instantiate_shoulder_at(location: &[(&str, f64)]) -> Shape {
7570 fn make_component_values(inp: &[(&str, f64)]) -> BTreeMap<SmolStr, f64> {
7571 inp.iter().map(|(k, v)| (k.to_smolstr(), *v)).collect()
7572 }
7573 let font = RawFont::load(&glyphs3_dir().join("SmartComponents.glyphs")).unwrap();
7574 let font = Font::try_from(font).unwrap();
7575
7576 let smart_comp = font.glyphs.get("_part.shoulder").unwrap();
7577 let default_pos = Component {
7578 name: "_part.shoulder".into(),
7579 smart_component_values: make_component_values(location),
7580 ..Default::default()
7581 };
7582
7583 let instance =
7584 smart_components::instantiate_for_layer("m01", &default_pos, smart_comp).unwrap();
7585 assert_eq!(instance.shapes.len(), 1);
7586 instance.shapes[0].clone()
7587 }
7588
7589 #[test]
7590 fn instantiate_smart_component_at_default() {
7591 let font = Font::load(&glyphs3_dir().join("SmartComponents.glyphs")).unwrap();
7592 let smart_comp = font.glyphs.get("_part.shoulder").unwrap();
7593 let shape = instantiate_shoulder_at(&[("shoulderWidth", 100.), ("crotchDepth", 0.)]);
7594
7595 assert_eq!(smart_comp.layers[1].layer_id, "m01");
7596 assert_eq!(shape, smart_comp.layers[1].shapes[0]);
7597 }
7598
7599 #[test]
7601 fn instantiate_smart_component_at_default_empty_values() {
7602 let font = Font::load(&glyphs3_dir().join("SmartComponents.glyphs")).unwrap();
7603 let smart_comp = font.glyphs.get("_part.shoulder").unwrap();
7604
7605 let component = Component {
7608 name: "_part.shoulder".into(),
7609 smart_component_values: BTreeMap::new(),
7610 ..Default::default()
7611 };
7612
7613 let instance =
7614 smart_components::instantiate_for_layer("m01", &component, smart_comp).unwrap();
7615 assert_eq!(instance.shapes.len(), 1);
7616
7617 let shape_with_explicit_defaults =
7619 instantiate_shoulder_at(&[("shoulderWidth", 100.), ("crotchDepth", 0.)]);
7620 assert_eq!(instance.shapes[0], shape_with_explicit_defaults);
7621 }
7622
7623 fn missing_poles_font() -> Font {
7624 Font::load_raw(glyphs2_dir().join("SmartComponentMissingPoles.glyphs")).unwrap()
7626 }
7627
7628 fn missing_poles_font_with_upper() -> Font {
7629 let mut font = missing_poles_font();
7632 let part = font.glyphs.get_mut("_part").unwrap();
7633 let mut upper = part.layers[1].clone();
7634 upper.layer_id = "upper".into();
7635 let Shape::Path(path) = &mut upper.shapes[0] else {
7636 panic!("expected path")
7637 };
7638 for node in &mut path.nodes {
7639 node.pt.x += 400.0;
7640 }
7641 upper.smart_component_positions = [("U".into(), AxisPole::Max)].into_iter().collect();
7642 part.layers.push(upper);
7643 font
7644 }
7645
7646 fn assert_smart_component_bounds(
7647 mut font: Font,
7648 values: &[(&str, f64)],
7649 expected_bounds: Rect,
7650 ) {
7651 let Shape::Component(component) =
7652 &mut font.glyphs.get_mut("a").unwrap().layers[0].shapes[0]
7653 else {
7654 panic!("expected component")
7655 };
7656 component.smart_component_values = values
7657 .iter()
7658 .map(|(name, value)| ((*name).into(), *value))
7659 .collect();
7660 font.preprocess().unwrap();
7661 let layer = &font.glyphs.get("a").unwrap().layers[0];
7662 assert_eq!(layer.shapes.len(), 1);
7663 let path = layer.shapes[0]
7664 .as_path()
7665 .expect("decomposed smart component");
7666 assert_eq!(path.bbox(), Some(expected_bounds));
7667 }
7668
7669 #[test]
7670 fn missing_default_pole_uses_top() {
7671 assert_smart_component_bounds(
7675 missing_poles_font(),
7676 &[("X", 30.0)],
7677 Rect::new(200.0, 0.0, 220.0, 20.0),
7678 );
7679 }
7680
7681 #[test]
7682 fn missing_default_pole_with_only_top_layers() {
7683 let mut font = missing_poles_font();
7686 font.glyphs.get_mut("_part").unwrap().layers[1].smart_component_positions =
7687 [("X".into(), AxisPole::Max), ("U".into(), AxisPole::Max)]
7688 .into_iter()
7689 .collect();
7690 assert_smart_component_bounds(
7691 font,
7692 &[("X", 30.0), ("U", 50.0)],
7693 Rect::new(200.0, 0.0, 220.0, 20.0),
7694 );
7695 }
7696
7697 #[rstest]
7698 #[case::bottom(AxisPole::Min, AxisPole::Max)]
7699 #[case::top(AxisPole::Max, AxisPole::Min)]
7700 fn missing_alternate_pole_inherits_default(
7701 #[case] base_pole: AxisPole,
7702 #[case] alternate_pole: AxisPole,
7703 ) {
7704 let mut font = missing_poles_font_with_upper();
7708 let part = font.glyphs.get_mut("_part").unwrap();
7709 part.layers[0]
7710 .smart_component_positions
7711 .insert("X".into(), base_pole);
7712 part.layers[1]
7713 .smart_component_positions
7714 .insert("X".into(), alternate_pole);
7715 assert_smart_component_bounds(
7716 font,
7717 &[("X", 30.0), ("U", 50.0)],
7718 Rect::new(500.0, 0.0, 520.0, 20.0),
7719 );
7720 }
7721
7722 #[test]
7723 fn empty_default_mapping_participates() {
7724 let mut font = missing_poles_font_with_upper();
7728 let part = font.glyphs.get_mut("_part").unwrap();
7729 part.layers[0].smart_component_positions.clear();
7730 part.layers[1].smart_component_positions =
7731 [("X".into(), AxisPole::Min)].into_iter().collect();
7732 part.layers[2].smart_component_positions =
7733 [("U".into(), AxisPole::Min)].into_iter().collect();
7734 assert_smart_component_bounds(
7735 font,
7736 &[("X", 80.0), ("U", 50.0)],
7737 Rect::new(400.0, 0.0, 420.0, 20.0),
7738 );
7739 }
7740
7741 #[test]
7742 fn instantiate_smart_component_at_not_default() {
7743 let Shape::Path(path) =
7744 instantiate_shoulder_at(&[("shoulderWidth", 0.), ("crotchDepth", -100.)])
7745 else {
7746 panic!("wat")
7747 };
7748 assert_eq!(path.nodes.last().unwrap().pt.round().y, 267.0);
7750 assert_eq!(
7752 path.nodes.iter().map(|nd| nd.pt.x.round() as i64).max(),
7753 Some(335)
7754 );
7755 }
7756
7757 impl crate::Path {
7758 fn bbox(&self) -> Option<Rect> {
7759 let points = self.to_points();
7760 let (head, rest) = points.as_slice().split_first()?;
7761 Some(
7762 rest.iter()
7763 .fold(Rect::ZERO.with_origin(*head), |bbox, pt| bbox.union_pt(*pt)),
7764 )
7765 }
7766 }
7767
7768 #[test]
7769 fn smart_component_v2() {
7770 let font = Font::load(&glyphs2_dir().join("SmartComponent.glyphs")).unwrap();
7771
7772 let glyph = font.glyphs.get("composite").unwrap();
7773 let shapes = &glyph.layers[0].shapes;
7774 let paths = shapes
7775 .iter()
7776 .map(|s| s.as_path().unwrap().to_points())
7777 .collect::<Vec<_>>();
7778 let expected1 = [(9., 405.), (9., 300.), (276., 300.), (276.0, 405.0)]
7779 .into_iter()
7780 .map(Point::from)
7781 .collect::<Vec<_>>();
7782
7783 let expected2 = [(9., 405.), (9., 383.), (276., 383.), (276.0, 405.0)]
7784 .into_iter()
7785 .map(|pt| Point::from(pt) + Vec2::new(100., 100.))
7786 .collect::<Vec<_>>();
7787
7788 assert_eq!(paths, [expected1, expected2]);
7789 }
7790
7791 #[test]
7795 fn corner_after_smart_component() {
7796 let mut font = Font::load_raw(glyphs3_dir().join("SmartComponents.glyphs")).unwrap();
7797 let line = |x, y| Node {
7798 pt: Point::new(x, y),
7799 node_type: NodeType::Line,
7800 };
7801 let corner = Layer {
7802 layer_id: "m01".into(),
7803 shapes: vec![Shape::Path(crate::Path {
7804 nodes: vec![line(0., 20.), line(-20., 20.), line(-20., 0.)],
7805 ..Default::default()
7806 })],
7807 ..Default::default()
7808 };
7809 font.glyphs.insert(
7810 "_corner.test".into(),
7811 Glyph {
7812 name: "_corner.test".into(),
7813 layers: vec![corner],
7814 ..Default::default()
7815 },
7816 );
7817 let layer = &mut font.glyphs.get_mut("n").unwrap().layers[0];
7818 layer.shapes.push(Shape::Path(crate::Path {
7819 closed: true,
7820 nodes: vec![
7821 line(400., 0.),
7822 line(500., 0.),
7823 line(500., 100.),
7824 line(400., 100.),
7825 ],
7826 ..Default::default()
7827 }));
7828 layer.hints.push(Hint {
7829 type_: HintType::Corner,
7830 name: "_corner.test".into(),
7831 shape_index: 2,
7832 node_index: 0,
7833 scale: Scale::default(),
7834 alignment: Alignment::OutStroke,
7835 });
7836 font.preprocess().unwrap();
7837
7838 let lengths: Vec<_> = font.glyphs["n"].layers[0]
7839 .shapes
7840 .iter()
7841 .map(|shape| shape.as_path().unwrap().nodes.len())
7842 .collect();
7843 assert_eq!(lengths, [11, 6, 20]);
7844 }
7845
7846 #[test]
7847 fn nested_smart_components() {
7848 let font = Font::load(&glyphs2_dir().join("NestedSmartComponent.glyphs")).unwrap();
7851 let glyph = font.glyphs.get("w").unwrap();
7852 let shapes = &glyph.layers[0].shapes;
7853 let rects = shapes
7854 .iter()
7855 .map(|s| s.as_path().unwrap().bbox().unwrap())
7856 .collect::<Vec<_>>();
7857 assert_eq!(
7858 rects,
7859 [
7860 Rect::new(0., 200., 400., 400.),
7861 Rect::new(0., 0., 400., 100.),
7862 Rect::new(500., 200., 550., 400.),
7863 Rect::new(500., 0., 550., 100.),
7864 ]
7865 );
7866 }
7867
7868 #[test]
7872 fn smart_component_preserves_explicit_anchors() {
7873 let font = Font::load(&glyphs3_dir().join("SmartComponentExplicitAnchors.glyphs")).unwrap();
7874 let glyph = font.glyphs.get("composite").unwrap();
7875 let layer = &glyph.layers[0];
7876
7877 let anchor_map: std::collections::HashMap<&str, (f64, f64)> = layer
7879 .anchors
7880 .iter()
7881 .map(|a| (a.name.as_str(), (a.pos.x, a.pos.y)))
7882 .collect();
7883
7884 assert_eq!(
7887 anchor_map.get("top"),
7888 Some(&(300.0, 700.0)),
7889 "explicit 'top' anchor was overridden by smart component"
7890 );
7891 assert_eq!(
7892 anchor_map.get("bottom"),
7893 Some(&(300.0, 0.0)),
7894 "explicit 'bottom' anchor was overridden by smart component"
7895 );
7896 }
7897
7898 #[test]
7901 fn smart_component_preserves_underscore_anchors() {
7902 let font =
7903 Font::load(&glyphs3_dir().join("SmartComponentUnderscoreAnchors.glyphs")).unwrap();
7904 let glyph = font.glyphs.get("knmAU").unwrap();
7905 let layer = &glyph.layers[0];
7906 let anchor_map: std::collections::HashMap<&str, (f64, f64)> = layer
7907 .anchors
7908 .iter()
7909 .map(|a| (a.name.as_str(), (a.pos.x, a.pos.y)))
7910 .collect();
7911
7912 assert_eq!(
7913 anchor_map.get("_headline"),
7914 Some(&(135.0, 383.0)),
7915 "_headline anchor was dropped during smart component instantiation"
7916 );
7917 assert_eq!(
7918 anchor_map.get("top"),
7919 Some(&(250.0, 600.0)),
7920 "top anchor was dropped during smart component instantiation"
7921 );
7922 }
7923
7924 #[test]
7925 fn parse_basic_corner_component_hint() {
7926 let font = Font::load_raw(glyphs3_dir().join("CornerComponents.glyphs")).unwrap();
7927
7928 let glyph = font.glyphs.get("aa_simple_angleinstroke").unwrap();
7929 let hints = &glyph.layers[0].hints;
7930
7931 assert_eq!(hints.len(), 1);
7932 assert_eq!(hints[0].name, "_corner.one");
7933 assert_eq!(hints[0].shape_index, 0);
7934 assert_eq!(hints[0].node_index, 0);
7935 assert_eq!(hints[0].type_, HintType::Corner);
7936 assert_eq!(hints[0].scale, Default::default());
7937 assert_eq!(hints[0].alignment, Alignment::OutStroke);
7938 }
7939
7940 #[test]
7941 fn parse_corner_component_hint_with_scale() {
7942 let font = Font::load_raw(glyphs3_dir().join("CornerComponents.glyphs")).unwrap();
7943
7944 let glyph = font.glyphs.get("ac_scale").unwrap();
7945 let hints = &glyph.layers[0].hints;
7946
7947 assert_eq!(hints.len(), 1);
7948 assert_eq!(hints[0].name, "_corner.one");
7949 assert_eq!(hints[0].shape_index, 0);
7950 assert_eq!(hints[0].node_index, 0);
7951 assert_eq!(hints[0].type_, HintType::Corner);
7952 assert_eq!(hints[0].scale, (Scale::new(1.2, 1.5)));
7953 assert_eq!(hints[0].alignment, Alignment::OutStroke);
7954 }
7955
7956 #[test]
7957 fn parse_corner_component_hint_with_alignment() {
7958 let font = Font::load_raw(glyphs3_dir().join("CornerComponents.glyphs")).unwrap();
7959
7960 let glyph = font.glyphs.get("aj_right_alignment").unwrap();
7961 let hints = &glyph.layers[0].hints;
7962
7963 assert_eq!(hints.len(), 1);
7964 assert_eq!(hints[0].name, "_corner.one");
7965 assert_eq!(hints[0].shape_index, 0);
7966 assert_eq!(hints[0].node_index, 1);
7967 assert_eq!(hints[0].type_, HintType::Corner);
7968 assert_eq!(hints[0].scale, Default::default());
7969 assert_eq!(hints[0].alignment, Alignment::InStroke);
7970 }
7971
7972 #[test]
7973 fn parse_v2_corner_component() {
7974 let hint_plist = r#"
7975{
7976origin = "{0, 0}";
7977scale = "{0.7, 1}";
7978type = Corner;
7979name = _corner.hi;
7980}
7981 "#;
7982
7983 let hint = RawHint::parse_plist(hint_plist).unwrap().to_hint().unwrap();
7984 assert_eq!(hint.scale.x, 0.7);
7985 assert_eq!(hint.scale.y, 1.0);
7986 }
7987
7988 #[test]
7989 fn link_metrics_with_first_master_parsing() {
7990 let font = Font::load(&glyphs3_dir().join("LinkMetricsWithFirstMaster.glyphs")).unwrap();
7991 assert_eq!(font.masters.len(), 2);
7992
7993 assert_eq!(
7995 font.masters[0]
7996 .custom_parameters
7997 .link_metrics_with_first_master,
7998 None
7999 );
8000 assert_eq!(
8002 font.masters[1]
8003 .custom_parameters
8004 .link_metrics_with_first_master,
8005 Some(true)
8006 );
8007 }
8008
8009 #[test]
8010 fn link_metrics_with_master_parsing() {
8011 let font = Font::load(&glyphs3_dir().join("LinkMetricsWithMaster.glyphs")).unwrap();
8012 assert_eq!(font.masters.len(), 3);
8013
8014 assert_eq!(
8016 font.masters[0].custom_parameters.link_metrics_with_master,
8017 None
8018 );
8019 assert_eq!(
8020 font.masters[1].custom_parameters.link_metrics_with_master,
8021 None
8022 );
8023 let link_target = font.masters[2]
8025 .custom_parameters
8026 .link_metrics_with_master
8027 .as_deref();
8028 assert_eq!(link_target, Some("m02"));
8029 assert_eq!(font.masters[1].id, "m02");
8030 assert_eq!(font.masters[1].name, "Bold");
8031 }
8032
8033 #[test]
8034 fn retain_master() {
8035 let font = Font::load(&glyphs3_dir().join("BagOfStatics.glyphs")).unwrap();
8036 let mut unknown = font.clone();
8037 assert!(!unknown.retain_master("nope"));
8038 assert_eq!(unknown, font);
8039
8040 for kept in ["m01", "m02"] {
8041 let mut reduced = font.clone();
8042 assert!(reduced.retain_master(kept));
8043 assert_eq!(
8044 reduced
8045 .masters
8046 .iter()
8047 .map(|m| m.id.as_str())
8048 .collect::<Vec<_>>(),
8049 [kept]
8050 );
8051 assert_eq!(reduced.default_master_idx, 0);
8052 let layers: Vec<_> = reduced.glyphs["a"]
8054 .layers
8055 .iter()
8056 .map(|l| l.layer_id.as_str())
8057 .collect();
8058 assert_eq!(layers, [kept]);
8059 assert_eq!(reduced.kerning_ltr.keys().collect::<Vec<_>>(), [kept]);
8060 assert_eq!(reduced.axes, font.axes);
8061 assert_eq!(reduced.instances, font.instances);
8062 }
8063 }
8064
8065 #[test]
8066 fn metrics_source_id_with_first_master() {
8067 let font = Font::load(&glyphs3_dir().join("LinkMetricsWithFirstMaster.glyphs")).unwrap();
8068
8069 assert_eq!(font.masters[0].metrics_source_id, None);
8071 assert_eq!(
8073 font.masters[1].metrics_source_id.as_ref(),
8074 Some(&font.masters[0].id)
8075 );
8076 }
8077
8078 #[test]
8079 fn metrics_source_id_with_master_by_id() {
8080 let font = Font::load(&glyphs3_dir().join("LinkMetricsWithMaster.glyphs")).unwrap();
8081
8082 assert_eq!(font.masters[0].metrics_source_id, None);
8083 assert_eq!(font.masters[1].metrics_source_id, None);
8084 assert_eq!(
8086 font.masters[2].metrics_source_id.as_ref(),
8087 Some(&font.masters[1].id)
8088 );
8089 }
8090
8091 #[test]
8092 fn metrics_source_id_with_master_by_name() {
8093 let font = Font::load(&glyphs2_dir().join("LinkMetricsWithMasterByName.glyphs")).unwrap();
8095
8096 assert_eq!(font.masters[0].metrics_source_id, None);
8097 assert_eq!(font.masters[1].metrics_source_id, None);
8098 assert_eq!(
8100 font.masters[2]
8101 .custom_parameters
8102 .link_metrics_with_master
8103 .as_deref(),
8104 Some("Bold")
8105 );
8106 assert_eq!(
8107 font.masters[2].metrics_source_id.as_ref(),
8108 Some(&font.masters[1].id)
8109 );
8110 }
8111
8112 #[test]
8113 fn metrics_source_id_with_missing_master() {
8114 let font = Font::load(&glyphs3_dir().join("LinkMetricsWithMissingMaster.glyphs")).unwrap();
8115
8116 assert_eq!(
8118 font.masters[1]
8119 .custom_parameters
8120 .link_metrics_with_master
8121 .as_deref(),
8122 Some("NonExistent")
8123 );
8124 assert_eq!(font.masters[1].metrics_source_id, None);
8126 }
8127
8128 #[test]
8129 fn duplicate_custom_params_uses_first_value() {
8130 let raw_params = RawCustomParameters(vec![
8134 RawCustomParameterValue {
8135 name: "Link Metrics With Master".into(),
8136 value: Plist::String("first_master_id".into()),
8137 disabled: None,
8138 },
8139 RawCustomParameterValue {
8140 name: "Link Metrics With Master".into(),
8141 value: Plist::String("second_master_id".into()),
8142 disabled: None,
8143 },
8144 ]);
8145
8146 let params = raw_params.to_custom_params().unwrap();
8147
8148 assert_eq!(
8150 params.link_metrics_with_master.as_deref(),
8151 Some("first_master_id")
8152 );
8153 }
8154
8155 #[test]
8157 fn parsing_name_table_entries() {
8158 assert_eq!(
8159 NameTableEntry::from_str("1024; FOO; BAZ").unwrap(),
8160 NameTableEntry {
8161 name_id: 1024,
8162 platform_id: 3,
8163 encoding_id: 1,
8164 lang_id: 0x409,
8165 value: "FOO; BAZ".into()
8166 }
8167 );
8168 assert_eq!(
8169 NameTableEntry::from_str("2048 1; FOO").unwrap(),
8170 NameTableEntry {
8171 name_id: 2048,
8172 platform_id: 1,
8173 encoding_id: 0,
8174 lang_id: 0,
8175 value: "FOO".into()
8176 }
8177 );
8178 assert_eq!(
8179 NameTableEntry::from_str("4096 1 2; FOO").unwrap(),
8180 NameTableEntry {
8181 name_id: 4096,
8182 platform_id: 1,
8183 encoding_id: 2,
8184 lang_id: 0,
8185 value: "FOO".into()
8186 }
8187 );
8188 assert_eq!(
8189 NameTableEntry::from_str("8192 1 2 3; FOO").unwrap(),
8190 NameTableEntry {
8191 name_id: 8192,
8192 platform_id: 1,
8193 encoding_id: 2,
8194 lang_id: 3,
8195 value: "FOO".into()
8196 }
8197 );
8198 assert_eq!(
8199 NameTableEntry::from_str("27 3 1 0x404; HEX").unwrap(),
8200 NameTableEntry {
8201 name_id: 27,
8202 platform_id: 3,
8203 encoding_id: 1,
8204 lang_id: 0x404,
8205 value: "HEX".into()
8206 }
8207 )
8208 }
8221
8222 #[test]
8223 fn parse_color_palette_numeric() {
8224 let plist = r#"{ colorPalette = 2; }"#;
8225 let attrs = LayerAttributes::parse_plist(plist).unwrap();
8226 assert_eq!(attrs.color_palette, Some(2));
8227 }
8228
8229 #[test]
8230 fn parse_color_palette_star() {
8231 let plist = r#"{ colorPalette = "*"; }"#;
8232 let attrs = LayerAttributes::parse_plist(plist).unwrap();
8233 assert_eq!(attrs.color_palette, Some(0xFFFF));
8234 }
8235
8236 #[test]
8237 fn ensure_lang_map_is_sorted() {
8238 assert!(GLYPHS_TO_OPENTYPE_LANGUAGE_ID.is_sorted())
8239 }
8240
8241 #[test]
8242 fn codepage_bits_from_integers() {
8243 let plist = Plist::Array(vec![Plist::Integer(1252), Plist::Integer(1258)]);
8244 assert_eq!(
8245 plist.as_codepage_bits(),
8246 Some(BTreeSet::from([0, 8])) );
8248 }
8249
8250 #[test]
8251 fn codepage_bits_from_strings() {
8252 let plist = Plist::Array(vec![
8254 Plist::String("1252".into()),
8255 Plist::String("1258".into()),
8256 Plist::String("bit 29".into()),
8257 ]);
8258 assert_eq!(plist.as_codepage_bits(), Some(BTreeSet::from([0, 8, 29])));
8259 }
8260
8261 #[test]
8262 fn read_codepage_range_bits_from_file() {
8263 let font = Font::load(&glyphs2_dir().join("WghtVar_OS2.glyphs")).unwrap();
8265 assert_eq!(
8266 font.custom_parameters.codepage_range_bits,
8267 Some(BTreeSet::from([0, 1, 19, 63]))
8268 );
8269 }
8270
8271 #[test]
8272 fn v2_instance_interpolation_custom_third_axis() {
8273 let font =
8277 Font::load(&glyphs2_dir().join("ThreeAxisWithInterpolationCustom.glyphs")).unwrap();
8278 assert_eq!(
8279 vec![
8280 (
8281 "Regular Caption",
8282 vec![("Weight", 400.0), ("Width", 100.0), ("Optical Size", 12.0)]
8283 ),
8284 (
8285 "Bold Display",
8286 vec![("Weight", 700.0), ("Width", 100.0), ("Optical Size", 72.0)]
8287 ),
8288 ],
8289 font.instances
8290 .iter()
8291 .map(|inst| (
8292 inst.name.as_str(),
8293 font.axes
8294 .iter()
8295 .zip(&inst.axes_values)
8296 .map(|(a, v)| (a.name.as_str(), v.0))
8297 .collect::<Vec<_>>()
8298 ))
8299 .collect::<Vec<_>>()
8300 );
8301 }
8302
8303 #[test]
8304 fn retains_font_level_user_data() {
8305 let font = Font::load_from_string(
8308 r#"{
8309.formatVersion = 3;
8310fontMaster = (
8311{
8312id = "m01";
8313}
8314);
8315unitsPerEm = 1000;
8316userData = {
8317com.github.googlei18n.ufo2ft.featureWriters = (
8318{
8319class = KernFeatureWriter;
8320options = {
8321mode = append;
8322};
8323}
8324);
8325};
8326}"#,
8327 )
8328 .unwrap();
8329 let writers = font
8330 .user_data
8331 .get("com.github.googlei18n.ufo2ft.featureWriters")
8332 .and_then(Plist::as_array)
8333 .expect("featureWriters retained as an array");
8334 assert_eq!(writers.len(), 1);
8335 assert_eq!(
8336 writers[0].get("class").and_then(Plist::as_str),
8337 Some("KernFeatureWriter")
8338 );
8339 }
8340}