diff --git a/apps/solidcraft-web/src/main.rs b/apps/solidcraft-web/src/main.rs index af8f37c5fb5..edbfdacd8c0 100644 --- a/apps/solidcraft-web/src/main.rs +++ b/apps/solidcraft-web/src/main.rs @@ -1705,12 +1705,18 @@ mod web { // browser's files window. A command that reads another kind of file // (Insert DXF or SVG, an image, a mesh, settings) gets a file dialog // offering that kind, and runs on the picked file. - pick_open: Some(Box::new(move |exts: &[&str]| match disk::open_route(disk::supported(), exts) { - disk::OpenRoute::Disk => Box::pin(disk::pick_open(&opener)), - disk::OpenRoute::Upload => Box::pin(files::pick_upload(&opener, exts)), - disk::OpenRoute::Panel => { - panel.panel.set(true); - Box::pin(std::future::ready(None)) + pick_open: Some(Box::new(move |filters: &[solidcraft_ui_egui::OpenFilter]| { + // The browser offers the files of every group the command names: its + // dialog has one list of types, not a filter per kind of file. + let offered = solidcraft_ui_egui::OpenFilter::every(filters); + let exts: Vec<&str> = offered.iter().map(String::as_str).collect(); + match disk::open_route(disk::supported(), &exts) { + disk::OpenRoute::Disk => Box::pin(disk::pick_open(&opener)), + disk::OpenRoute::Upload => Box::pin(files::pick_upload(&opener, &exts)), + disk::OpenRoute::Panel => { + panel.panel.set(true); + Box::pin(std::future::ready(None)) + } } })), // A design is saved to a file the user picks, or kept in the browser diff --git a/apps/solidcraft/src/main.rs b/apps/solidcraft/src/main.rs index e513487f995..e4ccd7e7df3 100644 --- a/apps/solidcraft/src/main.rs +++ b/apps/solidcraft/src/main.rs @@ -62,7 +62,7 @@ mod window_fit; mod winit_pointers; use solidcraft_engine::{Session, io}; -use solidcraft_ui_egui::{Services, SolveApp}; +use solidcraft_ui_egui::{OpenFilter, Services, SolveApp}; /// Windows: put the restored window back inside the monitor's work area if it is out of reach /// (a gone monitor, another scale, a taskbar edge). Sizes are in points, the work area in pixels. @@ -1168,15 +1168,22 @@ fn services(cc: &eframe::CreationContext<'_>, folder: &DialogFolder) -> Services #[cfg(target_os = "macos")] let any_folder = folder.clone(); Services { - pick_open: Some(Box::new(move |first: &[&str]| { + pick_open: Some(Box::new(move |filters: &[OpenFilter]| { // The chooser that opens may not be the desktop's own (#10159). #[cfg(target_os = "linux")] desktop_chooser::note_opening(&chooser_ctx); - // The file type the command reads comes first, so the picker opens on it (#1801). + // The groups the command names come first, so the picker opens on the first of them: + // the file type it reads, named after its extensions, or the kinds of file a person + // picks one of (Insert PCB's boards) (#1801, #26309). let mut dialog = open_folder.start(DialogKind::Open, open_parent.clone()); - if !first.is_empty() { - let label = first.iter().map(|e| e.to_uppercase()).collect::>().join(", "); - dialog = dialog.add_filter(label, &case_variants(first)); + for filter in filters { + let extensions: Vec<&str> = filter.extensions.iter().map(String::as_str).collect(); + let label = if filter.label.is_empty() { + filter.extensions.iter().map(|e| e.to_uppercase()).collect::>().join(", ") + } else { + filter.label.clone() + }; + dialog = dialog.add_filter(label, &case_variants(&extensions)); } // The groups come from the format registry, so a new format joins this dialog by itself. // Installed importer plugins read more kinds of file: they join "everything" and add diff --git a/assets/locales/ar.json b/assets/locales/ar.json index ca7390b6666..afb9b2d4617 100644 --- a/assets/locales/ar.json +++ b/assets/locales/ar.json @@ -1661,7 +1661,7 @@ "cmd.file_copy": "نسخ ملف التصميم", "cmd.file_export": "تصدير", "cmd.file_gerber_files": "ملفات لوحة الدوائر", - "cmd.file_insert_gerber": "إدراج لوحة دوائر مطبوعة (Gerber)", + "cmd.file_insert_gerber": "إدراج لوحة دوائر مطبوعة", "cmd.file_insert_mesh": "إدراج شبكة", "cmd.file_insert_step": "إدراج STEP", "cmd.file_move": "نقل ملف التصميم", diff --git a/assets/locales/ca.json b/assets/locales/ca.json index aa8ce6dbcb2..cdd41255d0f 100644 --- a/assets/locales/ca.json +++ b/assets/locales/ca.json @@ -1661,7 +1661,7 @@ "cmd.file_copy": "Copiar el fitxer de disseny", "cmd.file_export": "Exportar", "cmd.file_gerber_files": "Fitxers de PCB", - "cmd.file_insert_gerber": "Inserir PCB (Gerber)", + "cmd.file_insert_gerber": "Inserir PCB", "cmd.file_insert_mesh": "Inserir una malla", "cmd.file_insert_step": "Inserir STEP", "cmd.file_move": "Moure el fitxer de disseny", diff --git a/assets/locales/cs.json b/assets/locales/cs.json index ed7c04ce61c..0e34f5a4234 100644 --- a/assets/locales/cs.json +++ b/assets/locales/cs.json @@ -1637,7 +1637,7 @@ "cmd.file_copy": "Kopírovat soubor návrhu", "cmd.file_export": "Exportovat", "cmd.file_gerber_files": "Soubory DPS", - "cmd.file_insert_gerber": "Vložit DPS (Gerber)", + "cmd.file_insert_gerber": "Vložit DPS", "cmd.file_insert_mesh": "Vložit síť", "cmd.file_insert_step": "Vložit STEP", "cmd.file_move": "Přesunout soubor návrhu", diff --git a/assets/locales/de.json b/assets/locales/de.json index e48518dbab3..721e076a465 100644 --- a/assets/locales/de.json +++ b/assets/locales/de.json @@ -1621,7 +1621,7 @@ "cmd.file_copy": "Entwurfsdatei kopieren", "cmd.file_export": "Exportieren", "cmd.file_gerber_files": "Leiterplattendateien", - "cmd.file_insert_gerber": "Leiterplatte einfügen (Gerber)", + "cmd.file_insert_gerber": "Leiterplatte einfügen", "cmd.file_insert_mesh": "Netz einfügen", "cmd.file_insert_step": "STEP einfügen", "cmd.file_move": "Entwurfsdatei verschieben", diff --git a/assets/locales/en.json b/assets/locales/en.json index ec5f1a02955..39142c19ae3 100644 --- a/assets/locales/en.json +++ b/assets/locales/en.json @@ -1661,7 +1661,7 @@ "cmd.file_copy": "Copy Design File", "cmd.file_export": "Export", "cmd.file_gerber_files": "PCB Files", - "cmd.file_insert_gerber": "Insert PCB (Gerber)", + "cmd.file_insert_gerber": "Insert PCB", "cmd.file_insert_mesh": "Insert Mesh", "cmd.file_insert_step": "Insert STEP", "cmd.file_move": "Move Design File", @@ -3046,7 +3046,7 @@ "help.edit.restore_checkpoint": "Goes back to a checkpoint, undo history included. Use it to drop everything done since the checkpoint in one step.", "help.explode.create": "Creates an exploded view that pushes the parts away from the assembly's center, or by the moves you set. Use it to show how an assembly goes together, for instructions or presentations.", "help.face.delete": "Removes the selected faces and lets the neighboring faces close the gap, or leaves the gap open as a surface. Use it to take off a rounded edge, a hole or a boss that is in the way.", - "help.file.insert_gerber": "Builds a printed circuit board from its fabrication files: the Gerber board outline and the Excellon drill files become a sketch and a board body of the thickness you set, with every hole and slot cut through. Use it to design an enclosure or a bracket around a real board.", + "help.file.insert_gerber": "Brings a printed circuit board into this design as a component of its own, whichever way you have it. A KiCad board is read with the copper, silkscreen, holes and 3D models you choose and stays linked to its file, so Update Links reads it again when it changes. A board's fabrication files go in as one set: the Gerber outline and the Excellon drills become a sketch and a board body of the thickness you set, with every hole and slot cut through. Use it to design an enclosure or a bracket around a real board.", "help.file.insert_mesh": "Adds a 3MF, STL, OBJ, PLY or glTF file to the design as mesh bodies in a new component. Use it to place a downloaded or scanned model beside your design as a reference.", "help.file.insert_step": "Adds a STEP, IGES, FreeCAD or Rhino file to the design as solid bodies in a new component; an assembly's parts become nested components. Use it to bring in models from suppliers or other CAD programs.", "help.file.save_mesh": "Saves bodies as an STL, 3MF or OBJ mesh, with the smoothness of curved faces you choose. Use it to prepare parts for 3D printing or for programs that read meshes.", @@ -8465,7 +8465,7 @@ "ui.insert_drawing.middle": "Middle", "ui.insert_drawing.place_by": "Place by", "ui.insert_drawing.resolution": "Resolution", - "ui.insert_pcb.web_zip": "Insert PCB on the web takes the board's files as one zip", + "ui.insert_pcb.web_zip": "Insert PCB on the web takes one file: a KiCad board, or the board's fabrication files as one zip", "ui.insert_signed": "Inserted {name}; its file is signed by {key} (not checked)", "ui.insert_signed_unknown": "Inserted {name}; its file is signed (not checked)", "ui.insert_simplify": "Simplify", diff --git a/assets/locales/es.json b/assets/locales/es.json index 2e877e1e4a2..901d659f7d4 100644 --- a/assets/locales/es.json +++ b/assets/locales/es.json @@ -1661,7 +1661,7 @@ "cmd.file_copy": "Copiar archivo de diseño", "cmd.file_export": "Exportar", "cmd.file_gerber_files": "Archivos de PCB", - "cmd.file_insert_gerber": "Insertar PCB (Gerber)", + "cmd.file_insert_gerber": "Insertar PCB", "cmd.file_insert_mesh": "Insertar malla", "cmd.file_insert_step": "Insertar STEP", "cmd.file_move": "Mover archivo de diseño", diff --git a/assets/locales/eu.json b/assets/locales/eu.json index 511c6df32c4..54e67b6369f 100644 --- a/assets/locales/eu.json +++ b/assets/locales/eu.json @@ -62,7 +62,7 @@ "cmd.file_copy": "Kopiatu diseinu-fitxategia", "cmd.file_export": "Esportatu", "cmd.file_gerber_files": "PCB fitxategiak", - "cmd.file_insert_gerber": "Txertatu PCB (Gerber)", + "cmd.file_insert_gerber": "Txertatu PCB", "cmd.file_insert_mesh": "Txertatu sarea", "cmd.file_insert_step": "Txertatu STEP", "cmd.file_move": "Mugitu diseinu-fitxategia", diff --git a/assets/locales/fi.json b/assets/locales/fi.json index f5e9a9ee3bd..00c835f81fd 100644 --- a/assets/locales/fi.json +++ b/assets/locales/fi.json @@ -1581,7 +1581,7 @@ "cmd.file_copy": "Kopioi mallitiedosto", "cmd.file_export": "Vie", "cmd.file_gerber_files": "PCB-tiedostot", - "cmd.file_insert_gerber": "Lisää PCB (Gerber)", + "cmd.file_insert_gerber": "Lisää PCB", "cmd.file_insert_mesh": "Lisää verkko", "cmd.file_insert_step": "Lisää STEP", "cmd.file_move": "Siirrä mallitiedosto", diff --git a/assets/locales/fr.json b/assets/locales/fr.json index 83494535f4f..32a1e5c4d3f 100644 --- a/assets/locales/fr.json +++ b/assets/locales/fr.json @@ -1661,7 +1661,7 @@ "cmd.file_copy": "Copier le fichier de conception", "cmd.file_export": "Exporter", "cmd.file_gerber_files": "Fichiers de circuit imprimé", - "cmd.file_insert_gerber": "Insérer un circuit imprimé (Gerber)", + "cmd.file_insert_gerber": "Insérer un circuit imprimé", "cmd.file_insert_mesh": "Insérer un maillage", "cmd.file_insert_step": "Insérer un STEP", "cmd.file_move": "Déplacer le fichier de conception", diff --git a/assets/locales/he.json b/assets/locales/he.json index 5dcbcfb4265..c6434e79c55 100644 --- a/assets/locales/he.json +++ b/assets/locales/he.json @@ -1661,7 +1661,7 @@ "cmd.file_copy": "העתקת קובץ תכנון", "cmd.file_export": "ייצוא", "cmd.file_gerber_files": "קובצי מעגל מודפס", - "cmd.file_insert_gerber": "הוספת מעגל מודפס (Gerber)", + "cmd.file_insert_gerber": "הוספת מעגל מודפס", "cmd.file_insert_mesh": "הוספת רשת משולשים", "cmd.file_insert_step": "הוספת STEP", "cmd.file_move": "העברת קובץ תכנון", diff --git a/assets/locales/ja.json b/assets/locales/ja.json index ad34e2f60d7..3347eaef13c 100644 --- a/assets/locales/ja.json +++ b/assets/locales/ja.json @@ -1661,7 +1661,7 @@ "cmd.file_copy": "設計ファイルをコピー", "cmd.file_export": "エクスポート", "cmd.file_gerber_files": "基板ファイル", - "cmd.file_insert_gerber": "基板を挿入 (Gerber)", + "cmd.file_insert_gerber": "基板を挿入", "cmd.file_insert_mesh": "メッシュを挿入", "cmd.file_insert_step": "STEP を挿入", "cmd.file_move": "設計ファイルを移動", diff --git a/assets/locales/ka.json b/assets/locales/ka.json index 0c5e9bc0c73..5b08d4e148d 100644 --- a/assets/locales/ka.json +++ b/assets/locales/ka.json @@ -1614,7 +1614,7 @@ "cmd.file_copy": "პროექტის ფაილის კოპირება", "cmd.file_export": "ექსპორტირება", "cmd.file_gerber_files": "ბეჭდური დაფის ფაილები", - "cmd.file_insert_gerber": "ბეჭდური დაფის ჩასმა (Gerber)", + "cmd.file_insert_gerber": "ბეჭდური დაფის ჩასმა", "cmd.file_insert_mesh": "პოლიგონური ბადის ჩასმა", "cmd.file_insert_step": "STEP-ის ჩასმა", "cmd.file_move": "პროექტის ფაილის გადატანა", diff --git a/assets/locales/ko.json b/assets/locales/ko.json index a82b25bfdc8..6f6532945dc 100644 --- a/assets/locales/ko.json +++ b/assets/locales/ko.json @@ -1639,7 +1639,7 @@ "cmd.file_copy": "디자인 파일 복사", "cmd.file_export": "내보내기", "cmd.file_gerber_files": "PCB 파일", - "cmd.file_insert_gerber": "PCB 삽입 (Gerber)", + "cmd.file_insert_gerber": "PCB 삽입", "cmd.file_insert_mesh": "메시 삽입", "cmd.file_insert_step": "STEP 삽입", "cmd.file_move": "디자인 파일 이동", diff --git a/assets/locales/lv.json b/assets/locales/lv.json index a4e5d02ef01..ee63d2f454c 100644 --- a/assets/locales/lv.json +++ b/assets/locales/lv.json @@ -1661,7 +1661,7 @@ "cmd.file_copy": "Kopēt modeļa failu", "cmd.file_export": "Eksportēt", "cmd.file_gerber_files": "Iespiedplates faili", - "cmd.file_insert_gerber": "Ievietot iespiedplati (Gerber)", + "cmd.file_insert_gerber": "Ievietot iespiedplati", "cmd.file_insert_mesh": "Ievietot sietu", "cmd.file_insert_step": "Ievietot STEP", "cmd.file_move": "Pārvietot modeļa failu", diff --git a/assets/locales/pending/insert-pcb-any-board.json b/assets/locales/pending/insert-pcb-any-board.json new file mode 100644 index 00000000000..de13d67abb1 --- /dev/null +++ b/assets/locales/pending/insert-pcb-any-board.json @@ -0,0 +1,58 @@ +{ + "en": { + "ui.insert_pcb.filter_any": "All supported PCB files", + "ui.insert_pcb.filter_fabrication": "Gerber fabrication files", + "ui.insert_pcb.filter_kicad": "KiCad board", + "ui.insert_pcb.web_project": "Insert PCB on the web takes the board's own file (.kicad_pcb): a project file stands for a board beside it, which the browser cannot read", + "ui.insert_pcb.design_gone": "The design that asked for this board is no longer shown: insert the board again" + }, + "de": { + "ui.insert_pcb.filter_any": "Alle unterstützten PCB-Dateien", + "ui.insert_pcb.filter_fabrication": "Gerber-Fertigungsdateien", + "ui.insert_pcb.filter_kicad": "KiCad-Platine", + "ui.insert_pcb.web_project": "Insert PCB im Browser nimmt die Platine selbst (.kicad_pcb): eine Projektdatei steht für die Platine daneben, die der Browser nicht lesen kann", + "ui.insert_pcb.design_gone": "Die Platine wurde für ein Design angefordert, das nicht mehr angezeigt wird: fügen Sie sie erneut ein" + }, + "ar": { + "ui.insert_pcb.filter_any": "كل ملفات PCB المدعومة", + "ui.insert_pcb.filter_fabrication": "ملفات التصنيع بصيغة Gerber", + "ui.insert_pcb.filter_kicad": "لوحة KiCad", + "ui.insert_pcb.web_project": "لا يقبل زر Insert PCB في المتصفح إلا ملف اللوحة نفسه (.kicad_pcb): ملف المشروع يمثل لوحة بجانبه لا يستطيع المتصفح قراءتها", + "ui.insert_pcb.design_gone": "لم يعد التصميم الذي طلب هذه اللوحة معروضا: أدرجها من جديد" + }, + "he": { + "ui.insert_pcb.filter_any": "כל קובצי ה-PCB הנתמכים", + "ui.insert_pcb.filter_fabrication": "קובצי ייצור Gerber", + "ui.insert_pcb.filter_kicad": "לוח KiCad", + "ui.insert_pcb.web_project": "Insert PCB בדפדפן מקבל את קובץ הלוח עצמו (.kicad_pcb): קובץ פרויקט מייצג לוח שלצידו, והדפדפן אינו יכול לקרוא אותו", + "ui.insert_pcb.design_gone": "התכן שביקש את הלוח הזה אינו מוצג עוד: הוסף אותו שוב" + }, + "ja": { + "ui.insert_pcb.filter_any": "対応するすべての PCB ファイル", + "ui.insert_pcb.filter_fabrication": "Gerber 製作ファイル", + "ui.insert_pcb.filter_kicad": "KiCad 基板", + "ui.insert_pcb.web_project": "ブラウザーの Insert PCB は基板そのもののファイル(.kicad_pcb)を取ります。プロジェクトファイルは隣の基板を表すもので、ブラウザーはそれを読めません", + "ui.insert_pcb.design_gone": "この基板を求めた設計は表示されていません。もう一度挿入してください" + }, + "vi": { + "ui.insert_pcb.filter_any": "Mọi tệp PCB được hỗ trợ", + "ui.insert_pcb.filter_fabrication": "Tệp chế tạo Gerber", + "ui.insert_pcb.filter_kicad": "Bo mạch KiCad", + "ui.insert_pcb.web_project": "Insert PCB trên trình duyệt nhận chính tệp bo mạch (.kicad_pcb): tệp dự án đại diện cho bo mạch bên cạnh, mà trình duyệt không đọc được", + "ui.insert_pcb.design_gone": "Thiết kế đã yêu cầu bo mạch này không còn được hiển thị: hãy chèn lại" + }, + "zh": { + "ui.insert_pcb.filter_any": "所有受支持的 PCB 文件", + "ui.insert_pcb.filter_fabrication": "Gerber 制造文件", + "ui.insert_pcb.filter_kicad": "KiCad 电路板", + "ui.insert_pcb.web_project": "浏览器中的 Insert PCB 只取电路板本身的文件(.kicad_pcb):项目文件代表它旁边的电路板,浏览器无法读取", + "ui.insert_pcb.design_gone": "请求此电路板的设计已不再显示:请重新插入" + }, + "ko": { + "ui.insert_pcb.filter_any": "지원되는 모든 PCB 파일", + "ui.insert_pcb.filter_fabrication": "Gerber 제작 파일", + "ui.insert_pcb.filter_kicad": "KiCad 기판", + "ui.insert_pcb.web_project": "웹에서 Insert PCB는 기판 파일 자체(.kicad_pcb)를 받습니다. 프로젝트 파일은 옆에 있는 기판을 가리키며, 브라우저는 그것을 읽을 수 없습니다", + "ui.insert_pcb.design_gone": "이 기판을 요청한 설계가 더 이상 표시되지 않습니다. 다시 삽입하세요" + } +} diff --git a/assets/locales/pl.json b/assets/locales/pl.json index 46e3898c9a0..982ffed0f08 100644 --- a/assets/locales/pl.json +++ b/assets/locales/pl.json @@ -1537,7 +1537,7 @@ "cmd.file_copy": "Kopiuj plik projektu", "cmd.file_export": "Eksportuj", "cmd.file_gerber_files": "Pliki PCB", - "cmd.file_insert_gerber": "Wstaw płytkę PCB (Gerber)", + "cmd.file_insert_gerber": "Wstaw płytkę PCB", "cmd.file_insert_mesh": "Wstaw siatkę", "cmd.file_insert_step": "Wstaw STEP", "cmd.file_move": "Przenieś plik projektu", diff --git a/assets/locales/pt-BR.json b/assets/locales/pt-BR.json index 95ee74a3152..5744ed53f2f 100644 --- a/assets/locales/pt-BR.json +++ b/assets/locales/pt-BR.json @@ -1624,7 +1624,7 @@ "cmd.file_copy": "Copiar arquivo de projeto", "cmd.file_export": "Exportar", "cmd.file_gerber_files": "Arquivos PCB", - "cmd.file_insert_gerber": "Inserir PCB (Gerber)", + "cmd.file_insert_gerber": "Inserir PCB", "cmd.file_insert_mesh": "Inserir malha", "cmd.file_insert_step": "Inserir STEP", "cmd.file_move": "Mover arquivo de projeto", diff --git a/assets/locales/ru.json b/assets/locales/ru.json index f22f0ff25ed..03d624f1d5b 100644 --- a/assets/locales/ru.json +++ b/assets/locales/ru.json @@ -1635,7 +1635,7 @@ "cmd.file_copy": "Копировать файл дизайна", "cmd.file_export": "Экспорт", "cmd.file_gerber_files": "Файлы печатных плат", - "cmd.file_insert_gerber": "Вставить печатную плату (Gerber)", + "cmd.file_insert_gerber": "Вставить печатную плату", "cmd.file_insert_mesh": "Вставить меш", "cmd.file_insert_step": "Вставить STEP", "cmd.file_move": "Переместить файл дизайна", diff --git a/assets/locales/sr.json b/assets/locales/sr.json index e4e87a50e25..62bb7b6941c 100644 --- a/assets/locales/sr.json +++ b/assets/locales/sr.json @@ -1534,7 +1534,7 @@ "cmd.file_copy": "Копирај датотеку дизајна", "cmd.file_export": "Извоз", "cmd.file_gerber_files": "PCB датотеке", - "cmd.file_insert_gerber": "Уметни PCB (Gerber)", + "cmd.file_insert_gerber": "Уметни PCB", "cmd.file_insert_mesh": "Уметни мрежу", "cmd.file_insert_step": "Уметни STEP", "cmd.file_move": "Премести датотеку дизајна", diff --git a/assets/locales/tr.json b/assets/locales/tr.json index b0a5d3cfcab..4cb639576d1 100644 --- a/assets/locales/tr.json +++ b/assets/locales/tr.json @@ -1431,7 +1431,7 @@ "cmd.file_copy": "Tasarım Dosyasını Kopyala", "cmd.file_export": "Dışa aktar", "cmd.file_gerber_files": "PCB Dosyaları", - "cmd.file_insert_gerber": "PCB Ekle (Gerber)", + "cmd.file_insert_gerber": "PCB Ekle", "cmd.file_insert_mesh": "Ağ ekle", "cmd.file_insert_step": "STEP ekle", "cmd.file_move": "Tasarım Dosyasını Taşı", diff --git a/assets/locales/uk.json b/assets/locales/uk.json index e11e616bb43..1c513a257f8 100644 --- a/assets/locales/uk.json +++ b/assets/locales/uk.json @@ -1536,7 +1536,7 @@ "cmd.file_copy": "Копіювати файл проєкту", "cmd.file_export": "Експорт", "cmd.file_gerber_files": "Файли плати", - "cmd.file_insert_gerber": "Вставити плату (Gerber)", + "cmd.file_insert_gerber": "Вставити плату", "cmd.file_insert_mesh": "Вставити сітку", "cmd.file_insert_step": "Вставити STEP", "cmd.file_move": "Перемістити файл проєкту", diff --git a/assets/locales/vi.json b/assets/locales/vi.json index 5fa206f2fa1..05129778587 100644 --- a/assets/locales/vi.json +++ b/assets/locales/vi.json @@ -1661,7 +1661,7 @@ "cmd.file_copy": "Sao chép tệp thiết kế", "cmd.file_export": "Xuất tệp", "cmd.file_gerber_files": "Tệp mạch in", - "cmd.file_insert_gerber": "Chèn mạch in (Gerber)", + "cmd.file_insert_gerber": "Chèn mạch in", "cmd.file_insert_mesh": "Chèn lưới đa giác (Mesh)", "cmd.file_insert_step": "Chèn tệp STEP", "cmd.file_move": "Di chuyển tệp thiết kế", diff --git a/assets/locales/zh-TW.json b/assets/locales/zh-TW.json index 9026d8f5da4..3ad9a18ba59 100644 --- a/assets/locales/zh-TW.json +++ b/assets/locales/zh-TW.json @@ -1436,7 +1436,7 @@ "cmd.file_copy": "複製設計檔案", "cmd.file_export": "導出", "cmd.file_gerber_files": "電路板檔案", - "cmd.file_insert_gerber": "插入電路板 (Gerber)", + "cmd.file_insert_gerber": "插入電路板", "cmd.file_insert_mesh": "插入網格", "cmd.file_insert_step": "插入 STEP", "cmd.file_move": "移動設計檔案", diff --git a/assets/locales/zh.json b/assets/locales/zh.json index 604ca201869..88ee6e380e2 100644 --- a/assets/locales/zh.json +++ b/assets/locales/zh.json @@ -1661,7 +1661,7 @@ "cmd.file_copy": "复制设计文件", "cmd.file_export": "导出", "cmd.file_gerber_files": "电路板文件", - "cmd.file_insert_gerber": "插入电路板 (Gerber)", + "cmd.file_insert_gerber": "插入电路板", "cmd.file_insert_mesh": "插入网格", "cmd.file_insert_step": "插入 STEP", "cmd.file_move": "移动设计文件", diff --git a/crates/engine/src/cmd/board_import.rs b/crates/engine/src/cmd/board_import.rs index 068fddfa122..5d56174aa10 100644 --- a/crates/engine/src/cmd/board_import.rs +++ b/crates/engine/src/cmd/board_import.rs @@ -1,4 +1,5 @@ -//! Insert PCB (Gerber): a printed circuit board built from its fabrication files (#12797).; +//! Insert PCB: a printed circuit board in the active component, from its fabrication files +//! (#12797) or from a KiCad board (#26309).; //! //! The board goes into a new component named after it, made in the active component, as the //! STEP and mesh imports do. Inside it, the board outline layer (Gerber) and the drill files @@ -17,6 +18,14 @@ //! //! Which holes are inside the board is decided on the exact outline (its lines and arcs), never //! on a polygon or mesh made from it. +//! +//! A KiCad board (`.kicad_pcb`, or a `.kicad_pro` standing for its board) is the other way in: the +//! board is read as `doc.open` reads it, into a component of its own in the active component, and +//! that component is linked to the board file with the options it was read with, so Update Links +//! reads it again when it changes. That is the same component, with the same link, that opening +//! the board as a design of its own makes; here it goes into the design you are working in, with +//! no design of its own to hold it. The board's own options (`thickness`, `components`, `copper`, +//! `silkscreen`, `holes`, `color`, `representation`) are `doc.open`'s, and only a board reads them. use std::collections::{HashMap, HashSet}; use std::f64::consts::{FRAC_PI_2, TAU}; @@ -31,7 +40,7 @@ use super::board_layers::{self, Finish, Layer}; use super::sketch::{edit, ids_of}; use super::sketch_import::{add_geometry, bounds_of}; use crate::params::{bad, string_list}; -use crate::schema::board_import::{BoardImportResult, GerberFilesParams, GerberFilesResult, InsertGerberParams, SetFileInfo}; +use crate::schema::board_import::{BoardImportResult, GerberFilesParams, GerberFilesResult, InsertGerberParams, KicadInserted, PcbInserted, SetFileInfo}; use crate::schema::{TypedContract, output_schema_for}; use crate::{EngineError, Result, Session}; @@ -40,12 +49,12 @@ const CONTRACT: TypedContract = TypedContract::new(); const FILES_CMD: &str = "file.gerber_files"; const FILES_CONTRACT: TypedContract = TypedContract::new(); -pub static COMMANDS: &[CommandSpec] = &[CommandSpec::new("file.insert_gerber", "Insert PCB (Gerber)", crate::checked!("file.insert_gerber", insert_gerber)).begins_edit() +pub static COMMANDS: &[CommandSpec] = &[CommandSpec::new("file.insert_gerber", "Insert PCB", crate::checked!("file.insert_gerber", insert_gerber)).begins_edit() .at("SOLID", "INSERT") .icon("import") .contract(&CONTRACT) - .output(output_schema_for::) - .params("set?: a board's files as one: a zip, a folder, or any file in the board's folder; each file's layer is found from what it says (Gerber X2, Excellon), the job file (.gbrjob, which also gives thickness and finish) and its name, and outline, drills and layers then name files in the set to use instead; outline: path of the board outline Gerber (RS-274X) layer | outline_text: its text; drills?: path or [paths] of Excellon drill files (up to 16) and/or drills_text?: text or [texts]; thickness?: mm (default 1.6, more than 0, at most 20); name?: the new component's (default: the outline file's name without its extension, or Board); origin?: file (default: keep the files' coordinates) | corner (the lower-left corner of the box around the outline at the origin); layers?: {top_copper?, bottom_copper?, top_mask?, bottom_mask?, top_silk?, bottom_silk?: path of that Gerber layer} and/or layers_text?: the same keys with the layers' text; finish?: hasl (default) | enig, how bare copper looks → {component, component_name, sketch, feature, body, bodies, holes, slots, skipped, thickness, offset: [x, y] added to the files' coordinates, layer_sketches?: ids, prints?: names, warnings}: a new component in the active one, named after the board, holding a sketch Outline on XY with the outline (closed loops inside it are cut-outs) and every hole and slot wholly inside the board, and one extrude of the board by its thickness as the body Board; its properties pcb.outline, pcb.drills and pcb.thickness name the files and the thickness; a hole or slot outside the board or across its edge is skipped with a warning; gaps in the outline up to 0.05 mm are closed with a line and a warning, a wider gap is refused, naming it; each layer given is kept exactly as hidden sketches in the component (Top copper, Bottom mask...) and the board gets each side's printed look (solder mask, copper, finish, silkscreen) as an image on its face, Top print and Bottom print; component properties pcb. name the layer files. A sketch being edited is finished first. One undo step"), + .output(output_schema_for::) + .params("set?: a board's files as one: a zip, a folder, or any file in the board's folder; each file's layer is found from what it says (Gerber X2, Excellon), the job file (.gbrjob, which also gives thickness and finish) and its name, and outline, drills and layers then name files in the set to use instead; or a KiCad board (.kicad_pcb, or a .kicad_pro standing for its board), inserted as a component linked to the board file, with thickness?, components?, copper?, silkscreen?, holes?, color? and representation? as doc.open reads a board (ignored for a set of files); outline: path of the board outline Gerber (RS-274X) layer | outline_text: its text; drills?: path or [paths] of Excellon drill files (up to 16) and/or drills_text?: text or [texts]; thickness?: mm (default 1.6, more than 0, at most 20); name?: the new component's (default: the outline file's name without its extension, or Board); origin?: file (default: keep the files' coordinates) | corner (the lower-left corner of the box around the outline at the origin); layers?: {top_copper?, bottom_copper?, top_mask?, bottom_mask?, top_silk?, bottom_silk?: path of that Gerber layer} and/or layers_text?: the same keys with the layers' text; finish?: hasl (default) | enig, how bare copper looks → {component, component_name, sketch, feature, body, bodies, holes, slots, skipped, thickness, offset: [x, y] added to the files' coordinates, layer_sketches?: ids, prints?: names, warnings}, or, for a KiCad board, {component, component_name, occurrence, feature, name, bodies, created_bodies, board_path, board_solid?, subcomponents?, rigid_members?, warnings}: a new component in the active one, named after the board, holding a sketch Outline on XY with the outline (closed loops inside it are cut-outs) and every hole and slot wholly inside the board, and one extrude of the board by its thickness as the body Board; its properties pcb.outline, pcb.drills and pcb.thickness name the files and the thickness; a hole or slot outside the board or across its edge is skipped with a warning; gaps in the outline up to 0.05 mm are closed with a line and a warning, a wider gap is refused, naming it; each layer given is kept exactly as hidden sketches in the component (Top copper, Bottom mask...) and the board gets each side's printed look (solder mask, copper, finish, silkscreen) as an image on its face, Top print and Bottom print; component properties pcb. name the layer files. A sketch being edited is finished first. One undo step"), CommandSpec::new("file.gerber_files", "PCB Files", crate::checked!("file.gerber_files", gerber_files)) .icon("import") .noundo() @@ -59,10 +68,6 @@ fn read_set(cmd: &str, path: &str) -> Result { if path.trim().is_empty() || path.len() >= 4096 { return Err(bad(cmd, "a file path must be a path")); } - // A KiCad board would otherwise stand for its folder, read as a set with no outline (#26309). - if path.to_ascii_lowercase().ends_with(".kicad_pcb") { - return Err(bad(cmd, format!("{path} is a KiCad board, not a fabrication file: open it with File → Open (`doc.open`)"))); - } solidcraft_io::read_gerber_set(path).map_err(|e| EngineError::Other(format!("{path}: {e}"))) } @@ -87,6 +92,10 @@ fn set_name(set: &GerberSet) -> String { fn gerber_files(_s: &mut Session, p: &Value) -> Result { let path = text_key(p, "path")?.ok_or_else(|| bad(FILES_CMD, "give `path`: a zip, a folder, or a file in the board's folder"))?; + // A board holds no fabrication files to list: it is inserted as itself (#26309). + if solidcraft_io::is_kicad_path(path) { + return Err(bad(FILES_CMD, format!("{path} is a KiCad board, not a set of fabrication files: insert it with `{CMD}`"))); + } let set = read_set(FILES_CMD, path)?; let reply = GerberFilesResult { source: set.source.clone(), @@ -168,6 +177,11 @@ const SKETCH_NAME: &str = "Outline"; const BODY_NAME: &str = "Board"; fn insert_gerber(s: &mut Session, p: &Value) -> Result { + // A KiCad board is inserted as a component linked to it, as `doc.open` reads the same board + // into a design of its own (#26309): the board's own options, not a fabrication set's. + if let Some(path) = text_key(p, "set")?.filter(|path| solidcraft_io::is_kicad_path(path)) { + return insert_kicad(s, path, p); + } let thickness = match p.get("thickness") { None | Some(Value::Null) => None, Some(v) => v @@ -287,6 +301,36 @@ fn insert_gerber(s: &mut Session, p: &Value) -> Result { serde_json::to_value(reply).map_err(|e| EngineError::Other(e.to_string())) } +/// Insert the KiCad board at `path` into the active component, as a component of its own linked to +/// the board file, read with `p`'s board options: exactly the component, with the same link, that +/// `doc.open` makes when it opens the board into a design of its own (#26309). +fn insert_kicad(s: &mut Session, path: &str, p: &Value) -> Result { + // A sketch being edited is finished first, as a person would before inserting a board. + if s.active_sketch.is_some() { + run(s, "sketch.finish", &json!({}))?; + } + let name = match p.get("name") { + None | Some(Value::Null) => None, + Some(Value::String(n)) if n.chars().count() <= MAX_NAME => Some(n.trim()).filter(|n| !n.is_empty()), + Some(_) => return Err(bad(CMD, format!("`name` must be a name of at most {MAX_NAME} characters"))), + }; + // A board's own keys only: its outline and drills come from the board file itself. + for key in ["outline", "outline_text", "drills", "drills_text", "layers", "layers_text", "origin", "finish"] { + if p.get(key).is_some_and(|v| !v.is_null()) { + return Err(bad(CMD, format!("`{key}` names a board's fabrication files, and a KiCad board is read from its own file"))); + } + } + let options = super::file::kicad_options(p, CMD)?; + let r = super::file::add_kicad(s, path, name, &options, true)?; + // The board the person picked is the design's own link from now on: Update Links reads it + // again in this session, wherever it is. + if let Some(board) = r["board_path"].as_str() { + super::component_link::allow_linked_file(s, std::path::Path::new(board)); + } + let reply: KicadInserted = super::file::reply_from(r, CMD)?; + serde_json::to_value(reply).map_err(|e| EngineError::Other(e.to_string())) +} + /// A drill file that doesn't say how many decimal places its coordinates have was read with /// the usual number; a file written with one more or one fewer is ten times out, its holes off /// the board. Of the three readings, the one that puts the most holes in the box round the diff --git a/crates/engine/src/cmd/board_import_tests.rs b/crates/engine/src/cmd/board_import_tests.rs index 6c6f42cc983..2f6e45a1084 100644 --- a/crates/engine/src/cmd/board_import_tests.rs +++ b/crates/engine/src/cmd/board_import_tests.rs @@ -541,15 +541,77 @@ fn an_outline_drawn_in_tiny_steps_is_read_as_its_arcs() { near(volume(&mut s), (w * h - (4.0 - PI) * r * r) * 1.6); } +/// A board file for the tests: a 20 by 10 mm board, 2 mm thick, with one 9 mm track on it. +fn kicad_board(tag: &str) -> std::path::PathBuf { + let dir = std::env::temp_dir().join(format!("solidcraft-pcb-insert-{tag}-{}", std::process::id())); + let _ = std::fs::remove_dir_all(&dir); + std::fs::create_dir_all(&dir).unwrap(); + let path = dir.join("amp.kicad_pcb"); + let board = r#"(kicad_pcb (general (thickness 2)) + (gr_rect (start 0 0) (end 20 10) (layer "Edge.Cuts")) + (segment (start 1 2) (end 10 2) (width 0.3) (layer "F.Cu") (net 1)))"#; + std::fs::write(&path, board).unwrap(); + path +} + +/// Insert PCB takes a KiCad board: it goes into the design being worked in, as a component of its +/// own linked to the board file, as opening the board as a design of its own makes it (#26309). #[test] -fn a_kicad_board_says_to_open_it_instead() { +fn a_kicad_board_is_inserted_and_linked_to_its_file() { + let path = kicad_board("insert"); + let shown = path.to_string_lossy().into_owned(); let mut s = Session::default(); - for (command, params) in [ - ("file.insert_gerber", json!({"set": "boards/amp.kicad_pcb"})), - ("file.gerber_files", json!({"path": "boards/AMP.KICAD_PCB"})), - ("file.gerber_files", json!({"path": "boards/.kicad_pcb"})), - ] { - let refused = s.execute(command, ¶ms).unwrap_err().to_string(); - assert!(refused.contains("File → Open"), "{command}: {refused}"); + s.execute("solid.box", &json!({"length": 10, "width": 10, "height": 10})).unwrap(); + let components = s.doc.components.len(); + let r = s.execute("file.insert_gerber", &json!({"set": shown})).unwrap_or_else(|e| panic!("{e}")); + // The board is a component of its own, with the substrate as its own solid feature. + assert_eq!(r["component_name"], json!("amp"), "{r}"); + assert_eq!(r["board_path"], json!(shown), "{r}"); + assert_eq!(r["board_solid"], json!(true), "{r}"); + // The board is the substrate (named after the board) with its copper on top. + let bodies: Vec<&str> = r["bodies"].as_array().into_iter().flatten().filter_map(Value::as_str).collect(); + assert!(bodies.contains(&"amp") && bodies.contains(&"Copper F.Cu"), "{r}"); + let component = r["component"].as_u64().expect("a component"); + let link = s.doc.links.get(&component).unwrap_or_else(|| panic!("no link for {component}")); + assert_eq!(link.importer.as_ref().map(|i| i.format.as_str()), Some("kicad"), "{link:?}"); + assert!(link.path.ends_with("amp.kicad_pcb"), "{link:?}"); + // It is in the design that was open, beside the box, and the board's own 2 mm thickness is what + // was read. + assert_eq!(s.doc.components.len(), components + 1); + near(volume(&mut s), 1000.0 + 20.0 * 10.0 * 2.0); + // One undo takes the board out again, link and all. + s.execute("edit.undo", &json!({})).unwrap(); + assert_eq!(s.doc.components.len(), components); + assert!(s.doc.links.is_empty(), "{:?}", s.doc.links); + let _ = std::fs::remove_dir_all(path.parent().unwrap_or(&path)); +} + +/// The board's own options are `doc.open`'s, and a board takes none of the fabrication keys: those +/// name files the board already holds. +#[test] +fn a_kicad_board_takes_its_own_options_only() { + let path = kicad_board("options"); + let shown = path.to_string_lossy().into_owned(); + let mut s = Session::default(); + let r = s.execute("file.insert_gerber", &json!({"set": shown, "thickness": 1.0, "copper": "none"})).unwrap_or_else(|e| panic!("{e}")); + assert_eq!(r["component_name"], json!("amp"), "{r}"); + near(volume(&mut s), 20.0 * 10.0 * 1.0); + for (key, value) in [("outline", json!("amp-Edge_Cuts.gm1")), ("drills", json!("amp.drl")), ("finish", json!("enig"))] { + let mut params = json!({"set": shown}); + params[key] = value; + let refused = s.execute("file.insert_gerber", ¶ms).unwrap_err().to_string(); + assert!(refused.contains(key) && refused.contains("KiCad"), "{key}: {refused}"); + } + let _ = std::fs::remove_dir_all(path.parent().unwrap_or(&path)); +} + +/// A board is not a set of fabrication files, so the command that lists a set's files says which +/// command does read it, in any case. +#[test] +fn a_kicad_board_is_no_set_of_fabrication_files() { + let mut s = Session::default(); + for path in ["boards/AMP.KICAD_PCB", "boards/amp.kicad_pro"] { + let refused = s.execute("file.gerber_files", &json!({"path": path})).unwrap_err().to_string(); + assert!(refused.contains("file.insert_gerber"), "{path}: {refused}"); } } diff --git a/crates/engine/src/cmd/file.rs b/crates/engine/src/cmd/file.rs index e326e095f00..3f510595324 100644 --- a/crates/engine/src/cmd/file.rs +++ b/crates/engine/src/cmd/file.rs @@ -1578,7 +1578,7 @@ fn import_envelope(s: &mut Session, out: &Value) -> Result { } /// The KiCad import options a command's parameters name. -fn kicad_options(p: &Value, cmd: &str) -> Result { +pub(super) fn kicad_options(p: &Value, cmd: &str) -> Result { let mut options = solidcraft_io::KicadOptions::default(); if let Some(v) = p.get("thickness").filter(|v| !v.is_null()) { let value = v.as_f64().ok_or_else(|| bad(cmd, "`thickness` must be a finite number"))?; @@ -1721,7 +1721,7 @@ fn board_from_bytes(board_path: String, bytes: Vec, options: &solidcraft_io: Ok(KicadRead { imported, board_path, bytes, refused: refused_folders.take() }) } -fn add_kicad(s: &mut Session, path: &str, name: Option<&str>, options: &solidcraft_io::KicadOptions, keep_link: bool) -> Result { +pub(super) fn add_kicad(s: &mut Session, path: &str, name: Option<&str>, options: &solidcraft_io::KicadOptions, keep_link: bool) -> Result { add_kicad_with(s, path, name, options, keep_link, &KicadPaths::current()) } @@ -1887,10 +1887,20 @@ impl KicadPaths { /// These paths with the variables of the project beside `board_path`. A project that is /// missing, refused or malformed defines none. + /// + /// The project is looked for in the case the board's own extension is written in, then the + /// other one: a case-sensitive filesystem has `DEMO.KICAD_PRO` beside `DEMO.KICAD_PCB` only. fn for_board(&self, board_path: &str) -> Self { - let project = std::path::Path::new(board_path).with_extension("kicad_pro").to_string_lossy().into_owned(); - let bytes = solidcraft_io::vfs::check_design_path(&project, Some(board_path)).and_then(|()| solidcraft_io::vfs::read(&project, 16 << 20)); - Self { project: bytes.map(|bytes| kicad_project_variables_of(&bytes)).unwrap_or_default(), ..self.clone() } + let board = std::path::Path::new(board_path); + let upper = board.extension().is_some_and(|e| e.to_str().is_some_and(|e| e.eq_ignore_ascii_case("kicad_pcb") && e != "kicad_pcb")); + let names = if upper { ["KICAD_PRO", "kicad_pro"] } else { ["kicad_pro", "KICAD_PRO"] }; + let project = names + .iter() + .map(|extension| board.with_extension(extension).to_string_lossy().into_owned()) + .find(|path| solidcraft_io::vfs::is_file(path)); + let bytes = project + .map(|project| solidcraft_io::vfs::check_design_path(&project, Some(board_path)).and_then(|()| solidcraft_io::vfs::read(&project, 16 << 20))); + Self { project: bytes.and_then(std::result::Result::ok).map(|bytes| kicad_project_variables_of(&bytes)).unwrap_or_default(), ..self.clone() } } fn get(&self, name: &str) -> Option { @@ -2618,9 +2628,9 @@ fn reply(result: OpenResult) -> Result { serde_json::to_value(result).map_err(|e| EngineError::Other(format!("doc.open: {e}"))) } -/// What `doc.open` takes from the reply of the command that did the work (`from`). -fn reply_from(reply: Value, from: &str) -> Result { - serde_json::from_value(reply).map_err(|e| EngineError::Other(format!("doc.open: the reply of {from}: {e}"))) +/// What a command takes from the reply of the command that did the work (`from`). +pub(super) fn reply_from(reply: Value, from: &str) -> Result { + serde_json::from_value(reply).map_err(|e| EngineError::Other(format!("the reply of {from} cannot be read: {e}"))) } /// What `sketch.insert_dxf` and `sketch.insert_svg` reply, as far as `doc.open` passes it on. @@ -5522,6 +5532,35 @@ Shape { geometry Box { size 2 2 2 } }", let _ = std::fs::remove_dir_all(&base); } + /// The project is looked for beside a board written in capitals too: a case-sensitive + /// filesystem has `BOARD.KICAD_PRO` there, not `BOARD.kicad_pro` (#26309). + #[test] + fn an_uppercase_project_supplies_its_variables_to_its_board() { + let base = std::env::temp_dir().join(format!("solidcraft-kicad-upper-project-{}", std::process::id())); + let _ = std::fs::remove_dir_all(&base); + let (project, library) = (base.join("hw"), base.join("hw").join("lib")); + for dir in [&project, &library] { + std::fs::create_dir_all(dir).unwrap(); + } + std::fs::write(library.join("part.wrl"), b"#VRML V2.0 utf8\nShape { geometry Box { size 2 2 2 } }").unwrap(); + let board = project.join("BOARD.KICAD_PCB"); + std::fs::write( + &board, + "(kicad_pcb (general (thickness 1.6)) + (gr_rect (start 0 0) (end 20 10) (layer \"Edge.Cuts\")) + (footprint \"part\" (at 5 5) (layer \"F.Cu\") (property \"Reference\" \"U1\") + (model \"${SC_TEST_UPPER_LIB}/part.wrl\")))", + ) + .unwrap(); + std::fs::write(project.join("BOARD.KICAD_PRO"), r#"{"text_variables": {"SC_TEST_UPPER_LIB": "${KIPRJMOD}/lib"}}"#).unwrap(); + let mut s = Session::default(); + let options = solidcraft_io::KicadOptions::default(); + let reply = add_kicad_with(&mut s, &board.to_string_lossy(), None, &options, false, &KicadPaths::default()).unwrap(); + let warnings = reply["warnings"].to_string(); + assert!(!warnings.contains("part.wrl") && !warnings.contains("SC_TEST_UPPER_LIB"), "{warnings}"); + let _ = std::fs::remove_dir_all(&base); + } + /// The shell beats the project and the project beats KiCad's own table; variables that name /// each other, without end or many times over, are an error; a damaged project defines none. #[test] diff --git a/crates/engine/src/schema/board_import.rs b/crates/engine/src/schema/board_import.rs index 9ddcbdd8124..a4078c17ce5 100644 --- a/crates/engine/src/schema/board_import.rs +++ b/crates/engine/src/schema/board_import.rs @@ -8,8 +8,12 @@ use serde_json::Value; use super::check::whole; use super::types::StringList; -/// Insert a printed circuit board from its fabrication files into a new component named after -/// the board, in the active component: the board outline layer (Gerber, RS-274X) and any drill +/// Insert a printed circuit board into a new component named after the board, in the active +/// component: either from its fabrication files, or a KiCad board, which is read as `doc.open` +/// reads it and linked to the board file (a `.kicad_pcb`, or a `.kicad_pro` standing for its +/// board). +/// +/// From a board's fabrication files: the board outline layer (Gerber, RS-274X) and any drill /// files (Excellon) become a sketch `Outline` on XY with the outline and every drilled hole and /// routed slot, and one extrude of the board by its thickness as the body `Board`. Closed loops /// inside the outline are cut-outs. A hole or slot that is not wholly inside the board is skipped @@ -44,7 +48,8 @@ pub struct InsertGerberParams { /// Excellon drill files' text, instead of or as well as `drills`: one or a list of up to 16. #[serde(default)] pub drills_text: Option, - /// The board's thickness, in mm: more than 0, at most 20. Default: 1.6. + /// The board's thickness, in mm: more than 0. A KiCad board takes what `doc.open` takes, at + /// most 1000; a board built from its files takes at most 20. Default: 1.6, or the board's own. #[serde(default, deserialize_with = "thickness")] #[schemars(schema_with = "thickness_schema")] pub thickness: Option, @@ -68,6 +73,27 @@ pub struct InsertGerberParams { #[serde(default, deserialize_with = "finish")] #[schemars(schema_with = "finish_schema")] pub finish: Option, + /// A KiCad board only (ignored for a set of fabrication files): the components' 3D models. + /// Default: true. + #[serde(default)] + pub components: Option, + /// A KiCad board only: `none`, `overlay` (the default: flat copper just above the board) or + /// `mesh` (modelled with thickness); true means mesh, false none. + #[serde(default)] + pub copper: Option, + /// A KiCad board only: the silkscreen shapes and text. Default: true. + #[serde(default)] + pub silkscreen: Option, + /// A KiCad board only: which drilled holes come in: `mounting` (the default), `pads`, `all` + /// or `none`. + #[serde(default)] + pub holes: Option, + /// A KiCad board only: the substrate's colour, `#rrggbb` or [r, g, b] with values 0-255. + #[serde(default)] + pub color: Option, + /// A KiCad board only: `brep` (the default: a solid board) or `mesh`. + #[serde(default)] + pub representation: Option, } /// A board's image layers, each optional: a Gerber file's path (or text, in `layers_text`). @@ -107,17 +133,23 @@ fn finish_schema(_: &mut SchemaGenerator) -> Schema { json_schema!({"enum": ["hasl", "enig", null]}) } -/// The board's thickness as the handler reads it, with its message; `null` is the default. +/// The thickness a KiCad board may take, as `doc.open` reads it. +const KICAD_THICKNESS_MAX: f64 = 1000.0; + +/// The board's thickness as the handler reads it, `null` as the default. The check keeps the range +/// a KiCad board takes, so a board is not refused by the narrower bound of a set of files: the +/// handler refuses more than 20 mm for a set, in these very words, so a value that fails the check +/// for either route reads the same with the check on and off. fn thickness<'de, D: Deserializer<'de>>(d: D) -> Result, D::Error> { match Value::deserialize(d)? { Value::Null => Ok(None), - Value::Number(n) if n.as_f64().is_some_and(|t| t > 0.0 && t <= 20.0) => Ok(n.as_f64()), + Value::Number(n) if n.as_f64().is_some_and(|t| t > 0.0 && t <= KICAD_THICKNESS_MAX) => Ok(n.as_f64()), _ => Err(D::Error::custom(whole("`thickness` must be a number of mm, more than 0 and at most 20"))), } } fn thickness_schema(_: &mut SchemaGenerator) -> Schema { - json_schema!({"type": ["number", "null"], "exclusiveMinimum": 0, "maximum": 20}) + json_schema!({"type": ["number", "null"], "exclusiveMinimum": 0, "maximum": KICAD_THICKNESS_MAX}) } /// `file` or `corner`, with the handler's message; `null` is `file`. @@ -216,6 +248,55 @@ pub struct BoardImportResult { pub param_warnings: Vec, } +/// What `file.insert_gerber` returns for a KiCad board: the component the board was read into, and +/// its link to the board file (as `doc.open` makes it when the board is opened as a design of its +/// own). +#[derive(Debug, Deserialize, Serialize, JsonSchema)] +pub struct KicadInserted { + /// The board file read: the path the import was given. + pub path: String, + /// The `.kicad_pcb` the board was read from: the file itself, or the board a `.kicad_pro` + /// stands for. + pub board_path: String, + /// The new component's id: the board's feature and its bodies are in it. + pub component: u64, + /// The new component's name: the board's, or `name`. + pub component_name: String, + /// The board import feature's id: its copper, silkscreen and models. + pub feature: u64, + /// The feature's name. + pub name: String, + /// The bodies the import made, by name. + pub bodies: Vec, + /// The same names as `bodies`. + pub created_bodies: Vec, + /// What the board reader and the import noticed, worded for a person (a model that could not + /// be read, a folder an agent may not use...). + pub warnings: Vec, + /// The component's occurrence in the active component; null when it has none. + pub occurrence: Option, + /// How many components were made below it. Only when there are some. + #[serde(default, skip_serializing_if = "Option::is_none")] + pub subcomponents: Option, + /// How many occurrences its rigid group holds together. Only when `subcomponents` is given. + #[serde(default, skip_serializing_if = "Option::is_none")] + pub rigid_members: Option, + /// Whether the board's substrate is a solid of its own (a second feature), as it is by + /// default. Only when it has one. + #[serde(default, skip_serializing_if = "Option::is_none")] + pub board_solid: Option, +} + +/// What `file.insert_gerber` returns: a board built from its fabrication files, or a KiCad board. +#[derive(Debug, Serialize, JsonSchema)] +#[serde(untagged)] +pub enum PcbInserted { + /// A board built from its fabrication files: its sketch, the extrude and the layers' images. + Files(BoardImportResult), + /// A KiCad board, read and linked to its file. + Kicad(KicadInserted), +} + #[cfg(test)] #[path = "board_import_tests.rs"] mod tests; diff --git a/crates/engine/src/schema/board_import_tests.rs b/crates/engine/src/schema/board_import_tests.rs index 2753cef6d43..053a5dab916 100644 --- a/crates/engine/src/schema/board_import_tests.rs +++ b/crates/engine/src/schema/board_import_tests.rs @@ -1,7 +1,7 @@ use serde_json::Value; use solidcraft_derive::json; -use super::{BoardImportResult, InsertGerberParams}; +use super::{BoardImportResult, InsertGerberParams, KicadInserted, PcbInserted}; use crate::schema::tests::{assert_keys, assert_strict_keeps_todays_errors, conforms}; use crate::schema::{input_schema_for, output_schema_for}; @@ -9,7 +9,25 @@ use crate::schema::{input_schema_for, output_schema_for}; fn schemas_and_the_key_check_agree() { assert_keys( input_schema_for::(), - &["drills", "drills_text", "finish", "layers", "layers_text", "name", "origin", "outline", "outline_text", "set", "thickness"], + &[ + "color", + "components", + "copper", + "drills", + "drills_text", + "finish", + "holes", + "layers", + "layers_text", + "name", + "origin", + "outline", + "outline_text", + "representation", + "set", + "silkscreen", + "thickness", + ], ); } @@ -27,6 +45,31 @@ fn strict_keeps_todays_errors() { ]); } +/// Insert PCB's reply is one of two shapes, and the schema takes each: a board built from its +/// fabrication files, or a KiCad board read and linked to its file (#26309). +#[test] +fn a_kicad_board_reply_matches_the_same_schema() { + let reply = KicadInserted { + path: "amp.kicad_pcb".into(), + board_path: "amp.kicad_pcb".into(), + component: 1, + component_name: "amp".into(), + feature: 2, + name: "amp".into(), + bodies: vec!["board".into()], + created_bodies: vec!["board".into()], + warnings: Vec::new(), + occurrence: Some(3), + subcomponents: None, + rigid_members: None, + board_solid: Some(true), + }; + let r = serde_json::to_value(reply).unwrap_or(Value::Null); + let schema = output_schema_for::(); + let schema = schema.as_value(); + assert!(conforms(schema, schema, &r), "{r} doesn't match {schema}"); +} + /// The reply type's schema takes what the command returns. #[test] fn a_board_reply_matches_its_schema() { diff --git a/crates/io/src/kicad_in.rs b/crates/io/src/kicad_in.rs index 41ebb0e377c..f2dfb5bd0c2 100644 --- a/crates/io/src/kicad_in.rs +++ b/crates/io/src/kicad_in.rs @@ -478,11 +478,24 @@ pub fn kicad_file_thickness(path: &str) -> Option { } /// Resolve a selected KiCad project to its same-stem board, or keep a directly selected board. +/// +/// The board keeps the case the project's own extension has (`DEMO.KICAD_PRO` stands for +/// `DEMO.KICAD_PCB`): a case-sensitive filesystem has no other one. pub fn kicad_board_path(path: &Path) -> Result { - match path.extension().and_then(|e| e.to_str()).map(str::to_ascii_lowercase).as_deref() { - Some("kicad_pro") => Ok(path.with_extension("kicad_pcb")), + let extension = path.extension().and_then(|e| e.to_str()); + match extension.map(str::to_ascii_lowercase).as_deref() { + Some("kicad_pro") => { + // The underscore is not a letter, so the case is read from the extension as written. + let upper = extension == Some("KICAD_PRO"); + let names = if upper { ["KICAD_PCB", "kicad_pcb"] } else { ["kicad_pcb", "KICAD_PCB"] }; + let candidates: Vec = names.iter().map(|board| path.with_extension(board)).collect(); + // The board beside the project in its own case, else the one in the other case: a + // case-sensitive filesystem has one of them. With neither there, the first stands, so + // the failure names the board the project is expected to have. + Ok(candidates.iter().find(|board| crate::vfs::is_file(&board.to_string_lossy())).unwrap_or(&candidates[0]).clone()) + } Some("kicad_pcb") => Ok(path.to_path_buf()), - _ => Err(IoError::Format(path.extension().and_then(|e| e.to_str()).unwrap_or("unknown").to_string())), + _ => Err(IoError::Format(extension.unwrap_or("unknown").to_string())), } } diff --git a/crates/io/src/kicad_in_tests.rs b/crates/io/src/kicad_in_tests.rs index 83c44d92323..29c62923c97 100644 --- a/crates/io/src/kicad_in_tests.rs +++ b/crates/io/src/kicad_in_tests.rs @@ -502,7 +502,21 @@ fn handles_escaped_model_paths_and_kicad_extensions_case_insensitively() { fn resolves_project_to_same_stem_board_and_keeps_direct_board() { assert_eq!(kicad_board_path(Path::new("folder/demo.kicad_pro")).unwrap(), Path::new("folder/demo.kicad_pcb")); assert_eq!(kicad_board_path(Path::new("folder/demo.kicad_pcb")).unwrap(), Path::new("folder/demo.kicad_pcb")); + // An uppercase project stands for an uppercase board, as a case-sensitive filesystem has it. + assert_eq!(kicad_board_path(Path::new("folder/DEMO.KICAD_PRO")).unwrap(), Path::new("folder/DEMO.KICAD_PCB")); assert!(kicad_board_path(Path::new("folder/demo.step")).is_err()); + // Beside real files, the board next to the project wins, in whichever case it is written. + let dir = std::env::temp_dir().join(format!("solidcraft-kicad-project-case-{}", std::process::id())); + let _ = std::fs::remove_dir_all(&dir); + std::fs::create_dir_all(&dir).unwrap(); + let pairs = [("DEMO.KICAD_PCB", "DEMO.KICAD_PRO"), ("MIXED.kicad_pcb", "MIXED.KICAD_PRO"), ("UPPER.KICAD_PCB", "UPPER.kicad_pro")]; + for (board, project) in pairs { + std::fs::write(dir.join(board), "(kicad_pcb)").unwrap(); + std::fs::write(dir.join(project), "{}").unwrap(); + assert_eq!(kicad_board_path(&dir.join(project)).unwrap(), dir.join(board), "{project} stands for {board}"); + } + assert_eq!(kicad_board_path(&dir.join("gone.kicad_pro")).unwrap(), dir.join("gone.kicad_pcb"), "neither there: the board it is expected to have"); + let _ = std::fs::remove_dir_all(&dir); } #[test] diff --git a/crates/ui-egui/src/file_load.rs b/crates/ui-egui/src/file_load.rs index f85a1b063fa..23dd9849557 100644 --- a/crates/ui-egui/src/file_load.rs +++ b/crates/ui-egui/src/file_load.rs @@ -101,9 +101,10 @@ pub struct Request { /// Insert the file as a mesh whatever its extension says: a PLY goes to `pointcloud.insert` /// unless the person chose Insert Mesh for it (then it needs its faces). pub mesh: bool, - /// Insert the board this file (a zip, or any file in its folder) belongs to: its Gerber and - /// Excellon files as one (`file.insert_gerber` with the file as its `set`). - pub gerber: bool, + /// Insert it as a printed circuit board: a board's fabrication files as one (a zip, a folder, + /// or any file in the folder: `file.insert_gerber` with the file as its `set`), or a KiCad + /// board, which that command inserts and links to its file. + pub pcb: bool, /// The level the caller's own `param_check` named and the warnings it found before the run: /// the reply says both (#9184). pub(crate) param_check: Option<(solidcraft_engine::schema::ParamCheck, Vec)>, @@ -162,7 +163,7 @@ impl Request { chat_turn: None, app_only: false, mesh: false, - gerber: false, + pcb: false, param_check: None, note: None, serial: crate::operations::serial(), @@ -219,7 +220,7 @@ impl Request { match &self.kind { Kind::Open if self.plugin_import => ("file.import", self.params()), Kind::Open => ("doc.open", self.open_params()), - Kind::Insert if self.gerber => { + Kind::Insert if self.pcb => { let mut params = self.options.clone(); params.insert("set".into(), json!(self.path)); ("file.insert_gerber", Value::Object(params)) @@ -761,16 +762,28 @@ pub fn begin(app: &mut SolveApp, path: &str, insert: bool) { let _ = begin_request(app, request); } -/// Insert PCB: insert the board the picked `path` belongs to, beside the window. On the `web` -/// only a zip is taken: some browsers (iPhone, iPad) don't filter the picker, and one uploaded -/// file would be read with whatever else was uploaded before. +/// Insert PCB: insert the board the picked `path` is, or belongs to, beside the window. A KiCad +/// board is asked about first, with the rows File → Open shows for it, and then goes in as the +/// board component linked to its file; a board's fabrication files go in as the one set they are. +/// On the `web` only a zip or a board is taken: some browsers (iPhone, iPad) don't filter the +/// picker, and an uploaded fabrication file would be read with whatever else was uploaded before. pub(crate) fn insert_board(app: &mut SolveApp, path: &str, web: bool) { - if web && !solidcraft_engine::io::is_zip_path(path) { - app.set_status(tr!("ui.insert_pcb.web_zip"), true); + let board = solidcraft_engine::io::is_kicad_path(path); + // A project file stands for the board beside it, which the browser does not have. + let project = std::path::Path::new(path).extension().and_then(|e| e.to_str()).is_some_and(|e| e.eq_ignore_ascii_case("kicad_pro")); + if web && (project || (!board && !solidcraft_engine::io::is_zip_path(path))) { + let refused = if project { "ui.insert_pcb.web_project" } else { "ui.insert_pcb.web_zip" }; + let text = solidcraft_ui_text::tr_by_id(refused).to_string(); + app.set_status(text, true); + return; + } + // The board's own options (its copper, silkscreen, models...), and the dialog starts the + // insert itself. + if board && crate::import_options::ask_board_insert(app, path) { return; } let mut request = Request::new(path, Kind::Insert); - request.gerber = true; + request.pcb = true; if let Err(e) = begin_request(app, request) { app.set_status(e, true); } @@ -853,9 +866,16 @@ pub fn begin_request(app: &mut SolveApp, mut request: Request) -> Result<(), Str return Ok(()); } let r = match &request.kind { - Kind::Insert if request.gerber => { - let (command, params) = request.command(); - app.run(command, params) + Kind::Insert if request.pcb => { + // The board goes into the design whose tab asked for it, as the native queue sees to + // it: the browser has no queue for one that waits, so it says so instead of putting + // the board into a design the person did not pick (#26309). + if request.tab.is_some_and(|tab| tab != app.docs.active_tab()) { + Err(tr!("ui.insert_pcb.design_gone").to_string()) + } else { + let (command, params) = request.command(); + app.run(command, params) + } } // A failed import is the request's answer, as a staged one's is. Kind::Insert => app.insert_path_with(&request.path, &request.options, request.mesh).map(|()| Value::Null), @@ -1068,7 +1088,7 @@ pub fn control(app: &mut SolveApp, req: crate::control::ControlRequest) -> Optio chat_turn: req.chat_turn, app_only: req.app_only, mesh: false, - gerber: false, + pcb: false, param_check, note: None, serial: crate::operations::serial(), @@ -3113,6 +3133,45 @@ M30 let _ = std::fs::remove_dir_all(dir.parent().unwrap_or(&dir)); } + /// Insert PCB takes a KiCad board as it takes its fabrication files: the same button, the same + /// command, and the board goes into the design being worked in, linked to its file, with no + /// design of its own to hold it (#26309). + #[test] + fn insert_pcb_inserts_a_picked_kicad_board_into_the_design() { + const BOARD: &str = r#"(kicad_pcb (general (thickness 2)) + (gr_rect (start 0 0) (end 20 10) (layer "Edge.Cuts")) + (segment (start 1 2) (end 10 2) (width 0.3) (layer "F.Cu") (net 1)))"#; + let dir = std::env::temp_dir().join(format!("solidcraft-insert-pcb-board-{}", std::process::id())); + let _ = std::fs::remove_dir_all(&dir); + std::fs::create_dir_all(&dir).unwrap(); + let board = dir.join("amp.kicad_pcb"); + std::fs::write(&board, BOARD).unwrap(); + let picked = board.to_string_lossy().into_owned(); + let mut h = crate::scenario::Harness::new(); + h.app.run("solid.box", json!({"length": 10, "width": 10, "height": 10})).unwrap(); + let boxes = h.app.session.doc.components.len(); + h.app.services.pick_open = Some(Box::new(move |_| Box::pin(std::future::ready(Some(picked.clone()))))); + h.app.start("file.insert_gerber"); + h.frames(3); + // The board's own options are asked first, exactly as File → Open asks them for it. + let ask = h.app.import_options.clone().unwrap_or_else(|| panic!("the board was inserted without its options")); + assert_eq!((ask.values.format, ask.insert), ("kicad", true), "Insert PCB inserts it, beside the window"); + assert_eq!(h.app.import_options.as_ref().and_then(|ask| ask.tab), Some(h.app.docs.active_tab())); + assert!(h.app.file_load.idle(), "nothing is read before the options are chosen"); + h.step(&json!({"click": {"handle": "import_options:ok"}})).unwrap(); + h.settle(); + let c = h.app.session.doc.components.iter().find(|c| c.name == "amp").unwrap_or_else(|| panic!("no board: {:?}", h.app.status)); + let link = h.app.session.doc.links.get(&c.id).unwrap_or_else(|| panic!("the board is not linked to its file: {:?}", h.app.session.doc.links)); + assert!(link.path.ends_with("amp.kicad_pcb"), "{link:?}"); + // In the design that was open, in one undo step of its own. + assert_eq!(h.app.session.doc.components.len(), boxes + 1); + assert!(h.app.session.path.is_none(), "the design it went into is the one that was open"); + h.app.run("edit.undo", json!({})).unwrap(); + h.settle(); + assert_eq!(h.app.session.doc.components.len(), boxes, "one undo takes the board out again"); + let _ = std::fs::remove_dir_all(dir); + } + #[test] fn a_ply_is_a_point_cloud_unless_inserted_as_a_mesh() { let mut request = Request::new("scan.ply", Kind::Insert); @@ -3120,10 +3179,15 @@ M30 assert_eq!(Request::new("scan.ply", Kind::Open).command().0, "doc.open"); request.mesh = true; assert_eq!(request.command().0, "file.insert_mesh"); - // Insert PCB: the picked file is the board's set. + // Insert PCB: the picked file is the board's set, and a picked board is what that command + // inserts and links to its file. let mut request = Request::new("board.zip", Kind::Insert); - request.gerber = true; + request.pcb = true; assert_eq!(request.command(), ("file.insert_gerber", json!({"set": "board.zip"}))); + let mut request = Request::new("amp.kicad_pcb", Kind::Insert); + request.pcb = true; + request.options.insert("copper".into(), json!("none")); + assert_eq!(request.command(), ("file.insert_gerber", json!({"set": "amp.kicad_pcb", "copper": "none"}))); } /// A FreeCAD file comes in as its rebuilt features; with the preference off, as its solids in diff --git a/crates/ui-egui/src/file_picker.rs b/crates/ui-egui/src/file_picker.rs index 983f8c27047..dd947a6463f 100644 --- a/crates/ui-egui/src/file_picker.rs +++ b/crates/ui-egui/src/file_picker.rs @@ -10,6 +10,40 @@ use serde_json::{Value, json}; use crate::SolveApp; +/// One group of the host's Open dialog: the label it shows for the group, and the extensions it +/// offers (`*` for any file). A group with an empty label is the dialog's own first group, named +/// after its extensions (the type the command reads). +#[derive(Clone, Debug, Default, PartialEq)] +pub struct OpenFilter { + pub label: String, + pub extensions: Vec, +} + +impl OpenFilter { + /// The group a command of `extensions` asks for: no label of its own, as its type names it. + pub(crate) fn unnamed(extensions: &[&str]) -> Self { + OpenFilter { label: String::new(), extensions: extensions.iter().map(|e| e.to_string()).collect() } + } + + /// The group `label` asks for: the files a person picks by what they are, not by their type's + /// extensions. + pub(crate) fn named(label: &str, extensions: &[&str]) -> Self { + OpenFilter { label: label.to_string(), extensions: extensions.iter().map(|e| e.to_string()).collect() } + } + + /// Every extension the groups offer, in order, each once: what a host whose dialog has one list + /// of types rather than a filter per kind of file offers (the browser). + pub fn every(filters: &[OpenFilter]) -> Vec { + let mut out: Vec = Vec::new(); + for extension in filters.iter().flat_map(|filter| filter.extensions.iter()) { + if !out.contains(extension) { + out.push(extension.clone()); + } + } + out + } +} + /// A host picker answer: a selected path, or `None` when cancelled. pub type FilePickerFuture = Pin>>>; /// A host picker answer for several files: the selected paths, none when cancelled. @@ -67,17 +101,25 @@ impl SolveApp { } pub(crate) fn pick_open(&mut self, complete: impl FnOnce(&mut SolveApp, Option) + 'static) { - self.pick_open_for(&[], complete); + self.pick_open_filters(&[], complete); } /// Open a file of this type: the picker offers these extensions first (#1801). pub(crate) fn pick_open_for(&mut self, extensions: &[&str], complete: impl FnOnce(&mut SolveApp, Option) + 'static) { + let filters: Vec = (!extensions.is_empty()).then(|| OpenFilter::unnamed(extensions)).into_iter().collect(); + self.pick_open_filters(&filters, complete); + } + + /// Open a file, with the picker's groups named: the dialog opens on the first group, and the + /// host adds the kinds of file every Open offers after them (Insert PCB picks a board by what + /// it is, not by its files' extensions). + pub(crate) fn pick_open_filters(&mut self, filters: &[OpenFilter], complete: impl FnOnce(&mut SolveApp, Option) + 'static) { if self.file_picker_busy() { return; } // The dialog offers the files installed importer plugins read too. solidcraft_engine::io::formats::set_plugin_open_filters(solidcraft_engine::plugin::open_filters(&self.session)); - self.begin_picker(|services| services.pick_open.as_ref().map(|pick| pick(extensions)), Box::new(complete)); + self.begin_picker(|services| services.pick_open.as_ref().map(|pick| pick(filters)), Box::new(complete)); } /// Ask for one file of a kind (`label`, `extensions`), with the host's dialog for it, or the @@ -91,7 +133,7 @@ impl SolveApp { self.begin_picker( |services| match services.pick_file.as_ref() { Some(pick) => Some(pick(label, extensions)), - None => services.pick_open.as_ref().map(|pick| pick(extensions)), + None => services.pick_open.as_ref().map(|pick| pick(&[OpenFilter::named(label, extensions)])), }, Box::new(complete), ); @@ -562,8 +604,8 @@ mod tests { let mut h = crate::scenario::Harness::new(); let asked: Rc>>> = Rc::default(); let log = asked.clone(); - h.app.services.pick_open = Some(Box::new(move |extensions| { - log.borrow_mut().push(extensions.iter().map(|e| e.to_string()).collect()); + h.app.services.pick_open = Some(Box::new(move |filters: &[OpenFilter]| { + log.borrow_mut().push(filters.first().map(|filter| filter.extensions.clone()).unwrap_or_default()); Box::pin(std::future::ready(None)) })); h.app.run("sketch.create", json!({"plane": "XY"})).unwrap(); @@ -631,8 +673,8 @@ mod tests { h.app.home.open = false; let asked: Rc>>> = Rc::default(); let log = asked.clone(); - h.app.services.pick_open = Some(Box::new(move |types: &[&str]| { - log.borrow_mut().push(types.iter().map(|t| t.to_string()).collect()); + h.app.services.pick_open = Some(Box::new(move |filters: &[OpenFilter]| { + log.borrow_mut().push(filters.first().map(|filter| filter.extensions.clone()).unwrap_or_default()); Box::pin(std::future::ready(None)) })); crate::params_dialog::open(&mut h.app); diff --git a/crates/ui-egui/src/forms_prototype/interchange.rs b/crates/ui-egui/src/forms_prototype/interchange.rs index 11c876666dd..17f96fd2d6f 100644 --- a/crates/ui-egui/src/forms_prototype/interchange.rs +++ b/crates/ui-egui/src/forms_prototype/interchange.rs @@ -195,8 +195,8 @@ mod tests { let mut app = SolveApp::new(Default::default(), Default::default()); app.session.execute("form.prototype.create", &json!({"size":10,"segments":[1,1,1]})).unwrap(); let original = app.session.forms_prototype.as_ref().unwrap().cage.clone(); - app.services.pick_open = Some(Box::new(|ext| { - assert_eq!(ext, ["blend"]); + app.services.pick_open = Some(Box::new(|groups| { + assert_eq!(crate::OpenFilter::every(groups), ["blend"]); Box::pin(std::future::ready(None)) })); app.services.pick_save = Some(Box::new(|name, ext| { @@ -305,8 +305,8 @@ mod tests { h.app.services.pick_open = Some(Box::new({ let answer = answer_open.clone(); let calls = open_calls.clone(); - move |extensions| { - assert_eq!(extensions, ["blend"]); + move |groups| { + assert_eq!(crate::OpenFilter::every(groups), ["blend"]); calls.set(calls.get() + 1); let answer = answer.clone(); let path = open_path.clone(); diff --git a/crates/ui-egui/src/home.rs b/crates/ui-egui/src/home.rs index c3224f1d57c..097b37547ef 100644 --- a/crates/ui-egui/src/home.rs +++ b/crates/ui-egui/src/home.rs @@ -2009,8 +2009,8 @@ mod tests { let mut h = crate::scenario::Harness::new(); let asked: std::rc::Rc>>> = Default::default(); let log = asked.clone(); - h.app.services.pick_open = Some(Box::new(move |extensions| { - log.borrow_mut().push(extensions.iter().map(|e| e.to_string()).collect()); + h.app.services.pick_open = Some(Box::new(move |filters: &[crate::OpenFilter]| { + log.borrow_mut().push(filters.first().map(|filter| filter.extensions.clone()).unwrap_or_default()); Box::pin(std::future::ready(None)) })); h.app.home.show(0); diff --git a/crates/ui-egui/src/import_options.rs b/crates/ui-egui/src/import_options.rs index 8e3941b99c7..9b994def379 100644 --- a/crates/ui-egui/src/import_options.rs +++ b/crates/ui-egui/src/import_options.rs @@ -20,7 +20,9 @@ //! and thickness (starting at the board's own, read from its file) and whether the board is a solid //! or a mesh. A board always asks, whatever the preference says: it had its own window before the //! preference existed, and turning the preference off must not take its choices away. A board -//! chosen to insert opens as a design of its own, as it always has (`doc.open` reads boards). +//! opened, or dropped into a design, opens as a design of its own, as it always has (`doc.open` +//! reads boards); a board chosen with Insert PCB goes into the design being worked in instead, +//! beside the window, which is the same board component linked to the same file. //! //! Only interactive entry points ask ([`crate::file_load::begin`]): a script, the control channel //! or MCP calls the commands with their own options and never meets this dialog. @@ -258,6 +260,20 @@ fn next_prompt(app: &mut SolveApp) { /// while the preference is off (see the module docs). A file asked while another waits (several /// dropped at once) waits its turn, and is asked once that one is answered. pub fn ask(app: &mut SolveApp, path: &str, insert: bool) -> bool { + ask_about(app, path, insert, false) +} + +/// Ask a KiCad board's import options before Insert PCB inserts it into the design being worked +/// in: the same rows File → Open shows for the board, and the board goes in beside the window with +/// the values chosen, linked to its file as an opened one is. Returns whether the board was held +/// for the answer. +pub fn ask_board_insert(app: &mut SolveApp, path: &str) -> bool { + ask_about(app, path, true, true) +} + +/// Ask for `path`'s import options: an insert, or an open; `board_inserts`: a KiCad board is +/// inserted into the design being worked in rather than opened as a design of its own. +fn ask_about(app: &mut SolveApp, path: &str, insert: bool, board_inserts: bool) -> bool { let Some(target) = formats::import_for_path(path).and_then(|f| f.import.as_ref()).map(|i| i.target) else { return false }; let board = target == ImportTarget::Kicad; if !app.preferences.ask_import_options && !board { @@ -268,8 +284,9 @@ pub fn ask(app: &mut SolveApp, path: &str, insert: bool) -> bool { if values.fields.is_empty() { return false; } - // A board chosen to insert opens as a design of its own (see the module docs). - let insert = insert && !board; + // A board opened, or dropped into a design, opens as a design of its own (see the module + // docs): only Insert PCB puts it into the design being worked in. + let insert = insert && (board_inserts || !board); let tab = insert.then(|| app.docs.active_tab()); enqueue(app, Prompt::Options(Ask { path: path.into(), insert, values, tab })); true @@ -283,6 +300,9 @@ fn request(app: &SolveApp, ask: &Ask) -> file_load::Request { let mut request = file_load::Request::new(&ask.path, kind); request.options = ask.values.params_now(&ask.path, &file_load::preferred_options(app, &ask.path)); request.tab = ask.tab; + // Insert PCB takes a board as it takes a board's fabrication files: one command, with the + // picked file as its `set`. + request.pcb = ask.insert && ask.values.format == "kicad"; request } diff --git a/crates/ui-egui/src/lib.rs b/crates/ui-egui/src/lib.rs index 5780268805d..db9bad0ea4a 100644 --- a/crates/ui-egui/src/lib.rs +++ b/crates/ui-egui/src/lib.rs @@ -270,7 +270,7 @@ pub(crate) mod frame_watch; mod history_off_thread_tests; mod move_preview; pub use file_load::running_summary as file_load_running_summary; -pub use file_picker::{FilePickerFuture, FilesPickerFuture}; +pub use file_picker::{FilePickerFuture, FilesPickerFuture, OpenFilter}; #[cfg(test)] mod blend_arrow_tests; #[cfg(test)] @@ -713,9 +713,11 @@ pub struct Services { /// Open a dialog for several folders at once (the agent chat's files). `None`: one, with /// `pick_folder`. pub pick_folders: Option FilesPickerFuture>>, - /// Ask for a file to open. The extensions are the file type the command reads, offered as - /// the picker's first filter (`&[]`: designs, CAD files and meshes, #1801). - pub pick_open: Option FilePickerFuture>>, + /// Ask for a file to open. The groups are what the picker offers first, the first one being + /// what it opens on, each with the label it shows: the command's own type ([`OpenFilter::unnamed`]), + /// or the kinds of file a person picks one of (Insert PCB), and `&[]` for designs, CAD files and + /// meshes (#1801). The host adds the kinds of file every Open offers after them. + pub pick_open: Option FilePickerFuture>>, /// Open a dialog asking for a program (a slicer); `None` when the host has no such dialog. pub pick_program: Option FilePickerFuture>>, pub pick_save: Option FilePickerFuture>>, @@ -3536,11 +3538,33 @@ impl SolveApp { return; } if id == "file.insert_gerber" { - // Like Insert STEP: the board's zip, or any file in its folder, is picked and the - // board goes in beside the window, each file's layer found from what it says. - // On the web only the chosen file is uploaded, not its folder: there the board's zip. - let extensions: &[&str] = if cfg!(target_arch = "wasm32") { &["zip"] } else { &solidcraft_engine::io::BOARD_EXTENSIONS }; - self.pick_open_for(extensions, |app, path| { + // Every board goes in here, whatever it comes as: a KiCad board with its own options, or + // a board's fabrication files as one (a zip, a folder, or any file in its folder, each + // file's layer found from what it says). The picker offers them all first, as any board + // file does, then each kind on its own for someone narrowing it down (#26309). On the web + // only the chosen file is uploaded, not its folder. + let fabrication: &[&str] = if cfg!(target_arch = "wasm32") { &["zip"] } else { &solidcraft_engine::io::BOARD_EXTENSIONS }; + // On the web the picked file is the only one uploaded, and a project file stands for a + // board beside it: there a board is the board itself. + let kicad: Vec<&str> = solidcraft_engine::io::formats::find("kicad") + .map(|format| format.extensions) + .unwrap_or_default() + .iter() + .copied() + .filter(|extension| !(cfg!(target_arch = "wasm32") && *extension == "kicad_pro")) + .collect(); + let mut any = fabrication.to_vec(); + for extension in &kicad { + if !any.contains(extension) { + any.push(extension); + } + } + let filters = [ + OpenFilter::named(tr!("ui.insert_pcb.filter_any"), &any), + OpenFilter::named(tr!("ui.insert_pcb.filter_fabrication"), fabrication), + OpenFilter::named(tr!("ui.insert_pcb.filter_kicad"), &kicad), + ]; + self.pick_open_filters(&filters, |app, path| { if let Some(path) = path { file_load::insert_board(app, &path, cfg!(target_arch = "wasm32")); } diff --git a/crates/ui-egui/src/linked_source.rs b/crates/ui-egui/src/linked_source.rs index 66becff42ec..eeb258e4032 100644 --- a/crates/ui-egui/src/linked_source.rs +++ b/crates/ui-egui/src/linked_source.rs @@ -558,8 +558,8 @@ mod tests { } fn answer(app: &mut SolveApp, path: Option) { - app.services.pick_open = Some(Box::new(move |extensions| { - assert_eq!(extensions, &["sc", "solidcraft", "json"], "a design of any release, or a plain JSON design"); + app.services.pick_open = Some(Box::new(move |groups| { + assert_eq!(crate::OpenFilter::every(groups), ["sc", "solidcraft", "json"], "a design of any release, or a plain JSON design"); let result = path.clone(); Box::pin(async move { result }) })); diff --git a/crates/ui-egui/src/plugin_menu_tests.rs b/crates/ui-egui/src/plugin_menu_tests.rs index 35ad8294336..4d51cac347c 100644 --- a/crates/ui-egui/src/plugin_menu_tests.rs +++ b/crates/ui-egui/src/plugin_menu_tests.rs @@ -4648,8 +4648,8 @@ fn importer_menu_picks_first_only_when_its_manifest_says_file_first_and_cancel_o let mut h = crate::scenario::Harness::new(); h.app.plugin_menu.listed = vec![listed("sample", vec![file_first_entry()])]; h.app.plugin_menu.loaded = true; - h.app.services.pick_open = Some(Box::new(|extensions| { - assert_eq!(extensions, &["smp"]); + h.app.services.pick_open = Some(Box::new(|groups| { + assert_eq!(crate::OpenFilter::every(groups), ["smp"]); Box::pin(std::future::ready(None)) })); open_entry(&mut h.app, 0, 0); diff --git a/crates/ui-egui/src/prefs.rs b/crates/ui-egui/src/prefs.rs index 6d73520e615..9472274bbba 100644 --- a/crates/ui-egui/src/prefs.rs +++ b/crates/ui-egui/src/prefs.rs @@ -14287,7 +14287,7 @@ mod tests { let mut h = crate::scenario::Harness::new(); let answer = std::rc::Rc::new(std::cell::RefCell::new(None::>)); let response = answer.clone(); - h.app.services.pick_open = Some(Box::new(move |_: &[&str]| { + h.app.services.pick_open = Some(Box::new(move |_| { let response = response.clone(); Box::pin(std::future::poll_fn(move |_| response.borrow_mut().take().map_or(std::task::Poll::Pending, std::task::Poll::Ready))) }));