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

kicad_monkey_core/
worksheet.rs

1//! Source-backed KiCad worksheet/page-layout model and exact owned writer.
2
3use crate::sexpr::{
4    Error, ErrorKind, ErrorPhase, Lexer, Patch, Position, Sexp, TokenKind, apply_patches, build,
5    parse, utf8_text,
6};
7use crate::sexpr_projection::{FormSpan, Selector, scan_form_spans};
8use std::io::{Read, Write};
9
10/// KiCad's built-in drawing sheet source, shared by source consumers and plotting.
11pub const DEFAULT_WORKSHEET_SOURCE: &str = concat!(
12    "(kicad_wks (version 20210606) (generator pl_editor)\n",
13    "(setup (textsize 1.5 1.5)(linewidth 0.15)(textlinewidth 0.15)\n",
14    "(left_margin 10)(right_margin 10)(top_margin 10)(bottom_margin 10))\n",
15    "(rect (name \"\") (start 110 34) (end 2 2) (comment \"rect around the title block\"))\n",
16    "(rect (name \"\") (start 0 0 ltcorner) (end 0 0) (repeat 2) (incrx 2) (incry 2))\n",
17    "(line (name \"\") (start 50 2 ltcorner) (end 50 0 ltcorner) (repeat 30) (incrx 50))\n",
18    "(tbtext \"1\" (name \"\") (pos 25 1 ltcorner) (font (size 1.3 1.3)) (repeat 100) (incrx 50))\n",
19    "(line (name \"\") (start 50 2 lbcorner) (end 50 0 lbcorner) (repeat 30) (incrx 50))\n",
20    "(tbtext \"1\" (name \"\") (pos 25 1 lbcorner) (font (size 1.3 1.3)) (repeat 100) (incrx 50))\n",
21    "(line (name \"\") (start 0 50 ltcorner) (end 2 50 ltcorner) (repeat 30) (incry 50))\n",
22    "(tbtext \"A\" (name \"\") (pos 1 25 ltcorner) (font (size 1.3 1.3)) (justify center) (repeat 100) (incry 50))\n",
23    "(line (name \"\") (start 0 50 rtcorner) (end 2 50 rtcorner) (repeat 30) (incry 50))\n",
24    "(tbtext \"A\" (name \"\") (pos 1 25 rtcorner) (font (size 1.3 1.3)) (justify center) (repeat 100) (incry 50))\n",
25    "(tbtext \"Date: ${ISSUE_DATE}\" (name \"\") (pos 87 6.9))\n",
26    "(line (name \"\") (start 110 5.5) (end 2 5.5))\n",
27    "(tbtext \"${KICAD_VERSION}\" (name \"\") (pos 109 4.1) (comment \"Kicad version\"))\n",
28    "(line (name \"\") (start 110 8.5) (end 2 8.5))\n",
29    "(tbtext \"Rev: ${REVISION}\" (name \"\") (pos 24 6.9) (font bold))\n",
30    "(tbtext \"Size: ${PAPER}\" (name \"\") (pos 109 6.9) (comment \"Paper format name\"))\n",
31    "(tbtext \"Id: ${#}/${##}\" (name \"\") (pos 24 4.1) (comment \"Sheet id\"))\n",
32    "(line (name \"\") (start 110 12.5) (end 2 12.5))\n",
33    "(tbtext \"Title: ${TITLE}\" (name \"\") (pos 109 10.7) (font (size 2 2) bold italic))\n",
34    "(tbtext \"File: ${FILENAME}\" (name \"\") (pos 109 14.3))\n",
35    "(line (name \"\") (start 110 18.5) (end 2 18.5))\n",
36    "(tbtext \"Sheet: ${SHEETPATH}\" (name \"\") (pos 109 17))\n",
37    "(tbtext \"${COMPANY}\" (name \"\") (pos 109 20) (font bold) (comment \"Company name\"))\n",
38    "(tbtext \"${COMMENT1}\" (name \"\") (pos 109 23) (comment \"Comment 0\"))\n",
39    "(tbtext \"${COMMENT2}\" (name \"\") (pos 109 26) (comment \"Comment 1\"))\n",
40    "(tbtext \"${COMMENT3}\" (name \"\") (pos 109 29) (comment \"Comment 2\"))\n",
41    "(tbtext \"${COMMENT4}\" (name \"\") (pos 109 32) (comment \"Comment 3\"))\n",
42    "(line (name \"\") (start 90 8.5) (end 90 5.5))\n",
43    "(line (name \"\") (start 26 8.5) (end 26 2))\n",
44    ")\n",
45);
46
47#[derive(Clone, Copy, Debug, Eq, PartialEq)]
48pub enum WorksheetFormat {
49    Modern,
50    Legacy,
51}
52
53#[derive(Clone, Debug, Eq, PartialEq)]
54pub struct WorksheetMetadata {
55    pub format: WorksheetFormat,
56    pub version: i64,
57    pub generator: String,
58    pub generator_version: String,
59}
60
61#[derive(Clone, Copy, Debug, PartialEq)]
62pub struct WorksheetSetup {
63    pub text_size_x: f64,
64    pub text_size_y: f64,
65    pub line_width: f64,
66    pub text_line_width: f64,
67    pub left_margin: f64,
68    pub right_margin: f64,
69    pub top_margin: f64,
70    pub bottom_margin: f64,
71}
72
73impl Default for WorksheetSetup {
74    fn default() -> Self {
75        Self {
76            text_size_x: 1.5,
77            text_size_y: 1.5,
78            line_width: 0.15,
79            text_line_width: 0.15,
80            left_margin: 10.0,
81            right_margin: 10.0,
82            top_margin: 10.0,
83            bottom_margin: 10.0,
84        }
85    }
86}
87
88#[derive(Clone, Copy, Debug, Default, Eq, PartialEq)]
89pub enum WorksheetCorner {
90    #[default]
91    None,
92    LeftTop,
93    RightTop,
94    LeftBottom,
95    RightBottom,
96}
97
98#[derive(Clone, Copy, Debug, Default, PartialEq)]
99pub struct WorksheetPoint {
100    pub x: f64,
101    pub y: f64,
102    pub corner: WorksheetCorner,
103}
104
105#[derive(Clone, Copy, Debug, PartialEq)]
106pub struct WorksheetRepeat {
107    pub count: i64,
108    pub increment_x: f64,
109    pub increment_y: f64,
110    pub increment_label: i64,
111}
112
113impl Default for WorksheetRepeat {
114    fn default() -> Self {
115        Self {
116            count: 1,
117            increment_x: 0.0,
118            increment_y: 0.0,
119            increment_label: 0,
120        }
121    }
122}
123
124#[derive(Clone, Debug, PartialEq)]
125pub struct WorksheetLine {
126    pub name: String,
127    pub comment: String,
128    pub option: String,
129    pub start: WorksheetPoint,
130    pub end: WorksheetPoint,
131    pub line_width: Option<f64>,
132    pub repeat: WorksheetRepeat,
133}
134
135#[derive(Clone, Debug, PartialEq)]
136pub struct WorksheetRect {
137    pub name: String,
138    pub comment: String,
139    pub option: String,
140    pub start: WorksheetPoint,
141    pub end: WorksheetPoint,
142    pub line_width: Option<f64>,
143    pub repeat: WorksheetRepeat,
144}
145
146#[derive(Clone, Debug, PartialEq)]
147pub struct WorksheetPolygon {
148    pub name: String,
149    pub comment: String,
150    pub option: String,
151    pub position: WorksheetPoint,
152    pub rotate: f64,
153    pub line_width: Option<f64>,
154    pub repeat: WorksheetRepeat,
155    /// Independent filled contours, in source order. Additional sets are not holes.
156    pub point_sets: Vec<Vec<(f64, f64)>>,
157}
158
159#[derive(Clone, Copy, Debug, PartialEq)]
160pub struct WorksheetColor {
161    pub red: i64,
162    pub green: i64,
163    pub blue: i64,
164    pub alpha: f64,
165}
166
167#[derive(Clone, Debug, Default, PartialEq)]
168pub struct WorksheetFont {
169    pub size_x: f64,
170    pub size_y: f64,
171    pub line_width: Option<f64>,
172    pub bold: bool,
173    pub italic: bool,
174    pub face: String,
175    pub color: Option<WorksheetColor>,
176}
177
178#[derive(Clone, Debug, PartialEq)]
179pub struct WorksheetText {
180    pub text: String,
181    pub name: String,
182    pub comment: String,
183    pub option: String,
184    pub position: WorksheetPoint,
185    pub font: WorksheetFont,
186    pub justify: Vec<String>,
187    pub rotate: f64,
188    pub repeat: WorksheetRepeat,
189    pub max_length: f64,
190    pub max_height: f64,
191}
192
193#[derive(Clone, Debug, PartialEq)]
194pub struct WorksheetBitmap {
195    pub name: String,
196    pub comment: String,
197    pub option: String,
198    pub position: WorksheetPoint,
199    pub scale: f64,
200    pub repeat: WorksheetRepeat,
201    pub data_parts: Vec<String>,
202}
203
204/// Checked PNG source bytes and the worksheet's scale/DPI-derived drawn extent.
205#[derive(Clone, Debug, PartialEq)]
206pub struct WorksheetBitmapData {
207    pub bytes: Vec<u8>,
208    pub width_nm: i64,
209    pub height_nm: i64,
210}
211
212impl WorksheetBitmap {
213    /// Decode this bitmap only. This reads source facts, not projected drawing output.
214    pub fn image_data(&self) -> Result<WorksheetBitmapData, Error> {
215        use crate::schematic_plotter_ir::image_decode;
216        let bytes = image_decode::decode_base64(&self.data_parts.concat())?;
217        let metadata = image_decode::image_metadata(&bytes)?;
218        if metadata.format != image_decode::ImageFormat::Png {
219            return Err(source_error("worksheet bitmap is not PNG", Position::START));
220        }
221        Ok(WorksheetBitmapData {
222            width_nm: image_decode::extent_nm(metadata.width, self.scale, metadata.ppi_x)?,
223            height_nm: image_decode::extent_nm(metadata.height, self.scale, metadata.ppi_y)?,
224            bytes,
225        })
226    }
227}
228
229#[derive(Clone, Debug, PartialEq)]
230pub enum WorksheetItem {
231    Line(WorksheetLine),
232    Rect(WorksheetRect),
233    Polygon(WorksheetPolygon),
234    Text(WorksheetText),
235    Bitmap(WorksheetBitmap),
236}
237
238/// Borrowed, source-ordered worksheet view.
239#[derive(Clone, Debug)]
240pub struct WorksheetView<'a> {
241    source: &'a str,
242    root: FormSpan,
243    top_level: Vec<FormSpan>,
244}
245
246impl<'a> WorksheetView<'a> {
247    pub fn parse(source: &'a str) -> Result<Self, Error> {
248        let spans = scan_form_spans(
249            source,
250            &Selector {
251                min_depth: Some(0),
252                max_depth: Some(1),
253                ..Selector::default()
254            },
255        )?;
256        let roots = spans
257            .iter()
258            .filter(|span| span.depth == 0)
259            .collect::<Vec<_>>();
260        let [root] = roots.as_slice() else {
261            return Err(source_error(
262                "expected exactly one worksheet root",
263                Position::START,
264            ));
265        };
266        if !matches!(root.head.as_deref(), Some("kicad_wks" | "page_layout")) {
267            return Err(source_error(
268                "expected a kicad_wks or page_layout root",
269                root.start,
270            ));
271        }
272        let root = (*root).clone();
273        let top_level = spans
274            .into_iter()
275            .filter(|span| span.depth == 1)
276            .collect::<Vec<_>>();
277        Ok(Self {
278            source,
279            root,
280            top_level,
281        })
282    }
283
284    pub fn metadata(&self) -> Result<WorksheetMetadata, Error> {
285        Ok(WorksheetMetadata {
286            format: if self.root.head.as_deref() == Some("kicad_wks") {
287                WorksheetFormat::Modern
288            } else {
289                WorksheetFormat::Legacy
290            },
291            version: self
292                .first_scalar("version")?
293                .map_or(Ok(0), |value| integer_text(&value))?,
294            generator: self.first_scalar("generator")?.unwrap_or_default(),
295            generator_version: self.first_scalar("generator_version")?.unwrap_or_default(),
296        })
297    }
298
299    pub fn setup(&self) -> Result<WorksheetSetup, Error> {
300        self.first_form("setup")?
301            .as_ref()
302            .map_or(Ok(WorksheetSetup::default()), setup)
303    }
304
305    pub fn items(&self) -> impl Iterator<Item = Result<WorksheetItem, Error>> + '_ {
306        self.top_level
307            .iter()
308            .filter(|span| is_item_head(span.head.as_deref()))
309            .map(|span| self.item(span))
310    }
311
312    pub fn item_count(&self) -> usize {
313        self.top_level
314            .iter()
315            .filter(|span| is_item_head(span.head.as_deref()))
316            .count()
317    }
318
319    fn item(&self, span: &FormSpan) -> Result<WorksheetItem, Error> {
320        let value = self.parse_span(span)?;
321        match span.head.as_deref() {
322            Some("line") => line(value).map(WorksheetItem::Line),
323            Some("rect") => rect(value).map(WorksheetItem::Rect),
324            Some("polygon") => polygon(value).map(WorksheetItem::Polygon),
325            Some("tbtext") => text(value).map(WorksheetItem::Text),
326            Some("bitmap") => bitmap(value).map(WorksheetItem::Bitmap),
327            _ => Err(source_error("unknown worksheet item", span.start)),
328        }
329        .map_err(|error| rebase_error(error, span))
330    }
331
332    fn first_scalar(&self, head: &str) -> Result<Option<String>, Error> {
333        Ok(self
334            .first_form(head)?
335            .as_ref()
336            .and_then(|value| list(value).get(1))
337            .map(scalar))
338    }
339
340    fn first_form(&self, head: &str) -> Result<Option<Sexp>, Error> {
341        let Some(span) = self
342            .top_level
343            .iter()
344            .find(|span| span.head.as_deref() == Some(head))
345        else {
346            return Ok(None);
347        };
348        self.parse_span(span).map(Some)
349    }
350
351    fn parse_span(&self, span: &FormSpan) -> Result<Sexp, Error> {
352        let text = span.text(self.source)?;
353        parse(text).map_err(|error| rebase_error(error, span))
354    }
355}
356
357/// Owned exact worksheet source.
358#[derive(Clone, Debug)]
359pub struct WorksheetDocument {
360    source: String,
361}
362
363impl WorksheetDocument {
364    pub fn parse(source: String) -> Result<Self, Error> {
365        WorksheetView::parse(&source)?;
366        Ok(Self { source })
367    }
368
369    pub fn from_reader(mut reader: impl Read) -> Result<Self, Error> {
370        let mut bytes = Vec::new();
371        reader.read_to_end(&mut bytes).map_err(io_error)?;
372        Self::parse(utf8_text(&bytes)?.to_owned())
373    }
374
375    pub fn source(&self) -> &str {
376        &self.source
377    }
378
379    pub fn view(&self) -> Result<WorksheetView<'_>, Error> {
380        WorksheetView::parse(&self.source)
381    }
382
383    pub fn write_to(&self, mut writer: impl Write) -> Result<(), Error> {
384        writer.write_all(self.source.as_bytes()).map_err(io_error)
385    }
386
387    /// Update or create the worksheet setup line width and reparse before commit.
388    pub fn set_setup_line_width(&mut self, line_width: f64) -> Result<bool, Error> {
389        if !line_width.is_finite() {
390            return Err(source_error(
391                "worksheet line width must be finite",
392                Position::START,
393            ));
394        }
395        let replacement = build(&Sexp::Float(line_width))?;
396        let view = self.view()?;
397        let setup_spans = view
398            .top_level
399            .iter()
400            .filter(|span| span.head.as_deref() == Some("setup"))
401            .collect::<Vec<_>>();
402        let patch = match setup_spans.as_slice() {
403            [] => {
404                let form = format!("(setup (linewidth {replacement}))");
405                Some(insertion_patch(&self.source, &view.root, &form))
406            }
407            [setup_span] => self.setup_line_width_patch(setup_span, line_width, &replacement)?,
408            _ => {
409                return Err(source_error(
410                    "worksheet setup form is ambiguous",
411                    view.root.start,
412                ));
413            }
414        };
415        let Some(patch) = patch else {
416            return Ok(false);
417        };
418        self.commit_patch(patch)
419    }
420
421    fn setup_line_width_patch<'a>(
422        &self,
423        setup_span: &FormSpan,
424        line_width: f64,
425        replacement: &'a str,
426    ) -> Result<Option<Patch<'a>>, Error> {
427        let setup = setup_span.text(&self.source)?;
428        let spans = scan_form_spans(
429            setup,
430            &Selector {
431                heads: Some(["linewidth".to_owned()].into_iter().collect()),
432                min_depth: Some(1),
433                max_depth: Some(1),
434                ..Selector::default()
435            },
436        )
437        .map_err(|error| rebase_error(error, setup_span))?;
438        match spans.as_slice() {
439            [] => Ok(Some(insertion_patch(
440                &self.source,
441                setup_span,
442                &format!("(linewidth {replacement})"),
443            ))),
444            [span] => {
445                let (current, range) = scalar_value_range(setup, span)?;
446                if number(&current)? == line_width {
447                    return Ok(None);
448                }
449                Ok(Some(Patch::new(
450                    setup_span.range.start + range.start,
451                    setup_span.range.start + range.end,
452                    replacement,
453                )))
454            }
455            _ => Err(source_error(
456                "worksheet setup linewidth is ambiguous",
457                setup_span.start,
458            )),
459        }
460    }
461
462    fn commit_patch(&mut self, patch: Patch<'_>) -> Result<bool, Error> {
463        let candidate = apply_patches(&self.source, &[patch])?;
464        WorksheetView::parse(&candidate)?;
465        self.source = candidate;
466        Ok(true)
467    }
468}
469
470fn scalar_value_range(
471    source: &str,
472    span: &FormSpan,
473) -> Result<(Sexp, std::ops::Range<usize>), Error> {
474    let text = span.text(source)?;
475    let mut lexer = Lexer::new(text);
476    for expected in [TokenKind::Left, TokenKind::Atom] {
477        let token = lexer
478            .next()
479            .transpose()?
480            .ok_or_else(|| source_error("worksheet scalar form is incomplete", span.start))?;
481        if token.kind != expected {
482            return Err(source_error(
483                "worksheet scalar form is malformed",
484                span.start,
485            ));
486        }
487    }
488    let token = lexer
489        .next()
490        .transpose()?
491        .ok_or_else(|| source_error("worksheet scalar value is missing", span.start))?;
492    if matches!(token.kind, TokenKind::Left | TokenKind::Right) {
493        return Err(source_error(
494            "worksheet scalar value is malformed",
495            span.start,
496        ));
497    }
498    let value = match token.kind {
499        TokenKind::Integer => Sexp::Integer(
500            token
501                .lexeme
502                .parse()
503                .map_err(|_| source_error("expected worksheet integer", span.start))?,
504        ),
505        TokenKind::Float => Sexp::Float(
506            token
507                .lexeme
508                .parse()
509                .map_err(|_| source_error("expected worksheet number", span.start))?,
510        ),
511        _ => Sexp::Atom(token.lexeme.to_owned()),
512    };
513    Ok((
514        value,
515        (span.range.start + token.position.offset)
516            ..(span.range.start + token.position.offset + token.lexeme.len()),
517    ))
518}
519
520fn insertion_patch(source: &str, parent: &FormSpan, form: &str) -> Patch<'static> {
521    let close = parent.range.end.saturating_sub(1);
522    let line_start = source[..close].rfind('\n').map_or(0, |offset| offset + 1);
523    let close_prefix = &source[line_start..close];
524    let newline = if source.contains("\r\n") {
525        "\r\n"
526    } else {
527        "\n"
528    };
529    let parent_line_start = source[..parent.range.start]
530        .rfind('\n')
531        .map_or(0, |offset| offset + 1);
532    let parent_indent = source[parent_line_start..parent.range.start]
533        .chars()
534        .take_while(|character| character.is_whitespace())
535        .collect::<String>();
536    let child_indent = format!("{parent_indent}  ");
537    let (offset, replacement) = if close_prefix.trim().is_empty() {
538        (line_start, format!("{child_indent}{form}{newline}"))
539    } else {
540        (
541            close,
542            format!("{newline}{child_indent}{form}{newline}{parent_indent}"),
543        )
544    };
545    Patch::new(offset, offset, replacement)
546}
547
548fn setup(value: &Sexp) -> Result<WorksheetSetup, Error> {
549    let mut result = WorksheetSetup::default();
550    if let Some(values) = child(value, "textsize") {
551        result.text_size_x = number_at(values, 1, 1.5)?;
552        result.text_size_y = number_at(values, 2, result.text_size_x)?;
553    }
554    result.line_width = child_number(value, "linewidth", 0.15)?;
555    result.text_line_width = child_number(value, "textlinewidth", 0.15)?;
556    result.left_margin = child_number(value, "left_margin", 10.0)?;
557    result.right_margin = child_number(value, "right_margin", 10.0)?;
558    result.top_margin = child_number(value, "top_margin", 10.0)?;
559    result.bottom_margin = child_number(value, "bottom_margin", 10.0)?;
560    Ok(result)
561}
562
563fn line(value: Sexp) -> Result<WorksheetLine, Error> {
564    Ok(WorksheetLine {
565        name: child_string(&value, "name"),
566        comment: child_string(&value, "comment"),
567        option: option(&value),
568        start: point(&value, "start")?,
569        end: point(&value, "end")?,
570        line_width: child_optional_number(&value, "linewidth")?,
571        repeat: repeat(&value)?,
572    })
573}
574
575fn rect(value: Sexp) -> Result<WorksheetRect, Error> {
576    Ok(WorksheetRect {
577        name: child_string(&value, "name"),
578        comment: child_string(&value, "comment"),
579        option: option(&value),
580        start: point(&value, "start")?,
581        end: point(&value, "end")?,
582        line_width: child_optional_number(&value, "linewidth")?,
583        repeat: repeat(&value)?,
584    })
585}
586
587fn polygon(value: Sexp) -> Result<WorksheetPolygon, Error> {
588    let mut point_sets = Vec::new();
589    for values in children(&value, "pts") {
590        let mut points = Vec::new();
591        for xy in children_in(values, "xy") {
592            if xy.len() >= 3 {
593                points.push((number_at(xy, 1, 0.0)?, number_at(xy, 2, 0.0)?));
594            }
595        }
596        if !points.is_empty() {
597            point_sets.push(points);
598        }
599    }
600    Ok(WorksheetPolygon {
601        name: child_string(&value, "name"),
602        comment: child_string(&value, "comment"),
603        option: option(&value),
604        position: point(&value, "pos")?,
605        rotate: child_number(&value, "rotate", 0.0)?,
606        line_width: child_optional_number(&value, "linewidth")?,
607        repeat: repeat(&value)?,
608        point_sets,
609    })
610}
611
612fn text(value: Sexp) -> Result<WorksheetText, Error> {
613    let mut justify = Vec::new();
614    if let Some(values) = child(&value, "justify") {
615        for item in &values[1..] {
616            let value = scalar(item);
617            if matches!(
618                value.as_str(),
619                "left" | "center" | "right" | "top" | "bottom"
620            ) {
621                justify.push(value);
622            }
623        }
624    }
625    Ok(WorksheetText {
626        text: list(&value).get(1).map_or_else(String::new, scalar),
627        name: child_string(&value, "name"),
628        comment: child_string(&value, "comment"),
629        option: option(&value),
630        position: point(&value, "pos")?,
631        font: font(&value)?,
632        justify,
633        rotate: child_number(&value, "rotate", 0.0)?,
634        repeat: repeat(&value)?,
635        max_length: child_number(&value, "maxlen", 0.0)?,
636        max_height: child_number(&value, "maxheight", 0.0)?,
637    })
638}
639
640fn font(value: &Sexp) -> Result<WorksheetFont, Error> {
641    let Some(font) = child(value, "font") else {
642        return Ok(WorksheetFont::default());
643    };
644    let (size_x, size_y) = child_in(font, "size").map_or(Ok((0.0, 0.0)), |size| {
645        let x = number_at(size, 1, 0.0)?;
646        Ok((x, number_at(size, 2, x)?))
647    })?;
648    let color = child_in(font, "color")
649        .filter(|color| color.len() >= 5)
650        .map(|color| {
651            Ok(WorksheetColor {
652                red: integer_at(color, 1, 0)?,
653                green: integer_at(color, 2, 0)?,
654                blue: integer_at(color, 3, 0)?,
655                alpha: number_at(color, 4, 0.0)?,
656            })
657        })
658        .transpose()?;
659    Ok(WorksheetFont {
660        size_x,
661        size_y,
662        line_width: child_optional_number_from_list(font, "linewidth")?,
663        bold: has_atom(font, "bold"),
664        italic: has_atom(font, "italic"),
665        face: child_string_from_list(font, "face"),
666        color,
667    })
668}
669
670fn bitmap(value: Sexp) -> Result<WorksheetBitmap, Error> {
671    let mut data_parts = Vec::new();
672    if let Some(values) = child(&value, "data") {
673        data_parts.extend(values[1..].iter().filter_map(string_scalar));
674    } else if let Some(part) =
675        child(&value, "pngdata").and_then(|values| values[1..].iter().find_map(scalar_value))
676    {
677        data_parts.push(part);
678    }
679    Ok(WorksheetBitmap {
680        name: child_string(&value, "name"),
681        comment: child_string(&value, "comment"),
682        option: option(&value),
683        position: point(&value, "pos")?,
684        scale: child_number(&value, "scale", 1.0)?,
685        repeat: repeat(&value)?,
686        data_parts,
687    })
688}
689
690fn point(value: &Sexp, head: &str) -> Result<WorksheetPoint, Error> {
691    let Some(values) = child(value, head) else {
692        return Ok(WorksheetPoint::default());
693    };
694    Ok(WorksheetPoint {
695        x: number_at(values, 1, 0.0)?,
696        y: number_at(values, 2, 0.0)?,
697        corner: values
698            .get(3)
699            .map_or(WorksheetCorner::None, |value| corner(&scalar(value))),
700    })
701}
702
703fn repeat(value: &Sexp) -> Result<WorksheetRepeat, Error> {
704    Ok(WorksheetRepeat {
705        count: child(value, "repeat").map_or(Ok(1), |values| integer_at(values, 1, 1))?,
706        increment_x: child_number(value, "incrx", 0.0)?,
707        increment_y: child_number(value, "incry", 0.0)?,
708        increment_label: child(value, "incrlabel")
709            .map_or(Ok(0), |values| integer_at(values, 1, 0))?,
710    })
711}
712
713fn option(value: &Sexp) -> String {
714    match child_string(value, "option").as_str() {
715        "page1only" => "page1only".to_owned(),
716        "notonpage1" => "notonpage1".to_owned(),
717        _ => String::new(),
718    }
719}
720
721fn corner(value: &str) -> WorksheetCorner {
722    match value {
723        "ltcorner" => WorksheetCorner::LeftTop,
724        "rtcorner" => WorksheetCorner::RightTop,
725        "lbcorner" => WorksheetCorner::LeftBottom,
726        "rbcorner" => WorksheetCorner::RightBottom,
727        _ => WorksheetCorner::None,
728    }
729}
730
731fn is_item_head(head: Option<&str>) -> bool {
732    matches!(
733        head,
734        Some("line" | "rect" | "polygon" | "tbtext" | "bitmap")
735    )
736}
737
738fn list(value: &Sexp) -> &[Sexp] {
739    match value {
740        Sexp::List(values) => values,
741        _ => &[],
742    }
743}
744
745fn child<'a>(value: &'a Sexp, head: &str) -> Option<&'a [Sexp]> {
746    child_in(list(value), head)
747}
748
749fn children<'a>(value: &'a Sexp, head: &'a str) -> impl Iterator<Item = &'a [Sexp]> {
750    children_in(list(value), head)
751}
752
753fn child_in<'a>(value: &'a [Sexp], head: &str) -> Option<&'a [Sexp]> {
754    value.iter().find_map(|child| {
755        let values = list(child);
756        values
757            .first()
758            .is_some_and(|value| is_atom(value, head))
759            .then_some(values)
760    })
761}
762
763fn children_in<'a>(value: &'a [Sexp], head: &'a str) -> impl Iterator<Item = &'a [Sexp]> {
764    value.iter().filter_map(move |child| {
765        let values = list(child);
766        values
767            .first()
768            .is_some_and(|value| is_atom(value, head))
769            .then_some(values)
770    })
771}
772
773fn is_atom(value: &Sexp, expected: &str) -> bool {
774    matches!(value, Sexp::Atom(value) if value == expected)
775}
776
777fn child_string(value: &Sexp, head: &str) -> String {
778    child(value, head)
779        .and_then(|values| values.get(1))
780        .map_or_else(String::new, scalar)
781}
782
783fn child_string_from_list(value: &[Sexp], head: &str) -> String {
784    value
785        .iter()
786        .find_map(|child| {
787            let values = list(child);
788            (values.first().is_some_and(|value| is_atom(value, head)))
789                .then(|| values.get(1).map_or_else(String::new, scalar))
790        })
791        .unwrap_or_default()
792}
793
794fn child_number(value: &Sexp, head: &str, default: f64) -> Result<f64, Error> {
795    child(value, head).map_or(Ok(default), |values| number_at(values, 1, default))
796}
797
798fn child_optional_number(value: &Sexp, head: &str) -> Result<Option<f64>, Error> {
799    child(value, head)
800        .map(|values| number_at(values, 1, 0.0))
801        .transpose()
802}
803
804fn child_optional_number_from_list(value: &[Sexp], head: &str) -> Result<Option<f64>, Error> {
805    value
806        .iter()
807        .find_map(|child| {
808            let values = list(child);
809            values
810                .first()
811                .is_some_and(|value| is_atom(value, head))
812                .then_some(values)
813        })
814        .map(|values| number_at(values, 1, 0.0))
815        .transpose()
816}
817
818fn has_atom(value: &[Sexp], atom: &str) -> bool {
819    value
820        .iter()
821        .any(|value| matches!(value, Sexp::Atom(found) if found == atom))
822}
823
824fn number_at(values: &[Sexp], index: usize, default: f64) -> Result<f64, Error> {
825    values.get(index).map_or(Ok(default), number)
826}
827
828fn number(value: &Sexp) -> Result<f64, Error> {
829    let parsed = match value {
830        Sexp::Integer(value) => *value as f64,
831        Sexp::Float(value) => *value,
832        _ => scalar(value)
833            .parse::<f64>()
834            .map_err(|_| source_error("expected worksheet number", Position::START))?,
835    };
836    if !parsed.is_finite() {
837        return Err(source_error(
838            "worksheet number must be finite",
839            Position::START,
840        ));
841    }
842    Ok(parsed)
843}
844
845fn integer_at(values: &[Sexp], index: usize, default: i64) -> Result<i64, Error> {
846    values.get(index).map_or(Ok(default), integer)
847}
848
849fn integer(value: &Sexp) -> Result<i64, Error> {
850    match value {
851        Sexp::Integer(value) => Ok(*value),
852        _ => integer_text(&scalar(value)),
853    }
854}
855
856fn integer_text(value: &str) -> Result<i64, Error> {
857    value
858        .parse()
859        .map_err(|_| source_error("expected worksheet integer", Position::START))
860}
861
862fn scalar(value: &Sexp) -> String {
863    match value {
864        Sexp::Atom(value) | Sexp::Quoted(value) => value.clone(),
865        Sexp::Integer(value) => value.to_string(),
866        Sexp::Float(value) => value.to_string(),
867        Sexp::List(_) => String::new(),
868    }
869}
870
871fn string_scalar(value: &Sexp) -> Option<String> {
872    match value {
873        Sexp::Atom(value) | Sexp::Quoted(value) => Some(value.clone()),
874        _ => None,
875    }
876}
877
878fn scalar_value(value: &Sexp) -> Option<String> {
879    (!matches!(value, Sexp::List(_))).then(|| scalar(value))
880}
881
882fn rebase_error(mut error: Error, span: &FormSpan) -> Error {
883    if let Some(position) = error.position {
884        error.position = Some(Position {
885            offset: span.range.start.saturating_add(position.offset),
886            line: span
887                .start
888                .line
889                .saturating_add(position.line.saturating_sub(1)),
890            column: if position.line == 1 {
891                span.start
892                    .column
893                    .saturating_add(position.column.saturating_sub(1))
894            } else {
895                position.column
896            },
897        });
898    }
899    error
900}
901
902fn source_error(message: &'static str, position: Position) -> Error {
903    Error::at(
904        ErrorPhase::Tree,
905        ErrorKind::UnexpectedToken,
906        message,
907        position,
908    )
909}
910
911fn io_error(error: std::io::Error) -> Error {
912    Error::build(
913        ErrorKind::Io,
914        format!("worksheet source I/O failed: {error}"),
915    )
916}