lib_gerber_edit 0.5.0

A libary for manipululating extended gerber data (RS-274X)
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
use crate::error::ParseError;
use crate::excellon_format::{ExcellonLayerData, parse_excellon};
use crate::gerber::GerberLayerData;
use crate::{LayerMerge, LayerStepAndRepeat, LayerTransform, Pos};
use gerber_parser::gerber_types::{
    Command, CommentContent, ExtendedCode, ExtendedPosition, FileAttribute, FileFunction,
    FunctionCode, GCode, GerberResult, Position, Profile, StandardComment,
};
use std::fmt::{Display, Formatter};
use std::io::{BufReader, BufWriter, Read, Write};

#[cfg(feature = "serde")]
use ::serde::{Deserialize, Serialize};

#[derive(Debug, Clone, PartialEq)]
pub enum LayerData {
    Gerber(GerberLayerData),
    Excellon(ExcellonLayerData),
    Info(String),
}

#[derive(Debug, Clone, PartialEq)]
pub struct Layer {
    pub ty: LayerType,
    pub name: String,
    pub data: LayerData,
}

impl LayerData {
    pub fn parse<T>(
        ty: LayerType,
        reader: BufReader<T>,
    ) -> Result<(LayerType, LayerData), ParseError>
    where
        T: Read,
    {
        Ok(match ty {
            LayerType::Drill => (
                ty,
                LayerData::Excellon(
                    parse_excellon(reader).map_err(ParseError::ExcellonParseError)?,
                ),
            ),
            LayerType::UndefinedGerber => {
                let layer = GerberLayerData::from_commands(reader)?;
                (layer.layer_type, LayerData::Gerber(layer))
            }
            _ => (
                ty,
                LayerData::Gerber(GerberLayerData::from_type(ty, reader)?),
            ),
        })
    }

    pub fn write_to<T>(&self, writer: &mut BufWriter<T>) -> GerberResult<()>
    where
        T: Write,
    {
        match self {
            LayerData::Gerber(g) => g.write_to(writer)?,
            LayerData::Excellon(e) => e.write_to(writer)?,
            LayerData::Info(s) => writer.write_all(s.to_string().as_bytes())?,
        }
        Ok(())
    }

    pub fn get_type(&self) -> LayerType {
        match self {
            LayerData::Gerber(layer) => layer.layer_type,
            LayerData::Excellon(_) => LayerType::Drill,
            LayerData::Info(_) => LayerType::Info,
        }
    }

    pub fn is_empty(&self) -> bool {
        match self {
            LayerData::Gerber(layer) => layer.is_empty(),
            LayerData::Excellon(layer) => layer.is_empty(),
            LayerData::Info(data) => data.is_empty(),
        }
    }
}

impl LayerMerge for LayerData {
    fn merge(&mut self, other: &Self) {
        match (self, other) {
            (LayerData::Excellon(s), LayerData::Excellon(o)) => {
                s.merge(o);
            }
            (LayerData::Gerber(s), LayerData::Gerber(o)) => {
                s.merge(o);
            }
            _ => panic!("Cannot merge layers of diffrent type"),
        }
    }
}

impl LayerTransform for LayerData {
    fn transform(&mut self, transform: &Pos) {
        match self {
            LayerData::Excellon(s) => s.transform(transform),
            LayerData::Gerber(s) => s.transform(transform),
            LayerData::Info(_) => {}
        }
    }
}

impl LayerStepAndRepeat for LayerData {
    fn step_and_repeat(&mut self, x_repetitions: u32, y_repetitions: u32, offset: &Pos) {
        match self {
            LayerData::Gerber(g) => {
                g.step_and_repeat(x_repetitions, y_repetitions, offset);
            }
            LayerData::Excellon(e) => {
                e.step_and_repeat(x_repetitions, y_repetitions, offset);
            }
            LayerData::Info(_) => {}
        }
    }
}

/// Layer Type
///
/// All Layers except Drill are usually gerber layers
/// The grill layer is a excellon drill file
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
pub enum LayerType {
    Top,
    Bottom,
    Inner(i32),
    PasteTop,
    PasteBottom,
    MaskTop,
    MaskBottom,
    SilkScreenTop,
    SilkScreenBottom,
    Drill,
    Dimensions,
    Milling,
    VCut,
    SidePlating,
    KeepOut,
    Info,
    UndefinedGerber,
}

impl TryFrom<&str> for LayerType {
    type Error = String;

    fn try_from(value: &str) -> Result<Self, Self::Error> {
        match value.to_uppercase().as_str() {
            "GTL" => Ok(LayerType::Top),
            "GBL" => Ok(LayerType::Bottom),
            "GTP" => Ok(LayerType::PasteTop),
            "GBP" => Ok(LayerType::PasteBottom),
            "GTS" => Ok(LayerType::MaskTop),
            "GBS" => Ok(LayerType::MaskBottom),
            "GTO" => Ok(LayerType::SilkScreenTop),
            "GBO" => Ok(LayerType::SilkScreenBottom),
            "DRD" | "DRL" => Ok(LayerType::Drill),
            "GM1" => Ok(LayerType::Dimensions),
            "GM2" => Ok(LayerType::Milling),
            "GVC" => Ok(LayerType::VCut),
            "GSP" => Ok(LayerType::SidePlating),
            "GKO" => Ok(LayerType::KeepOut),
            "GBR" => Ok(LayerType::UndefinedGerber),
            _ if value.starts_with("GL") => {
                let inner_num = value[2..]
                    .parse::<i32>()
                    .map_err(|_| "GL must be followed by numbers")?;
                Ok(LayerType::Inner(inner_num))
            }
            _ => Err(format!("Invalid layer type: {}", value)),
        }
    }
}

impl LayerType {
    /// Searches for a matching FileAttribute in a set of commands
    pub fn from_commands<'a, I: IntoIterator<Item = &'a Command>>(value: I) -> Option<Self> {
        let mut iter = value.into_iter();
        iter.find_map(|c| match c {
            Command::ExtendedCode(ExtendedCode::FileAttribute(FileAttribute::FileFunction(
                file_function,
            ))) => Some(file_function),
            Command::FunctionCode(FunctionCode::GCode(GCode::Comment(
                CommentContent::Standard(StandardComment::FileAttribute(
                    FileAttribute::FileFunction(file_function),
                )),
            ))) => Some(file_function),
            _ => None,
        })
        .map(LayerType::layer_type)
    }
}

impl LayerType {
    /// Returns the default extensional
    pub const fn file_ending(&self) -> &'static str {
        match self {
            LayerType::Info => "txt",
            LayerType::Drill => "drl",
            LayerType::UndefinedGerber => "gbr",
            _ => "gbr",
        }
    }

    /// Converts FileFunction to matching LayerType
    #[allow(clippy::self_named_constructors)]
    pub fn layer_type(file_function: &FileFunction) -> LayerType {
        match file_function {
            FileFunction::Copper {
                layer: _,
                pos: ExtendedPosition::Top,
                copper_type: _,
            } => LayerType::Top,
            FileFunction::Copper {
                layer: _,
                pos: ExtendedPosition::Bottom,
                copper_type: _,
            } => LayerType::Bottom,
            FileFunction::Copper {
                layer,
                pos: ExtendedPosition::Inner,
                copper_type: _,
            } => LayerType::Inner(*layer),
            FileFunction::Paste(Position::Top) => LayerType::PasteTop,
            FileFunction::Paste(Position::Bottom) => LayerType::PasteBottom,
            FileFunction::SolderMask {
                pos: Position::Top,
                index: _,
            } => LayerType::MaskTop,
            FileFunction::SolderMask {
                pos: Position::Bottom,
                index: _,
            } => LayerType::MaskBottom,
            FileFunction::Legend {
                pos: Position::Top,
                index: _,
            } => LayerType::SilkScreenTop,
            FileFunction::Legend {
                pos: Position::Bottom,
                index: _,
            } => LayerType::SilkScreenBottom,
            FileFunction::DrillMap => LayerType::Drill,
            FileFunction::Profile(Some(Profile::Plated)) => LayerType::SidePlating,
            FileFunction::Profile(_) => LayerType::Dimensions,
            FileFunction::VCut(_) => LayerType::VCut,
            FileFunction::KeepOut(_) => LayerType::KeepOut,
            FileFunction::Other(_) => LayerType::Info,
            _ => LayerType::UndefinedGerber,
        }
    }

    /// Converts LayerType to matching FileFunction
    pub fn function(&self) -> FileFunction {
        match self {
            LayerType::Top => FileFunction::Copper {
                layer: 1,
                pos: ExtendedPosition::Top,
                copper_type: None,
            },
            LayerType::Bottom => FileFunction::Copper {
                layer: 99,
                pos: ExtendedPosition::Bottom,
                copper_type: None,
            },
            LayerType::Inner(layer) => FileFunction::Copper {
                layer: *layer,
                pos: ExtendedPosition::Inner,
                copper_type: None,
            },
            LayerType::PasteTop => FileFunction::Paste(Position::Top),
            LayerType::PasteBottom => FileFunction::Paste(Position::Bottom),
            LayerType::MaskTop => FileFunction::SolderMask {
                pos: Position::Top,
                index: None,
            },
            LayerType::MaskBottom => FileFunction::SolderMask {
                pos: Position::Bottom,
                index: None,
            },
            LayerType::SilkScreenTop => FileFunction::Legend {
                pos: Position::Top,
                index: None,
            },
            LayerType::SilkScreenBottom => FileFunction::Legend {
                pos: Position::Bottom,
                index: None,
            },
            LayerType::Drill => FileFunction::DrillMap,
            LayerType::Dimensions => FileFunction::Profile(None),
            LayerType::Milling => FileFunction::Profile(Some(Profile::NonPlated)),
            LayerType::VCut => FileFunction::VCut(None),
            LayerType::SidePlating => FileFunction::Profile(Some(Profile::Plated)),
            LayerType::KeepOut => FileFunction::KeepOut(Position::Top),
            LayerType::Info => FileFunction::Other(String::from("Text")),
            LayerType::UndefinedGerber => FileFunction::Other(String::from("Undefined")),
        }
    }
}

impl Display for LayerType {
    fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
        write!(f, "{} ", self.file_ending())?;
        match self {
            LayerType::Top => write!(f, "Copper Top Layer")?,
            LayerType::Bottom => write!(f, "Copper Bottom Layer")?,
            LayerType::Inner(num) => write!(f, "Copper Inner Layer {}", num)?,
            LayerType::PasteTop => write!(f, "Paste Top Layer")?,
            LayerType::PasteBottom => write!(f, "Paste Bottom Layer")?,
            LayerType::MaskTop => write!(f, "Mask Top Layer")?,
            LayerType::MaskBottom => write!(f, "Mask Bottom Layer")?,
            LayerType::SilkScreenTop => write!(f, "Silk Screen Top Layer")?,
            LayerType::SilkScreenBottom => write!(f, "Silk Screen Bottom Layer")?,
            LayerType::Drill => write!(f, "Drill Layer")?,
            LayerType::Dimensions => write!(f, "Dimension Layer")?,
            LayerType::Milling => write!(f, "Milling Layer")?,
            LayerType::VCut => write!(f, "V-Cut Layer")?,
            LayerType::SidePlating => write!(f, "Side Plating Layer")?,
            LayerType::KeepOut => write!(f, "Keep Out Layer")?,
            LayerType::Info => write!(f, "Info")?,
            LayerType::UndefinedGerber => write!(f, "Undefined")?,
        };
        Ok(())
    }
}

impl From<Layer> for LayerData {
    fn from(layer: Layer) -> Self {
        layer.data
    }
}

impl From<&Layer> for LayerData {
    fn from(layer: &Layer) -> Self {
        layer.data.clone()
    }
}

impl From<GerberLayerData> for Layer {
    /// Wraps a [`GerberLayerData`] in a [`Layer`].
    ///
    /// The `name` is set to the default file extension for the layer type
    /// (e.g. `"gto"` for `SilkScreenTop`). Override `layer.name` afterwards
    /// if a specific filename is needed.
    fn from(data: GerberLayerData) -> Self {
        Layer {
            name: data.layer_type.file_ending().to_string(),
            ty: data.layer_type,
            data: LayerData::Gerber(data),
        }
    }
}

impl From<ExcellonLayerData> for Layer {
    /// Wraps an [`ExcellonLayerData`] in a [`Layer`].
    ///
    /// The `name` is set to `"drl"`. Override `layer.name` afterwards if a
    /// specific filename is needed.
    fn from(data: ExcellonLayerData) -> Self {
        Layer {
            name: LayerType::Drill.file_ending().to_string(),
            ty: LayerType::Drill,
            data: LayerData::Excellon(data),
        }
    }
}

#[cfg(feature = "serde")]
mod serde {
    use crate::layer::{Layer, LayerData};
    use serde::ser::{Error, SerializeStruct};
    use serde::{Serialize, Serializer};
    use std::io::BufWriter;

    impl Serialize for LayerData {
        fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
        where
            S: Serializer,
        {
            let mut writer = BufWriter::new(Vec::new());
            self.write_to(&mut writer).map_err(S::Error::custom)?;
            serializer.serialize_str(&String::from_utf8_lossy(
                &writer.into_inner().map_err(S::Error::custom)?,
            ))
        }
    }

    impl Serialize for Layer {
        fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
        where
            S: Serializer,
        {
            let mut str = serializer.serialize_struct("Layer", 4)?;
            str.serialize_field("name", &self.name)?;
            str.serialize_field("type", &self.ty)?;
            str.serialize_field("file_type", &self.ty.file_ending())?;
            str.serialize_field("data", &self.data)?;
            str.end()
        }
    }
}