From feb0e1dd5186286e32390399949b76dc408109bf Mon Sep 17 00:00:00 2001 From: Dandaedre Date: Sat, 14 Nov 2026 21:03:25 +0100 Subject: [PATCH] Import dropped geometry files through mapping review --- crates/midra-layout/src/gui.rs | 235 ++++++++++++++++++++++- docs/interfaces/midra-layout-exchange.md | 10 +- docs/midra-layout/README.md | 4 +- docs/midra-layout/changelog.md | 2 + docs/midra-layout/guide/files.md | 9 + 5 files changed, 246 insertions(+), 14 deletions(-) diff --git a/crates/midra-layout/src/gui.rs b/crates/midra-layout/src/gui.rs index ec4904c..79b5dbc 100644 --- a/crates/midra-layout/src/gui.rs +++ b/crates/midra-layout/src/gui.rs @@ -649,23 +649,82 @@ impl Editor { } } fn read_geometry(path: &std::path::Path, p: &mut Paste) { + Self::read_geometry_files( + vec![egui::DroppedFile { + path: Some(path.to_path_buf()), + ..Default::default() + }], + p, + ); + } + fn geometry_drop(file: &egui::DroppedFile) -> bool { + let path = file + .path + .as_deref() + .unwrap_or_else(|| std::path::Path::new(&file.name)); + path.extension() + .and_then(|s| s.to_str()) + .is_some_and(|extension| { + let extension = extension.to_ascii_lowercase(); + midra_layout::interchange::extensions().contains(&extension.as_str()) + || matches!(extension.as_str(), "pptx" | "fig" | "ai") + }) + } + fn read_geometry_files(files: Vec, p: &mut Paste) { use std::io::Read; - let path = path.to_path_buf(); let (tx, rx) = std::sync::mpsc::channel(); p.import_job = Some(rx); p.pages.clear(); p.shapes.clear(); + p.mapping.clear(); + p.ignored.clear(); p.text.clear(); p.error.clear(); std::thread::spawn(move || { let result = (|| { - let mut bytes = Vec::new(); - std::fs::File::open(&path) - .map_err(|e| format!("Cannot open geometry file: {e}"))? - .take(midra_layout::exchange::MAX_EXCHANGE_BYTES as u64 + 1) - .read_to_end(&mut bytes) - .map_err(|e| format!("Cannot read geometry file: {e}"))?; - midra_layout::interchange::import(&bytes, &path.to_string_lossy()) + let mut pages = Vec::new(); + let mut remaining = midra_layout::exchange::MAX_EXCHANGE_BYTES; + let multiple = files.len() > 1; + for file in files { + let name = file + .path + .as_ref() + .map(|p| p.to_string_lossy().into_owned()) + .unwrap_or(file.name); + let bytes = if let Some(bytes) = file.bytes { + if bytes.len() > remaining { + return Err("Import exceeds 16 MiB across dropped files.".into()); + } + bytes.to_vec() + } else if let Some(path) = file.path { + let mut bytes = Vec::new(); + std::fs::File::open(&path) + .map_err(|e| format!("Cannot open geometry file {name}: {e}"))? + .take(remaining as u64 + 1) + .read_to_end(&mut bytes) + .map_err(|e| format!("Cannot read geometry file {name}: {e}"))?; + bytes + } else { + return Err("The dropped geometry file has no path or data.".into()); + }; + if bytes.len() > remaining { + return Err("Import exceeds 16 MiB across dropped files.".into()); + } + remaining -= bytes.len(); + let mut imported = midra_layout::interchange::import(&bytes, &name) + .map_err(|e| format!("{name}: {e}"))?; + if multiple { + let label = std::path::Path::new(&name) + .file_name() + .unwrap_or_default() + .to_string_lossy(); + for page in &mut imported { + page.name = format!("{label} · {}", page.name); + } + } + pages.extend(imported); + } + Ok(pages) })(); let _ = tx.send(result); }); @@ -938,7 +997,7 @@ impl Editor { if p.import_job.is_some() { ui.spinner(); ui.label("Reading document…"); } if p.pages.len() > 1 { let previous = p.page_index; - egui::ComboBox::from_label("Page / frame / slide").selected_text(&p.pages[p.page_index].name).show_ui(ui, |ui| { + egui::ComboBox::from_label("File / page / frame / slide").selected_text(&p.pages[p.page_index].name).show_ui(ui, |ui| { for (index, page) in p.pages.iter().enumerate() { ui.selectable_value(&mut p.page_index, index, &page.name); } }); if previous != p.page_index { p.set_document(p.pages[p.page_index].document.clone()); } @@ -3316,8 +3375,19 @@ impl Editor { let palette = theme::palette(ctx); let dropped = ctx.input(|i| i.raw.dropped_files.clone()); if self.files.loading.is_none() { + let mut geometry = Vec::new(); for file in &dropped { - self.load_reference(ctx, file); + if Self::geometry_drop(file) { + geometry.push(file.clone()); + } else { + self.load_reference(ctx, file); + } + } + if !geometry.is_empty() { + if self.paste.is_none() { + self.open_paste(String::new()); + } + Self::read_geometry_files(geometry, self.paste.as_mut().unwrap()); } } if !blocked { @@ -6118,6 +6188,151 @@ mod tests { } } } + #[test] + fn dropped_geometry_files_use_the_regular_review_without_changing_layers() { + use midra_layout::interchange::Codec; + let ctx = egui::Context::default(); + let mut app = Editor::default(); + let before = app.layout.layers().clone(); + let project = midra_layout::project::Project::from_layout(&app.layout); + let ids: Vec<_> = project.layers.iter().map(|l| l.id).collect(); + let dir = tempfile::tempdir().unwrap(); + for codec in Codec::available() + .into_iter() + .filter(|c| *c != Codec::Illustrator) + { + let bytes = + midra_layout::interchange::export(&project, &ids, codec, Default::default()) + .unwrap(); + let name = format!("example.{}", codec.extension().to_ascii_uppercase()); + for path_backed in [false, true] { + let file = if path_backed { + let path = dir.path().join(&name); + std::fs::write(&path, &bytes).unwrap(); + egui::DroppedFile { + path: Some(path), + ..Default::default() + } + } else { + egui::DroppedFile { + name: name.clone(), + bytes: Some(bytes.clone().into()), + ..Default::default() + } + }; + let _ = ctx.run( + egui::RawInput { + screen_rect: Some(Rect::from_min_size( + Pos2::ZERO, + Vec2::new(1440.0, 940.0), + )), + dropped_files: vec![file], + ..Default::default() + }, + |ctx| app.ui(ctx), + ); + let deadline = std::time::Instant::now() + std::time::Duration::from_secs(5); + while app.paste.as_ref().unwrap().import_job.is_some() + && std::time::Instant::now() < deadline + { + std::thread::sleep(std::time::Duration::from_millis(1)); + frame(&mut app, &ctx, vec![]); + } + let paste = app.paste.as_ref().unwrap(); + assert!(paste.import_job.is_none()); + assert!(paste.error.is_empty(), "{codec:?}: {}", paste.error); + assert_eq!( + paste.shapes.iter().filter(|s| !s.background_only).count(), + 2 + ); + assert_eq!(app.layout.layers(), &before); + assert!(app.references.is_empty()); + app.paste = None; + } + } + for extension in ["pptx", "fig", "ai", "xml"] { + assert!(Editor::geometry_drop(&egui::DroppedFile { + name: format!("test.{extension}"), + ..Default::default() + })); + } + assert!(!Editor::geometry_drop(&egui::DroppedFile { + name: "picture.png".into(), + ..Default::default() + })); + } + + #[test] + fn geometry_drop_batches_and_failures_keep_imports_atomic() { + let mut app = Editor::default(); + let before = app.layout.layers().clone(); + let project = midra_layout::project::Project::from_layout(&app.layout); + let ids: Vec<_> = project.layers.iter().map(|l| l.id).collect(); + let bytes = midra_layout::interchange::export( + &project, + &ids, + midra_layout::interchange::Codec::Svg, + Default::default(), + ) + .unwrap(); + let file = |name: &str, bytes: Vec| egui::DroppedFile { + name: name.into(), + bytes: Some(bytes.into()), + ..Default::default() + }; + app.open_paste(String::new()); + let paste = app.paste.as_mut().unwrap(); + Editor::read_geometry_files( + vec![ + file("first.svg", bytes.clone()), + file("second.svg", bytes.clone()), + ], + paste, + ); + let pages = paste + .import_job + .take() + .unwrap() + .recv_timeout(std::time::Duration::from_secs(5)) + .unwrap() + .unwrap(); + assert_eq!(pages.len(), 2); + assert!(pages[0].name.starts_with("first.svg")); + assert!(pages[1].name.starts_with("second.svg")); + Editor::read_geometry_files( + vec![file("good.svg", bytes), file("bad.svg", b"broken".to_vec())], + paste, + ); + let error = paste + .import_job + .take() + .unwrap() + .recv_timeout(std::time::Duration::from_secs(5)) + .unwrap() + .unwrap_err(); + assert!(error.contains("bad.svg")); + assert!(paste.shapes.is_empty()); + assert!(paste.mapping.is_empty()); + Editor::read_geometry_files( + vec![file( + "huge.svg", + vec![0; midra_layout::exchange::MAX_EXCHANGE_BYTES + 1], + )], + paste, + ); + assert!( + paste + .import_job + .take() + .unwrap() + .recv_timeout(std::time::Duration::from_secs(5)) + .unwrap() + .unwrap_err() + .contains("16 MiB") + ); + assert_eq!(app.layout.layers(), &before); + } + #[test] fn dropped_reference_warns_without_editing_layers_and_failed_replace_keeps_image() { let mut app = Editor::default(); diff --git a/docs/interfaces/midra-layout-exchange.md b/docs/interfaces/midra-layout-exchange.md index 6e3ff91..bbe21d2 100644 --- a/docs/interfaces/midra-layout-exchange.md +++ b/docs/interfaces/midra-layout-exchange.md @@ -292,8 +292,14 @@ background are allowed. No imported image is decoded or downloaded by the geometry importer. Export reference decoding retains the existing 8192-pixel per-side/256 MiB decoder bounds. Oversized exports fail before writing a file. -Use **Import → Geometry file…**, or paste supported text, then review and map shapes to -editor layers. Destination count need not match current selection. Import with +Use **Import → Geometry file…**, drop supported files, or paste supported text, +then review and map shapes to editor layers. Drops route case-insensitive registered +extensions (including draw.io XML and vendor formats) through the same asynchronous +byte importer as the picker; native-codec build restrictions still apply. Path-backed +and in-memory file drops are supported. Raster images retain reference-image behavior. +Several geometry files become named choices in the file/page/frame/slide selector, +with a combined 16 MiB input limit. Parsing is atomic across the geometry batch; +errors report the failed filename, and no geometry is applied before mapping confirmation. Destination count need not match current selection. Import with size and position enabled restores the rounded geometry in one Undo step. Output screen resolution is not imported. Mapped names, sources and Midra links stay with the destination layers. File replacement retains the existing explicit overwrite diff --git a/docs/midra-layout/README.md b/docs/midra-layout/README.md index b1b36ca..c0c4f21 100644 --- a/docs/midra-layout/README.md +++ b/docs/midra-layout/README.md @@ -65,8 +65,8 @@ See [formats and crop](guide/formats-and-crop.md) and - **Save your work:** use **Project → Save project…** for a `.midra.json` file that retains the full editor project. -- **Work with another application:** use **Import → Geometry file…** or - **Project → Export → Export layers…**. The [starter-file catalog](../templates/midra-layout/README.md) +- **Work with another application:** drop a supported geometry file into the window, + use **Import → Geometry file…**, or **Project → Export → Export layers…**. The [starter-file catalog](../templates/midra-layout/README.md) has matching Full HD and 4K files in SVG, draw.io, geometry JSON, CSV, DXF, HTML, PPTX, Figma FIG and Illustrator AI. It also lists format dependencies. - **Use an Eikos 4K:** connect, review layer mappings, then explicitly load or diff --git a/docs/midra-layout/changelog.md b/docs/midra-layout/changelog.md index b17620c..c53499d 100644 --- a/docs/midra-layout/changelog.md +++ b/docs/midra-layout/changelog.md @@ -4,6 +4,8 @@ ## Unreleased +- Route supported geometry file drops through the regular asynchronous import/mapping review, including SVG/draw.io and native formats when available. Keep raster drops as references; support path/data drops and multiple documents through the file/page chooser, with a combined 16 MiB limit and atomic failure. Regression tests cover codecs, case-insensitive names, batches and invalid/oversized inputs. + - Add an mdBook manual built from the existing guides, with local assets and downloads. Jenkins publishes successful main builds under `/mnt/books/manuals/`; staging, link validation and scoped publication have regression coverage. - Replace the long overview with a visual quick start, move detailed workflows into topic guides, and centralize all nine starter-file formats in one catalog. Add real application screenshots with reproducible capture notes; retain the existing template files and validation contracts. diff --git a/docs/midra-layout/guide/files.md b/docs/midra-layout/guide/files.md index 58f25f9..dd5d992 100644 --- a/docs/midra-layout/guide/files.md +++ b/docs/midra-layout/guide/files.md @@ -4,6 +4,15 @@ ## Paste layer values and import geometry +Drop SVG, draw.io/XML, geometry JSON/CSV, DXF, HTML, PPTX, FIG or AI files into +the window to open the same geometry review as **Import → Geometry file…**. +Native codecs still require their normal build options/dependencies. Filename +extensions are case-insensitive; PNG/JPEG/BMP drops remain reference images. +Multiple geometry files appear in the **File / page / frame / slide** chooser; +choose one document/page to map at a time. Reading runs in the background, and +nothing changes in the layout until Apply. The entire geometry drop is limited +to 16 MiB; a failed document leaves the batch unapplied and reports its filename. + 1. Choose destinations using **Choose destination layers…** in the Import menu or review window. Selecting them on the canvas or right-hand list also works (Shift-click for multiple layers).