altium-format 0.1.7

Core altium-cli library for reading and writing Altium Designer 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
//! Parameter collection for Altium's pipe-delimited key-value storage.
//!
//! Altium stores most schematic and library data as pipe-delimited parameters.
//! Example: `|RECORD=1|LIBREFERENCE=Component|COMPONENTDESCRIPTION=Resistor|`
//!
//! Key implementation details:
//! - Uses IndexMap to preserve insertion order
//! - Nesting level changes separator (`|` at level 0, `` ` `` at level 1)
//! - Handles `%UTF8%` prefix for Unicode values

use encoding_rs::WINDOWS_1252;
use indexmap::IndexMap;
use std::fmt;

use crate::io::reader::read_parameters_block;
use crate::io::writer::write_parameters_block;
use crate::traits::{FromBinary, ToBinary};
use crate::types::{Color, Coord, Layer, Unit};

/// Entry separators for different nesting levels.
const ENTRY_SEPARATORS: &[char] = &['|', '`'];

/// Key-value separator.
const KEY_VALUE_SEPARATOR: char = '=';

/// UTF-8 prefix marker.
const UTF8_PREFIX: &str = "%UTF8%";

/// Boolean true values.
const TRUE_VALUES: &[&str] = &["T", "TRUE"];

/// Boolean false values.
const FALSE_VALUES: &[&str] = &["F", "FALSE"];

/// Value of a parameter with typed conversion methods.
#[derive(Clone, Debug, Default)]
pub struct ParameterValue {
    data: String,
    level: usize,
}

impl ParameterValue {
    /// Creates a new parameter value.
    pub fn new(data: String, level: usize) -> Self {
        ParameterValue { data, level }
    }

    /// Gets the raw string value.
    #[inline]
    pub fn as_str(&self) -> &str {
        &self.data
    }

    /// Gets the string value, or a default if empty.
    pub fn as_string_or(&self, default: &str) -> String {
        if self.data.is_empty() {
            default.to_string()
        } else {
            self.data.clone()
        }
    }

    /// Parses the value as an integer.
    pub fn as_int(&self) -> Result<i32, std::num::ParseIntError> {
        self.data.trim().parse()
    }

    /// Gets the value as an integer, or a default on parse failure.
    pub fn as_int_or(&self, default: i32) -> i32 {
        self.data.trim().parse().unwrap_or(default)
    }

    /// Parses the value as a double.
    pub fn as_double(&self) -> Result<f64, std::num::ParseFloatError> {
        self.data.trim().parse()
    }

    /// Gets the value as a double, or a default on parse failure.
    pub fn as_double_or(&self, default: f64) -> f64 {
        self.data.trim().parse().unwrap_or(default)
    }

    /// Parses the value as a boolean.
    ///
    /// Accepts: "T", "TRUE" (true), "F", "FALSE" (false)
    pub fn as_bool(&self) -> Result<bool, &'static str> {
        let s = self.data.trim().to_uppercase();
        if TRUE_VALUES.contains(&s.as_str()) {
            Ok(true)
        } else if FALSE_VALUES.contains(&s.as_str()) || s.is_empty() {
            Ok(false)
        } else {
            Err("Invalid boolean value")
        }
    }

    /// Gets the value as a boolean, or a default on parse failure.
    pub fn as_bool_or(&self, default: bool) -> bool {
        self.as_bool().unwrap_or(default)
    }

    /// Parses the value as a Coord using unit suffix.
    pub fn as_coord(&self) -> Result<Coord, crate::error::AltiumError> {
        let (coord, _) = Unit::parse_with_unit(&self.data)?;
        Ok(coord)
    }

    /// Gets the value as a Coord, or a default on parse failure.
    pub fn as_coord_or(&self, default: Coord) -> Coord {
        self.as_coord().unwrap_or(default)
    }

    /// Parses the value as a Color (Win32 COLORREF).
    pub fn as_color(&self) -> Result<Color, std::num::ParseIntError> {
        let value: i32 = self.data.trim().parse()?;
        Ok(Color::from_win32(value))
    }

    /// Gets the value as a Color, or a default on parse failure.
    pub fn as_color_or(&self, default: Color) -> Color {
        self.as_color().unwrap_or(default)
    }

    /// Parses the value as a Layer.
    pub fn as_layer(&self) -> Layer {
        // Try parsing as number first, then as name
        if let Ok(value) = self.data.trim().parse::<u8>() {
            Layer::from_byte(value)
        } else {
            Layer::from_name(&self.data).unwrap_or(Layer::UNKNOWN)
        }
    }

    /// Parses the value as a nested ParameterCollection.
    pub fn as_parameters(&self) -> ParameterCollection {
        ParameterCollection::from_string_with_level(&self.data, self.level + 1)
    }

    /// Splits the value by the list separator and returns string items.
    pub fn as_string_list(&self) -> Vec<String> {
        self.as_list_impl().map(|s| s.to_string()).collect()
    }

    /// Splits the value by the list separator and returns integer items.
    pub fn as_int_list(&self) -> Vec<i32> {
        self.as_list_impl()
            .filter_map(|s| s.trim().parse().ok())
            .collect()
    }

    /// Splits the value by the list separator and returns double items.
    pub fn as_double_list(&self) -> Vec<f64> {
        self.as_list_impl()
            .filter_map(|s| s.trim().parse().ok())
            .collect()
    }

    /// Splits the value by the list separator and returns Coord items.
    pub fn as_coord_list(&self) -> Vec<Coord> {
        self.as_list_impl()
            .filter_map(|s| Unit::parse_with_unit(s).ok().map(|(c, _)| c))
            .collect()
    }

    /// Helper to split by comma.
    fn as_list_impl(&self) -> impl Iterator<Item = &str> {
        self.data.split(',').filter(|s| !s.is_empty())
    }

    /// Returns true if this value contains nested parameters.
    pub fn is_parameters(&self) -> bool {
        let sep = ENTRY_SEPARATORS.get(self.level + 1).copied().unwrap_or('`');
        self.data.contains(sep)
    }

    /// Returns true if this value is a list (contains commas).
    pub fn is_list(&self) -> bool {
        self.data.contains(',')
    }
}

impl fmt::Display for ParameterValue {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        write!(f, "{}", self.data)
    }
}

/// Collection of key-value parameters.
///
/// Preserves insertion order and supports nested parameter strings.
#[derive(Clone, Debug, Default)]
pub struct ParameterCollection {
    /// Raw data string (optional, for debugging).
    #[allow(dead_code)] // Preserved for debugging and round-trip support
    data: Option<String>,
    /// Nesting level (affects separator character).
    level: usize,
    /// Keys in insertion order.
    keys: Vec<String>,
    /// Key-value storage (keys are uppercase).
    parameters: IndexMap<String, String>,
    /// Whether to use long boolean format ("TRUE"/"FALSE" vs "T"/"F").
    use_long_booleans: bool,
}

impl ParameterCollection {
    /// Creates an empty parameter collection.
    pub fn new() -> Self {
        ParameterCollection::default()
    }

    /// Creates a parameter collection from a string.
    pub fn from_string(data: &str) -> Self {
        Self::from_string_with_level(data, 0)
    }

    /// Creates a parameter collection from a string at a specific nesting level.
    pub fn from_string_with_level(data: &str, level: usize) -> Self {
        let mut collection = ParameterCollection {
            data: Some(data.to_string()),
            level,
            keys: Vec::new(),
            parameters: IndexMap::new(),
            use_long_booleans: false,
        };
        collection.parse_data(data);
        collection
    }

    /// Parses the data string into key-value pairs.
    fn parse_data(&mut self, data: &str) {
        let separator = ENTRY_SEPARATORS.get(self.level).copied().unwrap_or('|');
        let mut ignored: std::collections::HashSet<String> = std::collections::HashSet::new();

        for entry in data.split(separator).filter(|s| !s.is_empty()) {
            let entry = entry.trim_end_matches(&['\r', '\n'] as &[char]);

            let (key, value) = if let Some(pos) = entry.find(KEY_VALUE_SEPARATOR) {
                let (k, v) = entry.split_at(pos);
                (k.to_string(), v[1..].to_string())
            } else {
                (String::new(), entry.to_string())
            };

            // Skip if already processed as UTF8
            let upper_key = key.to_uppercase();
            if ignored.contains(&upper_key) {
                continue;
            }

            // Handle UTF8 prefix
            let (final_key, final_value) = if let Some(stripped) = key.strip_prefix(UTF8_PREFIX) {
                let real_key = stripped.to_string();
                // Decode UTF-8 from Windows-1252 interpretation
                let decoded = Self::decode_utf8_from_win1252(&value);
                ignored.insert(real_key.to_uppercase());
                (real_key, decoded)
            } else {
                (key, value)
            };

            self.add_internal(&final_key, &final_value);
        }
    }

    /// Decodes a UTF-8 string that was stored as Windows-1252.
    fn decode_utf8_from_win1252(s: &str) -> String {
        let (bytes, _, _) = WINDOWS_1252.encode(s);
        match std::str::from_utf8(bytes.as_ref()) {
            Ok(decoded) => decoded.to_string(),
            Err(_) => s.to_string(),
        }
    }

    /// Internal method to add a key-value pair.
    fn add_internal(&mut self, key: &str, value: &str) {
        let upper_key = key.to_uppercase();
        if !self.parameters.contains_key(&upper_key) {
            self.keys.push(upper_key.clone());
        }
        self.parameters.insert(upper_key, value.to_string());
    }

    /// Returns true if the collection contains the given key.
    pub fn contains(&self, key: &str) -> bool {
        self.parameters.contains_key(&key.to_uppercase())
    }

    /// Gets a parameter value by key.
    pub fn get(&self, key: &str) -> Option<ParameterValue> {
        self.parameters
            .get(&key.to_uppercase())
            .map(|v| ParameterValue::new(v.clone(), self.level))
    }

    /// Gets a parameter value by key, or returns a default value.
    pub fn get_or(&self, key: &str, default: &str) -> ParameterValue {
        self.get(key)
            .unwrap_or_else(|| ParameterValue::new(default.to_string(), self.level))
    }

    /// Gets the value at the given index.
    pub fn get_at(&self, index: usize) -> Option<(&str, ParameterValue)> {
        self.keys.get(index).and_then(|k| {
            self.parameters
                .get(k)
                .map(|v| (k.as_str(), ParameterValue::new(v.clone(), self.level)))
        })
    }

    /// Returns the index of a key, or None if not found.
    pub fn index_of(&self, key: &str) -> Option<usize> {
        let upper = key.to_uppercase();
        self.keys.iter().position(|k| k == &upper)
    }

    /// Adds a string value.
    pub fn add(&mut self, key: &str, value: &str) {
        self.add_internal(key, value);
    }

    /// Adds an integer value.
    pub fn add_int(&mut self, key: &str, value: i32) {
        if value != 0 {
            self.add_internal(key, &value.to_string());
        }
    }

    /// Adds a double value with specified decimal places.
    pub fn add_double(&mut self, key: &str, value: f64, decimals: usize) {
        if value != 0.0 {
            let formatted = format!("{:.prec$}", value, prec = decimals);
            self.add_internal(key, &formatted);
        }
    }

    /// Adds a boolean value.
    pub fn add_bool(&mut self, key: &str, value: bool) {
        if value {
            let s = if self.use_long_booleans { "TRUE" } else { "T" };
            self.add_internal(key, s);
        }
    }

    /// Adds a coordinate value as mils.
    pub fn add_coord(&mut self, key: &str, value: Coord) {
        if value.to_raw() != 0 {
            let mils = value.to_mils();
            let formatted = format!("{:.5}mil", mils);
            self.add_internal(key, &formatted);
        }
    }

    /// Adds a color value.
    pub fn add_color(&mut self, key: &str, value: Color) {
        self.add_int(key, value.to_win32());
    }

    /// Removes a parameter by key.
    pub fn remove(&mut self, key: &str) {
        let upper = key.to_uppercase();
        self.parameters.swap_remove(&upper);
        self.keys.retain(|k| k != &upper);
    }

    /// Returns the number of parameters.
    pub fn len(&self) -> usize {
        self.parameters.len()
    }

    /// Returns true if empty.
    pub fn is_empty(&self) -> bool {
        self.parameters.is_empty()
    }

    /// Returns an iterator over (key, value) pairs.
    pub fn iter(&self) -> impl Iterator<Item = (&str, ParameterValue)> {
        self.keys.iter().filter_map(move |k| {
            self.parameters
                .get(k)
                .map(|v| (k.as_str(), ParameterValue::new(v.clone(), self.level)))
        })
    }

    /// Returns the nesting level.
    pub fn level(&self) -> usize {
        self.level
    }

    /// Sets whether to use long boolean format.
    pub fn set_use_long_booleans(&mut self, value: bool) {
        self.use_long_booleans = value;
    }

    /// Converts the collection back to a parameter string.
    pub fn to_param_string(&self) -> String {
        let separator = ENTRY_SEPARATORS.get(self.level).copied().unwrap_or('|');
        let mut result = String::new();

        for (key, value) in self.iter() {
            result.push(separator);
            result.push_str(key);
            result.push(KEY_VALUE_SEPARATOR);
            result.push_str(&value.data);
        }

        result
    }
}

impl FromBinary for ParameterCollection {
    fn read_from<R: std::io::Read>(reader: &mut R) -> crate::error::Result<Self> {
        read_parameters_block(reader)
    }
}

impl ToBinary for ParameterCollection {
    fn write_to<W: std::io::Write>(&self, writer: &mut W) -> crate::error::Result<()> {
        write_parameters_block(writer, self)
    }

    fn binary_size(&self) -> usize {
        // 4-byte size prefix + bytes for null-terminated parameter string.
        4 + self.to_param_string().len() + 1
    }
}

impl fmt::Display for ParameterCollection {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        write!(f, "{}", self.to_param_string())
    }
}

impl<'a> IntoIterator for &'a ParameterCollection {
    type Item = (&'a str, ParameterValue);
    type IntoIter = Box<dyn Iterator<Item = (&'a str, ParameterValue)> + 'a>;

    fn into_iter(self) -> Self::IntoIter {
        Box::new(self.keys.iter().filter_map(move |k| {
            self.parameters
                .get(k)
                .map(|v| (k.as_str(), ParameterValue::new(v.clone(), self.level)))
        }))
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn test_parse_parameters() {
        let data = "|RECORD=1|LIBREFERENCE=Resistor|VALUE=10k|";
        let params = ParameterCollection::from_string(data);

        assert_eq!(params.len(), 3);
        assert_eq!(params.get("RECORD").unwrap().as_int_or(0), 1);
        assert_eq!(params.get("LIBREFERENCE").unwrap().as_str(), "Resistor");
        assert_eq!(params.get("VALUE").unwrap().as_str(), "10k");
    }

    #[test]
    fn test_boolean_values() {
        let data = "|VISIBLE=T|LOCKED=FALSE|";
        let params = ParameterCollection::from_string(data);

        assert!(params.get("VISIBLE").unwrap().as_bool_or(false));
        assert!(!params.get("LOCKED").unwrap().as_bool_or(true));
    }

    #[test]
    fn test_coordinate_values() {
        let data = "|X=100mil|Y=2.54mm|";
        let params = ParameterCollection::from_string(data);

        let x = params.get("X").unwrap().as_coord_or(Coord::ZERO);
        assert!((x.to_mils() - 100.0).abs() < 0.1);

        let y = params.get("Y").unwrap().as_coord_or(Coord::ZERO);
        assert!((y.to_mils() - 100.0).abs() < 0.2);
    }

    #[test]
    fn test_integer_list() {
        let data = "|POINTS=1,2,3,4,5|";
        let params = ParameterCollection::from_string(data);

        let list = params.get("POINTS").unwrap().as_int_list();
        assert_eq!(list, vec![1, 2, 3, 4, 5]);
    }

    #[test]
    fn test_to_param_string() {
        let mut params = ParameterCollection::new();
        params.add("RECORD", "1");
        params.add("NAME", "Test");

        let s = params.to_param_string();
        assert!(s.contains("|RECORD=1"));
        assert!(s.contains("|NAME=Test"));
    }
}