Skip to main content
← Back to kicad-monkey Rust Docs kicad-monkey Rust Crate API Reference

kicad_monkey_core/
project.rs

1//! `.kicad_pro` JSON source model and exact owned writer.
2
3mod fabrication_rules;
4pub(crate) mod json_preflight;
5pub use fabrication_rules::ProjectFabricationRules;
6
7use serde::{Deserialize, Serialize};
8use serde_json::{Map, Value};
9use std::fmt::{Display, Formatter};
10use std::io::{Read, Write};
11
12use json_preflight::preflight_json_structure;
13
14/// Stack-safety bound on JSON nesting. serde_json builds, clones, serializes
15/// and drops `Value` recursively, so deeper input could overflow the stack.
16/// A project file that exceeds it is unreadable; the schematic still loads.
17pub const PROJECT_MAX_JSON_DEPTH: usize = 512;
18
19/// The root sheet's name when nothing names it: KiCad's untranslated
20/// `_( "Root" )` (eeschema/eeschema_helpers.cpp:194), as kicad-cli prints it.
21pub const ROOT_SHEET_DEFAULT_NAME: &str = "Root";
22
23#[derive(Clone, Copy, Debug, Eq, PartialEq)]
24pub enum ProjectErrorKind {
25    InvalidUtf8,
26    InvalidJson,
27    RootNotObject,
28    ResourceLimit,
29    InvalidPath,
30    Conflict,
31    Io,
32}
33
34#[derive(Clone, Debug, Eq, PartialEq)]
35pub struct ProjectError {
36    pub kind: ProjectErrorKind,
37    pub message: String,
38}
39
40impl ProjectError {
41    fn new(kind: ProjectErrorKind, message: impl Into<String>) -> Self {
42        Self {
43            kind,
44            message: message.into(),
45        }
46    }
47}
48
49impl Display for ProjectError {
50    fn fmt(&self, formatter: &mut Formatter<'_>) -> std::fmt::Result {
51        write!(formatter, "{}", self.message)
52    }
53}
54
55impl std::error::Error for ProjectError {}
56
57#[derive(Clone, Debug, Eq, PartialEq, Serialize)]
58pub struct ProjectVariant {
59    pub name: String,
60    pub description: Option<String>,
61}
62
63#[derive(Clone, Debug, Eq, PartialEq, Serialize)]
64pub struct ProjectBusAlias {
65    pub name: String,
66    pub members: Vec<String>,
67}
68
69#[derive(Clone, Debug, PartialEq, Serialize)]
70pub struct ProjectNetClass {
71    pub name: String,
72    pub description: String,
73    pub track_width: Option<f64>,
74    pub clearance: Option<f64>,
75    pub diff_pair_gap: Option<f64>,
76    pub diff_pair_width: Option<f64>,
77    pub diff_pair_via_gap: Option<f64>,
78    pub via_diameter: Option<f64>,
79    pub via_drill: Option<f64>,
80    pub microvia_diameter: Option<f64>,
81    pub microvia_drill: Option<f64>,
82    pub bus_width: Option<f64>,
83    pub wire_width: Option<f64>,
84    pub pcb_color: String,
85    pub schematic_color: String,
86    pub line_style: Option<i64>,
87    pub priority: Option<i64>,
88    pub tuning_profile: String,
89}
90
91#[derive(Clone, Debug, Eq, PartialEq, Serialize)]
92pub struct ProjectNetClassPattern {
93    pub pattern: String,
94    pub netclass_name: String,
95}
96
97#[derive(Clone, Debug, PartialEq, Serialize)]
98pub struct ProjectNetSettings {
99    pub classes: Vec<ProjectNetClass>,
100    pub assignments: Vec<(String, Vec<String>)>,
101    pub patterns: Vec<ProjectNetClassPattern>,
102    pub colors: Vec<(String, String)>,
103}
104
105#[derive(Clone, Debug, PartialEq, Serialize)]
106pub struct ProjectDiffPairDimensions {
107    pub width: Option<f64>,
108    pub gap: Option<f64>,
109    pub via_gap: Option<f64>,
110}
111
112#[derive(Clone, Debug, PartialEq, Serialize)]
113pub struct ProjectTuningDefaults {
114    pub spacing: Option<f64>,
115    pub min_amplitude: Option<f64>,
116    pub max_amplitude: Option<f64>,
117    pub corner_style: Option<i64>,
118    pub corner_radius_percentage: Option<i64>,
119    pub single_sided: Option<bool>,
120}
121
122#[derive(Clone, Debug, PartialEq, Serialize)]
123pub struct ProjectTuningSettings {
124    pub diff_pair_defaults: ProjectTuningDefaults,
125    pub diff_pair_skew_defaults: ProjectTuningDefaults,
126    pub single_track_defaults: ProjectTuningDefaults,
127}
128
129#[derive(Clone, Debug, PartialEq, Serialize)]
130pub struct ProjectBoardDesignSettings {
131    pub diff_pair_dimensions: Vec<ProjectDiffPairDimensions>,
132    pub tuning: ProjectTuningSettings,
133}
134
135#[derive(Clone, Copy, Debug)]
136pub struct ProjectView<'a> {
137    root: &'a Map<String, Value>,
138}
139
140impl<'a> ProjectView<'a> {
141    #[must_use]
142    pub const fn raw(&self) -> &'a Map<String, Value> {
143        self.root
144    }
145
146    /// Exact selected schematic worksheet locator; an absent/empty value selects the default.
147    /// The caller resolves a relative locator against the explicitly selected project directory.
148    pub fn schematic_worksheet_path(&self) -> Result<Option<&'a str>, ProjectError> {
149        let Some(value) = path(self.root, &["schematic", "page_layout_descr_file"]) else {
150            return Ok(None);
151        };
152        let value = value.as_str().ok_or_else(|| {
153            ProjectError::new(
154                ProjectErrorKind::InvalidPath,
155                "schematic.page_layout_descr_file must be a string",
156            )
157        })?;
158        Ok((!value.is_empty()).then_some(value))
159    }
160
161    pub fn text_variables(&self) -> Result<Vec<(String, String)>, ProjectError> {
162        let Some(values) = self.root.get("text_variables").and_then(Value::as_object) else {
163            return Ok(Vec::new());
164        };
165        Ok(values
166            .iter()
167            .map(|(name, value)| (name.clone(), project_string(value)))
168            .collect())
169    }
170
171    /// Return KiCad's schematic drawing settings in the units consumed by the
172    /// typed plotter. Project line thickness is stored in mils.
173    #[must_use]
174    pub fn schematic_drawing_settings(&self) -> crate::SchematicDrawingSettings {
175        const MIN_PLOT_PEN_WIDTH_NM: i64 = 84_700;
176        let defaults = crate::SchematicDrawingSettings::default();
177        let drawing = path(self.root, &["schematic", "drawing"]).and_then(Value::as_object);
178        let text_offset_ratio = drawing
179            .and_then(|value| value.get("text_offset_ratio"))
180            .and_then(Value::as_f64)
181            .filter(|value| value.is_finite() && *value >= 0.0)
182            .unwrap_or(defaults.text_offset_ratio);
183        let default_line_width_nm = drawing
184            .and_then(|value| value.get("default_line_thickness"))
185            .and_then(Value::as_f64)
186            .filter(|value| value.is_finite() && *value >= 0.0)
187            .map(|mils| (mils * 25_400.0).round_ties_even() as i64)
188            .map_or(defaults.default_line_width_nm, |value| {
189                value.max(MIN_PLOT_PEN_WIDTH_NM)
190            });
191        crate::SchematicDrawingSettings {
192            text_offset_ratio,
193            default_line_width_nm,
194        }
195    }
196
197    /// The diameter KiCad draws a junction whose own diameter is zero
198    /// (`SCHEMATIC_SETTINGS::GetJunctionSize`): the Default net class's wire
199    /// width (6 mil unless the project sets one) times the multiplier
200    /// `junction_size_choice` selects (None, Smallest, Small, Default, Large,
201    /// Largest), rounded to KiCad's 100 nm unit, nanometres.
202    #[must_use]
203    pub fn schematic_junction_diameter_nm(&self) -> i64 {
204        const MULTIPLIERS: [f64; 6] = [0.0, 1.7, 4.0, 6.0, 9.0, 12.0];
205        const DEFAULT_CHOICE: usize = 3;
206        const DEFAULT_WIRE_MILS: f64 = 6.0;
207        let drawing = path(self.root, &["schematic", "drawing"]).and_then(Value::as_object);
208        let choice = drawing
209            .and_then(|value| value.get("junction_size_choice"))
210            .and_then(Value::as_u64)
211            .and_then(|choice| usize::try_from(choice).ok())
212            .filter(|choice| *choice < MULTIPLIERS.len())
213            .unwrap_or(DEFAULT_CHOICE);
214        let wire_mils = self
215            .net_settings()
216            .ok()
217            .and_then(|settings| settings.classes.into_iter().find(|c| c.name == "Default"))
218            .and_then(|class| class.wire_width)
219            .filter(|value| value.is_finite() && *value > 0.0)
220            .unwrap_or(DEFAULT_WIRE_MILS);
221        let wire_iu = (wire_mils * 254.0).round();
222        (wire_iu * MULTIPLIERS[choice]).round() as i64 * 100
223    }
224
225    /// `schematic.top_level_sheets`: each entry's `(filename, name)`, in order.
226    /// A field that is not a string reads as empty.
227    #[must_use]
228    pub fn top_level_sheets(&self) -> Vec<(String, String)> {
229        let text = |value: &Map<String, Value>, field: &str| {
230            value
231                .get(field)
232                .and_then(Value::as_str)
233                .unwrap_or_default()
234                .to_owned()
235        };
236        path(self.root, &["schematic", "top_level_sheets"])
237            .and_then(Value::as_array)
238            .map_or(&[][..], Vec::as_slice)
239            .iter()
240            .filter_map(Value::as_object)
241            .map(|value| (text(value, "filename"), text(value, "name")))
242            .collect()
243    }
244
245    /// The name KiCad 10.0.8 gives the root sheet when it loads
246    /// `root_schematic_file` (a `/`-separated path relative to the project
247    /// directory) with this project, as `${SHEETNAME}` shows it.
248    ///
249    /// `PROJECT_FILE::LoadFromFile` (common/project/project_file.cpp:692-755)
250    /// gives a project without top-level sheets one entry named for the
251    /// project, `<project_name>.kicad_sch`, and points an entry whose file is
252    /// missing at that file. `EESCHEMA_HELPERS::LoadSchematic`
253    /// (eeschema/eeschema_helpers.cpp:140-196) then takes the name of the
254    /// entry for the loaded file. With one entry, an empty name or no matching
255    /// entry gives "Root"; with several, the entry's name is kept as it is.
256    /// Without a project the name is "Root" (see [`ROOT_SHEET_DEFAULT_NAME`]).
257    #[must_use]
258    pub fn root_sheet_name(
259        &self,
260        project_name: &str,
261        root_schematic_file: &str,
262        file_exists: impl Fn(&str) -> bool,
263    ) -> String {
264        let project_file = format!("{project_name}.kicad_sch");
265        let mut sheets = self.top_level_sheets();
266        if sheets.is_empty() {
267            sheets.push((project_file.clone(), project_name.to_owned()));
268        }
269        for (filename, name) in &mut sheets {
270            if !file_exists(&normalized_sheet_file(filename)) && file_exists(&project_file) {
271                filename.clone_from(&project_file);
272                name.clear();
273                name.push_str(project_name);
274            }
275        }
276        let root = normalized_sheet_file(root_schematic_file);
277        let named = sheets
278            .iter()
279            .find(|(filename, _)| normalized_sheet_file(filename) == root);
280        match named {
281            Some((_, name)) if sheets.len() > 1 => name.clone(),
282            Some((_, name)) if !name.is_empty() => name.clone(),
283            _ => ROOT_SHEET_DEFAULT_NAME.to_owned(),
284        }
285    }
286
287    pub fn variants(&self) -> Result<Vec<ProjectVariant>, ProjectError> {
288        let values = path(self.root, &["schematic", "variants"])
289            .and_then(Value::as_array)
290            .map_or(&[][..], Vec::as_slice);
291        Ok(values
292            .iter()
293            .filter_map(Value::as_object)
294            .map(|value| ProjectVariant {
295                name: object_string(value, "name"),
296                description: match value.get("description") {
297                    None | Some(Value::Null) => None,
298                    Some(value) => Some(project_string(value)),
299                },
300            })
301            .collect())
302    }
303    pub fn bus_aliases(&self) -> Result<Vec<ProjectBusAlias>, ProjectError> {
304        let Some(values) =
305            path(self.root, &["schematic", "bus_aliases"]).and_then(Value::as_object)
306        else {
307            return Ok(Vec::new());
308        };
309        let mut aliases = Vec::<ProjectBusAlias>::new();
310        for (raw_name, raw_members) in values {
311            let Some(raw_members) = raw_members.as_array() else {
312                continue;
313            };
314            let name = raw_name.trim();
315            if name.is_empty() {
316                continue;
317            }
318            let mut members = Vec::new();
319            for raw_member in raw_members {
320                let Some(raw_member) = raw_member.as_str() else {
321                    continue;
322                };
323                let member = raw_member.trim();
324                if member.is_empty() {
325                    continue;
326                }
327                members.push(member.to_owned());
328            }
329            if let Some(position) = aliases.iter().position(|alias| alias.name == name) {
330                aliases.remove(position);
331            }
332            aliases.push(ProjectBusAlias {
333                name: name.to_owned(),
334                members,
335            });
336        }
337        Ok(aliases)
338    }
339    pub fn net_settings(&self) -> Result<ProjectNetSettings, ProjectError> {
340        let settings = self.root.get("net_settings").and_then(Value::as_object);
341        Ok(ProjectNetSettings {
342            classes: net_classes(settings),
343            assignments: net_assignments(settings),
344            patterns: net_patterns(settings),
345            colors: net_colors(settings),
346        })
347    }
348
349    pub fn board_design_settings(&self) -> Result<ProjectBoardDesignSettings, ProjectError> {
350        let settings = path(self.root, &["board", "design_settings"]).and_then(Value::as_object);
351        let dimensions = settings
352            .and_then(|value| value.get("diff_pair_dimensions"))
353            .and_then(Value::as_array)
354            .map_or(&[][..], Vec::as_slice);
355        let diff_pair_dimensions = dimensions
356            .iter()
357            .filter_map(Value::as_object)
358            .map(|value| ProjectDiffPairDimensions {
359                width: optional_number(value, "width"),
360                gap: optional_number(value, "gap"),
361                via_gap: optional_number(value, "via_gap"),
362            })
363            .collect();
364        let tuning = settings
365            .and_then(|value| value.get("tuning_pattern_settings"))
366            .and_then(Value::as_object);
367        Ok(ProjectBoardDesignSettings {
368            diff_pair_dimensions,
369            tuning: ProjectTuningSettings {
370                diff_pair_defaults: tuning_defaults(tuning, "diff_pair_defaults"),
371                diff_pair_skew_defaults: tuning_defaults(tuning, "diff_pair_skew_defaults"),
372                single_track_defaults: tuning_defaults(tuning, "single_track_defaults"),
373            },
374        })
375    }
376
377    #[must_use]
378    pub fn get_path(&self, dotted_path: &str) -> Option<&'a Value> {
379        let mut parts = dotted_path.split('.');
380        let first = parts.next()?;
381        if first.is_empty() {
382            return None;
383        }
384        let mut value = self.root.get(first)?;
385        for part in parts {
386            value = value.as_object()?.get(part)?;
387        }
388        Some(value)
389    }
390}
391
392#[derive(Clone, Debug)]
393pub struct ProjectDocument {
394    source: String,
395    root: Map<String, Value>,
396}
397
398impl ProjectDocument {
399    pub fn parse(source: String) -> Result<Self, ProjectError> {
400        preflight_json_structure(&source)?;
401        let value = deserialize_project(&source)?;
402        let Value::Object(root) = value else {
403            return Err(ProjectError::new(
404                ProjectErrorKind::RootNotObject,
405                ".kicad_pro root must be a JSON object",
406            ));
407        };
408        Ok(Self { source, root })
409    }
410
411    pub fn from_reader(mut reader: impl Read) -> Result<Self, ProjectError> {
412        let mut bytes = Vec::new();
413        reader.read_to_end(&mut bytes).map_err(io_error)?;
414        let source = String::from_utf8(bytes).map_err(|error| {
415            ProjectError::new(
416                ProjectErrorKind::InvalidUtf8,
417                format!(
418                    "project source is not UTF-8 at byte {}",
419                    error.utf8_error().valid_up_to()
420                ),
421            )
422        })?;
423        Self::parse(source)
424    }
425
426    #[must_use]
427    pub fn source(&self) -> &str {
428        &self.source
429    }
430
431    #[must_use]
432    pub const fn view(&self) -> ProjectView<'_> {
433        ProjectView { root: &self.root }
434    }
435
436    pub fn write_to(&self, mut writer: impl Write) -> Result<(), ProjectError> {
437        writer.write_all(self.source.as_bytes()).map_err(io_error)
438    }
439
440    pub fn canonical_text(&self) -> Result<String, ProjectError> {
441        serialize_project(&self.root)
442    }
443
444    pub fn set_text_variable(&mut self, name: &str, value: &str) -> Result<bool, ProjectError> {
445        let mut root = self.root.clone();
446        let text_variables = object_field(&mut root, "text_variables", true)?;
447        if text_variables.get(name).and_then(Value::as_str) == Some(value) {
448            return Ok(false);
449        }
450        text_variables.insert(name.to_owned(), Value::String(value.to_owned()));
451        self.commit(root)
452    }
453
454    pub fn remove_text_variable(&mut self, name: &str) -> Result<bool, ProjectError> {
455        let mut root = self.root.clone();
456        let Some(value) = root.get_mut("text_variables") else {
457            return Ok(false);
458        };
459        let Some(values) = value.as_object_mut() else {
460            return Ok(false);
461        };
462        if values.shift_remove(name).is_none() {
463            return Ok(false);
464        }
465        self.commit(root)
466    }
467
468    pub fn add_variant(
469        &mut self,
470        name: &str,
471        description: Option<&str>,
472    ) -> Result<ProjectVariant, ProjectError> {
473        if name.is_empty() {
474            return Err(conflict_error("project variant name must not be empty"));
475        }
476        let mut root = self.root.clone();
477        let variants = variants_mut(&mut root, true)?;
478        if variants.iter().any(|value| {
479            value
480                .as_object()
481                .and_then(|value| value.get("name"))
482                .and_then(Value::as_str)
483                == Some(name)
484        }) {
485            return Err(conflict_error("project variant already exists"));
486        }
487        let mut entry = Map::new();
488        entry.insert("name".to_owned(), Value::String(name.to_owned()));
489        if let Some(description) = description {
490            entry.insert(
491                "description".to_owned(),
492                Value::String(description.to_owned()),
493            );
494        }
495        variants.push(Value::Object(entry));
496        self.commit(root)?;
497        Ok(ProjectVariant {
498            name: name.to_owned(),
499            description: description.map(str::to_owned),
500        })
501    }
502
503    pub fn remove_variant(&mut self, name: &str) -> Result<Option<ProjectVariant>, ProjectError> {
504        if !variant_exists(&self.root, name)? {
505            return Ok(None);
506        }
507        let mut root = self.root.clone();
508        let variants = variants_mut(&mut root, false)?;
509        let Some(index) = variants.iter().position(|value| {
510            value
511                .as_object()
512                .and_then(|value| value.get("name"))
513                .and_then(Value::as_str)
514                == Some(name)
515        }) else {
516            return Ok(None);
517        };
518        let removed = variant_from_value(&variants.remove(index));
519        self.commit(root)?;
520        Ok(removed)
521    }
522
523    pub fn rename_variant(&mut self, old_name: &str, new_name: &str) -> Result<bool, ProjectError> {
524        if new_name.is_empty() {
525            return Err(conflict_error("project variant name must not be empty"));
526        }
527        if variant_exists(&self.root, new_name)? {
528            return Err(conflict_error("project variant already exists"));
529        }
530        if !variant_exists(&self.root, old_name)? {
531            return Ok(false);
532        }
533        let mut root = self.root.clone();
534        let variants = variants_mut(&mut root, false)?;
535        let Some(entry) = variants.iter_mut().find_map(|value| {
536            let object = value.as_object_mut()?;
537            (object.get("name").and_then(Value::as_str) == Some(old_name)).then_some(object)
538        }) else {
539            return Ok(false);
540        };
541        entry.insert("name".to_owned(), Value::String(new_name.to_owned()));
542        self.commit(root)
543    }
544
545    pub fn set_path(&mut self, dotted_path: &str, value: Value) -> Result<bool, ProjectError> {
546        let parts = valid_path_parts(dotted_path)?;
547        let mut root = self.root.clone();
548        let mut current = &mut root;
549        for part in &parts[..parts.len() - 1] {
550            if !current.contains_key(*part) {
551                current.insert((*part).to_owned(), Value::Object(Map::new()));
552            }
553            current = current
554                .get_mut(*part)
555                .and_then(Value::as_object_mut)
556                .ok_or_else(|| conflict_error("project path crosses a non-object value"))?;
557        }
558        let final_part = parts[parts.len() - 1];
559        if current.get(final_part) == Some(&value) {
560            return Ok(false);
561        }
562        current.insert(final_part.to_owned(), value);
563        self.commit(root)
564    }
565
566    fn commit(&mut self, root: Map<String, Value>) -> Result<bool, ProjectError> {
567        let candidate = serialize_project(&root)?;
568        let parsed = Self::parse(candidate)?;
569        validate_promoted(&parsed)?;
570        self.source = parsed.source;
571        self.root = parsed.root;
572        Ok(true)
573    }
574}
575
576fn net_classes(settings: Option<&Map<String, Value>>) -> Vec<ProjectNetClass> {
577    array_field(settings, "classes")
578        .iter()
579        .filter_map(Value::as_object)
580        .map(|value| ProjectNetClass {
581            name: object_string(value, "name"),
582            description: object_string(value, "description"),
583            track_width: optional_number(value, "track_width"),
584            clearance: optional_number(value, "clearance"),
585            diff_pair_gap: optional_number(value, "diff_pair_gap"),
586            diff_pair_width: optional_number(value, "diff_pair_width"),
587            diff_pair_via_gap: optional_number(value, "diff_pair_via_gap"),
588            via_diameter: optional_number(value, "via_diameter"),
589            via_drill: optional_number(value, "via_drill"),
590            microvia_diameter: optional_number(value, "microvia_diameter"),
591            microvia_drill: optional_number(value, "microvia_drill"),
592            bus_width: optional_number(value, "bus_width"),
593            wire_width: optional_number(value, "wire_width"),
594            pcb_color: object_string(value, "pcb_color"),
595            schematic_color: object_string(value, "schematic_color"),
596            line_style: optional_integer(value, "line_style"),
597            priority: optional_integer(value, "priority"),
598            tuning_profile: object_string(value, "tuning_profile"),
599        })
600        .collect()
601}
602
603fn validate_promoted(document: &ProjectDocument) -> Result<(), ProjectError> {
604    let view = document.view();
605    view.text_variables()?;
606    view.variants()?;
607    view.bus_aliases()?;
608    view.net_settings()?;
609    view.board_design_settings()?;
610    Ok(())
611}
612
613fn net_assignments(settings: Option<&Map<String, Value>>) -> Vec<(String, Vec<String>)> {
614    let Some(values) = settings
615        .and_then(|value| value.get("netclass_assignments"))
616        .and_then(Value::as_object)
617    else {
618        return Vec::new();
619    };
620    values
621        .iter()
622        .map(|(name, classes)| {
623            let typed = classes
624                .as_array()
625                .map_or(&[][..], Vec::as_slice)
626                .iter()
627                .map(project_string)
628                .filter(|class| !class.is_empty())
629                .collect();
630            (name.clone(), typed)
631        })
632        .collect()
633}
634
635fn net_patterns(settings: Option<&Map<String, Value>>) -> Vec<ProjectNetClassPattern> {
636    array_field(settings, "netclass_patterns")
637        .iter()
638        .filter_map(Value::as_object)
639        .map(|value| ProjectNetClassPattern {
640            pattern: object_string(value, "pattern"),
641            netclass_name: object_string(value, "netclass"),
642        })
643        .collect()
644}
645
646fn net_colors(settings: Option<&Map<String, Value>>) -> Vec<(String, String)> {
647    let Some(values) = settings
648        .and_then(|value| value.get("net_colors"))
649        .and_then(Value::as_object)
650    else {
651        return Vec::new();
652    };
653    values
654        .iter()
655        .map(|(name, value)| (name.clone(), project_string(value)))
656        .collect()
657}
658
659fn tuning_defaults(settings: Option<&Map<String, Value>>, field: &str) -> ProjectTuningDefaults {
660    let value = settings
661        .and_then(|value| value.get(field))
662        .and_then(Value::as_object);
663    ProjectTuningDefaults {
664        spacing: value.and_then(|value| optional_number(value, "spacing")),
665        min_amplitude: value.and_then(|value| optional_number(value, "min_amplitude")),
666        max_amplitude: value.and_then(|value| optional_number(value, "max_amplitude")),
667        corner_style: value.and_then(|value| optional_integer(value, "corner_style")),
668        corner_radius_percentage: value
669            .and_then(|value| optional_integer(value, "corner_radius_percentage")),
670        single_sided: value
671            .and_then(|value| value.get("single_sided"))
672            .and_then(Value::as_bool),
673    }
674}
675
676fn variants_mut(
677    root: &mut Map<String, Value>,
678    create: bool,
679) -> Result<&mut Vec<Value>, ProjectError> {
680    let schematic = object_field(root, "schematic", create)?;
681    if create && !schematic.contains_key("variants") {
682        schematic.insert("variants".to_owned(), Value::Array(Vec::new()));
683    }
684    schematic
685        .get_mut("variants")
686        .and_then(Value::as_array_mut)
687        .ok_or_else(|| conflict_error("project schematic.variants field must be a JSON array"))
688}
689
690fn variant_exists(root: &Map<String, Value>, name: &str) -> Result<bool, ProjectError> {
691    let Some(value) = path(root, &["schematic", "variants"]) else {
692        return Ok(false);
693    };
694    if value.is_null() {
695        return Ok(false);
696    }
697    let values = value
698        .as_array()
699        .ok_or_else(|| conflict_error("project schematic.variants field must be a JSON array"))?;
700    Ok(values.iter().any(|value| {
701        value
702            .as_object()
703            .and_then(|value| value.get("name"))
704            .and_then(Value::as_str)
705            == Some(name)
706    }))
707}
708
709fn object_field<'a>(
710    root: &'a mut Map<String, Value>,
711    field: &str,
712    create: bool,
713) -> Result<&'a mut Map<String, Value>, ProjectError> {
714    if create && !root.contains_key(field) {
715        root.insert(field.to_owned(), Value::Object(Map::new()));
716    }
717    root.get_mut(field)
718        .and_then(Value::as_object_mut)
719        .ok_or_else(|| conflict_error("project field must be a JSON object"))
720}
721
722fn variant_from_value(value: &Value) -> Option<ProjectVariant> {
723    let value = value.as_object()?;
724    Some(ProjectVariant {
725        name: object_string(value, "name"),
726        description: match value.get("description") {
727            None | Some(Value::Null) => None,
728            Some(value) => Some(project_string(value)),
729        },
730    })
731}
732
733fn deserialize_project(source: &str) -> Result<Value, ProjectError> {
734    let mut deserializer = serde_json::Deserializer::from_str(source);
735    // The iterative preflight has already enforced the caller limit and the
736    // library hard cap, so Serde's lower implicit recursion ceiling must not
737    // replace the public resource contract.
738    deserializer.disable_recursion_limit();
739    let value = Value::deserialize(&mut deserializer).map_err(json_error)?;
740    deserializer.end().map_err(json_error)?;
741    Ok(value)
742}
743
744fn json_error(error: serde_json::Error) -> ProjectError {
745    ProjectError::new(ProjectErrorKind::InvalidJson, error.to_string())
746}
747
748fn serialize_project(root: &Map<String, Value>) -> Result<String, ProjectError> {
749    let mut bytes = Vec::new();
750    let mut serializer = serde_json::Serializer::with_formatter(
751        &mut bytes,
752        serde_json::ser::PrettyFormatter::with_indent(b"  "),
753    );
754    root.serialize(&mut serializer)
755        .map_err(|error| ProjectError::new(ProjectErrorKind::InvalidJson, error.to_string()))?;
756    bytes.push(b'\n');
757    String::from_utf8(bytes).map_err(|_| {
758        ProjectError::new(
759            ProjectErrorKind::InvalidUtf8,
760            "serialized project output is not UTF-8",
761        )
762    })
763}
764
765/// A top-level sheet file as `wxFileName` compares it once made absolute
766/// against the project directory: `/`-separated, without `./` segments.
767fn normalized_sheet_file(path: &str) -> String {
768    path.replace('\\', "/")
769        .split('/')
770        .filter(|part| !part.is_empty() && *part != ".")
771        .collect::<Vec<_>>()
772        .join("/")
773}
774
775fn path<'a>(root: &'a Map<String, Value>, parts: &[&str]) -> Option<&'a Value> {
776    let mut value = root.get(*parts.first()?)?;
777    for part in &parts[1..] {
778        value = value.as_object()?.get(*part)?;
779    }
780    Some(value)
781}
782
783fn array_field<'a>(settings: Option<&'a Map<String, Value>>, field: &str) -> &'a [Value] {
784    settings
785        .and_then(|value| value.get(field))
786        .and_then(Value::as_array)
787        .map_or(&[], Vec::as_slice)
788}
789
790fn optional_number(value: &Map<String, Value>, field: &str) -> Option<f64> {
791    value.get(field).and_then(Value::as_f64)
792}
793
794fn optional_integer(value: &Map<String, Value>, field: &str) -> Option<i64> {
795    value.get(field).and_then(Value::as_i64)
796}
797
798fn object_string(value: &Map<String, Value>, field: &str) -> String {
799    value.get(field).map_or_else(String::new, project_string)
800}
801
802fn project_string(value: &Value) -> String {
803    match value {
804        Value::Null | Value::Bool(false) => String::new(),
805        Value::String(value) => value.clone(),
806        Value::Number(value) if value.as_f64() == Some(0.0) => String::new(),
807        _ => value.to_string(),
808    }
809}
810
811fn valid_path_parts(dotted_path: &str) -> Result<Vec<&str>, ProjectError> {
812    let parts = dotted_path.split('.').collect::<Vec<_>>();
813    if parts.is_empty() || parts.iter().any(|part| part.is_empty()) {
814        return Err(ProjectError::new(
815            ProjectErrorKind::InvalidPath,
816            "project dotted path must contain only nonempty components",
817        ));
818    }
819    Ok(parts)
820}
821
822fn limit_error(message: impl Into<String>) -> ProjectError {
823    ProjectError::new(ProjectErrorKind::ResourceLimit, message)
824}
825
826fn conflict_error(message: impl Into<String>) -> ProjectError {
827    ProjectError::new(ProjectErrorKind::Conflict, message)
828}
829
830fn io_error(error: std::io::Error) -> ProjectError {
831    ProjectError::new(ProjectErrorKind::Io, format!("project I/O failed: {error}"))
832}