Skip to main content

brep_app/panels/
kicad_library.rs

1//! The `--kicad-library` window: importing KiCad parts, and nothing else.
2//!
3//! `brep-app --kicad-library` opens THIS window instead of the CAD window. It
4//! is the only flag that does: every other launch runs the same full
5//! `eframe::run_native` shell. There is no viewport, no history tree and no
6//! workbench here — a part is read, reviewed, and written to the model store as
7//! a document the CAD window then opens.
8//!
9//! # Two sources, one chain
10//!
11//! * **Clone** — KiCad's own three library repositories, cloned with git at a
12//!   pinned 9.x tag ([`brep_ecad_core::kicad_git`]) into folders laid out like a
13//!   KiCad install, then read exactly as an install is. When git is missing or
14//!   GitLab cannot be reached the window says so and switches to the install
15//!   source, whose three folder fields are where the user names their own.
16//! * **Your KiCad install** — the folders already on this machine, found the
17//!   way the in-app dialog finds them ([`KicadLibrary::load`]).
18//!
19//! Both end in the SAME call: `part_from_symbol` follows the symbol to its
20//! footprint to its `.step`, and [`import_part`](crate::panels::kicad_import::import_part) writes the IMPORT3D feature,
21//! the `symbol` and `pads` blocks and the `Pins` port group. The only
22//! difference is which folders it reads.
23//!
24//! # One part, or all of them
25//!
26//! Either source also offers a BULK import: every symbol of one library,
27//! of the libraries the search box matches, or of all 223. That is
28//! [`super::kicad_bulk`] on a worker thread, reported here as a progress bar and
29//! stopped by a button, and it can be stopped and restarted as often as the user
30//! likes — what it finished is written to a ledger beside the clones, and a
31//! later run skips it without converting it again.
32//!
33//! # Its own state machine
34//!
35//! The in-app dialog ([`super::kicad_import::KicadImport`]) is driven by the
36//! file explorer and reads the chain on the UI thread, which a clone and a
37//! library's worth of STEP parsing cannot share. This window therefore keeps its own [`Stage`], reads every part on a
38//! worker ([`read_part`]) and reuses the dialog's chain, notes and review
39//! wording rather than its staging. The stage transitions are plain methods
40//! with no egui in them, so the suite drives the whole window headless.
41
42#![cfg(not(target_arch = "wasm32"))]
43
44use super::kicad_bulk::{
45    AppStoreWriter, BulkRun, Ledger, PartWriter, Progress, StoreWriter, Sweep,
46};
47use super::kicad_import::{
48    part_from_symbol, read_symbol_library, DiskFiles, Folder, FootprintChoice, Imported, KicadFiles,
49    KicadLibrary, KicadPart,
50};
51use crate::store::{default_model_store, ModelStore};
52use brep_ecad_core::kicad_git::{self, Repo};
53use brep_ecad_core::Symbol;
54use eframe::egui;
55use std::path::{Path, PathBuf};
56use std::sync::atomic::{AtomicBool, Ordering};
57use std::sync::Arc;
58
59/// The release a clone reads; the window's tag field starts here.
60pub const DEFAULT_TAG: &str = kicad_git::TAG;
61
62/// Where clones and the bulk ledger live when the user names no folder: beside
63/// the app's own state (the model store's `<config>/brep-app`), so they
64/// survive a session — `%APPDATA%` on Windows.
65pub fn default_cache_root() -> PathBuf {
66    crate::plm::config::app_config_dir().join("kicad-library")
67}
68
69/// The `*.kicad_sym` library names among `names`, without their extension,
70/// sorted.
71pub fn symbol_libraries(names: &[String]) -> Vec<String> {
72    let mut found: Vec<String> = names
73        .iter()
74        .filter_map(|name| name.strip_suffix(".kicad_sym"))
75        .map(str::to_owned)
76        .collect();
77    found.sort();
78    found
79}
80
81/// The variables KiCad names its SYMBOL folder by, newest first. The importer's
82/// own library record holds footprints and 3D models only, because a symbol
83/// reaches it as a file the user opened; this window lists a folder of them, so
84/// it needs the third one.
85const SYMBOL_VARS: &[&str] = &[
86    "KICAD9_SYMBOL_DIR",
87    "KICAD8_SYMBOL_DIR",
88    "KICAD7_SYMBOL_DIR",
89    "KICAD6_SYMBOL_DIR",
90];
91
92/// Where the symbol libraries of a local install are: the variable when it
93/// names a folder, else `symbols` beside the footprints folder, which is how
94/// KiCad lays its share directory out.
95pub fn symbols_folder(env: &dyn Fn(&str) -> Option<String>, footprints: &str, files: &dyn KicadFiles) -> String {
96    for var in SYMBOL_VARS {
97        if let Some(path) = env(var).filter(|path| files.is_dir(path)) {
98            return path;
99        }
100    }
101    std::path::Path::new(footprints)
102        .parent()
103        .map(|dir| dir.join("symbols").to_string_lossy().into_owned())
104        .unwrap_or_else(|| "symbols".into())
105}
106
107/// The `*.kicad_sym` library names in `dir`, without their extension, sorted.
108/// The local twin of [`symbol_libraries`].
109pub fn local_symbol_libraries(dir: &str, files: &dyn KicadFiles) -> Vec<String> {
110    symbol_libraries(&files.list(dir))
111}
112
113/// A document name for a part: the symbol's own name, with anything a file name
114/// cannot hold replaced. `Timer:NE555D` becomes `NE555D`.
115pub fn document_name(library_id: &str) -> String {
116    let bare = library_id.rsplit(':').next().unwrap_or(library_id);
117    let cleaned: String = bare
118        .chars()
119        .map(|c| if c.is_ascii_alphanumeric() || c == '-' || c == '_' || c == '.' { c } else { '_' })
120        .collect();
121    let trimmed = cleaned.trim_matches(['_', '.']).to_owned();
122    if trimmed.is_empty() {
123        "kicad-part".into()
124    } else {
125        trimmed
126    }
127}
128
129// ============================================================================
130// The local source
131// ============================================================================
132
133/// A symbol library being read off the UI thread. KiCad 9.0.9.1's largest is
134/// `MCU_ST_STM32H7.kicad_sym` at **15.4 MB** and its `MCU_ST_STM32F4` is 6.6 MB
135/// (measured against gitlab.com), so neither the download nor the parse belongs
136/// on the thread drawing the window — the same reason the chain does not.
137struct LibraryReader {
138    answer: std::sync::mpsc::Receiver<Result<(Vec<Symbol>, Vec<String>), String>>,
139    library: String,
140}
141
142/// A KiCad install on disk, as a [`PartSource`].
143pub struct LocalSource {
144    library: KicadLibrary,
145}
146
147impl LocalSource {
148    pub fn new(library: KicadLibrary) -> Self {
149        Self { library }
150    }
151}
152
153impl KicadFiles for LocalSource {
154    fn read(&self, path: &str) -> Option<Vec<u8>> {
155        DiskFiles.read(path)
156    }
157    fn is_file(&self, path: &str) -> bool {
158        DiskFiles.is_file(path)
159    }
160    fn is_dir(&self, path: &str) -> bool {
161        DiskFiles.is_dir(path)
162    }
163    fn list(&self, dir: &str) -> Vec<String> {
164        DiskFiles.list(dir)
165    }
166}
167
168impl PartSource for LocalSource {
169    fn library(&self) -> KicadLibrary {
170        self.library.clone()
171    }
172}
173
174/// Where one import's files come from, for [`read_part`].
175pub trait PartSource: KicadFiles + Send + 'static {
176    /// The folders the chain follows a footprint and a model through.
177    fn library(&self) -> KicadLibrary;
178}
179
180/// A part being read off the UI thread: the chain and the STEP parse.
181pub struct PartReader {
182    answer: std::sync::mpsc::Receiver<KicadPart>,
183}
184
185impl PartReader {
186    /// The answer, once the worker has one. `None` while it works; a worker
187    /// that died without one answers with a note rather than hanging.
188    pub fn take(&self) -> Option<KicadPart> {
189        match self.answer.try_recv() {
190            Ok(answer) => Some(answer),
191            Err(std::sync::mpsc::TryRecvError::Empty) => None,
192            Err(std::sync::mpsc::TryRecvError::Disconnected) => Some(KicadPart {
193                notes: vec!["the part reader stopped without an answer".into()],
194                ..KicadPart::default()
195            }),
196        }
197    }
198}
199
200/// Follow `symbol`'s chain through `source` on a worker thread: the footprint,
201/// the 3D model, and the model's STEP parsed (529 ms for a real SOIC-8).
202pub fn read_part(symbol: Symbol, choice: FootprintChoice, source: impl PartSource) -> PartReader {
203    let (send, answer) = std::sync::mpsc::channel();
204    std::thread::spawn(move || {
205        let library = source.library();
206        let part = part_from_symbol(symbol, &choice, &library, &source).parsed();
207        // A window closed meanwhile has dropped the receiver; nobody waits.
208        let _ = send.send(part);
209    });
210    PartReader { answer }
211}
212
213/// KiCad's three repositories being cloned on a worker.
214pub struct CloneRun {
215    updates: std::sync::mpsc::Receiver<CloneUpdate>,
216    cancel: Arc<AtomicBool>,
217    /// git's latest progress line.
218    pub line: String,
219}
220
221enum CloneUpdate {
222    Line(String),
223    Done(Result<(), String>),
224}
225
226impl CloneRun {
227    /// Clone each of the three that is not under `root` yet, from `base`.
228    fn start(base: String, tag: String, root: PathBuf) -> Self {
229        let (send, updates) = std::sync::mpsc::channel();
230        let cancel = Arc::new(AtomicBool::new(false));
231        let flag = Arc::clone(&cancel);
232        std::thread::spawn(move || {
233            let mut result = kicad_git::git_version().map(|_| ());
234            for repo in Repo::ALL {
235                if result.is_err() {
236                    break;
237                }
238                let mut report = |line: &str| {
239                    let _ = send.send(CloneUpdate::Line(format!("{}: {line}", repo.project())));
240                };
241                let dest = root.join(repo.install_folder());
242                result = kicad_git::clone(&repo.url(&base), &tag, &dest, &mut report, &flag).map(|_| ());
243            }
244            let _ = send.send(CloneUpdate::Done(result));
245        });
246        Self { updates, cancel, line: "starting git".into() }
247    }
248
249    /// Stop git; the repository in hand is removed, those already cloned stay.
250    pub fn stop(&self) {
251        self.cancel.store(true, Ordering::Relaxed);
252    }
253
254    pub fn stopping(&self) -> bool {
255        self.cancel.load(Ordering::Relaxed)
256    }
257}
258
259// ============================================================================
260// The window's state
261// ============================================================================
262
263/// Which source the window is reading.
264#[derive(Clone, Copy, Debug, PartialEq, Eq)]
265pub enum Source {
266    /// KiCad's repositories, cloned at the window's tag.
267    Download,
268    /// This machine's KiCad install.
269    Install,
270}
271
272impl Source {
273    fn label(self) -> &'static str {
274        match self {
275            Source::Download => "Clone KiCad's library",
276            Source::Install => "Use my KiCad install",
277        }
278    }
279}
280
281/// Where the window is.
282pub enum Stage {
283    /// Neither source chosen yet.
284    Choose,
285    /// A source chosen: pick one symbol library out of its list.
286    Libraries,
287    /// A library being read, on a worker.
288    Opening { library: String },
289    /// A library read: pick one of its symbols.
290    Symbols { library: String, symbols: Vec<Symbol>, warnings: Vec<String> },
291    /// A symbol chosen and its chain being read, on a worker.
292    Reading { symbol: String },
293    /// A part read: review it and save it.
294    Review { part: Box<KicadPart>, warnings: Vec<String> },
295    /// Every symbol of one or more libraries being imported, on a worker.
296    Bulk,
297}
298
299/// The `--kicad-library` window.
300pub struct KicadLibraryWindow {
301    pub stage: Stage,
302    source: Source,
303    /// The install's three folders, editable.
304    symbols_dir: String,
305    footprints_dir: String,
306    models_dir: String,
307    /// Where clones and the bulk ledger go, and the release cloned; editable.
308    /// The clones are `<cache_dir>/<tag>/{symbols,footprints,3dmodels}`.
309    cache_dir: String,
310    tag: String,
311    /// Where the clone source clones from; the suite names a local repository.
312    clone_base: String,
313    /// The library names of the chosen source, once listed.
314    libraries: Vec<String>,
315    /// The clone in flight.
316    pub cloning: Option<CloneRun>,
317    /// The chain in flight.
318    reader: Option<PartReader>,
319    /// The symbol library in flight.
320    library_reader: Option<LibraryReader>,
321    search: String,
322    /// The warnings the chosen library carried, held from [`Self::read_symbol`]
323    /// until the worker answers in a later frame.
324    pending_warnings: Vec<String>,
325    /// The document the next save writes.
326    document: String,
327    pub status: String,
328    store: Box<dyn ModelStore>,
329    /// Every part written this session, newest last — the window's own record
330    /// of its work, since there is no viewport to show it in.
331    pub saved: Vec<String>,
332    /// The sweep in flight, and the view of it the frame loop draws.
333    pub bulk: Option<BulkRun>,
334    /// Whether the next sweep redoes what the ledger has already settled.
335    force_reimport: bool,
336    /// What the tag's ledger held the last time it was read, for the line above
337    /// the library list. Recomputed when a source is chosen and when a sweep
338    /// stops, not every frame: it is a file read.
339    ledger_line: String,
340    /// Where a sweep writes. The app's is the ordinary model store, built inside
341    /// the worker; the suite substitutes an in-memory one so a sweep never
342    /// touches the user's documents.
343    new_writer: Arc<dyn Fn() -> Box<dyn PartWriter + Send> + Send + Sync>,
344}
345
346impl KicadLibraryWindow {
347    /// Build the window against the app's own model store.
348    pub fn new() -> Self {
349        Self::with_store(default_model_store())
350    }
351
352    /// Build it against `store` — the seam the suite writes into memory through.
353    pub fn with_store(store: Box<dyn ModelStore>) -> Self {
354        let env = |var: &str| std::env::var(var).ok().filter(|value| !value.is_empty());
355        let library = KicadLibrary::load(store.as_ref(), &env, &DiskFiles);
356        let symbols = symbols_folder(&env, &library.footprints.path, &DiskFiles);
357        Self {
358            stage: Stage::Choose,
359            source: Source::Download,
360            symbols_dir: symbols,
361            footprints_dir: library.footprints.path.clone(),
362            models_dir: library.models.path.clone(),
363            cache_dir: default_cache_root().to_string_lossy().into_owned(),
364            tag: DEFAULT_TAG.into(),
365            clone_base: kicad_git::BASE_URL.into(),
366            libraries: Vec::new(),
367            cloning: None,
368            reader: None,
369            library_reader: None,
370            search: String::new(),
371            pending_warnings: Vec::new(),
372            document: String::new(),
373            status: String::new(),
374            store,
375            saved: Vec::new(),
376            bulk: None,
377            force_reimport: false,
378            ledger_line: String::new(),
379            new_writer: Arc::new(|| Box::new(AppStoreWriter)),
380        }
381    }
382
383    /// Point a sweep at another place to write — the seam the suite drives a
384    /// whole sweep through, with no documents in the user's config folder.
385    pub fn sweep_through(&mut self, write: Arc<dyn Fn() -> Box<dyn PartWriter + Send> + Send + Sync>) {
386        self.new_writer = write;
387    }
388
389    /// Clone from `base` and into `cache_dir` instead — the suite's local
390    /// repositories and temp folder.
391    pub fn clone_from(&mut self, base: &str, cache_dir: &Path) {
392        self.clone_base = base.to_owned();
393        self.cache_dir = cache_dir.to_string_lossy().into_owned();
394    }
395
396    /// Where the clones of the window's tag are.
397    fn clone_root(&self) -> PathBuf {
398        Path::new(&self.cache_dir).join(&self.tag)
399    }
400
401    /// The symbols, footprints and 3D-model folders the chosen source reads.
402    fn folders(&self) -> (String, String, String) {
403        match self.source {
404            Source::Install => (self.symbols_dir.clone(), self.footprints_dir.clone(), self.models_dir.clone()),
405            Source::Download => {
406                let root = self.clone_root();
407                let [symbols, footprints, models] =
408                    Repo::ALL.map(|repo| root.join(repo.install_folder()).to_string_lossy().into_owned());
409                (symbols, footprints, models)
410            }
411        }
412    }
413
414    /// The chosen source's folders as the chain wants them.
415    fn library(&self) -> KicadLibrary {
416        let (_, footprints, models) = self.folders();
417        let from = match self.source {
418            Source::Install => "your KiCad install",
419            Source::Download => "the clone of KiCad's library",
420        };
421        let folder = |path: String| Folder { from: format!("{from} ({path})"), path };
422        KicadLibrary { footprints: folder(footprints), models: folder(models) }
423    }
424
425    /// Choose a source and list its symbol libraries. The install lists a
426    /// folder here and now; the clone source lists its clone, cloning it first
427    /// on a worker when it is not there yet.
428    pub fn choose(&mut self, source: Source, ctx: Option<&egui::Context>) {
429        self.source = source;
430        self.stage = Stage::Libraries;
431        self.libraries.clear();
432        self.search.clear();
433        // Drop whatever the other source had in flight. A listing page landing
434        // after the switch would extend the new source's list with the old
435        // one's names; a chain landing after it would put the window in a
436        // Review of a part nobody asked for any more. Dropping the receiver is
437        // the "nobody waits" case the workers already expect.
438        self.reader = None;
439        self.library_reader = None;
440        // A sweep is NOT dropped here: it owns no stage of its own to be
441        // confused by, its worker writes documents and ledger lines that are
442        // complete either way, and a user who switches source to look at
443        // something should not silently lose an hour of importing. Its progress
444        // keeps arriving and `Stage::Bulk` is still reachable.
445        self.refresh_ledger_line();
446        let cloned = Repo::ALL.iter().all(|repo| self.clone_root().join(repo.install_folder()).is_dir());
447        if source == Source::Download && !cloned {
448            if self.cloning.is_none() {
449                self.cloning = Some(CloneRun::start(self.clone_base.clone(), self.tag.clone(), self.clone_root()));
450            }
451            self.status = format!(
452                "cloning KiCad {}'s libraries into {} with git (about 5.6 GB, once)\u{2026}",
453                self.tag,
454                self.clone_root().display()
455            );
456            if let Some(ctx) = ctx {
457                ctx.request_repaint_after(std::time::Duration::from_millis(100));
458            }
459            return;
460        }
461        self.list_libraries();
462    }
463
464    /// List the chosen source's symbol folder.
465    fn list_libraries(&mut self) {
466        let (symbols, _, _) = self.folders();
467        self.libraries = local_symbol_libraries(&symbols, &DiskFiles);
468        self.status = if self.libraries.is_empty() {
469            format!("no .kicad_sym library in {symbols}")
470        } else {
471            format!("{} symbol libraries in {symbols} (type to search)", self.libraries.len())
472        };
473    }
474
475    /// The clone's news, once per frame: git's progress, then either the
476    /// library list or why it failed — and the folder fields to fill instead.
477    fn poll_clone(&mut self) {
478        let Some(run) = &mut self.cloning else {
479            return;
480        };
481        let mut done = None;
482        let mut gone = false;
483        loop {
484            match run.updates.try_recv() {
485                Ok(CloneUpdate::Line(line)) => run.line = line,
486                Ok(CloneUpdate::Done(result)) => done = Some(result),
487                Err(std::sync::mpsc::TryRecvError::Empty) => break,
488                Err(std::sync::mpsc::TryRecvError::Disconnected) => {
489                    gone = true;
490                    break;
491                }
492            }
493        }
494        let done = match done {
495            Some(done) => done,
496            None if gone => Err("the clone stopped without saying why".into()),
497            None => return,
498        };
499        self.cloning = None;
500        match done {
501            Ok(()) if self.source == Source::Download => self.list_libraries(),
502            Ok(()) => self.status = format!("KiCad {}'s libraries are cloned", self.tag),
503            Err(error) => {
504                self.source = Source::Install;
505                self.stage = Stage::Choose;
506                self.status = format!(
507                    "KiCad's libraries were not cloned: {error}. Install git, or name the folders of \
508                     a KiCad library on this machine above and choose \"{}\".",
509                    Source::Install.label()
510                );
511            }
512        }
513    }
514
515    /// Read one symbol library on a worker. See `LibraryReader` for why this
516    /// is not done in the frame.
517    pub fn open_library(&mut self, library: &str) {
518        let file = format!("{library}.kicad_sym");
519        let path = Path::new(&self.folders().0).join(&file);
520        let (send, answer) = std::sync::mpsc::channel();
521        std::thread::spawn(move || {
522            let read = std::fs::read(&path).map_err(|error| format!("{}: {error}", path.display()));
523            let _ = send.send(read.and_then(|bytes| read_symbol_library(&file, &bytes)));
524        });
525        self.library_reader = Some(LibraryReader { answer, library: library.to_owned() });
526        self.status = format!("reading {library}\u{2026}");
527        self.stage = Stage::Opening { library: library.to_owned() };
528    }
529
530    /// Follow one symbol's chain on a worker. A symbol that names no footprint
531    /// imports with its symbol alone: this window offers no footprint chooser.
532    pub fn read_symbol(&mut self, symbol: Symbol) {
533        let name = symbol.library_id.clone();
534        self.pending_warnings = match &self.stage {
535            Stage::Symbols { warnings, .. } => warnings.clone(),
536            _ => Vec::new(),
537        };
538        self.document = document_name(&name);
539        self.status = format!("reading {name}\u{2026}");
540        self.reader = Some(read_part(symbol, FootprintChoice::Named, LocalSource::new(self.library())));
541        self.stage = Stage::Reading { symbol: name };
542    }
543
544    /// The worker's answer, once it has one.
545    pub fn poll(&mut self, ctx: Option<&egui::Context>) {
546        if let Some(run) = &mut self.bulk {
547            let was_running = !run.progress.finished;
548            let moved = run.poll();
549            let stopped = moved && was_running && run.progress.finished;
550            if !run.progress.finished {
551                if let Some(ctx) = ctx {
552                    ctx.request_repaint_after(std::time::Duration::from_millis(250));
553                }
554            }
555            if stopped {
556                // It has stopped: say how, and re-read the ledger it wrote so the
557                // library list's summary is the new truth.
558                let line = run.progress.line();
559                self.status = format!("import {line}");
560                self.refresh_ledger_line();
561            }
562        }
563        if self.cloning.is_some() {
564            self.poll_clone();
565            if let (Some(ctx), Some(_)) = (ctx, &self.cloning) {
566                ctx.request_repaint_after(std::time::Duration::from_millis(250));
567            }
568        }
569        if let Some(reader) = &self.library_reader {
570            match reader.answer.try_recv() {
571                Ok(Ok((symbols, warnings))) => {
572                    let library = reader.library.clone();
573                    self.library_reader = None;
574                    self.status = format!("{library} holds {} symbols", symbols.len());
575                    self.search.clear();
576                    self.stage = Stage::Symbols { library, symbols, warnings };
577                }
578                Ok(Err(error)) => {
579                    self.status = format!("{} was not read: {error}", reader.library);
580                    self.library_reader = None;
581                    self.stage = Stage::Libraries;
582                }
583                Err(std::sync::mpsc::TryRecvError::Empty) => {
584                    if let Some(ctx) = ctx {
585                        ctx.request_repaint_after(std::time::Duration::from_millis(100));
586                    }
587                }
588                Err(std::sync::mpsc::TryRecvError::Disconnected) => {
589                    self.status = format!("{} was not read: the reader stopped", reader.library);
590                    self.library_reader = None;
591                    self.stage = Stage::Libraries;
592                }
593            }
594        }
595        let Some(reader) = &self.reader else {
596            return;
597        };
598        match reader.take() {
599            Some(part) => {
600                self.reader = None;
601                self.status = "read".into();
602                let warnings = std::mem::take(&mut self.pending_warnings);
603                self.stage = Stage::Review { part: Box::new(part), warnings };
604            }
605            None => {
606                if let Some(ctx) = ctx {
607                    ctx.request_repaint_after(std::time::Duration::from_millis(100));
608                }
609            }
610        }
611    }
612
613    /// Write the reviewed part as a document, through the ordinary model store.
614    /// The part goes into a FRESH engine every time, so two saves in one
615    /// session never share a history.
616    pub fn save(&mut self) -> Result<Imported, String> {
617        let Stage::Review { part, .. } = &self.stage else {
618            return Err("nothing has been read yet".into());
619        };
620        let name = self.document.trim();
621        if name.is_empty() {
622            return Err("the part needs a name".into());
623        }
624        let name = name.to_owned();
625        // The same call the sweep makes, so a part imported by hand and the same
626        // part imported by a sweep are the same document.
627        let imported = super::kicad_bulk::write_part(&StoreWriter(self.store.as_ref()), &name, part)?;
628        self.saved.push(name.clone());
629        self.status = format!("saved {name}: {}", imported.summary);
630        self.stage = Stage::Libraries;
631        Ok(imported)
632    }
633
634    /// Where the window is, in words — the line the suite and the status bar
635    /// both read.
636    pub fn stage_name(&self) -> &'static str {
637        match self.stage {
638            Stage::Choose => "choose",
639            Stage::Libraries => "libraries",
640            Stage::Opening { .. } => "opening",
641            Stage::Symbols { .. } => "symbols",
642            Stage::Reading { .. } => "reading",
643            Stage::Review { .. } => "review",
644            Stage::Bulk => "bulk",
645        }
646    }
647
648    /// The ledger's own summary for the tag and cache folder now named, read off
649    /// disk. Empty when nothing has ever been swept into this folder.
650    pub fn refresh_ledger_line(&mut self) {
651        let ledger = Ledger::read(std::path::Path::new(&self.cache_dir), &self.tag);
652        let (done, retry) = ledger.counts();
653        if done == 0 && retry == 0 {
654            self.ledger_line = format!("nothing imported into {} yet", self.cache_dir);
655            return;
656        }
657        let grades: Vec<String> = ledger
658            .grades()
659            .into_iter()
660            .filter(|(_, count)| *count > 0)
661            .map(|(grade, count)| format!("{count} {}", grade.as_str()))
662            .collect();
663        let torn = if ledger.dropped() > 0 {
664            format!(", {} unreadable line(s) ignored", ledger.dropped())
665        } else {
666            String::new()
667        };
668        self.ledger_line = format!(
669            "KiCad {}: {done} parts already imported ({}), {retry} to retry{torn} \u{2014} {}",
670            self.tag,
671            grades.join(", "),
672            ledger.path().display()
673        );
674    }
675
676    /// Start a sweep over `libraries`, resuming from the tag's ledger unless the
677    /// force box is ticked.
678    pub fn start_bulk(&mut self, libraries: Vec<String>) {
679        if libraries.is_empty() {
680            self.status = "there is no library to import".into();
681            return;
682        }
683        if self.bulk.as_ref().is_some_and(|run| !run.finished()) {
684            self.status = "a sweep is already running".into();
685            return;
686        }
687        let plan = Sweep {
688            cache_root: PathBuf::from(&self.cache_dir),
689            tag: self.tag.clone(),
690            symbols_dir: PathBuf::from(self.folders().0),
691            library: self.library(),
692            libraries,
693            force: self.force_reimport,
694        };
695        let wanted = plan.libraries.len();
696        match super::kicad_bulk::start(plan, Box::new(DiskFiles), (self.new_writer)()) {
697            Ok(run) => {
698                self.status = format!(
699                    "importing {wanted} librar{} into {}; {} parts already done{}",
700                    if wanted == 1 { "y" } else { "ies" },
701                    self.cache_dir,
702                    run.resumed,
703                    if self.force_reimport {
704                        ", and every one of them again"
705                    } else {
706                        ", which are skipped"
707                    }
708                );
709                self.bulk = Some(run);
710                self.stage = Stage::Bulk;
711            }
712            Err(error) => self.status = format!("the import did not start: {error}"),
713        }
714    }
715
716    /// The sweep's latest snapshot, for the suite and the status strip.
717    pub fn bulk_progress(&self) -> Option<&Progress> {
718        self.bulk.as_ref().map(|run| &run.progress)
719    }
720
721    /// The libraries on offer, narrowed by the search field.
722    fn matching(&self) -> Vec<String> {
723        let needle = self.search.to_lowercase();
724        self.libraries
725            .iter()
726            .filter(|name| name.to_lowercase().contains(&needle))
727            .cloned()
728            .collect()
729    }
730}
731
732impl eframe::App for KicadLibraryWindow {
733    /// eframe 0.35 hands the app a `Ui` filling the window, so the status strip
734    /// is a bottom panel INSIDE it and everything else fills what is left.
735    fn ui(&mut self, ui: &mut egui::Ui, _frame: &mut eframe::Frame) {
736        let ctx = ui.ctx().clone();
737        self.poll(Some(&ctx));
738        egui::Panel::bottom("kicad-library-status").show(ui, |ui| {
739            ui.horizontal_wrapped(|ui| ui.weak(&self.status));
740            if !self.saved.is_empty() {
741                ui.weak(format!("saved this session: {}", self.saved.join(", ")));
742            }
743        });
744        ui.heading("Import from KiCad");
745        ui.add_space(4.0);
746        self.show_source(ui);
747        ui.separator();
748        egui::ScrollArea::vertical().auto_shrink([false, false]).show(ui, |ui| {
749            self.show_stage(ui);
750        });
751    }
752}
753
754impl KicadLibraryWindow {
755    /// The two paths, and the folders whichever one is chosen reads.
756    fn show_source(&mut self, ui: &mut egui::Ui) {
757        // The two sources as one dropdown (the form's enum field): nothing
758        // shown until one is chosen.
759        let mut chosen = None;
760        ui.horizontal(|ui| {
761            ui.label("Library");
762            let choices = [
763                (Some(Source::Download), "download", Source::Download.label()),
764                (Some(Source::Install), "install", Source::Install.label()),
765            ];
766            let mut picked = (!matches!(self.stage, Stage::Choose)).then_some(self.source);
767            let (changed, _) = crate::form::enum_dropdown(ui, "library:source", &choices, &mut picked, None, None);
768            if changed {
769                chosen = picked;
770            }
771        });
772        match self.source {
773            Source::Download => {
774                let idle = self.cloning.is_none();
775                egui::Grid::new("kicad-library-remote").num_columns(2).show(ui, |ui| {
776                    ui.label("KiCad release");
777                    ui.add_enabled(idle, egui::TextEdit::singleline(&mut self.tag));
778                    ui.end_row();
779                    ui.label("Cloned into");
780                    ui.add_enabled(idle, egui::TextEdit::singleline(&mut self.cache_dir));
781                    ui.end_row();
782                });
783                ui.weak(
784                    "Symbols, footprints and 3D models are cloned with git from KiCad's own \
785                     repositories, once (about 5.6 GB), into folders laid out like a KiCad install. \
786                     git must be installed; without it, use your own KiCad folders instead.",
787                );
788                if let Some(run) = &self.cloning {
789                    let stopping = run.stopping();
790                    ui.horizontal(|ui| {
791                        ui.spinner();
792                        ui.label(&run.line);
793                        if ui.add_enabled(!stopping, egui::Button::new("Stop")).clicked() {
794                            run.stop();
795                        }
796                    });
797                }
798            }
799            Source::Install => {
800                egui::Grid::new("kicad-library-local").num_columns(2).show(ui, |ui| {
801                    for (label, field) in [
802                        ("Symbols", &mut self.symbols_dir),
803                        ("Footprints", &mut self.footprints_dir),
804                        ("3D models", &mut self.models_dir),
805                    ] {
806                        ui.label(label);
807                        ui.text_edit_singleline(field);
808                        ui.end_row();
809                    }
810                });
811            }
812        }
813        if let Some(source) = chosen {
814            let ctx = ui.ctx().clone();
815            self.choose(source, Some(&ctx));
816        }
817    }
818
819    fn show_stage(&mut self, ui: &mut egui::Ui) {
820        let mut open = None;
821        let mut read = None;
822        let mut sweep = None;
823        // The bulk controls and the search field are drawn BEFORE the match, which
824        // borrows the stage: both need `&mut self`.
825        if matches!(self.stage, Stage::Libraries) && !self.libraries.is_empty() {
826            sweep = self.show_bulk_controls(ui);
827            ui.separator();
828        }
829        if matches!(self.stage, Stage::Libraries | Stage::Symbols { .. }) {
830            ui.text_edit_singleline(&mut self.search);
831        }
832        match &self.stage {
833            Stage::Choose => {
834                ui.weak("Choose a source above.");
835            }
836            Stage::Libraries => {
837                for name in self.matching() {
838                    ui.horizontal(|ui| {
839                        if ui.selectable_label(false, &name).clicked() {
840                            open = Some(name.clone());
841                        }
842                        // One library is how a user samples a sweep before
843                        // committing to all 165 of them, and it is the only
844                        // size of sweep that has been measured end to end.
845                        if ui.small_button("import all of it").clicked() {
846                            sweep = Some(vec![name.clone()]);
847                        }
848                    });
849                }
850                if self.libraries.is_empty() {
851                    ui.weak("No symbol library here yet.");
852                }
853            }
854            Stage::Symbols { library, symbols, .. } => {
855                ui.label(format!("{library}: {} symbols", symbols.len()));
856                let needle = self.search.to_lowercase();
857                for symbol in symbols {
858                    if !symbol.library_id.to_lowercase().contains(&needle) {
859                        continue;
860                    }
861                    let row = ui.selectable_label(
862                        false,
863                        format!("{}  ({})", symbol.library_id, crate::panels::count(symbol.pins.len(), "pin", "pins")),
864                    );
865                    if row.clicked() {
866                        read = Some(symbol.clone());
867                    }
868                }
869            }
870            Stage::Opening { library } => {
871                ui.horizontal(|ui| {
872                    ui.spinner();
873                    ui.label(format!("reading {library}\u{2026}"));
874                });
875            }
876            Stage::Reading { symbol } => {
877                ui.horizontal(|ui| {
878                    ui.spinner();
879                    ui.label(format!("reading {symbol} and its 3D model\u{2026}"));
880                });
881            }
882            Stage::Review { part, warnings } => {
883                show_review(ui, part, warnings);
884            }
885            Stage::Bulk => {
886                if let Some(run) = &self.bulk {
887                    show_sweep(ui, run);
888                } else {
889                    ui.weak("No import has been started.");
890                }
891            }
892        }
893        if matches!(self.stage, Stage::Bulk) {
894            ui.separator();
895            let running = self.bulk.as_ref().is_some_and(|run| !run.finished());
896            let stopping = self.bulk.as_ref().is_some_and(BulkRun::stopping);
897            ui.horizontal(|ui| {
898                if running {
899                    if ui.add_enabled(!stopping, egui::Button::new("Stop")).clicked() {
900                        if let Some(run) = &self.bulk {
901                            run.stop();
902                        }
903                        self.status = "stopping after the part being imported \u{2014} \
904                                       it is finished and recorded first"
905                            .into();
906                    }
907                    if stopping {
908                        ui.weak("stopping\u{2026}");
909                    }
910                } else if ui.button("Back to the libraries").clicked() {
911                    self.stage = Stage::Libraries;
912                }
913            });
914        }
915        if matches!(self.stage, Stage::Review { .. }) {
916            ui.separator();
917            ui.horizontal(|ui| {
918                ui.label("Save as");
919                ui.text_edit_singleline(&mut self.document);
920                if ui.button("Save part").clicked() {
921                    if let Err(error) = self.save() {
922                        self.status = format!("not saved: {error}");
923                    }
924                }
925                if ui.button("Back").clicked() {
926                    self.stage = Stage::Libraries;
927                }
928            });
929        }
930        if let Some(libraries) = sweep {
931            self.start_bulk(libraries);
932        }
933        if let Some(name) = open {
934            self.open_library(&name);
935        }
936        if let Some(symbol) = read {
937            self.read_symbol(symbol);
938        }
939    }
940
941    /// The bulk row above the library list: what the ledger already holds, the
942    /// force box, and the button that starts the whole sweep. Answers with the
943    /// libraries to sweep when one was asked for.
944    fn show_bulk_controls(&mut self, ui: &mut egui::Ui) -> Option<Vec<String>> {
945        let mut wanted = None;
946        let matching = self.matching();
947        let running = self.bulk.as_ref().is_some_and(|run| !run.finished());
948        ui.horizontal_wrapped(|ui| {
949            let all = egui::Button::new(format!("Import every part of all {} libraries", self.libraries.len()));
950            if ui.add_enabled(!running && !self.libraries.is_empty(), all).clicked() {
951                wanted = Some(self.libraries.clone());
952            }
953            if matching.len() != self.libraries.len() && !matching.is_empty() {
954                let some = egui::Button::new(format!("\u{2026}or just the {} matching", matching.len()));
955                if ui.add_enabled(!running, some).clicked() {
956                    wanted = Some(matching);
957                }
958            }
959            ui.checkbox(&mut self.force_reimport, "Force reimport")
960                .on_hover_text(
961                    "Redo parts this cache has already imported, instead of skipping them. \
962                     Off, an import carries on where the last one stopped.",
963                );
964            if running && ui.button("Show the import in progress").clicked() {
965                self.stage = Stage::Bulk;
966            }
967        });
968        ui.weak(&self.ledger_line);
969        ui.weak(
970            "An import can be stopped and started again as often as you like: what it finished \
971             is written down, and a later run skips it without converting it again. A part with no footprint or no 3D model still becomes a part, and says so.",
972        );
973        wanted
974    }
975}
976
977/// The progress of a sweep: two bars, because the only honest denominator is
978/// libraries — how many symbols a library holds is unknown until its
979/// `.kicad_sym` has been parsed.
980fn show_sweep(ui: &mut egui::Ui, run: &BulkRun) {
981    let progress = &run.progress;
982    ui.add(egui::ProgressBar::new(progress.fraction()).show_percentage());
983    if progress.symbols_total > 0 {
984        let within = progress.symbols_done as f32 / progress.symbols_total as f32;
985        ui.add(
986            egui::ProgressBar::new(within.clamp(0.0, 1.0))
987                .desired_height(6.0)
988                .text(format!(
989                    "{}: {}/{}",
990                    progress.library, progress.symbols_done, progress.symbols_total
991                )),
992        );
993    }
994    ui.add_space(4.0);
995    egui::Grid::new("kicad-library-sweep").num_columns(2).show(ui, |ui| {
996        for (label, value) in [
997            ("Library", format!("{} of {}", progress.libraries_done.min(progress.libraries_total), progress.libraries_total)),
998            ("Now", if progress.symbol.is_empty() { progress.library.clone() } else { progress.symbol.clone() }),
999            ("Imported", progress.imported.to_string()),
1000            ("Already done", progress.skipped.to_string()),
1001            ("Failed, to retry later", progress.failed.to_string()),
1002            ("Recorded in", run.ledger.display().to_string()),
1003        ] {
1004            ui.label(label);
1005            ui.label(value);
1006            ui.end_row();
1007        }
1008        if progress.libraries_failed > 0 {
1009            ui.label("Libraries not read");
1010            ui.label(progress.libraries_failed.to_string());
1011            ui.end_row();
1012        }
1013    });
1014    if let Some(error) = &progress.error {
1015        ui.colored_label(egui::Color32::from_rgb(220, 120, 60), error);
1016    }
1017    if !progress.notes.is_empty() {
1018        ui.add_space(4.0);
1019        ui.weak("What went wrong, most recent last \u{2014} a later import retries exactly these:");
1020        for note in &progress.notes {
1021            ui.weak(note);
1022        }
1023    }
1024    if progress.finished && !progress.cancelled && progress.error.is_none() {
1025        ui.add_space(4.0);
1026        ui.label("Finished.");
1027    }
1028}
1029
1030/// What the save will write, and every note the chain left.
1031fn show_review(ui: &mut egui::Ui, part: &KicadPart, warnings: &[String]) {
1032    egui::Grid::new("kicad-library-review").num_columns(2).show(ui, |ui| {
1033        ui.label("Symbol");
1034        ui.label(
1035            part.symbol
1036                .as_ref()
1037                .map_or("none".into(), |s| format!("{} ({})", s.library_id, crate::panels::count(s.pins.len(), "pin", "pins"))),
1038        );
1039        ui.end_row();
1040        ui.label("Pads");
1041        ui.label(match (&part.footprint, &part.footprint_file) {
1042            (Some(f), Some(file)) => format!("{} ({}) from {file}", f.name, crate::panels::count(f.pads.len(), "pad", "pads")),
1043            (Some(f), None) => format!("{} ({})", f.name, crate::panels::count(f.pads.len(), "pad", "pads")),
1044            (None, _) => "none".into(),
1045        });
1046        ui.end_row();
1047        ui.label("3D model");
1048        ui.label(match &part.model {
1049            Some(model) => format!("{} ({})", model.step_file, crate::panels::count(model.bodies.len(), "body", "bodies")),
1050            None => "none".into(),
1051        });
1052        ui.end_row();
1053        if let Some(symbol) = &part.symbol {
1054            ui.label("Connection points");
1055            ui.label(format!(
1056                "{} in the part's `Pins` group, {}",
1057                symbol.pins.len(),
1058                if part.footprint.is_some() { "each at its pin's pad" } else { "at the part origin" }
1059            ));
1060            ui.end_row();
1061        }
1062    });
1063    for note in warnings.iter().chain(&part.notes) {
1064        ui.colored_label(ui.visuals().warn_fg_color, format!("\u{2022} {note}"));
1065    }
1066}
1067