TransJLC 0.4.0

TransJLC is a tool for converting Gerber files from other EDAs to JLCEDA style
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
//! Core conversion engine for TransJLC
//!
//! This module orchestrates the conversion process from various EDA formats
//! to JLC format, handling file discovery, pattern matching, and processing.

use crate::{
    archive::{ArchiveCreator, ArchiveExtractor},
    colorful::{ColorfulOptions, ColorfulSilkscreenGenerator},
    config::{Config, EdaType},
    error::{Result, ResultExt, TransJlcError},
    gerber::GerberProcessor,
    patterns::{EdaPatterns, LayerType, PatternMatcher},
    progress::ProgressTracker,
};
use anyhow::Context;
use rust_embed::RustEmbed;
use std::{
    collections::{HashMap, HashSet},
    fs,
    path::{Path, PathBuf},
};
use tracing::{debug, info, warn};

#[derive(RustEmbed)]
#[folder = "Assets/"]
struct Asset;

/// The main conversion engine
pub struct Converter {
    config: Config,
    progress_tracker: ProgressTracker,
    archive_extractor: ArchiveExtractor,
    gerber_processor: GerberProcessor,
    processed_files: HashMap<LayerType, PathBuf>,
    extra_files: Vec<PathBuf>,
}

impl Converter {
    /// Create a new converter with the given configuration
    pub fn new(config: Config) -> Self {
        let progress_enabled = !config.no_progress;

        Self {
            config,
            progress_tracker: ProgressTracker::new(progress_enabled),
            archive_extractor: ArchiveExtractor::new(),
            gerber_processor: GerberProcessor::new(),
            processed_files: HashMap::new(),
            extra_files: Vec::new(),
        }
    }

    /// Run the complete conversion process
    pub fn run(&mut self) -> Result<()> {
        let start = std::time::Instant::now();
        info!("Starting conversion process...");

        // Validate configuration
        self.config
            .validate()
            .context("Configuration validation failed")?;

        // Extract archive if needed
        let working_path = self
            .extract_input_files()
            .context("Failed to extract input files")?;

        // Discover and analyze files
        let files = self
            .discover_files(&working_path)
            .context("Failed to discover input files")?;

        // Detect EDA format and create pattern matcher
        let patterns = self
            .create_pattern_matcher(&files)
            .context("Failed to create pattern matcher")?;
        let eda_kind = patterns.name.to_lowercase();
        let inject_header = self
            .config
            .inject_header_override()
            .unwrap_or(eda_kind != "jlc");
        let pass_through_unmatched = self
            .config
            .pass_through_unmatched_override()
            .unwrap_or(eda_kind == "jlc");
        self.gerber_processor = GerberProcessor::new().with_inject_header(inject_header);
        info!(
            "Using EDA={} inject_header={} pass_through_unmatched={}",
            eda_kind, inject_header, pass_through_unmatched
        );

        // Process files
        self.process_files(&files, &patterns, &working_path, pass_through_unmatched)
            .context("Failed to process files")?;

        // Add required assets
        self.add_required_assets()
            .context("Failed to add required assets")?;

        // Optional colorful silkscreen generation
        self.generate_colorful_silkscreens()
            .context("Failed to generate colorful silkscreen files")?;

        // Create final output
        self.create_output().context("Failed to create output")?;

        info!("Conversion completed in {} ms", start.elapsed().as_millis());
        Ok(())
    }

    /// Extract input files from archive if necessary
    fn extract_input_files(&mut self) -> Result<PathBuf> {
        let progress = self.progress_tracker.create_spinner("Analyzing input...");

        let working_path = self
            .archive_extractor
            .extract_if_needed(&self.config.path, !self.config.no_progress)
            .with_path_context("analyze input", &self.config.path)?;

        ProgressTracker::finish_progress(progress, "Input analysis completed");
        Ok(working_path)
    }

    /// Discover all files in the working directory
    fn discover_files(&self, working_path: &Path) -> Result<Vec<PathBuf>> {
        info!("Processing files in {}", working_path.display());

        let mut files = fs::read_dir(working_path)
            .with_path_context("read directory", working_path)?
            .filter_map(|entry| {
                entry.ok().and_then(|e| {
                    let path = e.path();
                    if path.is_file() {
                        Some(path)
                    } else {
                        None
                    }
                })
            })
            .collect::<Vec<_>>();
        files.sort();

        info!("Discovered {} files", files.len());
        debug!("Files found: {:?}", files);

        if files.is_empty() {
            return Err(TransJlcError::FileNotFound {
                path: working_path.display().to_string(),
            }
            .into());
        }

        Ok(files)
    }

    /// Create appropriate pattern matcher based on configuration and file analysis
    fn create_pattern_matcher(&self, files: &[PathBuf]) -> Result<EdaPatterns> {
        info!("Detecting EDA tool type for {} files...", files.len());

        let patterns = match self.config.get_eda_type() {
            EdaType::Auto => {
                info!("Attempting to auto-detect an EDA format");
                PatternMatcher::auto_detect_eda(files)?
            }
            EdaType::KiCad => {
                info!("Using KiCad naming patterns");
                PatternMatcher::create_kicad_patterns()
            }
            EdaType::Protel => {
                info!("Using Protel naming patterns");
                PatternMatcher::create_protel_patterns()
            }
            EdaType::Jlc => {
                info!("Using JLC naming patterns");
                PatternMatcher::create_jlc_patterns()
            }
            EdaType::Custom(name) => {
                warn!("Using custom pattern matcher for: {}", name);
                PatternMatcher::create_custom_patterns(name)
            }
        };

        Ok(patterns)
    }

    /// Process all discovered files using the pattern matcher
    fn process_files(
        &mut self,
        files: &[PathBuf],
        patterns: &EdaPatterns,
        working_path: &Path,
        pass_through_unmatched: bool,
    ) -> Result<()> {
        info!("Processing Gerber files...");

        let progress = self
            .progress_tracker
            .create_conversion_progress(files.len());
        let needs_g54_aperture_prefix = self.determine_g54_requirement(files, patterns)?;

        for file in files {
            self.process_single_file(
                file,
                patterns,
                working_path,
                needs_g54_aperture_prefix,
                pass_through_unmatched,
            )
            .with_path_context("process file", file)?;

            ProgressTracker::update_progress(&progress, 1, None);
        }

        ProgressTracker::finish_progress(progress, "File processing completed");

        info!("Processed {} files", self.processed_files.len());
        Ok(())
    }

    /// Process a single file
    fn process_single_file(
        &mut self,
        file_path: &Path,
        patterns: &EdaPatterns,
        _working_path: &Path,
        needs_g54_aperture_prefix: bool,
        pass_through_unmatched: bool,
    ) -> Result<()> {
        let filename = file_path
            .file_name()
            .and_then(|name| name.to_str())
            .context("Invalid filename")?;

        debug!("Processing file: {}", filename);

        if filename == "PCB下单必读.txt" {
            debug!("Skipping source ordering instruction asset: {}", filename);
            return Ok(());
        }

        // Try to match the file to a layer type
        if let Some(layer_type) = patterns.match_filename(filename) {
            info!("Matched {} to layer type: {:?}", filename, layer_type);
            if matches!(layer_type, LayerType::Other) {
                debug!("Skipping file matched as Other: {}", filename);
                return Ok(());
            }

            if let Some(existing) = self.processed_files.get(&layer_type) {
                warn!(
                    "Layer {:?} is already filled by {}; skipping {}",
                    layer_type,
                    existing.display(),
                    filename
                );
                return Ok(());
            }

            // Determine output filename and path
            let output_filename = layer_type.to_jlc_filename();
            let output_path = self.get_output_file_path(&output_filename);

            // Read and process file content
            let content =
                fs::read_to_string(file_path).with_path_context("read file content", file_path)?;

            // Apply processing if it's a Gerber file (not drill files)
            let processed_content = if self.should_process_gerber(&layer_type) {
                self.gerber_processor
                    .process_gerber_content(content, needs_g54_aperture_prefix)?
            } else {
                self.gerber_processor
                    .normalize_excellon_drill_content(content)?
            };

            // Write processed content
            self.write_output_file(&output_path, &processed_content)
                .with_path_context("write output file", &output_path)?;

            // Track the processed file
            self.processed_files.insert(layer_type, output_path);
        } else if pass_through_unmatched {
            let output_path = self.get_output_file_path(filename);
            self.copy_passthrough_file(file_path, &output_path)
                .with_path_context("pass through unmatched file", file_path)?;
            self.extra_files.push(output_path);
        } else {
            debug!("No pattern match for file: {}", filename);
        }

        Ok(())
    }

    /// Determine whether any target file is missing the required G54 aperture prefix
    fn determine_g54_requirement(&self, files: &[PathBuf], patterns: &EdaPatterns) -> Result<bool> {
        for file in files {
            let Some(filename) = file.file_name().and_then(|name| name.to_str()) else {
                continue;
            };

            let Some(layer_type) = patterns.match_filename(filename) else {
                continue;
            };

            if !self.should_process_gerber(&layer_type) {
                continue;
            }

            let content = fs::read_to_string(file).with_path_context("read file content", file)?;

            if self
                .gerber_processor
                .has_missing_g54_aperture_prefix(&content)?
            {
                return Ok(true);
            }
        }

        Ok(false)
    }

    /// Determine if a layer type should undergo Gerber processing
    fn should_process_gerber(&self, layer_type: &LayerType) -> bool {
        !matches!(
            layer_type,
            LayerType::NpthThrough | LayerType::PthThrough | LayerType::PthThroughVia
        )
    }

    /// Get the full output file path
    fn get_output_file_path(&self, filename: &str) -> PathBuf {
        self.get_working_output_dir().join(filename)
    }

    /// Get the working output directory (temporary or final output directory)
    fn get_working_output_dir(&self) -> PathBuf {
        // If we have a temporary extraction directory, use it for intermediate processing
        if let Some(temp_path) = self.archive_extractor.temp_path() {
            temp_path.to_path_buf()
        } else {
            self.config.output_path.clone()
        }
    }

    /// Write content to output file, creating directories as needed
    fn write_output_file(&self, output_path: &Path, content: &str) -> Result<()> {
        if let Some(parent) = output_path.parent() {
            fs::create_dir_all(parent).with_path_context("create output directory", parent)?;
        }

        fs::write(output_path, content).with_path_context("write file", output_path)?;

        debug!("Written output file: {}", output_path.display());
        Ok(())
    }

    /// Copy an unmatched file into the working output directory without changing bytes
    fn copy_passthrough_file(&self, input_path: &Path, output_path: &Path) -> Result<()> {
        if input_path == output_path {
            debug!(
                "Pass-through source and destination are identical: {}",
                input_path.display()
            );
            return Ok(());
        }

        if let Some(parent) = output_path.parent() {
            fs::create_dir_all(parent).with_path_context("create output directory", parent)?;
        }

        fs::copy(input_path, output_path)
            .with_path_context("copy pass-through file", output_path)?;
        debug!("Pass-through file copied: {}", output_path.display());
        Ok(())
    }

    /// Add required assets (like PCB ordering instructions)
    fn add_required_assets(&mut self) -> Result<()> {
        info!("Adding required assets");

        const ASSET_NAME: &str = "PCB下单必读.txt";

        let content =
            Asset::get(ASSET_NAME).context("Required asset not found in embedded files")?;

        let output_path = self.get_working_output_dir().join(ASSET_NAME);

        fs::write(&output_path, content.data.as_ref())
            .with_path_context("write required asset", &output_path)?;

        // Track the asset as an "other" file
        self.processed_files.insert(LayerType::Other, output_path);

        info!("Added required asset: {}", ASSET_NAME);
        Ok(())
    }

    /// Create the final output (files or ZIP archive)
    fn create_output(&self) -> Result<()> {
        info!("Creating final output");

        let file_paths = self.collect_output_files();

        if self.config.zip {
            // Create ZIP archive
            let zip_path = self
                .config
                .output_path
                .join(format!("{}.zip", self.config.zip_name));

            ArchiveCreator::create_zip(&file_paths, &zip_path, !self.config.no_progress)?;

            info!("Created ZIP archive: {}", zip_path.display());
        } else {
            // Copy files to final output directory
            self.copy_files_to_output(&file_paths)?;
            info!("Copied {} files to output directory", file_paths.len());
        }

        Ok(())
    }

    /// Copy processed files to the final output directory
    fn copy_files_to_output(&self, file_paths: &[PathBuf]) -> Result<()> {
        let progress = self
            .progress_tracker
            .create_file_progress(file_paths.len(), "Copying files to output");

        // Ensure output directory exists
        fs::create_dir_all(&self.config.output_path)
            .with_path_context("create output directory", &self.config.output_path)?;

        for file_path in file_paths {
            if let Some(filename) = file_path.file_name() {
                let dest_path = self.config.output_path.join(filename);

                if file_path != &dest_path {
                    fs::copy(file_path, &dest_path)
                        .with_path_context("copy file to output", &dest_path)?;
                }

                ProgressTracker::update_progress(&progress, 1, None);
            }
        }

        ProgressTracker::finish_progress(progress, "File copying completed");
        Ok(())
    }

    /// Collect processed and pass-through output paths, deduplicating while preserving order
    fn collect_output_files(&self) -> Vec<PathBuf> {
        let mut seen = HashSet::new();
        let mut files = Vec::new();

        for path in self.processed_files.values().chain(self.extra_files.iter()) {
            if seen.insert(path.clone()) {
                files.push(path.clone());
            }
        }

        files
    }

    /// Get statistics about the conversion process
    pub fn get_conversion_stats(&self) -> ConversionStats {
        ConversionStats {
            total_files_processed: self.processed_files.len(),
            total_extra_files: self.extra_files.len(),
            layer_types_found: self.processed_files.keys().cloned().collect(),
            output_format: if self.config.zip { "ZIP" } else { "Files" }.to_string(),
        }
    }

    /// Generate colorful silkscreen outputs if requested
    fn generate_colorful_silkscreens(&mut self) -> Result<()> {
        if self.config.top_color_image.is_none() && self.config.bottom_color_image.is_none() {
            return Ok(());
        }

        let Some(outline_path) = self.processed_files.get(&LayerType::BoardOutline) else {
            return Err(TransJlcError::FileNotFound {
                path: "Board outline (Gerber_BoardOutlineLayer.GKO) not found; required for colorful silkscreen".to_string(),
            }
            .into());
        };

        info!("Generating colorful silkscreen files");
        let options = ColorfulOptions {
            top_image: self.config.top_color_image.clone(),
            bottom_image: self.config.bottom_color_image.clone(),
            top_solder_mask: self.processed_files.get(&LayerType::TopSoldermask).cloned(),
            bottom_solder_mask: self
                .processed_files
                .get(&LayerType::BottomSoldermask)
                .cloned(),
        };

        let generator = ColorfulSilkscreenGenerator::new(options);
        let output_dir = self.get_working_output_dir();
        let generated_files = generator
            .generate(outline_path, &output_dir)
            .with_path_context("generate colorful silkscreen", outline_path)?;

        for (layer, path) in generated_files {
            self.processed_files.insert(layer, path);
        }

        Ok(())
    }
}

/// Statistics about the conversion process
#[derive(Debug)]
pub struct ConversionStats {
    pub total_files_processed: usize,
    pub total_extra_files: usize,
    pub layer_types_found: Vec<LayerType>,
    pub output_format: String,
}

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

    #[test]
    fn test_converter_creation() {
        let config = Config {
            eda: "kicad".to_string(),
            path: PathBuf::from("."),
            output_path: PathBuf::from("./output"),
            zip: false,
            zip_name: "test".to_string(),
            verbose: false,
            no_progress: true,
            top_color_image: None,
            bottom_color_image: None,
            inject_header: false,
            no_inject_header: false,
            passthrough: false,
            no_passthrough: false,
        };

        let converter = Converter::new(config);
        assert!(converter.processed_files.is_empty());
    }

    #[test]
    fn test_working_output_dir() {
        let config = Config {
            eda: "kicad".to_string(),
            path: PathBuf::from("."),
            output_path: PathBuf::from("./output"),
            zip: false,
            zip_name: "test".to_string(),
            verbose: false,
            no_progress: true,
            top_color_image: None,
            bottom_color_image: None,
            inject_header: false,
            no_inject_header: false,
            passthrough: false,
            no_passthrough: false,
        };

        let converter = Converter::new(config);
        let working_dir = converter.get_working_output_dir();

        // Should use config output path when no temp directory
        assert_eq!(working_dir, PathBuf::from("./output"));
    }

    #[test]
    fn test_should_process_gerber() {
        let config = Config {
            eda: "kicad".to_string(),
            path: PathBuf::from("."),
            output_path: PathBuf::from("./output"),
            zip: false,
            zip_name: "test".to_string(),
            verbose: false,
            no_progress: true,
            top_color_image: None,
            bottom_color_image: None,
            inject_header: false,
            no_inject_header: false,
            passthrough: false,
            no_passthrough: false,
        };

        let converter = Converter::new(config);

        // Drill files should not be processed as Gerber
        assert!(!converter.should_process_gerber(&LayerType::NpthThrough));
        assert!(!converter.should_process_gerber(&LayerType::PthThrough));
        assert!(!converter.should_process_gerber(&LayerType::PthThroughVia));

        // Other layer types should be processed
        assert!(converter.should_process_gerber(&LayerType::TopCopper));
        assert!(converter.should_process_gerber(&LayerType::BoardOutline));
        assert!(converter.should_process_gerber(&LayerType::InnerLayer(1)));
    }

    #[test]
    fn test_conversion_stats() {
        let config = Config {
            eda: "kicad".to_string(),
            path: PathBuf::from("."),
            output_path: PathBuf::from("./output"),
            zip: true,
            zip_name: "test".to_string(),
            verbose: false,
            no_progress: true,
            top_color_image: None,
            bottom_color_image: None,
            inject_header: false,
            no_inject_header: false,
            passthrough: false,
            no_passthrough: false,
        };

        let mut converter = Converter::new(config);

        // Add some mock processed files
        converter
            .processed_files
            .insert(LayerType::TopCopper, PathBuf::from("top.gtl"));
        converter
            .processed_files
            .insert(LayerType::BottomCopper, PathBuf::from("bottom.gbl"));

        let stats = converter.get_conversion_stats();

        assert_eq!(stats.total_files_processed, 2);
        assert_eq!(stats.output_format, "ZIP");
        assert!(stats.layer_types_found.contains(&LayerType::TopCopper));
        assert!(stats.layer_types_found.contains(&LayerType::BottomCopper));
    }

    #[test]
    fn test_determine_g54_requirement() {
        let temp_dir = tempdir().expect("Failed to create temp dir");
        let file_missing = temp_dir.path().join("project-F_Cu.gbr");
        let file_prefixed = temp_dir.path().join("project-B_Cu.gbr");

        fs::write(&file_missing, "G04*\nD10*\n").expect("Failed to write missing file");
        fs::write(&file_prefixed, "G04*\nG54D11*\n").expect("Failed to write prefixed file");

        let config = Config {
            eda: "kicad".to_string(),
            path: PathBuf::from("."),
            output_path: PathBuf::from("./output"),
            zip: false,
            zip_name: "test".to_string(),
            verbose: false,
            no_progress: true,
            top_color_image: None,
            bottom_color_image: None,
            inject_header: false,
            no_inject_header: false,
            passthrough: false,
            no_passthrough: false,
        };

        let converter = Converter::new(config);
        let patterns = PatternMatcher::create_kicad_patterns();
        let files = vec![file_missing.clone(), file_prefixed.clone()];

        let needs_prefix = converter
            .determine_g54_requirement(&files, &patterns)
            .expect("Detection should succeed");

        assert!(needs_prefix);

        fs::write(&file_missing, "G04*\nG54D10*\n").expect("Failed to rewrite missing file");

        let needs_prefix = converter
            .determine_g54_requirement(&files, &patterns)
            .expect("Detection should succeed");

        assert!(!needs_prefix);
    }
}