norad 0.18.4

Read and write Unified Font Object files.
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
//! Reading and writing designspace files.

#![deny(rustdoc::broken_intra_doc_links)]

use serde::{Deserialize, Serialize};
use std::{fs::File, io::BufReader, path::Path};

use plist::Dictionary;

use crate::error::{DesignSpaceLoadError, DesignSpaceSaveError};
use crate::serde_xml_plist as serde_plist;
use crate::Name;

/// A [designspace].
///
/// [designspace]: https://fonttools.readthedocs.io/en/latest/designspaceLib/index.html
#[derive(Clone, Debug, Default, PartialEq, Serialize, Deserialize)]
#[serde(from = "RawDesignSpaceDocument", into = "RawDesignSpaceDocument")]
pub struct DesignSpaceDocument {
    /// Design space format version.
    pub format: f32,
    /// One or more axes.
    pub axes: Vec<Axis>,
    /// Optional avar2-style axis mappings.
    pub axis_mappings: Option<AxisMappings>,
    /// One or more rules.
    pub rules: Rules,
    /// One or more sources.
    pub sources: Vec<Source>,
    /// One or more instances.
    pub instances: Vec<Instance>,
    /// Additional arbitrary user data
    pub lib: Dictionary,
}

/// An [axis].
///
/// [axis]: https://fonttools.readthedocs.io/en/latest/designspaceLib/xml.html#axis-element
#[derive(Clone, Debug, Default, PartialEq, Serialize, Deserialize)]
#[serde(rename = "axis")]
pub struct Axis {
    /// Name of the axis that is used in the location elements.
    #[serde(rename = "@name")]
    pub name: String,
    /// 4 letters. Some axis tags are registered in the OpenType Specification.
    #[serde(rename = "@tag")]
    pub tag: String,
    /// The default value for this axis, in user space coordinates.
    #[serde(rename = "@default")]
    pub default: f32,
    /// Records whether this axis needs to be hidden in interfaces.
    #[serde(default, rename = "@hidden", skip_serializing_if = "is_false")]
    pub hidden: bool,
    /// The minimum value for a continuous axis, in user space coordinates.
    #[serde(rename = "@minimum", skip_serializing_if = "Option::is_none")]
    pub minimum: Option<f32>,
    /// The maximum value for a continuous axis, in user space coordinates.
    #[serde(rename = "@maximum", skip_serializing_if = "Option::is_none")]
    pub maximum: Option<f32>,
    /// The possible values for a discrete axis, in user space coordinates.
    #[serde(rename = "@values", skip_serializing_if = "Option::is_none")]
    pub values: Option<Vec<f32>>,
    /// Mapping between user space coordinates and design space coordinates.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub map: Option<Vec<AxisMapping>>,
    /// Localised UI strings for the axis name.
    #[serde(rename = "labelname", default, skip_serializing_if = "Vec::is_empty")]
    pub label_names: Vec<LocalizedString>,
}

fn is_false(value: &bool) -> bool {
    !(*value)
}

/// Localised string for UI use.
#[derive(Clone, Debug, Default, PartialEq, Serialize, Deserialize)]
pub struct LocalizedString {
    /// Language tag, e.g. `"fa-IR"`.
    // `quick-xml` strips the `xml:` prefix, so the incoming attribute is just
    // `lang`.  We keep `xml:lang` as the primary name used when serializing, but
    // add an alias to `lang` to be used when deserializing.
    #[serde(rename = "@xml:lang", alias = "@lang")]
    pub language: String,
    /// The label name
    #[serde(rename = "$text")]
    pub string: String,
}

/// Maps one input value (user space coord) to one output value (design space coord).
#[derive(Copy, Clone, Debug, Default, PartialEq, Serialize, Deserialize)]
#[serde(rename = "map")]
pub struct AxisMapping {
    /// user space coordinate
    #[serde(rename = "@input")]
    pub input: f32,
    /// designspace coordinate
    #[serde(rename = "@output")]
    pub output: f32,
}

/// A group of [axis mappings] for avar2-style mappings.
///
/// [axis mappings]: https://fonttools.readthedocs.io/en/latest/designspaceLib/xml.html#mappings-element
#[derive(Clone, Debug, Default, PartialEq, Serialize, Deserialize)]
pub struct AxisMappings {
    /// Optional description of this mappings group.
    #[serde(rename = "@description", skip_serializing_if = "Option::is_none")]
    pub description: Option<String>,
    /// The individual axis mappings.
    #[serde(default, rename = "mapping")]
    pub mappings: Vec<AxisMappingEntry>,
}

impl AxisMappings {
    /// Returns `true` if there are no mappings.
    pub fn is_empty(&self) -> bool {
        self.mappings.is_empty()
    }
}

/// A single axis mapping entry with input and output locations.
#[derive(Clone, Debug, Default, PartialEq, Serialize, Deserialize)]
pub struct AxisMappingEntry {
    /// Optional description of this mapping.
    #[serde(rename = "@description", skip_serializing_if = "Option::is_none")]
    pub description: Option<String>,
    /// The input location in designspace coordinates.
    #[serde(with = "serde_impls::location")]
    pub input: Vec<Dimension>,
    /// The output location in designspace coordinates.
    #[serde(with = "serde_impls::location")]
    pub output: Vec<Dimension>,
}

/// Describes the substitution [rules] of the Designspace.
///
/// [rules]: https://fonttools.readthedocs.io/en/latest/designspaceLib/xml.html#rules-element
#[derive(Clone, Debug, Default, PartialEq, Serialize, Deserialize)]
pub struct Rules {
    /// Indicates whether substitution rules should be applied before or after
    /// other glyph substitution features.
    #[serde(default, rename = "@processing")]
    pub processing: RuleProcessing,
    /// The rules.
    #[serde(default, rename = "rule")]
    pub rules: Vec<Rule>,
}

/// Indicates whether substitution rules should be applied before or after other
/// glyph substitution features.
#[derive(Copy, Clone, Debug, Default, PartialEq, Serialize, Deserialize)]
#[serde(rename_all = "lowercase")]
pub enum RuleProcessing {
    /// Apply before other substitution features.
    #[default]
    First,
    /// Apply after other substitution features.
    Last,
}

/// Describes a single set of substitution rules.
///
/// Supports both modern `<conditionset>` wrappers and legacy standalone
/// `<condition>` elements directly inside `<rule>`. Bare conditions are
/// collected into a single implicit condition set, matching fonttools behavior.
#[derive(Clone, Debug, Default, PartialEq, Serialize, Deserialize)]
#[serde(from = "RawRule", into = "RawRule")]
pub struct Rule {
    /// Name of the rule.
    pub name: Option<String>,
    /// Condition sets. If any condition set is true or is empty,
    /// the rule is applied.
    pub condition_sets: Vec<ConditionSet>,
    /// Substitutions (in, out).
    pub substitutions: Vec<Substitution>,
}

/// Internal deserialization helper that captures both `<conditionset>` and
/// bare `<condition>` children of a `<rule>` element.
#[derive(Clone, Debug, Default, PartialEq, Serialize, Deserialize)]
struct RawRule {
    #[serde(rename = "@name", skip_serializing_if = "Option::is_none")]
    name: Option<String>,
    #[serde(rename = "conditionset", default, skip_serializing_if = "Vec::is_empty")]
    condition_sets: Vec<ConditionSet>,
    /// Legacy bare conditions outside a `<conditionset>`.
    #[serde(rename = "condition", default, skip_serializing_if = "Vec::is_empty")]
    conditions: Vec<Condition>,
    #[serde(rename = "sub", default, skip_serializing_if = "Vec::is_empty")]
    substitutions: Vec<Substitution>,
}

impl From<RawRule> for Rule {
    fn from(raw: RawRule) -> Self {
        let mut condition_sets = raw.condition_sets;
        // Legacy format: bare <condition> elements outside <conditionset>
        // are wrapped into a single implicit condition set.
        if !raw.conditions.is_empty() {
            condition_sets.push(ConditionSet { conditions: raw.conditions });
        }
        Rule { name: raw.name, condition_sets, substitutions: raw.substitutions }
    }
}

impl From<Rule> for RawRule {
    fn from(rule: Rule) -> Self {
        RawRule {
            name: rule.name,
            condition_sets: rule.condition_sets,
            conditions: Vec::new(),
            substitutions: rule.substitutions,
        }
    }
}

/// Describes a single substitution.
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct Substitution {
    /// Substitute this glyph...
    #[serde(rename = "@name")]
    pub name: Name,
    /// ...with this one.
    #[serde(rename = "@with")]
    pub with: Name,
}

/// Describes a set of conditions that must all be met for the rule to apply.
#[derive(Clone, Debug, Default, PartialEq, Serialize, Deserialize)]
pub struct ConditionSet {
    /// The conditions.
    #[serde(rename = "condition", default)]
    pub conditions: Vec<Condition>,
}

/// Describes a single condition.
#[derive(Clone, Debug, Default, PartialEq, Serialize, Deserialize)]
pub struct Condition {
    /// The name of the axis.
    #[serde(rename = "@name")]
    pub name: String,
    /// Lower bounds in design space coordinates.
    #[serde(rename = "@minimum", default, skip_serializing_if = "Option::is_none")]
    pub minimum: Option<f32>,
    /// Upper bounds in design space coordinates.
    #[serde(rename = "@maximum", default, skip_serializing_if = "Option::is_none")]
    pub maximum: Option<f32>,
}

/// A [source].
///
/// [source]: https://fonttools.readthedocs.io/en/latest/designspaceLib/xml.html#id25
#[derive(Clone, Debug, Default, PartialEq, Serialize, Deserialize)]
#[serde(rename = "source")]
pub struct Source {
    /// The family name of the source font.
    #[serde(rename = "@familyname", skip_serializing_if = "Option::is_none")]
    pub familyname: Option<String>,
    /// The style name of the source font.
    #[serde(rename = "@stylename", skip_serializing_if = "Option::is_none")]
    pub stylename: Option<String>,
    /// A unique name that can be used to identify this font if it needs to be referenced elsewhere.
    #[serde(rename = "@name", skip_serializing_if = "Option::is_none")]
    pub name: Option<String>,
    /// A path to the source file, relative to the root path of this document.
    ///
    /// The path can be at the same level as the document or lower.
    #[serde(rename = "@filename")]
    pub filename: String,
    /// The name of the layer in the source file.
    ///
    /// If no layer attribute is given assume the foreground layer should be used.
    #[serde(rename = "@layer", skip_serializing_if = "Option::is_none")]
    pub layer: Option<String>,
    /// Location in designspace coordinates.
    #[serde(with = "serde_impls::location")]
    pub location: Vec<Dimension>,
}

/// An [instance].
///
/// [instance]: https://fonttools.readthedocs.io/en/latest/designspaceLib/xml.html#instance-element
#[derive(Clone, Debug, Default, PartialEq, Serialize, Deserialize)]
#[serde(rename = "instance")]
pub struct Instance {
    // per @anthrotype, contrary to spec, filename, familyname and stylename are optional
    /// The family name of the instance font. Corresponds with font.info.familyName
    #[serde(rename = "@familyname", skip_serializing_if = "Option::is_none")]
    pub familyname: Option<String>,
    /// The style name of the instance font. Corresponds with font.info.styleName
    #[serde(rename = "@stylename", skip_serializing_if = "Option::is_none")]
    pub stylename: Option<String>,
    /// A unique name that can be used to identify this font if it needs to be referenced elsewhere.
    #[serde(rename = "@name", skip_serializing_if = "Option::is_none")]
    pub name: Option<String>,
    /// A path to the instance file, relative to the root path of this document. The path can be at the same level as the document or lower.
    #[serde(rename = "@filename", skip_serializing_if = "Option::is_none")]
    pub filename: Option<String>,
    /// Corresponds with font.info.postscriptFontName
    #[serde(rename = "@postscriptfontname", skip_serializing_if = "Option::is_none")]
    pub postscriptfontname: Option<String>,
    /// Corresponds with styleMapFamilyName
    #[serde(rename = "@stylemapfamilyname", skip_serializing_if = "Option::is_none")]
    pub stylemapfamilyname: Option<String>,
    /// Corresponds with styleMapStyleName
    #[serde(rename = "@stylemapstylename", skip_serializing_if = "Option::is_none")]
    pub stylemapstylename: Option<String>,
    /// Location in designspace.
    #[serde(with = "serde_impls::location")]
    pub location: Vec<Dimension>,
    /// Arbitrary data about this instance
    #[serde(default, with = "serde_plist", skip_serializing_if = "Dictionary::is_empty")]
    pub lib: Dictionary,
}

/// A design space dimension.
///
/// [design space location]: https://fonttools.readthedocs.io/en/latest/designspaceLib/xml.html#location-element-source
#[derive(Clone, Debug, Default, PartialEq, Serialize, Deserialize)]
#[serde(rename = "dimension")]
pub struct Dimension {
    /// Name of the axis, e.g. Weight.
    #[serde(rename = "@name")]
    pub name: String,
    /// Value on the axis in user coordinates.
    #[serde(rename = "@uservalue", skip_serializing_if = "Option::is_none")]
    pub uservalue: Option<f32>,
    /// Value on the axis in designcoordinates.
    #[serde(rename = "@xvalue", skip_serializing_if = "Option::is_none")]
    pub xvalue: Option<f32>,
    /// Separate value for anisotropic interpolations.
    #[serde(rename = "@yvalue", skip_serializing_if = "Option::is_none")]
    pub yvalue: Option<f32>,
}

impl DesignSpaceDocument {
    /// Load a designspace.
    pub fn load<P: AsRef<Path>>(path: P) -> Result<DesignSpaceDocument, DesignSpaceLoadError> {
        let reader = BufReader::new(File::open(path).map_err(DesignSpaceLoadError::Io)?);
        quick_xml::de::from_reader(reader).map_err(DesignSpaceLoadError::DeError)
    }

    /// Save a designspace.
    pub fn save(&self, path: impl AsRef<Path>) -> Result<(), DesignSpaceSaveError> {
        let mut buf = String::from("<?xml version='1.0' encoding='UTF-8'?>\n");
        let mut xml_writer = quick_xml::se::Serializer::new(&mut buf);
        xml_writer.indent(' ', 2);
        self.serialize(xml_writer)?;
        buf.push('\n'); // trailing newline
        close_already::fs::write(path, buf)?;
        Ok(())
    }
}

impl Rules {
    /// Returns `true` if there are no rules.
    fn is_empty(&self) -> bool {
        self.rules.is_empty()
    }
}

/// Internal struct matching the XML structure for (de)serialization.
#[derive(Clone, Debug, Default, PartialEq, Serialize, Deserialize)]
#[serde(rename = "designspace")]
struct RawDesignSpaceDocument {
    #[serde(rename = "@format")]
    format: f32,
    #[serde(default, skip_serializing_if = "RawAxes::is_empty")]
    axes: RawAxes,
    #[serde(default, skip_serializing_if = "Rules::is_empty")]
    rules: Rules,
    #[serde(default, with = "serde_impls::sources", skip_serializing_if = "Vec::is_empty")]
    sources: Vec<Source>,
    #[serde(default, with = "serde_impls::instances", skip_serializing_if = "Vec::is_empty")]
    instances: Vec<Instance>,
    #[serde(default, with = "serde_plist", skip_serializing_if = "Dictionary::is_empty")]
    lib: Dictionary,
}

/// Internal container for axes and their optional mappings.
#[derive(Clone, Debug, Default, PartialEq, Serialize, Deserialize)]
struct RawAxes {
    #[serde(default, rename = "axis")]
    axis: Vec<Axis>,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    mappings: Option<AxisMappings>,
}

impl RawAxes {
    fn is_empty(&self) -> bool {
        self.axis.is_empty() && self.mappings.as_ref().is_none_or(|m| m.is_empty())
    }
}

impl From<RawDesignSpaceDocument> for DesignSpaceDocument {
    fn from(raw: RawDesignSpaceDocument) -> Self {
        Self {
            format: raw.format,
            axes: raw.axes.axis,
            axis_mappings: raw.axes.mappings,
            rules: raw.rules,
            sources: raw.sources,
            instances: raw.instances,
            lib: raw.lib,
        }
    }
}

impl From<DesignSpaceDocument> for RawDesignSpaceDocument {
    fn from(doc: DesignSpaceDocument) -> Self {
        Self {
            format: doc.format,
            axes: RawAxes { axis: doc.axes, mappings: doc.axis_mappings },
            rules: doc.rules,
            sources: doc.sources,
            instances: doc.instances,
            lib: doc.lib,
        }
    }
}

mod serde_impls {
    /// Produces a self-contained module to (de)serialise an XML list of a given type
    ///
    /// Example usage:
    /// ```ignore
    /// # use serde::{Serialize, Deserialize};
    ///
    /// // In XML, the locations are referred to as <dimension/>
    /// serde_from_field!(locations, dimension, Dimension);
    ///
    /// #[derive(Serialize, Deserialize)]
    /// struct DesignSpaceDocument {
    ///     #[serde(with = "locations")]
    ///     location: Vec<Dimension>,
    /// }
    ///
    /// #[derive(Serialize, Deserialize)]
    /// struct Dimension;
    /// ```
    ///
    /// the generated code is approximately:
    /// ```ignore
    /// pub(super) mod locations {
    ///     # use serde::{Deserialize, Deserializer, Serializer, Serialize};
    ///     # use norad::designspace::Dimension;
    ///     pub(crate) fn deserialize<'de, D>(deserializer: D) -> Result<Vec<Dimension>, D::Error>
    ///     where
    ///         D: Deserializer<'de>,
    ///     {
    ///         #[derive(Deserialize)]
    ///         struct Helper {
    ///             dimension: Vec<Dimension>,
    ///         }
    ///         Helper::deserialize(deserializer).map(|x| x.dimension)
    ///     }
    ///
    ///     pub(crate) fn serialize<S>(
    ///         dimension: &[Dimension],
    ///         serializer: S,
    ///     ) -> Result<S::Ok, S::Error>
    ///     where
    ///         S: Serializer,
    ///     {
    ///         #[derive(Serialize)]
    ///         struct Helper<'a> {
    ///             dimension: &'a [Dimension],
    ///         }
    ///         let helper = Helper { dimension };
    ///         helper.serialize(serializer)
    ///     }
    /// }
    /// ```
    macro_rules! serde_from_field {
        ($mod_name:ident, $field_name:ident, $inner:path) => {
            pub(super) mod $mod_name {
                pub(crate) fn deserialize<'de, D>(deserializer: D) -> Result<Vec<$inner>, D::Error>
                where
                    D: ::serde::Deserializer<'de>,
                {
                    use serde::Deserialize as _;
                    #[derive(::serde::Deserialize)]
                    struct Helper {
                        $field_name: Vec<$inner>,
                    }
                    Helper::deserialize(deserializer).map(|x| x.$field_name)
                }

                pub(crate) fn serialize<S>(
                    $field_name: &[$inner],
                    serializer: S,
                ) -> Result<S::Ok, S::Error>
                where
                    S: ::serde::Serializer,
                {
                    use serde::Serialize as _;
                    #[derive(::serde::Serialize)]
                    struct Helper<'a> {
                        $field_name: &'a [$inner],
                    }
                    let helper = Helper { $field_name };
                    helper.serialize(serializer)
                }
            }
        };
    }

    serde_from_field!(location, dimension, crate::designspace::Dimension);
    serde_from_field!(instances, instance, crate::designspace::Instance);
    serde_from_field!(sources, source, crate::designspace::Source);
}

#[cfg(test)]
mod tests {
    use std::path::Path;

    use plist::Value;
    use pretty_assertions::assert_eq;
    use tempfile::TempDir;

    use crate::designspace::{AxisMapping, Dimension};

    use super::*;

    fn dim_name_xvalue(name: &str, xvalue: f32) -> Dimension {
        Dimension { name: name.to_string(), uservalue: None, xvalue: Some(xvalue), yvalue: None }
    }

    #[test]
    fn read_single_wght() {
        let ds = DesignSpaceDocument::load(Path::new("testdata/single_wght.designspace")).unwrap();
        assert_eq!(1, ds.axes.len());
        let axis = &ds.axes[0];
        assert_eq!(axis.minimum, Some(400.));
        assert_eq!(axis.maximum, Some(600.));
        assert_eq!(axis.default, 500.);
        assert_eq!(
            &vec![AxisMapping { input: 400., output: 100. }],
            ds.axes[0].map.as_ref().unwrap()
        );
        assert_eq!(1, ds.sources.len());
        let weight_100 = dim_name_xvalue("Weight", 100.);
        assert_eq!(vec![weight_100.clone()], ds.sources[0].location);
        assert_eq!(1, ds.instances.len());
        assert_eq!(vec![weight_100], ds.instances[0].location);
    }

    #[test]
    fn read_wght_variable() {
        let ds = DesignSpaceDocument::load("testdata/wght.designspace").unwrap();
        assert_eq!(1, ds.axes.len());
        assert!(ds.axes[0].map.is_none());
        assert_eq!(
            vec![
                ("TestFamily-Regular.ufo".to_string(), vec![dim_name_xvalue("Weight", 400.)]),
                ("TestFamily-Bold.ufo".to_string(), vec![dim_name_xvalue("Weight", 700.)]),
            ],
            ds.sources
                .into_iter()
                .map(|s| (s.filename, s.location))
                .collect::<Vec<(String, Vec<Dimension>)>>()
        );
        assert!(ds.axes[0].label_names.is_empty());
    }

    #[test]
    fn read_label_names() {
        let ds = DesignSpaceDocument::load("testdata/labelname_wght.designspace").unwrap();
        assert_eq!(1, ds.axes.len());
        assert!(!ds.axes[0].label_names.is_empty());

        assert_eq!(ds.axes[0].label_names[0].language, "fa-IR");
        assert_eq!(ds.axes[0].label_names[0].string, "قطر");

        assert_eq!(ds.axes[0].label_names[1].language, "en");
        assert_eq!(ds.axes[0].label_names[1].string, "Weight");
    }

    // <https://github.com/linebender/norad/issues/300>
    #[test]
    fn load_with_no_instances() {
        DesignSpaceDocument::load("testdata/no_instances.designspace").unwrap();
    }

    #[test]
    fn load_with_no_source_name() {
        let ds = DesignSpaceDocument::load("testdata/optional_source_names.designspace").unwrap();
        assert!(ds.sources[0].name.is_none());
        assert_eq!(ds.sources[1].name.as_deref(), Some("Test Family Bold"));
    }

    #[test]
    fn load_with_no_instance_name() {
        let ds = DesignSpaceDocument::load("testdata/optional_instance_names.designspace").unwrap();
        assert_eq!(ds.instances[0].name.as_deref(), Some("Test Family Regular"));
        assert!(ds.instances[1].name.is_none());
    }

    #[test]
    fn load_lib() {
        let loaded = DesignSpaceDocument::load("testdata/wght.designspace").unwrap();
        assert_eq!(
            loaded.lib.get("org.linebender.hasLoadedLibCorrectly"),
            Some(&Value::String("Absolutely!".into()))
        );

        let params = loaded.instances[0]
            .lib
            .get("com.schriftgestaltung.customParameters")
            .and_then(Value::as_array)
            .unwrap();
        assert_eq!(params[0].as_array().unwrap()[0].as_string(), Some("xHeight"));
        assert_eq!(params[0].as_array().unwrap()[1].as_string(), Some("536"));
        assert_eq!(
            params[1].as_array().unwrap()[1].as_array().unwrap()[0].as_unsigned_integer(),
            Some(2)
        );
    }

    #[test]
    fn do_not_serialize_empty_lib() {
        let ds_initial = DesignSpaceDocument::load("testdata/single_wght.designspace").unwrap();
        let serialized = quick_xml::se::to_string(&ds_initial).expect("should serialize");

        assert!(!serialized.contains("<lib>"));
        assert!(!serialized.contains("<lib/>"));
    }

    #[test]
    fn load_save_round_trip() {
        // Given
        let dir = TempDir::new().unwrap();
        let ds_test_save_location = dir.path().join("wght.designspace");

        // When
        let ds_initial = DesignSpaceDocument::load("testdata/wght.designspace").unwrap();
        ds_initial.save(&ds_test_save_location).expect("failed to save designspace");
        let ds_after = DesignSpaceDocument::load(ds_test_save_location)
            .expect("failed to load saved designspace");

        // Then
        assert_eq!(ds_initial, ds_after);
    }

    #[test]
    fn load_save_round_trip_mutatorsans() {
        // Given
        let dir = TempDir::new().unwrap();
        let ds_test_save_location = dir.path().join("MutatorSans.designspace");

        // When
        let ds_initial = DesignSpaceDocument::load("testdata/MutatorSans.designspace").unwrap();
        ds_initial.save(&ds_test_save_location).expect("failed to save designspace");
        let ds_after = DesignSpaceDocument::load(ds_test_save_location)
            .expect("failed to load saved designspace");

        // Then
        assert_eq!(
            &ds_after.rules,
            &Rules {
                processing: RuleProcessing::Last,
                rules: vec![
                    Rule {
                        name: Some("fold_I_serifs".into()),
                        condition_sets: vec![ConditionSet {
                            conditions: vec![Condition {
                                name: "width".into(),
                                minimum: Some(0.0),
                                maximum: Some(328.0),
                            }],
                        }],
                        substitutions: vec![Substitution {
                            name: "I".into(),
                            with: "I.narrow".into()
                        }],
                    },
                    Rule {
                        name: Some("fold_S_terminals".into()),
                        condition_sets: vec![ConditionSet {
                            conditions: vec![
                                Condition {
                                    name: "width".into(),
                                    minimum: Some(0.0),
                                    maximum: Some(1000.0),
                                },
                                Condition {
                                    name: "weight".into(),
                                    minimum: Some(0.0),
                                    maximum: Some(500.0),
                                },
                            ],
                        }],
                        substitutions: vec![Substitution {
                            name: "S".into(),
                            with: "S.closed".into()
                        }],
                    },
                ]
            }
        );
        assert_eq!(ds_initial, ds_after);
    }

    #[test]
    fn load_save_round_trip_label_names() {
        // Given
        let dir = TempDir::new().unwrap();
        let ds_test_save_location = dir.path().join("labelname_wght.designspace");

        // When
        let ds_initial = DesignSpaceDocument::load("testdata/labelname_wght.designspace").unwrap();
        ds_initial.save(&ds_test_save_location).expect("failed to save designspace");

        let ds_after = DesignSpaceDocument::load(ds_test_save_location.clone())
            .expect("failed to load saved designspace");

        // Then
        assert_eq!(ds_initial, ds_after);

        // Check the raw file content to ensure 'xml:lang' which gets stripped on deserialization
        // is correctly serialized.
        let saved_content = std::fs::read_to_string(&ds_test_save_location)
            .expect("Failed to read saved designspace file");
        assert!(saved_content.contains("xml:lang=\"fa-IR\""));
        assert!(saved_content.contains("xml:lang=\"en\""),);
    }

    #[test]
    fn accept_bare_conditions_in_rule() {
        // Legacy format: <condition> elements directly inside <rule> without <conditionset>
        let designspace = DesignSpaceDocument::load("testdata/BareConditions.designspace").unwrap();

        assert_eq!(
            &designspace.rules,
            &Rules {
                processing: RuleProcessing::Last,
                rules: vec![
                    Rule {
                        name: Some("fold_I_serifs".into()),
                        condition_sets: vec![ConditionSet {
                            conditions: vec![Condition {
                                name: "width".into(),
                                minimum: Some(0.0),
                                maximum: Some(328.0),
                            }],
                        }],
                        substitutions: vec![Substitution {
                            name: "I".into(),
                            with: "I.narrow".into()
                        }],
                    },
                    Rule {
                        name: Some("fold_S_terminals".into()),
                        condition_sets: vec![ConditionSet {
                            conditions: vec![
                                Condition {
                                    name: "width".into(),
                                    minimum: Some(0.0),
                                    maximum: Some(1000.0),
                                },
                                Condition {
                                    name: "weight".into(),
                                    minimum: Some(0.0),
                                    maximum: Some(500.0),
                                },
                            ],
                        }],
                        substitutions: vec![Substitution {
                            name: "S".into(),
                            with: "S.closed".into()
                        }],
                    },
                ]
            }
        );
    }

    #[test]
    fn accept_always_on_rules() {
        // Given
        let designspace =
            DesignSpaceDocument::load("testdata/MutatorSansAlwaysOnRules.designspace").unwrap();

        // Then
        assert_eq!(
            &designspace.rules,
            &Rules {
                processing: RuleProcessing::Last,
                rules: vec![
                    Rule {
                        name: Some("fold_I_serifs".into()),
                        condition_sets: vec![ConditionSet { conditions: vec![] }],
                        substitutions: vec![Substitution {
                            name: "I".into(),
                            with: "I.narrow".into()
                        }],
                    },
                    Rule {
                        name: Some("fold_S_terminals".into()),
                        condition_sets: vec![ConditionSet { conditions: vec![] }],
                        substitutions: vec![Substitution {
                            name: "S".into(),
                            with: "S.closed".into()
                        }],
                    },
                ]
            }
        );
    }

    #[test]
    fn load_axis_mappings() {
        // Given
        let ds = DesignSpaceDocument::load("testdata/with_mappings.designspace").unwrap();
        let mappings = ds.axis_mappings.as_ref().expect("should have axis_mappings");

        // Then
        assert_eq!(mappings.description.as_deref(), Some("Test avar2 mappings"));
        assert_eq!(mappings.mappings.len(), 2);
        let m1 = &mappings.mappings[0];
        assert_eq!(m1.description.as_deref(), Some("Heavy at wide gets less heavy"));
        assert_eq!(m1.input.len(), 2);
        assert_eq!(m1.input[0].name, "Weight");
        assert_eq!(m1.input[0].xvalue, Some(700.0));
        assert_eq!(m1.input[1].name, "Width");
        assert_eq!(m1.input[1].xvalue, Some(125.0));
        assert_eq!(m1.output.len(), 1);
        assert_eq!(m1.output[0].name, "Weight");
        assert_eq!(m1.output[0].xvalue, Some(680.0));
        assert!(mappings.mappings[1].description.is_none());
    }

    #[test]
    fn load_save_round_trip_with_mappings() {
        // Given
        let dir = TempDir::new().unwrap();
        let ds_test_save_location = dir.path().join("with_mappings.designspace");

        // When
        let ds_initial = DesignSpaceDocument::load("testdata/with_mappings.designspace").unwrap();
        ds_initial.save(&ds_test_save_location).expect("failed to save designspace");
        let ds_after = DesignSpaceDocument::load(&ds_test_save_location)
            .expect("failed to load saved designspace");

        // Then
        assert_eq!(ds_initial, ds_after);
        let saved_content = std::fs::read_to_string(&ds_test_save_location)
            .expect("Failed to read saved designspace file");
        assert!(saved_content.contains("<mappings"));
        assert!(saved_content.contains("<mapping"));
        assert!(saved_content.contains("<input>"));
        assert!(saved_content.contains("<output>"));
    }

    #[test]
    fn designspace_without_mappings_has_none() {
        let ds = DesignSpaceDocument::load("testdata/wght.designspace").unwrap();
        assert!(ds.axis_mappings.is_none());
    }
}