diff --git a/crates/ui-egui/src/panels/links.rs b/crates/ui-egui/src/panels/links.rs index 3f5900d5bb..881129e87f 100644 --- a/crates/ui-egui/src/panels/links.rs +++ b/crates/ui-egui/src/panels/links.rs @@ -640,6 +640,12 @@ impl<'a> Facts<'a> { ids(&self.rows, |r| r["linked"] == true) } + /// The linked rows Embed and Break Link can act on: images placed from DCS files stay linked, + /// as `links.embed` refuses them. + fn embeddable(&self) -> Vec { + ids(&self.rows, |r| r["linked"] == true && r["format"] != "DCS") + } + fn modified(&self) -> Vec { ids(&self.rows, is_modified) } @@ -674,7 +680,7 @@ fn can(app: &VectorcraftApp, act: Act, f: &Facts, row: Option<&Value>) -> bool { Act::GoTo => row.map_or(f.rows.len() == 1, |r| in_canvas(app, r)), Act::Update => !f.modified().is_empty(), Act::Edit | Act::Reveal => editable, - Act::Embed | Act::BreakLink => !f.linked().is_empty(), + Act::Embed | Act::BreakLink => !f.embeddable().is_empty(), Act::Unembed => can_unembed(app, f.embedded().len()), Act::Placement | Act::CopyInfo => any, } @@ -706,8 +712,8 @@ fn act(app: &mut VectorcraftApp, act: Act, target: Option) { } Act::Edit => crate::menus::invoke(app, "links.editOriginal", file_arg()), Act::Reveal => crate::menus::invoke(app, "links.reveal", file_arg()), - Act::Embed => embed_images(app, f.linked()), - Act::BreakLink => break_link(app, f.linked()), + Act::Embed => embed_images(app, f.embeddable()), + Act::BreakLink => break_link(app, f.embeddable()), Act::Unembed => match &f.embedded()[..] { [] => {} [r] => { @@ -911,7 +917,7 @@ fn break_link(app: &mut VectorcraftApp, ids: Vec) { } /// Embed images `ids` (`links.embed`). -fn embed_images(app: &mut VectorcraftApp, ids: Vec) { +pub(crate) fn embed_images(app: &mut VectorcraftApp, ids: Vec) { let r = app.run("links.embed", json!({ "ids": ids })); report(app, r, |v| { let missing = v["missing"].as_array().map_or(0, Vec::len); diff --git a/crates/ui-egui/src/panels/properties.rs b/crates/ui-egui/src/panels/properties.rs index 201e2f909f..4fcefa0be3 100644 --- a/crates/ui-egui/src/panels/properties.rs +++ b/crates/ui-egui/src/panels/properties.rs @@ -156,7 +156,16 @@ fn body(app: &mut VectorcraftApp, ui: &mut Ui, first: Option<&Node>, n_sel: usiz } fn quick_action_buttons(app: &mut VectorcraftApp, ui: &mut Ui) { + // Several images and nothing else: Embed and Unembed… for them, first. + let images = crate::place::SeveralImages::selected(app); Grid::new(&HALVES).show(ui, |ui, _| { + if let Some(images) = &images { + for action in images.shown(app) { + if Button::new(action.label()).show(ui).clicked() { + images.run(app, action); + } + } + } for action in quick_actions(app) { Button::command(action.command).label(action.label).show(ui); } diff --git a/crates/ui-egui/src/panels/properties/object_sections.rs b/crates/ui-egui/src/panels/properties/object_sections.rs index 977c21324e..844305a187 100644 --- a/crates/ui-egui/src/panels/properties/object_sections.rs +++ b/crates/ui-egui/src/panels/properties/object_sections.rs @@ -32,7 +32,7 @@ pub(super) fn image_section(app: &mut VectorcraftApp, ui: &mut Ui) { Text::new(details.clone()).shade(Shade::Muted).show(ui); Grid::new(&HALVES).show(ui, |ui, _| { // PLAN: assumed `crate::place::LinkAction::{shown(linked) -> &'static [LinkAction], label(self), run(self, app, id, &name)}` (files-w14, fl.A18) - for action in crate::place::LinkAction::shown(linked) { + for action in crate::place::LinkAction::shown(linked, crate::place::is_dcs_image(app, id)) { if Button::new(action.label()).sizing(Sizing::FillWidth).show(ui).clicked() { action.run(app, id, &name); } diff --git a/crates/ui-egui/src/panels/tests_links.rs b/crates/ui-egui/src/panels/tests_links.rs index 15cc220638..e1a60e1c45 100644 --- a/crates/ui-egui/src/panels/tests_links.rs +++ b/crates/ui-egui/src/panels/tests_links.rs @@ -708,6 +708,174 @@ fn replace_image_with_a_desktop_path_remains_linked() { assert_eq!(image.link.as_ref().unwrap().path, path); } +/// The Properties panel and the Control bar, each drawn over `app` in a room wide enough for its +/// image controls (a narrow Control bar drops its lower ranks). +fn image_surfaces(app: impl Fn() -> VectorcraftApp) -> [(&'static str, Panel); 2] { + let mut bar = Panel::new(app(), crate::chrome::control_bar); + bar.room(vec2(2200.0, 200.0)).frame(); + [("Properties", Panel::new(app(), super::properties::show)), ("Control bar", bar)] +} + +/// Whether image `id` is embedded. +fn is_embedded(app: &mut VectorcraftApp, id: u64) -> bool { + app.run("links.info", json!({"id": id})).unwrap()["status"] == "embedded" +} + +/// With several linked images selected, the Properties panel's Quick Actions and the Control bar +/// offer Embed, which embeds every one of them in one undo step. +#[test] +fn embed_takes_several_selected_linked_images() { + let dir = Folder::new("embed-several"); + let placed = Cell::new(0); + let app = || { + let mut app = VectorcraftApp::new(Session::new(), Default::default()); + app.run("file.new", json!({"width": 400, "height": 300})).unwrap(); + for i in 0..2 { + placed.set(placed.get() + 1); + let path = dir.file(&format!("linked-{}.png", placed.get()), &png(30, 20)); + app.run("file.place", json!({"path": path, "at": [50 + 100 * i, 50]})).unwrap(); + } + app.run("select.all", json!({})).unwrap(); + app + }; + for (surface, mut h) in image_surfaces(app) { + let ids = selected(&h.app()); + assert_eq!(ids.len(), 2, "{surface}"); + assert!(!h.shows("Unembed…"), "{surface}: no image is embedded"); + let undo = h.app().session.doc().unwrap().history.undo.len(); + h.click("Embed"); + let mut app = h.app(); + assert!(ids.iter().all(|id| is_embedded(&mut app, *id)), "{surface}: every selected image is embedded"); + assert_eq!(app.session.doc().unwrap().history.undo.len(), undo + 1, "{surface}: in one undo step"); + app.run("edit.undo", json!({})).unwrap(); + assert!(ids.iter().all(|id| !is_embedded(&mut app, *id)), "{surface}: one undo links them again"); + } +} + +/// With a linked and an embedded image selected, both surfaces offer Embed for the linked one and +/// Unembed… for the embedded one. +#[test] +fn several_mixed_images_offer_embed_and_unembed() { + let dir = Folder::new("mixed-several"); + let app = || { + let (mut app, linked, embedded) = app(&dir); + app.run("select.set", json!({"ids": [linked, embedded]})).unwrap(); + app + }; + for (surface, h) in image_surfaces(app) { + assert!(h.shows("Embed") && h.shows("Unembed…"), "{surface}"); + } +} + +/// A single-file DCS 2.0 file with one Cyan plate, a 2 × 2 grayscale image on a 20 × 10 pt page, +/// made from scratch as http://www.telegraphics.net/doc/DCS.txt describes it; without a clipping +/// path it places as a plain linked image. +fn dcs_file() -> Vec { + let plate = "%!PS-Adobe-3.0 EPSF-3.0\n%%BoundingBox: 0 0 20 10\n%%EndComments\n20 10 scale\n2 2 8 [2 0 0 -2 0 2] <0000ffff> image\nshowpage\n%%Trailer\n%%EOF\n"; + let header = |at: usize| { + format!( + "%!PS-Adobe-3.0 EPSF-3.0\n%%BoundingBox: 0 0 20 10\n%%PlateFile: (Cyan) EPS #{at:010} {:010}\n%%EndComments\n20 10 scale 2 2 8 [2 0 0 -2 0 2] <808080808080808080808080> false 3 colorimage showpage\n%%EOF\n", + plate.len() + ) + }; + let mut out = header(header(0).len()).into_bytes(); + out.extend(plate.as_bytes()); + out +} + +/// Images placed from DCS files stay linked (`links.embed` refuses them): with one selected, +/// neither surface offers Embed; with a DCS image and a linked image selected, Embed embeds the +/// linked one and leaves the DCS image linked; with a DCS image and an embedded one, only +/// Unembed… is offered. +#[test] +fn several_images_leave_dcs_images_out_of_embed() { + let dir = Folder::new("dcs-several"); + let placed = Cell::new(0); + let setup = |with: &'static str| { + let mut app = VectorcraftApp::new(Session::new(), Default::default()); + app.run("file.new", json!({"width": 400, "height": 300})).unwrap(); + placed.set(placed.get() + 1); + let dcs = dir.file(&format!("plates-{}.eps", placed.get()), &dcs_file()); + let r = app.run("file.place", json!({"path": dcs, "at": [50, 50]})).unwrap(); + let dcs = r["ids"][0].as_u64().unwrap(); + let png = dir.file(&format!("other-{}.png", placed.get()), &png(30, 20)); + let other = match with { + "linked" => Some(app.run("file.place", json!({"path": png, "at": [200, 50]})).unwrap()["ids"][0].as_u64().unwrap()), + "embedded" => Some(app.run("file.place", json!({"path": png, "at": [200, 50], "link": false})).unwrap()["ids"][0].as_u64().unwrap()), + _ => None, + }; + let ids: Vec = [Some(dcs), other].into_iter().flatten().collect(); + app.run("select.set", json!({"ids": ids})).unwrap(); + (app, dcs, other) + }; + let alone = || setup("alone").0; + { + let app = alone(); + let st = app.session.active().unwrap(); + let id = st.selection.objects[0]; + assert!(matches!(st.doc.node(id).unwrap().kind, vectorcraft_doc::NodeKind::Image(_)), "placed as one image"); + } + for (surface, h) in image_surfaces(alone) { + assert!(h.shows("Edit Original") && !h.shows("Embed"), "{surface}: one DCS image"); + } + let ids = RefCell::new(vec![]); + let with_linked = || { + let (app, dcs, other) = setup("linked"); + ids.borrow_mut().push((dcs, other.unwrap())); + app + }; + // Each surface draws its own app, made in this order. + for (n, (surface, mut h)) in image_surfaces(with_linked).into_iter().enumerate() { + let (dcs, linked) = ids.borrow()[n]; + assert_eq!(selected(&h.app()).len(), 2, "{surface}"); + h.click("Embed"); + let mut app = h.app(); + assert!(is_embedded(&mut app, linked), "{surface}: the linked image is embedded"); + assert!(!is_embedded(&mut app, dcs), "{surface}: the DCS image stays linked"); + } + for (surface, h) in image_surfaces(|| setup("embedded").0) { + assert!(h.shows("Unembed…") && !h.shows("Embed"), "{surface}: a DCS image and an embedded one"); + } +} + +/// The Links panel's Embed and Break Link leave images placed from DCS files out: with a DCS image +/// and a linked image selected, each embeds the linked one and leaves the DCS image linked; with +/// only the DCS image selected, its row menu's Embed Image is unavailable. +#[test] +fn links_panel_leaves_dcs_images_out_of_embed() { + let dir = Folder::new("dcs-links-panel"); + let placed = Cell::new(0); + let setup = || { + let mut app = VectorcraftApp::new(Session::new(), Default::default()); + app.run("file.new", json!({"width": 400, "height": 300})).unwrap(); + placed.set(placed.get() + 1); + let dcs = dir.file(&format!("plates-{}.eps", placed.get()), &dcs_file()); + let dcs = app.run("file.place", json!({"path": dcs, "at": [50, 50]})).unwrap()["ids"][0].as_u64().unwrap(); + let png = dir.file(&format!("other-{}.png", placed.get()), &png(30, 20)); + let linked = app.run("file.place", json!({"path": png, "at": [200, 50]})).unwrap()["ids"][0].as_u64().unwrap(); + app.run("select.set", json!({"ids": [dcs, linked]})).unwrap(); + (app, dcs, linked) + }; + for (how, act) in [("Embed", "ui.links.embed"), ("Break Link", "")] { + let (app, dcs, linked) = setup(); + let mut h = Panel::new(app, super::links::show); + if act.is_empty() { + h.click(how); + } else { + super::links::run(&mut h.app(), act, &json!({})).expect("a panel command").unwrap(); + h.frame(); + } + let mut app = h.app(); + assert!(is_embedded(&mut app, linked), "{how}: the linked image is embedded"); + assert!(!is_embedded(&mut app, dcs), "{how}: the DCS image stays linked"); + } + let (mut app, dcs, _) = setup(); + app.run("select.set", json!({"ids": [dcs]})).unwrap(); + let mut h = Panel::new(app, super::links::show); + h.secondary_click(&format!("plates-{}.eps", placed.get())); + assert!(!h.menu_item_enabled("Embed Image"), "one DCS image"); +} + /// Unembed… acts on several selected embedded images: it asks for one folder, writes a file for /// each image there and links each one to its file; with no folder picked, nothing changes. #[test] diff --git a/crates/ui-egui/src/place.rs b/crates/ui-egui/src/place.rs index cf03fc108d..97d17b6810 100644 --- a/crates/ui-egui/src/place.rs +++ b/crates/ui-egui/src/place.rs @@ -1108,9 +1108,14 @@ pub(crate) enum LinkAction { } impl LinkAction { - /// The actions that apply to an image, `linked` or embedded. - pub(crate) fn shown(linked: bool) -> &'static [LinkAction] { - if linked { &[LinkAction::Embed, LinkAction::EditOriginal] } else { &[LinkAction::Unembed] } + /// The actions that apply to an image, `linked` or embedded. An image placed from a DCS file + /// (`dcs`) stays linked, as `links.embed` refuses it, so it has no Embed. + pub(crate) fn shown(linked: bool, dcs: bool) -> &'static [LinkAction] { + match (linked, dcs) { + (true, false) => &[LinkAction::Embed, LinkAction::EditOriginal], + (true, true) => &[LinkAction::EditOriginal], + (false, _) => &[LinkAction::Unembed], + } } /// The action's label in the interface language. @@ -1125,22 +1130,106 @@ impl LinkAction { /// Runs the action for image `id`, named `name`. pub(crate) fn run(self, app: &mut VectorcraftApp, id: u64, name: &str) { match self { - LinkAction::Embed => { - app.run("links.embed", json!({ "ids": [id] })).ok(); - } + LinkAction::Embed => crate::panels::links::embed_images(app, vec![id]), LinkAction::EditOriginal => crate::menus::invoke(app, "links.editOriginal", json!({ "id": id })), LinkAction::Unembed => crate::panels::links::unembed(app, id, name), } } } +/// Is image `id` of the active document placed from a DCS file (its pixels hold plates), which +/// `links.embed` refuses? +pub(crate) fn is_dcs_image(app: &VectorcraftApp, id: u64) -> bool { + let Some(st) = app.session.active() else { return false }; + let Some(NodeKind::Image(im)) = st.doc.node(vectorcraft_doc::NodeId(id)).map(|n| &n.kind) else { return false }; + im.link.is_some() && st.doc.images.get(&im.key).is_some_and(vectorcraft_doc::ImageBlob::is_separated) +} + +/// Several selected objects that are all images: the ids of the linked ones that can be embedded +/// and of the embedded ones, in selection order. Images placed from DCS files are in neither. +#[derive(Clone, Debug, Default, PartialEq, Eq)] +pub(crate) struct SeveralImages { + /// The linked images, except those placed from DCS files. + pub(crate) linked: Vec, + /// The embedded images. + pub(crate) embedded: Vec, +} + +impl SeveralImages { + /// The selection as [`SeveralImages`], when two or more objects are selected and each is an + /// image. + pub(crate) fn selected(app: &VectorcraftApp) -> Option { + let st = app.session.active()?; + if st.selection.objects.len() < 2 { + return None; + } + let mut out = SeveralImages::default(); + for id in &st.selection.objects { + let NodeKind::Image(im) = &st.doc.node(*id)?.kind else { return None }; + match &im.link { + None => out.embedded.push(id.0), + Some(_) if st.doc.images.get(&im.key).is_some_and(vectorcraft_doc::ImageBlob::is_separated) => {} + Some(_) => out.linked.push(id.0), + } + } + Some(out) + } + + /// The actions that apply to these images: Embed while one of them is linked and not placed + /// from a DCS file, and Unembed… while one is embedded and they can be written out. Edit + /// Original opens one file, so the + /// surfaces offer it for one image only. + pub(crate) fn shown(&self, app: &VectorcraftApp) -> Vec { + let mut shown = vec![]; + if !self.linked.is_empty() { + shown.push(LinkAction::Embed); + } + if crate::panels::links::can_unembed(app, self.embedded.len()) { + shown.push(LinkAction::Unembed); + } + shown + } + + /// Runs `action` on these images: Embed embeds every linked one, and Unembed… writes every + /// embedded one out, each in one undo step. + pub(crate) fn run(&self, app: &mut VectorcraftApp, action: LinkAction) { + match (action, &self.embedded[..]) { + (LinkAction::Embed, _) => crate::panels::links::embed_images(app, self.linked.clone()), + (LinkAction::EditOriginal, _) | (LinkAction::Unembed, []) => {} + (LinkAction::Unembed, [one]) => { + let info = app.session.execute("image.info", &json!({ "id": one })).unwrap_or_default(); + let (name, _) = image_summary(&info); + crate::panels::links::unembed(app, *one, &name); + } + (LinkAction::Unembed, ids) => crate::panels::links::unembed_several(app, ids.to_vec()), + } + } +} + +/// The Control bar for several selected images and nothing else: Embed and Unembed… for them +/// ([`SeveralImages::shown`]), each a ranked row. +fn control_bar_several(app: &mut VectorcraftApp, ui: &mut egui::Ui, images: &SeveralImages) { + for action in images.shown(app) { + Row::new().fit_rank(crate::chrome::rank::GROUP).show(ui, |ui, _| { + if clicked(&Button::new(action.label().to_string()).show(ui)) { + images.run(app, action); + } + }); + } +} + /// The Control bar for the one selected image: its file name, colour mode and effective /// resolution, Embed or Unembed, Edit Original (a linked file), Image Trace, Mask, Crop Image and /// Remove Background, each a ranked row that leaves a shrinking bar whole. While the Crop Image /// tool is in use, the bar shows the file name, colour mode and resolution only, and the tool's -/// cropping options follow them. Whether one image is selected. +/// cropping options follow them. For several selected images and nothing else, the bar shows +/// their Embed and Unembed… ([`SeveralImages`]). Whether one image is selected. pub fn control_bar_details(app: &mut VectorcraftApp, ui: &mut egui::Ui) -> bool { use crate::chrome::rank; + if let Some(images) = SeveralImages::selected(app) { + control_bar_several(app, ui, &images); + return false; + } let Some(i) = selected_image_info(app) else { return false }; let (name, details) = image_summary(i); let (Some(id), linked) = (i["id"].as_u64(), i["linked"] == true) else { return false }; @@ -1176,7 +1265,7 @@ pub fn control_bar_details(app: &mut VectorcraftApp, ui: &mut egui::Ui) -> bool if app.session.tool_id() == vectorcraft_tools::cropimage::ID { return true; } - for action in LinkAction::shown(linked) { + for action in LinkAction::shown(linked, is_dcs_image(app, id)) { let at = if *action == LinkAction::EditOriginal { rank::DETAIL } else { rank::GROUP }; Row::new().fit_rank(at).show(ui, |ui, _| { if clicked(&Button::new(action.label().to_string()).show(ui)) {