1#![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
59pub const DEFAULT_TAG: &str = kicad_git::TAG;
61
62pub fn default_cache_root() -> PathBuf {
66 crate::plm::config::app_config_dir().join("kicad-library")
67}
68
69pub 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
81const SYMBOL_VARS: &[&str] = &[
86 "KICAD9_SYMBOL_DIR",
87 "KICAD8_SYMBOL_DIR",
88 "KICAD7_SYMBOL_DIR",
89 "KICAD6_SYMBOL_DIR",
90];
91
92pub 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
107pub fn local_symbol_libraries(dir: &str, files: &dyn KicadFiles) -> Vec<String> {
110 symbol_libraries(&files.list(dir))
111}
112
113pub 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
129struct LibraryReader {
138 answer: std::sync::mpsc::Receiver<Result<(Vec<Symbol>, Vec<String>), String>>,
139 library: String,
140}
141
142pub 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
174pub trait PartSource: KicadFiles + Send + 'static {
176 fn library(&self) -> KicadLibrary;
178}
179
180pub struct PartReader {
182 answer: std::sync::mpsc::Receiver<KicadPart>,
183}
184
185impl PartReader {
186 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
200pub 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 let _ = send.send(part);
209 });
210 PartReader { answer }
211}
212
213pub struct CloneRun {
215 updates: std::sync::mpsc::Receiver<CloneUpdate>,
216 cancel: Arc<AtomicBool>,
217 pub line: String,
219}
220
221enum CloneUpdate {
222 Line(String),
223 Done(Result<(), String>),
224}
225
226impl CloneRun {
227 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 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#[derive(Clone, Copy, Debug, PartialEq, Eq)]
265pub enum Source {
266 Download,
268 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
281pub enum Stage {
283 Choose,
285 Libraries,
287 Opening { library: String },
289 Symbols { library: String, symbols: Vec<Symbol>, warnings: Vec<String> },
291 Reading { symbol: String },
293 Review { part: Box<KicadPart>, warnings: Vec<String> },
295 Bulk,
297}
298
299pub struct KicadLibraryWindow {
301 pub stage: Stage,
302 source: Source,
303 symbols_dir: String,
305 footprints_dir: String,
306 models_dir: String,
307 cache_dir: String,
310 tag: String,
311 clone_base: String,
313 libraries: Vec<String>,
315 pub cloning: Option<CloneRun>,
317 reader: Option<PartReader>,
319 library_reader: Option<LibraryReader>,
321 search: String,
322 pending_warnings: Vec<String>,
325 document: String,
327 pub status: String,
328 store: Box<dyn ModelStore>,
329 pub saved: Vec<String>,
332 pub bulk: Option<BulkRun>,
334 force_reimport: bool,
336 ledger_line: String,
340 new_writer: Arc<dyn Fn() -> Box<dyn PartWriter + Send> + Send + Sync>,
344}
345
346impl KicadLibraryWindow {
347 pub fn new() -> Self {
349 Self::with_store(default_model_store())
350 }
351
352 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 pub fn sweep_through(&mut self, write: Arc<dyn Fn() -> Box<dyn PartWriter + Send> + Send + Sync>) {
386 self.new_writer = write;
387 }
388
389 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 fn clone_root(&self) -> PathBuf {
398 Path::new(&self.cache_dir).join(&self.tag)
399 }
400
401 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 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 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 self.reader = None;
439 self.library_reader = None;
440 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 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 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 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 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 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 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 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 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 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 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 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 pub fn bulk_progress(&self) -> Option<&Progress> {
718 self.bulk.as_ref().map(|run| &run.progress)
719 }
720
721 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 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 fn show_source(&mut self, ui: &mut egui::Ui) {
757 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 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 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 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
977fn 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
1030fn 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