diff --git a/ROADMAP.md b/ROADMAP.md index 2dd318199c..c973199e32 100644 --- a/ROADMAP.md +++ b/ROADMAP.md @@ -74,8 +74,8 @@ the icon art). 1. **Alpha blockers** (≈20–25 h): DOCX fidelity corpus, footnote continuation, column balancing, native printing, autosave soak test, first signed release. -2. **Objects** (≈12 h): tight/through (contour) wrap, rotation handles on the canvas, - grouping, z-order polish, track-changes balloons and formatting revisions. +2. **Objects** (≈10 h): tight/through (contour) wrap, rotation handles on the canvas, + moving a multi-selection together, z-order polish, track-changes balloons and formatting revisions. 3. **Draw tab / ink** (≈15 h). 4. **Charts (own renderer) and SmartArt-style diagrams** (≈20 h). 5. **Equation editor** — done: OMML read/write, 2D layout, in-place editing with Word's Equation tab (structures, symbols, built-ins, Unicode/LaTeX input, build-up, Math AutoCorrect, `#` numbers, structure commands). Remaining: line breaking of long display equations, ink equations (≈4 h). @@ -102,7 +102,7 @@ the icon art). | M8 | View | mostly done | | M9 | Mailings | done (first version) | | M10 | File/Backstage | mostly done; native printing missing | -| M11 | Draw + objects | text wrap and text boxes done; ink, rotation, grouping missing | +| M11 | Draw + objects | text wrap, text boxes and grouping done; ink, rotation missing | | M12 | Formats breadth (PDF, ODT, RTF, HTML, MD, TXT) | **done** (first versions) | | M13 | Performance budgets | on track (1.4 ms relayout) | | M14 | 1.0 polish, packaging, signing | pipeline written; waiting on remote and secrets | diff --git a/crates/doc/src/edit.rs b/crates/doc/src/edit.rs index 006b9b6688..54b8de8bd9 100644 --- a/crates/doc/src/edit.rs +++ b/crates/doc/src/edit.rs @@ -76,7 +76,7 @@ fn each_para_mut(b: &mut Block, depth: usize, f: &mut dyn FnMut(&mut Paragraph)) /// Text box story ids of a paragraph's shapes. fn box_ids(p: &Paragraph) -> impl Iterator + '_ { - p.objects.iter().filter_map(|o| if let InlineObject::Shape { story: Some(id), .. } = o { Some(*id) } else { None }) + p.objects.iter().flat_map(InlineObject::text_boxes) } impl Document { @@ -320,11 +320,11 @@ impl Document { each_para_mut(b, 0, &mut |p| { let mut changed = false; for o in p.objects.iter_mut() { - if let InlineObject::Shape { story, .. } = o - && let Some(old) = *story - { - *story = self.adopt_text_box(old, parts, depth, budget); - changed = true; + for story in o.text_box_slots() { + if let Some(old) = *story { + *story = self.adopt_text_box(old, parts, depth, budget); + changed = true; + } } } if changed { diff --git a/crates/doc/src/lib.rs b/crates/doc/src/lib.rs index ada4b6c0d8..d62e3aabf8 100644 --- a/crates/doc/src/lib.rs +++ b/crates/doc/src/lib.rs @@ -587,7 +587,7 @@ impl Document { for path in self.para_paths(story) { let Some(p) = self.para(story, &path) else { continue }; for off in p.object_offsets() { - if matches!(p.object_at(off), Some(InlineObject::Shape { story: Some(id), .. }) if *id == part) { + if p.object_at(off).is_some_and(|o| o.text_boxes().contains(&part)) { return Some(Pos { story, path, off: off + para::OBJ.len_utf8() }); } } @@ -691,9 +691,8 @@ impl Document { /// document order. Headers, footers, comments and stories nothing points at aren't included. pub fn counted_stories(&self) -> Vec { self.reachable(vec![StoryRef::Body], &|o| match o { - InlineObject::Shape { story: Some(id), .. } => Some((*id, &[PartKind::TextBox])), - InlineObject::NoteRef { id, .. } => Some((*id, &[PartKind::Footnote, PartKind::Endnote])), - _ => None, + InlineObject::NoteRef { id, .. } => vec![(*id, &[PartKind::Footnote, PartKind::Endnote][..])], + o => o.text_boxes().into_iter().map(|id| (id, &[PartKind::TextBox][..])).collect(), }) } @@ -707,10 +706,7 @@ impl Document { let roots = std::iter::once(StoryRef::Body) .chain(self.parts.iter().filter(|(_, p)| p.kind != PartKind::TextBox).map(|(id, _)| StoryRef::Part(*id))) .collect(); - let live = self.reachable(roots, &|o| match o { - InlineObject::Shape { story: Some(id), .. } => Some((*id, &[PartKind::TextBox])), - _ => None, - }); + let live = self.reachable(roots, &|o| o.text_boxes().into_iter().map(|id| (id, &[PartKind::TextBox][..])).collect()); let before = self.parts.len(); self.parts.retain(|id, p| p.kind != PartKind::TextBox || live.contains(&StoryRef::Part(*id))); before - self.parts.len() @@ -756,13 +752,16 @@ impl Document { for b in blocks { edit::each_para(b, 0, &mut |p| { for (k, o) in p.objects.iter().enumerate() { - if f(p, k) - && let InlineObject::Shape { story: Some(id), .. } = o - && let Some(part) = self.parts.get(id).filter(|p| p.kind == PartKind::TextBox) - && budget.enter(*id) - { - self.walk_objects(&part.blocks, budget, f); - budget.leave(); + if !f(p, k) { + continue; + } + for id in o.text_boxes() { + if let Some(part) = self.parts.get(&id).filter(|p| p.kind == PartKind::TextBox) + && budget.enter(id) + { + self.walk_objects(&part.blocks, budget, f); + budget.leave(); + } } } }); @@ -771,7 +770,7 @@ impl Document { /// `roots`, then every story their objects lead to (`follow`: an object's story id and the /// part kinds that count), transitively, in the order found. - fn reachable(&self, roots: Vec, follow: &dyn Fn(&InlineObject) -> Option<(u32, &'static [PartKind])>) -> Vec { + fn reachable(&self, roots: Vec, follow: &dyn Fn(&InlineObject) -> Vec<(u32, &'static [PartKind])>) -> Vec { let mut out = roots; let mut seen: std::collections::BTreeSet = out.iter().copied().collect(); let mut i = 0; @@ -780,7 +779,7 @@ impl Document { let mut found = Vec::new(); for b in self.story(s).into_iter().flatten() { edit::each_para(b, 0, &mut |p| { - found.extend(p.objects.iter().filter_map(follow)); + found.extend(p.objects.iter().flat_map(follow)); }); } for (id, kinds) in found { diff --git a/crates/doc/src/para.rs b/crates/doc/src/para.rs index 10129085d8..03363a24a4 100644 --- a/crates/doc/src/para.rs +++ b/crates/doc/src/para.rs @@ -214,6 +214,20 @@ pub enum InlineObject { #[serde(default)] story: Option, }, + /// Pictures, shapes and text boxes grouped into one object (Layout › Arrange › Group): it + /// moves, wraps and resizes as one. Its members are laid out in the group's own coordinate + /// space, `ch_w` × `ch_h`, which is stretched over the group's `w` × `h` (DrawingML's + /// `a:chExt` and `a:ext`), so resizing the group scales them. + Group { + w: f32, + h: f32, + #[serde(default)] + float: Float, + /// Size of the members' coordinate space (their offsets and sizes are in it). + ch_w: f32, + ch_h: f32, + children: Vec, + }, /// A field: `instr` is the field code (`PAGE`, `NUMPAGES`, `DATE \@ "M/d/yyyy"`, `TOC \o "1-3"`…); /// `result` the cached display text. Field { @@ -273,7 +287,93 @@ pub enum InlineObject { }, } +/// One member of an [`InlineObject::Group`]: a picture or shape (its own `w`, `h` and story), at +/// `x`, `y` in the group's coordinate space. Its `float` is unused. +#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] +#[serde(rename_all = "camelCase")] +pub struct GroupChild { + pub x: f32, + pub y: f32, + pub obj: InlineObject, +} + +/// Most members a group keeps (hostile files). +pub const MAX_GROUP_CHILDREN: usize = 1000; + impl InlineObject { + /// A picture, shape, text box or group: something drawn with a frame, sized and wrapped. + pub fn is_drawing(&self) -> bool { + matches!(self, InlineObject::Image { .. } | InlineObject::Shape { .. } | InlineObject::Group { .. }) + } + /// A drawing's size and placement. + pub fn frame(&self) -> Option<(f32, f32, &Float)> { + match self { + InlineObject::Image { w, h, float, .. } | InlineObject::Shape { w, h, float, .. } | InlineObject::Group { w, h, float, .. } => { + Some((*w, *h, float)) + } + _ => None, + } + } + /// A drawing's placement, to change. + pub fn float_mut(&mut self) -> Option<&mut Float> { + match self { + InlineObject::Image { float, .. } | InlineObject::Shape { float, .. } | InlineObject::Group { float, .. } => Some(float), + _ => None, + } + } + /// Resize a drawing (a group's members scale with it). + pub fn set_size(&mut self, nw: f32, nh: f32) { + if let InlineObject::Image { w, h, .. } | InlineObject::Shape { w, h, .. } | InlineObject::Group { w, h, .. } = self { + *w = nw; + *h = nh; + } + } + /// The text box story this object shows, if it is a text box. + pub fn text_box(&self) -> Option { + match self { + InlineObject::Shape { story, .. } => *story, + _ => None, + } + } + /// The text box stories this object shows: a text box's, or its group members'. + pub fn text_boxes(&self) -> Vec { + match self { + InlineObject::Shape { story: Some(id), .. } => vec![*id], + InlineObject::Group { children, .. } => children.iter().filter_map(|c| c.obj.text_box()).collect(), + _ => Vec::new(), + } + } + /// The text box story slots of this object and its group members, to repoint. + pub fn text_box_slots(&mut self) -> Vec<&mut Option> { + match self { + InlineObject::Shape { story, .. } => vec![story], + InlineObject::Group { children, .. } => children + .iter_mut() + .filter_map(|c| match &mut c.obj { + InlineObject::Shape { story, .. } => Some(story), + _ => None, + }) + .collect(), + _ => Vec::new(), + } + } + /// A group's members placed in a `w` × `h` box at (`x`, `y`): each member's rectangle + /// (x, y, w, h) and the member. Empty for anything else. + pub fn group_rects(&self, x: f32, y: f32, w: f32, h: f32) -> Vec<([f32; 4], &InlineObject)> { + let InlineObject::Group { ch_w, ch_h, children, .. } = self else { return Vec::new() }; + let fin = |v: f32| if v.is_finite() { v } else { 0.0 }; + let sx = if fin(*ch_w) > 0.0 { fin(w) / ch_w } else { 1.0 }; + let sy = if fin(*ch_h) > 0.0 { fin(h) / ch_h } else { 1.0 }; + children + .iter() + .take(MAX_GROUP_CHILDREN) + .filter_map(|c| { + let (cw, chh, _) = c.obj.frame()?; + let r = [x + fin(c.x) * sx, y + fin(c.y) * sy, (fin(cw) * sx).clamp(0.0, 4000.0), (fin(chh) * sy).clamp(0.0, 4000.0)]; + (!matches!(c.obj, InlineObject::Group { .. })).then_some((r, &c.obj)) + }) + .collect() + } /// Zero-width markers don't take part in layout. pub fn is_marker(&self) -> bool { matches!( @@ -288,7 +388,7 @@ impl InlineObject { } pub fn is_floating(&self) -> bool { match self { - InlineObject::Image { float, .. } | InlineObject::Shape { float, .. } => float.wrap != Wrap::Inline, + InlineObject::Image { float, .. } | InlineObject::Shape { float, .. } | InlineObject::Group { float, .. } => float.wrap != Wrap::Inline, _ => false, } } diff --git a/crates/docx/src/read/story.rs b/crates/docx/src/read/story.rs index f57570881c..b8d2065a40 100644 --- a/crates/docx/src/read/story.rs +++ b/crates/docx/src/read/story.rs @@ -124,7 +124,7 @@ fn clean_text(s: &str) -> String { fn children_of_choice(ac: &El) -> Option<&El> { // Prefer a Choice whose requirements we understand; else the Fallback; else any Choice. - const KNOWN: &[&str] = &["wps", "w14", "w15", "wp14", "a14", "w16se", "w16cid", "w16", "w16cex", "w16sdtdh", "v"]; + const KNOWN: &[&str] = &["wps", "wpg", "w14", "w15", "wp14", "a14", "w16se", "w16cid", "w16", "w16cex", "w16sdtdh", "v"]; let ok = |c: &El| c.attr("Requires").unwrap_or("").split_whitespace().all(|r| KNOWN.contains(&r)); ac.children("mc:Choice").find(|c| ok(c)).or_else(|| ac.child("mc:Fallback")).or_else(|| ac.child("mc:Choice")) } @@ -649,19 +649,11 @@ impl Reader<'_> { } } let gd = c.child("a:graphic").and_then(|g| g.child("a:graphicData"))?; - if let Some(blip) = gd.find("a:blip") { - let media = blip.attr("r:embed").and_then(|id| self.media_for(rels, id))?; - let mut crop = [0.0f32; 4]; - if let Some(sr) = gd.find("a:srcRect") { - for (i, n) in ["l", "t", "r", "b"].iter().enumerate() { - if let Some(v) = sr.attr(n).and_then(int) - && let Some(slot) = crop.get_mut(i) - { - *slot = (v.clamp(0, 100_000) as f32 / 100_000.0).clamp(0.0, 1.0); - } - } - } - return Some(InlineObject::Image { media, w, h, alt, float, crop }); + if let Some(g) = gd.child("wpg:wgp") { + return self.read_group(sc, g, rels, w, h, float); + } + if gd.find("a:blip").is_some() { + return self.read_pic(gd, rels, w, h, alt, float); } if let Some(wsp) = gd.find("wps:wsp") { return Some(self.read_wsp(sc, wsp, rels, w, h, float)); @@ -669,6 +661,99 @@ impl Reader<'_> { None } + /// A picture: the first `a:blip` in `pic` and its crop. + fn read_pic(&mut self, pic: &El, rels: &Rels, w: f32, h: f32, alt: String, float: Float) -> Option { + let blip = pic.find("a:blip")?; + let media = blip.attr("r:embed").and_then(|id| self.media_for(rels, id))?; + let mut crop = [0.0f32; 4]; + if let Some(sr) = pic.find("a:srcRect") { + for (i, n) in ["l", "t", "r", "b"].iter().enumerate() { + if let Some(v) = sr.attr(n).and_then(int) + && let Some(slot) = crop.get_mut(i) + { + *slot = (v.clamp(0, 100_000) as f32 / 100_000.0).clamp(0.0, 1.0); + } + } + } + Some(InlineObject::Image { media, w, h, alt, float, crop }) + } + + /// A `wpg:wgp` group (`w` × `h`): its pictures, shapes and text boxes, nested groups + /// flattened into it. `None` when it has no member we can show. + fn read_group(&mut self, sc: &mut StoryCtx, g: &El, rels: &Rels, w: f32, h: f32, float: Float) -> Option { + let x = group_xfrm(g.child("wpg:grpSpPr")); + // The members' space; without `a:chExt` it is the group's own size. + let (ch_w, ch_h) = match x.ch_ext { + Some((cw, ch)) if cw > 0.0 && ch > 0.0 => (cw, ch), + _ => (w.max(1.0), h.max(1.0)), + }; + let (cx, cy) = x.ch_off.unwrap_or((0.0, 0.0)); + let mut children = Vec::new(); + self.group_members(sc, g, rels, (-cx, -cy, 1.0, 1.0), 0, &mut children); + if children.is_empty() { + return None; + } + Some(InlineObject::Group { w, h, float, ch_w, ch_h, children }) + } + + /// The members of group `g` into `out`, mapped into the outermost group's space by `t` + /// (x0, y0, sx, sy: outer = x0 + inner × sx). + fn group_members( + &mut self, + sc: &mut StoryCtx, + g: &El, + rels: &Rels, + t: (f32, f32, f32, f32), + depth: usize, + out: &mut Vec, + ) { + let (x0, y0, sx, sy) = t; + for e in g.els() { + if out.len() >= wordcraft_doc::para::MAX_GROUP_CHILDREN { + return; + } + let e = match e.name.as_str() { + "mc:AlternateContent" => match children_of_choice(e).and_then(|c| c.els().next()) { + Some(c) => c, + None => continue, + }, + _ => e, + }; + let sppr = match e.name.as_str() { + "wps:wsp" => e.child("wps:spPr"), + "pic:pic" => e.child("pic:spPr"), + "wpg:grpSp" => e.child("wpg:grpSpPr"), + _ => continue, + }; + let x = group_xfrm(sppr); + let ((ox, oy), (ew, eh)) = (x.off, x.ext); + if e.name == "wpg:grpSp" { + if depth >= 8 { + continue; + } + // Its members' space maps onto its own box. + let (cox, coy) = x.ch_off.unwrap_or((0.0, 0.0)); + let (cw, ch) = x.ch_ext.filter(|(cw, ch)| *cw > 0.0 && *ch > 0.0).unwrap_or((ew.max(1.0), eh.max(1.0))); + let (kx, ky) = (ew / cw, eh / ch); + let nt = (x0 + (ox - cox * kx) * sx, y0 + (oy - coy * ky) * sy, sx * kx, sy * ky); + self.group_members(sc, e, rels, nt, depth + 1, out); + continue; + } + let max = crate::units::MAX_LEN_PT; + let fit = |v: f32, lo: f32| wordcraft_geom::finite(v).clamp(lo, max); + let (w, h) = (fit(ew * sx, 0.0), fit(eh * sy, 0.0)); + let obj = if e.name == "pic:pic" { + let alt = e.find("pic:cNvPr").and_then(|p| p.attr("descr")).unwrap_or("").to_string(); + self.read_pic(e, rels, w, h, alt, Float::default()) + } else { + Some(self.read_wsp(sc, e, rels, w, h, Float::default())) + }; + if let Some(obj) = obj { + out.push(wordcraft_doc::para::GroupChild { x: fit(x0 + ox * sx, -max), y: fit(y0 + oy * sy, -max), obj }); + } + } + } + fn read_wsp(&mut self, sc: &mut StoryCtx, wsp: &El, rels: &Rels, w: f32, h: f32, float: Float) -> InlineObject { let sppr = wsp.child("wps:spPr"); let prst = sppr.and_then(|s| s.child("a:prstGeom")).and_then(|g| g.attr("prst")).unwrap_or("rect"); @@ -914,3 +999,30 @@ fn vml_float(shape: &El, style: &str) -> Float { ..Float::default() } } + +/// A DrawingML `a:xfrm` (ECMA-376 §20.1.7.5/6) in points: offset, extent and, for a group, its +/// members' offset and extent. +struct Xfrm { + off: (f32, f32), + ext: (f32, f32), + ch_off: Option<(f32, f32)>, + ch_ext: Option<(f32, f32)>, +} + +/// The `a:xfrm` in shape properties `sppr` (zeros when missing). +fn group_xfrm(sppr: Option<&El>) -> Xfrm { + let x = sppr.and_then(|s| s.child("a:xfrm")); + let pair = |name: &str, a: &str, b: &str, lim: f32| { + let e = x.and_then(|x| x.child(name))?; + let v = |n: &str| e.attr(n).and_then(|v| measure(v, 12_700.0)).map(|v| v.clamp(-lim, lim)).unwrap_or(0.0); + Some((v(a), v(b))) + }; + let max = crate::units::MAX_LEN_PT; + let pos = |p: Option<(f32, f32)>| p.map(|(a, b)| (a.max(0.0), b.max(0.0))); + Xfrm { + off: pair("a:off", "x", "y", max).unwrap_or((0.0, 0.0)), + ext: pos(pair("a:ext", "cx", "cy", max)).unwrap_or((0.0, 0.0)), + ch_off: pair("a:chOff", "x", "y", max), + ch_ext: pos(pair("a:chExt", "cx", "cy", max)), + } +} diff --git a/crates/docx/src/write/story.rs b/crates/docx/src/write/story.rs index f397e6c20a..07c997f6ad 100644 --- a/crates/docx/src/write/story.rs +++ b/crates/docx/src/write/story.rs @@ -369,10 +369,8 @@ impl Writer<'_> { w.close("w:r"); self.rev_close(w, props); } - InlineObject::Image { media, w: iw, h: ih, alt, float, crop } => { + InlineObject::Image { media, w: iw, h: ih, alt, float, .. } => { let Some(file) = self.media_files.get(media).cloned() else { return }; - let rid = rels.add(rt::IMAGE, &format!("media/{file}"), false); - self.used_media.insert(media.clone()); self.rev_open(w, props); w.open("w:r", &[]); rpr(w, props); @@ -383,30 +381,7 @@ impl Writer<'_> { w.empty("wp:cNvGraphicFramePr", &[]); w.open("a:graphic", &[]); w.open("a:graphicData", &[("uri", "http://schemas.openxmlformats.org/drawingml/2006/picture")]); - w.open("pic:pic", &[]); - w.open("pic:nvPicPr", &[]); - w.empty("pic:cNvPr", &[("id", "0"), ("name", &file), ("descr", alt)]); - w.open("pic:cNvPicPr", &[]); - w.empty("a:picLocks", &[("noChangeAspect", "1"), ("noChangeArrowheads", "1")]); - w.close("pic:cNvPicPr"); - w.close("pic:nvPicPr"); - w.open("pic:blipFill", &[]); - w.empty("a:blip", &[("r:embed", &rid)]); - if crop.iter().any(|c| *c > 0.0) { - let c = |v: f32| n((wordcraft_geom::finite(v).clamp(0.0, 1.0) * 100_000.0).round() as i64); - w.empty("a:srcRect", &[("l", &c(crop[0])), ("t", &c(crop[1])), ("r", &c(crop[2])), ("b", &c(crop[3]))]); - } - w.open("a:stretch", &[]); - w.empty("a:fillRect", &[]); - w.close("a:stretch"); - w.close("pic:blipFill"); - w.open("pic:spPr", &[("bwMode", "auto")]); - xfrm(w, *iw, *ih); - w.open("a:prstGeom", &[("prst", "rect")]); - w.empty("a:avLst", &[]); - w.close("a:prstGeom"); - w.close("pic:spPr"); - w.close("pic:pic"); + self.pic(w, o, &file, (0.0, 0.0), rels); w.close("a:graphicData"); w.close("a:graphic"); w.close(if float.wrap == Wrap::Inline { "wp:inline" } else { "wp:anchor" }); @@ -414,7 +389,7 @@ impl Writer<'_> { w.close("w:r"); self.rev_close(w, props); } - InlineObject::Shape { kind, w: sw, h: sh, fill, stroke, stroke_width, float, story } => { + InlineObject::Shape { w: sw, h: sh, float, .. } => { self.rev_open(w, props); w.open("w:r", &[]); rpr(w, props); @@ -425,66 +400,53 @@ impl Writer<'_> { w.empty("wp:cNvGraphicFramePr", &[]); w.open("a:graphic", &[]); w.open("a:graphicData", &[("uri", "http://schemas.microsoft.com/office/word/2010/wordprocessingShape")]); - w.open("wps:wsp", &[]); - if *kind == ShapeKind::TextBox { - w.empty("wps:cNvSpPr", &[("txBox", "1")]); - } else { - w.empty("wps:cNvSpPr", &[]); - } - w.open("wps:spPr", &[]); - xfrm(w, *sw, *sh); - let prst = match kind { - ShapeKind::Rectangle | ShapeKind::TextBox => "rect", - ShapeKind::RoundedRectangle => "roundRect", - ShapeKind::Ellipse => "ellipse", - ShapeKind::Triangle => "triangle", - ShapeKind::Diamond => "diamond", - ShapeKind::Line => "line", - ShapeKind::Arrow => "rightArrow", - ShapeKind::Star => "star5", - ShapeKind::Heart => "heart", - }; - w.open("a:prstGeom", &[("prst", prst)]); - w.empty("a:avLst", &[]); - w.close("a:prstGeom"); - match fill { - Some(c) => { - w.open("a:solidFill", &[]); - w.empty("a:srgbClr", &[("val", &c.hex())]); - w.close("a:solidFill"); - } - None => w.empty("a:noFill", &[]), - } - match stroke { - Some(c) => { - w.open("a:ln", &[("w", &emu(stroke_width.clamp(0.0, 100.0)))]); - w.open("a:solidFill", &[]); - w.empty("a:srgbClr", &[("val", &c.hex())]); - w.close("a:solidFill"); - w.close("a:ln"); - } - None => { - w.open("a:ln", &[]); - w.empty("a:noFill", &[]); - w.close("a:ln"); + self.wsp(w, o, None, (0.0, 0.0), rels, depth); + w.close("a:graphicData"); + w.close("a:graphic"); + w.close(if float.wrap == Wrap::Inline { "wp:inline" } else { "wp:anchor" }); + w.close("w:drawing"); + w.close("w:r"); + self.rev_close(w, props); + } + InlineObject::Group { w: gw, h: gh, float, ch_w, ch_h, children } => { + self.rev_open(w, props); + w.open("w:r", &[]); + rpr(w, props); + w.open("w:drawing", &[]); + let docpr = self.next_docpr(); + let name = format!("Group {docpr}"); + self.drawing_open(w, float, *gw, *gh, &docpr, &name, ""); + w.empty("wp:cNvGraphicFramePr", &[]); + w.open("a:graphic", &[]); + w.open("a:graphicData", &[("uri", "http://schemas.microsoft.com/office/word/2010/wordprocessingGroup")]); + // ECMA-376 §20.1.7.6 (`a:xfrm` of a group): the members' space `a:chOff`/`a:chExt` + // maps onto the group's `a:off`/`a:ext`. + w.open("wpg:wgp", &[]); + w.empty("wpg:cNvGrpSpPr", &[]); + w.open("wpg:grpSpPr", &[]); + w.open("a:xfrm", &[]); + w.empty("a:off", &[("x", "0"), ("y", "0")]); + w.empty("a:ext", &[("cx", &emu(gw.max(0.0))), ("cy", &emu(gh.max(0.0)))]); + w.empty("a:chOff", &[("x", "0"), ("y", "0")]); + w.empty("a:chExt", &[("cx", &emu(ch_w.max(0.0))), ("cy", &emu(ch_h.max(0.0)))]); + w.close("a:xfrm"); + w.close("wpg:grpSpPr"); + for c in children.iter().take(wordcraft_doc::para::MAX_GROUP_CHILDREN) { + let at = (c.x, c.y); + match &c.obj { + InlineObject::Image { media, .. } => { + if let Some(file) = self.media_files.get(media).cloned() { + self.pic(w, &c.obj, &file, at, rels); + } + } + InlineObject::Shape { .. } => { + let id = self.next_docpr(); + self.wsp(w, &c.obj, Some(&id), at, rels, depth); + } + _ => {} } } - w.close("wps:spPr"); - // Its text, within the same bounds layout shows boxes inside boxes with. - if let Some(id) = *story - && let Some(part) = self.doc.parts.get(&id).filter(|p| p.kind == wordcraft_doc::PartKind::TextBox) - && self.boxes.enter(id) - { - w.open("wps:txbx", &[]); - w.open("w:txbxContent", &[]); - let blocks = part.blocks.clone(); - self.blocks(w, &blocks, rels, false, depth + 1); - w.close("w:txbxContent"); - w.close("wps:txbx"); - self.boxes.leave(); - } - w.empty("wps:bodyPr", &[]); - w.close("wps:wsp"); + w.close("wpg:wgp"); w.close("a:graphicData"); w.close("a:graphic"); w.close(if float.wrap == Wrap::Inline { "wp:inline" } else { "wp:anchor" }); @@ -574,6 +536,107 @@ impl Writer<'_> { run(w, &|w| w.empty("w:fldChar", &[("w:fldCharType", "separate")])); } + /// A picture's `pic:pic` (the image in `media/{file}`), at `off` in its group (or 0, 0). + fn pic(&mut self, w: &mut W, o: &InlineObject, file: &str, off: (f32, f32), rels: &mut PartRels) { + let InlineObject::Image { media, w: iw, h: ih, alt, crop, .. } = o else { return }; + let rid = rels.add(rt::IMAGE, &format!("media/{file}"), false); + self.used_media.insert(media.clone()); + w.open("pic:pic", &[]); + w.open("pic:nvPicPr", &[]); + w.empty("pic:cNvPr", &[("id", "0"), ("name", file), ("descr", alt)]); + w.open("pic:cNvPicPr", &[]); + w.empty("a:picLocks", &[("noChangeAspect", "1"), ("noChangeArrowheads", "1")]); + w.close("pic:cNvPicPr"); + w.close("pic:nvPicPr"); + w.open("pic:blipFill", &[]); + w.empty("a:blip", &[("r:embed", &rid)]); + if crop.iter().any(|c| *c > 0.0) { + let c = |v: f32| n((wordcraft_geom::finite(v).clamp(0.0, 1.0) * 100_000.0).round() as i64); + w.empty("a:srcRect", &[("l", &c(crop[0])), ("t", &c(crop[1])), ("r", &c(crop[2])), ("b", &c(crop[3]))]); + } + w.open("a:stretch", &[]); + w.empty("a:fillRect", &[]); + w.close("a:stretch"); + w.close("pic:blipFill"); + w.open("pic:spPr", &[("bwMode", "auto")]); + xfrm(w, off, *iw, *ih); + w.open("a:prstGeom", &[("prst", "rect")]); + w.empty("a:avLst", &[]); + w.close("a:prstGeom"); + w.close("pic:spPr"); + w.close("pic:pic"); + } + + /// A shape's or text box's `wps:wsp`, at `off` in its group (or 0, 0). In a group it carries + /// its own `wps:cNvPr` with drawing id `id`. + fn wsp(&mut self, w: &mut W, o: &InlineObject, id: Option<&str>, off: (f32, f32), rels: &mut PartRels, depth: usize) { + let InlineObject::Shape { kind, w: sw, h: sh, fill, stroke, stroke_width, story, .. } = o else { return }; + w.open("wps:wsp", &[]); + if let Some(id) = id { + let name = format!("Shape {id}"); + w.empty("wps:cNvPr", &[("id", id), ("name", &name)]); + } + if *kind == ShapeKind::TextBox { + w.empty("wps:cNvSpPr", &[("txBox", "1")]); + } else { + w.empty("wps:cNvSpPr", &[]); + } + w.open("wps:spPr", &[]); + xfrm(w, off, *sw, *sh); + let prst = match kind { + ShapeKind::Rectangle | ShapeKind::TextBox => "rect", + ShapeKind::RoundedRectangle => "roundRect", + ShapeKind::Ellipse => "ellipse", + ShapeKind::Triangle => "triangle", + ShapeKind::Diamond => "diamond", + ShapeKind::Line => "line", + ShapeKind::Arrow => "rightArrow", + ShapeKind::Star => "star5", + ShapeKind::Heart => "heart", + }; + w.open("a:prstGeom", &[("prst", prst)]); + w.empty("a:avLst", &[]); + w.close("a:prstGeom"); + match fill { + Some(c) => { + w.open("a:solidFill", &[]); + w.empty("a:srgbClr", &[("val", &c.hex())]); + w.close("a:solidFill"); + } + None => w.empty("a:noFill", &[]), + } + match stroke { + Some(c) => { + w.open("a:ln", &[("w", &emu(stroke_width.clamp(0.0, 100.0)))]); + w.open("a:solidFill", &[]); + w.empty("a:srgbClr", &[("val", &c.hex())]); + w.close("a:solidFill"); + w.close("a:ln"); + } + None => { + w.open("a:ln", &[]); + w.empty("a:noFill", &[]); + w.close("a:ln"); + } + } + w.close("wps:spPr"); + // Its text, within the same bounds layout shows boxes inside boxes with. + if let Some(id) = *story + && let Some(part) = self.doc.parts.get(&id).filter(|p| p.kind == wordcraft_doc::PartKind::TextBox) + && self.boxes.enter(id) + { + w.open("wps:txbx", &[]); + w.open("w:txbxContent", &[]); + let blocks = part.blocks.clone(); + self.blocks(w, &blocks, rels, false, depth + 1); + w.close("w:txbxContent"); + w.close("wps:txbx"); + self.boxes.leave(); + } + w.empty("wps:bodyPr", &[]); + w.close("wps:wsp"); + } + #[allow(clippy::too_many_arguments)] fn drawing_open(&mut self, w: &mut W, float: &Float, iw: f32, ih: f32, docpr: &str, name: &str, alt: &str) { let (cx, cy) = (emu(iw.max(0.0)), emu(ih.max(0.0))); @@ -774,9 +837,9 @@ impl Writer<'_> { } } -fn xfrm(w: &mut W, cw: f32, ch: f32) { +fn xfrm(w: &mut W, (x, y): (f32, f32), cw: f32, ch: f32) { w.open("a:xfrm", &[]); - w.empty("a:off", &[("x", "0"), ("y", "0")]); + w.empty("a:off", &[("x", &emu(x)), ("y", &emu(y))]); w.empty("a:ext", &[("cx", &emu(cw.max(0.0))), ("cy", &emu(ch.max(0.0)))]); w.close("a:xfrm"); } diff --git a/crates/docx/tests/fixtures.rs b/crates/docx/tests/fixtures.rs index 00ac2c8f3f..9e47e22c92 100644 --- a/crates/docx/tests/fixtures.rs +++ b/crates/docx/tests/fixtures.rs @@ -6,7 +6,7 @@ use wordcraft_doc::para::{Anchor, FloatAlign, NoteKind, ShapeKind, Wrap}; use wordcraft_doc::props::{Align, Border, BorderStyle, Rgb, TextColor, VMerge}; use wordcraft_doc::{Block, Document, InlineObject, Paragraph}; -const W_NS: &str = r#"xmlns:w="http://schemas.openxmlformats.org/wordprocessingml/2006/main" xmlns:r="http://schemas.openxmlformats.org/officeDocument/2006/relationships" xmlns:wp="http://schemas.openxmlformats.org/drawingml/2006/wordprocessingDrawing" xmlns:a="http://schemas.openxmlformats.org/drawingml/2006/main" xmlns:pic="http://schemas.openxmlformats.org/drawingml/2006/picture" xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006" xmlns:wps="http://schemas.microsoft.com/office/word/2010/wordprocessingShape" xmlns:v="urn:schemas-microsoft-com:vml" xmlns:o="urn:schemas-microsoft-com:office:office""#; +const W_NS: &str = r#"xmlns:w="http://schemas.openxmlformats.org/wordprocessingml/2006/main" xmlns:r="http://schemas.openxmlformats.org/officeDocument/2006/relationships" xmlns:wp="http://schemas.openxmlformats.org/drawingml/2006/wordprocessingDrawing" xmlns:a="http://schemas.openxmlformats.org/drawingml/2006/main" xmlns:pic="http://schemas.openxmlformats.org/drawingml/2006/picture" xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006" xmlns:wps="http://schemas.microsoft.com/office/word/2010/wordprocessingShape" xmlns:wpg="http://schemas.microsoft.com/office/word/2010/wordprocessingGroup" xmlns:v="urn:schemas-microsoft-com:vml" xmlns:o="urn:schemas-microsoft-com:office:office""#; const ROOT_RELS: &str = r#""#; @@ -646,3 +646,28 @@ fn hostile_vml_style_values_stay_finite() { assert!([*w, *h, float.x, float.y, float.dist, float.dist_top].iter().all(|v| v.is_finite()), "{w} {h} {float:?}"); assert_eq!((float.h_align, float.dist, float.dist_top), (None, 0.0, 1584.0)); } + +/// A group as Word saves one (in `mc:AlternateContent`, needing `wpg`): its members' space +/// starts at `a:chOff`, and a nested group is flattened into it through its own transform. +#[test] +fn word_group_with_nested_group() { + let body = r#"00 + + + + +"#; + let d = read_body(body); + let p = paras(&d); + let InlineObject::Group { w, h, float, ch_w, ch_h, children } = &p[0].objects[0] else { panic!("{:?}", p[0].objects) }; + assert_eq!((*w, *h, *ch_w, *ch_h), (200.0, 100.0, 200.0, 100.0)); + assert_eq!(float.wrap, Wrap::Square); + let got: Vec<(f32, f32, ShapeKind, f32, f32)> = children + .iter() + .map(|c| match &c.obj { + InlineObject::Shape { kind, w, h, .. } => (c.x, c.y, *kind, *w, *h), + o => panic!("{o:?}"), + }) + .collect(); + assert_eq!(got, [(0.0, 0.0, ShapeKind::Rectangle, 100.0, 50.0), (110.0, 60.0, ShapeKind::Ellipse, 20.0, 10.0)]); +} diff --git a/crates/docx/tests/roundtrip.rs b/crates/docx/tests/roundtrip.rs index 39cdd7b9da..cc64310975 100644 --- a/crates/docx/tests/roundtrip.rs +++ b/crates/docx/tests/roundtrip.rs @@ -817,6 +817,75 @@ fn shapes_textboxes_equations_dropcaps_round_trip() { assert_eq!(got[1].props, dc.props); } +/// A group of a picture, a shape and a text box (`wpg:wgp`) comes back as it was saved: its +/// size, placement and members' space, and each member's offset, size and content. +#[test] +fn groups_round_trip() { + use wordcraft_doc::para::GroupChild; + let mut d = Document::new(); + let key = d.add_media(tiny_png(), "png"); + let story = d.add_part(PartKind::TextBox, vec![para_block(Paragraph::with_text("In the group", CharProps::default()))]); + let pic = InlineObject::Image { media: key, w: 60.0, h: 40.0, alt: "A picture".into(), float: Float::default(), crop: [0.0; 4] }; + let oval = InlineObject::Shape { + kind: ShapeKind::Ellipse, + w: 50.0, + h: 30.0, + fill: Some(Rgb(200, 0, 0)), + stroke: None, + stroke_width: 0.0, + float: Float::default(), + story: None, + }; + let tb = InlineObject::Shape { + kind: ShapeKind::TextBox, + w: 100.0, + h: 40.0, + fill: Some(Rgb(255, 255, 255)), + stroke: Some(Rgb(0, 0, 0)), + stroke_width: 0.75, + float: Float::default(), + story: Some(story), + }; + let float = Float { wrap: Wrap::Square, h_rel: Anchor::Column, v_rel: Anchor::Paragraph, x: 20.0, y: 10.0, dist: 9.0, ..Default::default() }; + let group = InlineObject::Group { + w: 240.0, + h: 120.0, + float, + ch_w: 200.0, + ch_h: 100.0, + children: vec![ + GroupChild { x: 0.0, y: 0.0, obj: pic }, + GroupChild { x: 150.0, y: 10.0, obj: oval.clone() }, + GroupChild { x: 50.0, y: 60.0, obj: tb }, + ], + }; + let mut p = Paragraph::with_text("grouped ", CharProps::default()); + let end = p.len(); + p.insert_object(end, group, &CharProps::default()).unwrap(); + d.body = vec![para_block(p)]; + let r = rt(&d); + let got = paras(&r); + let InlineObject::Group { w, h, float: f, ch_w, ch_h, children } = &got[0].objects[0] else { panic!("{:?}", got[0].objects) }; + assert_eq!((*w, *h, *ch_w, *ch_h), (240.0, 120.0, 200.0, 100.0)); + assert_eq!(*f, float); + assert_eq!(children.iter().map(|c| (c.x, c.y)).collect::>(), [(0.0, 0.0), (150.0, 10.0), (50.0, 60.0)]); + match &children[0].obj { + InlineObject::Image { media, w, h, alt, .. } => { + assert_eq!((*w, *h, alt.as_str()), (60.0, 40.0, "A picture")); + assert_eq!(r.media.get(media).map(|m| m.as_slice()), Some(tiny_png().as_slice())); + } + o => panic!("{o:?}"), + } + assert_eq!(children[1].obj, oval); + match &children[2].obj { + InlineObject::Shape { kind, w, h, story, .. } => { + assert_eq!((*kind, *w, *h), (ShapeKind::TextBox, 100.0, 40.0)); + assert_eq!(part_text(&r, *story), "In the group"); + } + o => panic!("{o:?}"), + } +} + #[test] fn compatibility_mode_round_trips() { // New documents are Word 2013+ documents; an older file keeps its mode, so saving it doesn't diff --git a/crates/engine/src/catalog.rs b/crates/engine/src/catalog.rs index adbd11d26f..1de0965dd1 100644 --- a/crates/engine/src/catalog.rs +++ b/crates/engine/src/catalog.rs @@ -500,6 +500,6 @@ mod tests { let p = parity(®); let pct = p["percent"].as_f64().unwrap(); // The floor only ever rises. - assert!(pct >= 60.0, "parity {pct}%"); + assert!(pct >= 88.5, "parity {pct}%"); } } diff --git a/crates/engine/src/cmd/objects.rs b/crates/engine/src/cmd/objects.rs index 7360d7abd7..f9fa38ad91 100644 --- a/crates/engine/src/cmd/objects.rs +++ b/crates/engine/src/cmd/objects.rs @@ -22,10 +22,19 @@ fn has_object(s: &Session) -> Option<&'static str> { } fn has_floating(s: &Session) -> Option<&'static str> { match selected(s) { - Some((_, InlineObject::Image { float, .. } | InlineObject::Shape { float, .. })) if float.wrap != Wrap::Inline => None, + Some((_, o)) if o.is_floating() => None, _ => Some("select a floating picture or shape first"), } } +fn has_group(s: &Session) -> Option<&'static str> { + match selected(s) { + Some((_, InlineObject::Group { .. })) => None, + _ => Some("select a group first"), + } +} +fn can_group(s: &Session) -> Option<&'static str> { + if picked_objects(s).len() >= 2 { None } else { Some("select two or more pictures or shapes first (Shift+click)") } +} fn has_shape(s: &Session) -> Option<&'static str> { match selected(s) { Some((_, InlineObject::Shape { .. })) => None, @@ -260,6 +269,13 @@ pub fn specs() -> Vec { }) .params(r#"{"dx"?: pt, "dy"?: pt}"#) .when(has_floating), + CommandSpec::new("arrange.group", "Group", "Layout › Arrange", group) + .params(r#"{} (groups the selected pictures, shapes and text boxes: the selected one plus those added with select.addObject)"#) + .when(can_group), + CommandSpec::new("arrange.ungroup", "Ungroup", "Layout › Arrange", ungroup).when(has_group), + CommandSpec::new("select.addObject", "Add Object to Selection", "Home › Editing › Select", add_object) + .params(r#"{"pos"?: Pos, "index"?: n, "objects"?: [Pos | n]} (n: its Selection Pane index; with no object selected yet, the first one becomes the selection)"#) + .pure(), CommandSpec::new("select.objects", "Select Objects", "Home › Editing › Select", |s, v| { let n = p::u64(v, "index").unwrap_or(0) as usize; let list = all_objects(s); @@ -315,7 +331,7 @@ pub fn object_selection(s: &Session) -> Option<(Pos, &InlineObject)> { return None; } let o = s.doc.para_at(&a)?.object_at(a.off)?; - matches!(o, InlineObject::Image { .. } | InlineObject::Shape { .. }).then_some((a, o)) + o.is_drawing().then_some((a, o)) } /// The first picture/shape in the selection, or just before a collapsed caret. @@ -334,7 +350,7 @@ pub fn selected(s: &Session) -> Option<(Pos, InlineObject)> { if !inside { continue; } - if let Some(o @ (InlineObject::Image { .. } | InlineObject::Shape { .. })) = p.object_at(off) { + if let Some(o) = p.object_at(off).filter(|o| o.is_drawing()) { return Some((Pos { story, path: path.clone(), off }, o.clone())); } } @@ -363,12 +379,7 @@ fn bounds(s: &mut Session, v: &Value) -> CmdResult { let w = p::f32(v, "width").unwrap_or(w0).clamp(min, MAX_OFFSET); let h = p::f32(v, "height").unwrap_or(h0).clamp(min, MAX_OFFSET); if (w, h) != (w0, h0) { - with_obj(s, |o| { - if let InlineObject::Image { w: ow, h: oh, .. } | InlineObject::Shape { w: ow, h: oh, .. } = o { - *ow = w; - *oh = h; - } - })?; + with_obj(s, |o| o.set_size(w, h))?; } let pos = match to { Some((x, y)) => move_object(s, pos, p::u64(v, "page"), x, y, (w, h))?, @@ -448,7 +459,7 @@ fn move_object(s: &mut Session, pos: Pos, page: Option, x: f32, y: f32, (w, fn unalign(s: &mut Session) -> Result<(), CmdError> { use wordcraft_doc::para::Anchor; let (pos, obj) = selected(s).ok_or_else(|| CmdError::Disabled("no picture or shape selected".into()))?; - let (InlineObject::Image { float, .. } | InlineObject::Shape { float, .. }) = &obj else { return Ok(()) }; + let Some((_, _, float)) = obj.frame() else { return Ok(()) }; if float.h_align.is_none() && float.v_align.is_none() { return Ok(()); } @@ -497,10 +508,7 @@ fn nearest_line(layout: &wordcraft_layout::DocLayout, page: usize, y: f32) -> Op } fn obj_size(o: &InlineObject) -> (f32, f32) { - match o { - InlineObject::Image { w, h, .. } | InlineObject::Shape { w, h, .. } => (*w, *h), - _ => (0.0, 0.0), - } + o.frame().map_or((0.0, 0.0), |(w, h, _)| (w, h)) } fn with_obj(s: &mut Session, f: impl Fn(&mut InlineObject)) -> CmdResult { @@ -521,15 +529,15 @@ fn edit_obj(s: &mut Session, pos: &Pos, f: impl Fn(&mut InlineObject)) -> Result fn edit_float(s: &mut Session, pos: &Pos, f: impl Fn(&mut Float)) -> Result { edit_obj(s, pos, |o| { - if let InlineObject::Image { float, .. } | InlineObject::Shape { float, .. } = o { + if let Some(float) = o.float_mut() { f(float); } }) } fn with_float(s: &mut Session, f: impl Fn(&mut Float)) -> CmdResult { - with_obj(s, |o| match o { - InlineObject::Image { float, .. } | InlineObject::Shape { float, .. } => { + with_obj(s, |o| { + if let Some(float) = o.float_mut() { let was_inline = float.wrap == Wrap::Inline; f(float); // Word's distance from text for a newly wrapped object: 0.125" at the sides. @@ -537,7 +545,6 @@ fn with_float(s: &mut Session, f: impl Fn(&mut Float)) -> CmdResult { float.dist = 9.0; } } - _ => {} }) } @@ -737,12 +744,188 @@ fn picture_style(img: image::DynamicImage, style: &str) -> image::DynamicImage { } } +/// The selected pictures, shapes, text boxes and groups: the one the selection holds, then +/// those added to it ([`Session::also_selected`]), each once, in the body. +pub fn picked_objects(s: &Session) -> Vec { + let Some((first, _)) = object_selection(s) else { return Vec::new() }; + let mut out = vec![first]; + for p in &s.also_selected { + if !out.contains(p) && s.doc.para_at(p).and_then(|q| q.object_at(p.off)).is_some_and(InlineObject::is_drawing) { + out.push(p.clone()); + } + } + out +} + +/// The object a `select.addObject` item names: a position, or a Selection Pane index. +fn object_ref(s: &Session, v: &Value) -> Result { + let pos = match v.as_u64() { + Some(n) => all_objects(s).into_iter().nth(usize::try_from(n).unwrap_or(usize::MAX)).map(|(p, _)| p), + None => super::parse_pos(v), + }; + pos.filter(|p| p.story == StoryRef::Body && s.doc.para_at(p).and_then(|q| q.object_at(p.off)).is_some_and(InlineObject::is_drawing)) + .ok_or_else(|| CmdError::Params("no picture or shape there".into())) +} + +/// Add objects to the selection (Shift+click): the first one is selected if no object is yet; +/// one already selected is taken out again. +fn add_object(s: &mut Session, v: &Value) -> CmdResult { + let mut items: Vec = match v.get("objects").and_then(Value::as_array) { + Some(a) => a.iter().take(1000).cloned().collect(), + None => Vec::new(), + }; + if let Some(p) = v.get("pos") { + items.push(p.clone()); + } + if let Some(i) = v.get("index") { + items.push(i.clone()); + } + if items.is_empty() { + return Err(CmdError::Params("`pos`, `index` or `objects` required".into())); + } + for it in &items { + let pos = object_ref(s, it)?; + match object_selection(s).map(|(p, _)| p) { + None => { + s.also_selected.clear(); + s.sel = Selection { anchor: pos.clone(), focus: Pos { off: pos.off + wordcraft_doc::para::OBJ.len_utf8(), ..pos } }; + } + Some(first) if first == pos => {} + Some(_) => { + if let Some(i) = s.also_selected.iter().position(|p| *p == pos) { + s.also_selected.remove(i); + } else { + s.also_selected.push(pos); + } + } + } + } + Ok(json!({"selected": picked_objects(s).iter().map(super::pos_json).collect::>()})) +} + +/// Group the selected objects (Layout › Arrange › Group): one floating group object, anchored +/// where the first of them was, in the box around them all; they keep their places and sizes. +/// A group among them is merged in (its members join the new group). +fn group(s: &mut Session, _: &Value) -> CmdResult { + use wordcraft_doc::para::GroupChild; + let mut picks = picked_objects(s); + if picks.len() < 2 { + return Err(CmdError::Disabled("select two or more pictures or shapes first".into())); + } + picks.sort(); + let layout = s.layout(); + let mut found = Vec::new(); + for pos in &picks { + if pos.story != StoryRef::Body || pos.path.depth() > 0 { + return Err(CmdError::Disabled("only objects in the body text (not in tables) can be grouped".into())); + } + let obj = s.doc.para_at(pos).and_then(|p| p.object_at(pos.off)).cloned().ok_or_else(|| CmdError::Failed("object vanished".into()))?; + if !obj.is_floating() { + return Err(CmdError::Disabled("objects in line with text can't be grouped: choose a text wrapping for them first".into())); + } + let hit = layout.object(pos, s.page_hint).ok_or_else(|| CmdError::Failed("the object isn't laid out".into()))?; + found.push((obj, hit)); + } + let page = found.first().map(|(_, h)| h.page).unwrap_or(0); + if found.iter().any(|(_, h)| h.page != page) { + return Err(CmdError::Disabled("objects on different pages can't be grouped".into())); + } + let (mut x0, mut y0, mut x1, mut y1) = (f32::MAX, f32::MAX, f32::MIN, f32::MIN); + for (_, h) in &found { + (x0, y0) = (x0.min(h.rect.x), y0.min(h.rect.y)); + (x1, y1) = (x1.max(h.rect.right()), y1.max(h.rect.bottom())); + } + let (w, h) = ((x1 - x0).clamp(1.0, MAX_OFFSET), (y1 - y0).clamp(1.0, MAX_OFFSET)); + let mut children = Vec::new(); + let member = |obj: &InlineObject, r: [f32; 4]| { + let mut obj = obj.clone(); + obj.set_size(r[2], r[3]); + if let Some(f) = obj.float_mut() { + *f = Float::default(); + } + GroupChild { x: r[0] - x0, y: r[1] - y0, obj } + }; + for (obj, hit) in &found { + let r = hit.rect; + match obj { + InlineObject::Group { .. } => children.extend(obj.group_rects(r.x, r.y, r.w, r.h).into_iter().map(|(cr, c)| member(c, cr))), + _ => children.push(member(obj, [r.x, r.y, r.w, r.h])), + } + } + let float = found.first().and_then(|(o, _)| o.frame()).map(|(_, _, f)| *f).unwrap_or_default(); + let grouped = InlineObject::Group { w, h, float, ch_w: w, ch_h: h, children }; + // Take the members out, last first so the earlier positions hold, and put the group where + // the first one was. + let len = wordcraft_doc::para::OBJ.len_utf8(); + for pos in picks.iter().rev() { + s.doc.delete_range(pos, &Pos { off: pos.off + len, ..pos.clone() })?; + } + let first = picks.first().cloned().ok_or_else(|| CmdError::Failed("nothing to group".into()))?; + let at = s.doc.clamp(&first); + s.doc.insert_object(&at, grouped, &wordcraft_doc::CharProps::default())?; + s.touch(); + let pos = move_object(s, at, Some(page as u64), x0, y0, (w, h))?; + s.also_selected.clear(); + s.sel = Selection { anchor: pos.clone(), focus: Pos { off: pos.off + len, ..pos.clone() } }; + let o = s.doc.para_at(&pos).and_then(|p| p.object_at(pos.off)).cloned(); + Ok(json!({"object": serde_json::to_value(o).unwrap_or(Value::Null), "pos": super::pos_json(&pos)})) +} + +/// Split the selected group back into its pictures and shapes (Layout › Arrange › Ungroup), in +/// the places and sizes the group shows them, anchored where the group was. They stay +/// selected, so Group puts them back together. +fn ungroup(s: &mut Session, _: &Value) -> CmdResult { + let (pos, obj) = selected(s).ok_or_else(|| CmdError::Disabled("select a group first".into()))?; + let InlineObject::Group { w, h, float, .. } = &obj else { return Err(CmdError::Disabled("select a group first".into())) }; + // Its offsets, explicit: the members are placed from the same anchor. + let pos = if float.wrap == Wrap::Inline { + if pos.story != StoryRef::Body || pos.path.depth() > 0 { + return Err(CmdError::Disabled("only groups in the body text can be ungrouped in line with text".into())); + } + let hit = s.layout().object(&pos, s.page_hint).ok_or_else(|| CmdError::Failed("the object isn't laid out".into()))?; + move_object(s, pos, Some(hit.page as u64), hit.rect.x, hit.rect.y, (*w, *h))? + } else { + unalign(s)?; + pos + }; + let obj = s.doc.para_at(&pos).and_then(|p| p.object_at(pos.off)).cloned().ok_or_else(|| CmdError::Failed("object vanished".into()))?; + let Some((w, h, float)) = obj.frame() else { return Err(CmdError::Failed("object vanished".into())) }; + let float = *float; + let members: Vec = obj + .group_rects(0.0, 0.0, w, h) + .into_iter() + .map(|([x, y, cw, ch], c)| { + let mut c = c.clone(); + c.set_size(cw.max(min_size(&c)), ch.max(min_size(&c))); + if let Some(f) = c.float_mut() { + *f = Float { x: (float.x + x).clamp(-MAX_OFFSET, MAX_OFFSET), y: (float.y + y).clamp(-MAX_OFFSET, MAX_OFFSET), ..float }; + } + c + }) + .collect(); + if members.is_empty() { + return Err(CmdError::Failed("the group is empty".into())); + } + let len = wordcraft_doc::para::OBJ.len_utf8(); + s.doc.delete_range(&pos, &Pos { off: pos.off + len, ..pos.clone() })?; + let mut at = s.doc.clamp(&pos); + let mut placed = Vec::new(); + for m in members { + placed.push(at.clone()); + at = s.doc.insert_object(&at, m, &wordcraft_doc::CharProps::default())?; + } + let first = placed.first().cloned().unwrap_or(pos); + s.sel = Selection { anchor: first.clone(), focus: Pos { off: first.off + len, ..first } }; + s.also_selected = placed.into_iter().skip(1).collect(); + sel_result(s) +} + fn all_objects(s: &Session) -> Vec<(Pos, InlineObject)> { let mut v = Vec::new(); for path in s.doc.para_paths(StoryRef::Body) { let Some(p) = s.doc.para(StoryRef::Body, &path) else { continue }; for off in p.object_offsets() { - if let Some(o @ (InlineObject::Image { .. } | InlineObject::Shape { .. })) = p.object_at(off) { + if let Some(o) = p.object_at(off).filter(|o| o.is_drawing()) { v.push((Pos { story: StoryRef::Body, path: path.clone(), off }, o.clone())); } } @@ -759,6 +942,7 @@ fn objects_list(s: &mut Session, _: &Value) -> CmdResult { let (kind, name) = match &o { InlineObject::Image { alt, .. } => ("picture", if alt.is_empty() { format!("Picture {}", i + 1) } else { alt.clone() }), InlineObject::Shape { kind, .. } => ("shape", format!("{kind:?} {}", i + 1)), + InlineObject::Group { .. } => ("group", format!("Group {}", i + 1)), _ => ("object", format!("Object {}", i + 1)), }; json!({"index": i, "kind": kind, "name": name, "pos": super::pos_json(&pos), "size": obj_size(&o)}) @@ -862,6 +1046,66 @@ mod tests { assert!(s.run("picture.crop", &json!({"left": 0.1})).is_err()); } + /// The page rectangle of the object at `pos`. + fn rect_of(s: &mut Session, pos: &Pos) -> [f32; 4] { + let r = s.layout().object(pos, 0).unwrap().rect; + [r.x, r.y, r.w, r.h] + } + + fn near(a: [f32; 4], b: [f32; 4]) -> bool { + a.iter().zip(b).all(|(x, y)| (x - y).abs() < 0.5) + } + + /// Two floating shapes, Shift+clicked together and grouped: one object that moves as one with + /// its members in place; ungrouping puts them back where the group showed them, still + /// selected, so Group regroups them. + #[test] + fn group_moves_as_one_and_ungroups() { + let mut s = Session::new(wordcraft_doc::Document::new()); + s.run("document.setText", &json!({"text": "one\ntwo\nthree\nfour"})).unwrap(); + s.sel = Selection::caret(s.doc.start_of(StoryRef::Body)); + s.run("insert.shape", &json!({"kind": "rectangle", "width": 100, "height": 50})).unwrap(); + s.run("arrange.bounds", &json!({"page": 0, "x": 100, "y": 150})).unwrap(); + s.run("select.collapse", &json!({"end": true})).unwrap(); + s.run("insert.shape", &json!({"kind": "ellipse", "width": 60, "height": 40})).unwrap(); + s.run("arrange.bounds", &json!({"page": 0, "x": 300, "y": 200})).unwrap(); + // One shape selected: nothing to group yet. + assert!(s.run("arrange.group", &json!({})).is_err()); + let r = s.run("select.addObject", &json!({"index": 0})).unwrap(); + assert_eq!(r["selected"].as_array().unwrap().len(), 2); + let g = s.run("arrange.group", &json!({})).unwrap(); + let pos: Pos = serde_json::from_value(g["pos"].clone()).unwrap(); + let list = s.run("arrange.selectionPane", &json!({})).unwrap(); + assert_eq!(list.as_array().unwrap().len(), 1, "{list}"); + assert_eq!(list[0]["kind"], "group"); + assert!(s.also_selected.is_empty()); + assert!(near(rect_of(&mut s, &pos), [100.0, 150.0, 260.0, 90.0]), "{:?}", rect_of(&mut s, &pos)); + + // Moving the group moves its members with it. + s.run("arrange.nudge", &json!({"dx": 20, "dy": 10})).unwrap(); + let (pos, obj) = selected(&s).unwrap(); + let [x, y, w, h] = rect_of(&mut s, &pos); + let members: Vec<[f32; 4]> = obj.group_rects(x, y, w, h).into_iter().map(|(r, _)| r).collect(); + assert!(near(members[0], [120.0, 160.0, 100.0, 50.0]) && near(members[1], [320.0, 210.0, 60.0, 40.0]), "{members:?}"); + // Drawn there too: the page shows both shapes inside the group's frame. + let shapes = s.layout().pages[0].items.iter().filter(|i| matches!(i, wordcraft_layout::Placed::Shape { .. })).count(); + assert_eq!(shapes, 2); + + // Ungroup: two shapes again, where the group showed them, both still selected. + s.run("arrange.ungroup", &json!({})).unwrap(); + let list = all_objects(&s); + assert_eq!(list.len(), 2); + let rects: Vec<[f32; 4]> = list.iter().map(|(p, _)| rect_of(&mut s, p)).collect(); + assert!(rects.iter().any(|r| near(*r, [120.0, 160.0, 100.0, 50.0])), "{rects:?}"); + assert!(rects.iter().any(|r| near(*r, [320.0, 210.0, 60.0, 40.0])), "{rects:?}"); + assert_eq!(picked_objects(&s).len(), 2); + s.run("arrange.group", &json!({})).unwrap(); + assert_eq!(all_objects(&s).len(), 1); + // Undo goes back step by step. + s.run("edit.undo", &json!({})).unwrap(); + assert_eq!(all_objects(&s).len(), 2); + } + #[test] fn picture_alt_and_crop_round_trip() { let mut s = Session::new(wordcraft_doc::Document::new()); diff --git a/crates/engine/src/session.rs b/crates/engine/src/session.rs index f779da5056..e20670239d 100644 --- a/crates/engine/src/session.rs +++ b/crates/engine/src/session.rs @@ -210,6 +210,9 @@ pub struct Session { pub math_latex: bool, /// Text typed into equations is normal (non-math) text. pub math_normal_text: bool, + /// More pictures and shapes selected along with the one the selection holds (Shift+click), + /// for Group. Cleared by any edit or selection change other than adding to it. + pub also_selected: Vec, } /// The equation being edited. @@ -281,6 +284,7 @@ impl Session { math: None, math_latex: false, math_normal_text: false, + also_selected: Vec::new(), prefs: Prefs::default(), read_aloud: Default::default(), } @@ -415,6 +419,7 @@ impl Session { self.doc.ensure_nonempty(); self.sel = Selection::caret(self.doc.start_of(StoryRef::Body)); self.pending = None; + self.also_selected.clear(); self.reset_history(); self.touch(); self.dirty = false; @@ -481,6 +486,7 @@ impl Session { math: _, math_latex: _, math_normal_text: _, + also_selected: _, } = self; let head = if history.len() + SNAPSHOT_HEAD > MAX_UNDO { history.iter().take(SNAPSHOT_HEAD).cloned().collect() } else { Vec::new() }; EditSnapshot { @@ -509,6 +515,7 @@ impl Session { self.undo_evicted = evicted; self.doc = doc; self.sel = sel; + self.also_selected.clear(); self.history.truncate(history_len); self.redo = redo; self.typing_open = typing_open; @@ -599,6 +606,7 @@ impl Session { } else if spec.id.starts_with("caret.") { self.typing_open = false; } + let sel_before = self.sel.clone(); let run = spec.run; let result = std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| run(self, params))); let result = match result { @@ -616,6 +624,10 @@ impl Session { self.doc.prune_text_boxes(); } self.clamp_selection(); + // Extra selected objects last until something else is edited or selected. + if !matches!(id, "select.addObject" | "arrange.ungroup") && (spec.mutates || self.sel != sel_before) { + self.also_selected.clear(); + } } Err(e) => { if let Some((d, s, h, r, t, ev)) = before_doc { diff --git a/crates/layout/src/display.rs b/crates/layout/src/display.rs index 7ad8ed9a01..7038b17f90 100644 --- a/crates/layout/src/display.rs +++ b/crates/layout/src/display.rs @@ -484,6 +484,18 @@ fn lines( Some(InlineObject::Shape { kind, fill, stroke, stroke_width, .. }) => { out.push(Draw::Shape { rect, kind: *kind, fill: *fill, stroke: *stroke, stroke_width: *stroke_width }) } + Some(g @ InlineObject::Group { .. }) => { + for ([x, y, w, h], c) in g.group_rects(rect.x, rect.y, rect.w, rect.h) { + let rect = Rect::new(x, y, w, h); + match c { + InlineObject::Image { media, crop, .. } => out.push(Draw::Image { rect, media: media.clone(), crop: *crop, alpha }), + InlineObject::Shape { kind, fill, stroke, stroke_width, .. } => { + out.push(Draw::Shape { rect, kind: *kind, fill: *fill, stroke: *stroke, stroke_width: *stroke_width }) + } + _ => {} + } + } + } Some(InlineObject::Equation { .. }) => { if let Some((_, ml)) = pl.maths.iter().find(|(k, _)| *k == oi) { equation(&ml.items, cx, base, alpha, opts.placeholders, out); @@ -607,9 +619,6 @@ pub fn text_color(c: &TextColor, background: Option) -> Rgb { /// Where inline object `obj` is drawn, given its cluster's box (`adv` × `obj_h` standing on the /// baseline at `cx`): inside the room kept for its effects. pub(crate) fn inline_rect(obj: Option<&InlineObject>, cx: f32, base: f32, adv: f32, obj_h: f32) -> Rect { - let [l, t, r, b] = match obj { - Some(InlineObject::Image { float, .. } | InlineObject::Shape { float, .. }) => float.effect_extent(), - _ => [0.0; 4], - }; + let [l, t, r, b] = obj.and_then(InlineObject::frame).map_or([0.0; 4], |(_, _, float)| float.effect_extent()); Rect::new(cx + l, base - obj_h + t, (adv - l - r).max(0.0), (obj_h - t - b).max(0.0)) } diff --git a/crates/layout/src/lib.rs b/crates/layout/src/lib.rs index 944f06c1ad..e2d011a213 100644 --- a/crates/layout/src/lib.rs +++ b/crates/layout/src/lib.rs @@ -957,10 +957,7 @@ struct PageFrame<'a> { /// A floating (not inline) picture or shape: its size and placement. fn floating(o: &InlineObject) -> Option<(f32, f32, &Float)> { - match o { - InlineObject::Image { w, h, float, .. } | InlineObject::Shape { w, h, float, .. } if float.wrap != Wrap::Inline => Some((*w, *h, float)), - _ => None, - } + o.frame().filter(|(_, _, float)| float.wrap != Wrap::Inline) } /// Where a floating object goes, in the coordinates of the box `frame` places on the page. @@ -1023,19 +1020,25 @@ fn rel_exclusions(excl: &[(Rect, bool)], x0: f32, y0: f32) -> Vec Option { +/// The items drawing floating object `o` at `rect` (a group: its members). +fn float_items(o: &InlineObject, rect: Rect, story: StoryRef, path: &[u32], off: usize) -> Vec { match o { InlineObject::Image { media, crop, .. } => { - Some(Placed::Image { rect, media: media.clone(), crop: *crop, story, path: Path(path.to_vec()), off }) + vec![Placed::Image { rect, media: media.clone(), crop: *crop, story, path: Path(path.to_vec()), off }] } InlineObject::Shape { kind, fill, stroke, stroke_width, .. } => { - Some(Placed::Shape { rect, kind: *kind, fill: *fill, stroke: *stroke, stroke_width: *stroke_width }) + vec![Placed::Shape { rect, kind: *kind, fill: *fill, stroke: *stroke, stroke_width: *stroke_width }] } - _ => None, + InlineObject::Group { .. } => group_members(o, rect).into_iter().flat_map(|(r, c)| float_items(c, r, story, path, off)).collect(), + _ => Vec::new(), } } +/// A group's members, each with its rectangle when the group is at `rect`. +fn group_members(o: &InlineObject, rect: Rect) -> Vec<(Rect, &InlineObject)> { + o.group_rects(rect.x, rect.y, rect.w, rect.h).into_iter().map(|([x, y, w, h], c)| (Rect::new(x, y, w, h), c)).collect() +} + /// Position the floating objects anchored in `p` for a paragraph whose text starts at `y0` in /// the current column, add their wrap areas to the page (replacing any from an earlier attempt, /// from `excl_mark` on) and lay the paragraph out around them, with its list `label`. @@ -1113,18 +1116,19 @@ fn place_objects( if left_out(oi) { continue; } - let Some(obj @ (InlineObject::Image { w, h, float, .. } | InlineObject::Shape { w, h, float, .. })) = p.objects.get(oi) else { continue }; + let Some(obj) = p.objects.get(oi) else { continue }; + let Some((w, h, float)) = obj.frame() else { continue }; let floating = float.wrap != Wrap::Inline; let rect = if floating { - floats.get(&oi).copied().unwrap_or_else(|| float_rect(at.page, at.col, at.para_y, *w, *h, float)) + floats.get(&oi).copied().unwrap_or_else(|| float_rect(at.page, at.col, at.para_y, w, h, float)) } else { let cx = x + line.cl_left(k).unwrap_or(0.0); display::inline_rect(Some(obj), cx, y + (line.baseline - fl.top), c.adv, c.obj_h) }; let layer = if float.wrap == Wrap::BehindText { &mut behind } else { &mut front }; // Floating ones are drawn here; inline ones with their line. - if floating && let Some(it) = float_item(obj, rect, story, path, c.start) { - layer.push(it); + if floating { + layer.extend(float_items(obj, rect, story, path, c.start)); } let text_box = match obj { InlineObject::Shape { story: Some(id), .. } if ctx.doc.parts.get(id).is_some_and(|p| p.kind == wordcraft_doc::PartKind::TextBox) => { @@ -1141,16 +1145,30 @@ fn place_objects( wrap: float.wrap, origin: Point::new(at.col.0, at.para_y), }); - // Its text, unless the box budget says no (a box inside itself, too deep, too many). - let Some(id) = text_box.filter(|id| ctx.boxes.enter(*id)) else { continue }; - let blocks = ctx.doc.parts.get(&id).map(|p| p.blocks.clone()).unwrap_or_default(); - let (inner, _) = layout_box(ctx, StoryRef::Part(id), &blocks, &[], (rect.w - 2.0 * BOX_INSET_X).max(12.0), None, depth + 1, None); - ctx.boxes.leave(); - let layer = if float.wrap == Wrap::BehindText { &mut behind } else { &mut front }; - // Text that doesn't fit inside the margins is hidden, as in Word. - for mut it in fit_box(inner, rect.h - 2.0 * BOX_INSET_Y) { - it.translate(rect.x + BOX_INSET_X, rect.y + BOX_INSET_Y); - layer.push(it); + // Its text (a group: its text boxes'), unless the box budget says no (a box inside + // itself, too deep, too many). + let boxes: Vec<(u32, Rect)> = match obj { + InlineObject::Group { .. } => group_members(obj, rect) + .into_iter() + .filter_map(|(r, c)| { + c.text_box().filter(|id| ctx.doc.parts.get(id).is_some_and(|p| p.kind == wordcraft_doc::PartKind::TextBox)).map(|id| (id, r)) + }) + .collect(), + _ => text_box.map(|id| (id, rect)).into_iter().collect(), + }; + for (id, rect) in boxes { + if !ctx.boxes.enter(id) { + continue; + } + let blocks = ctx.doc.parts.get(&id).map(|p| p.blocks.clone()).unwrap_or_default(); + let (inner, _) = layout_box(ctx, StoryRef::Part(id), &blocks, &[], (rect.w - 2.0 * BOX_INSET_X).max(12.0), None, depth + 1, None); + ctx.boxes.leave(); + let layer = if float.wrap == Wrap::BehindText { &mut behind } else { &mut front }; + // Text that doesn't fit inside the margins is hidden, as in Word. + for mut it in fit_box(inner, rect.h - 2.0 * BOX_INSET_Y) { + it.translate(rect.x + BOX_INSET_X, rect.y + BOX_INSET_Y); + layer.push(it); + } } } } @@ -1161,12 +1179,14 @@ fn place_objects( /// (on the box's cluster), as (cluster, note id). fn para_notes(doc: &Document, p: &Paragraph, pl: &ParaLayout) -> Vec<(usize, u32)> { let mut notes = pl.notes.clone(); - if p.objects.iter().any(|o| matches!(o, InlineObject::Shape { story: Some(_), .. })) { + if p.objects.iter().any(|o| !o.text_boxes().is_empty()) { for (ci, c) in pl.clusters.iter().enumerate() { if let para::ClKind::Object(oi) = c.kind - && let Some(InlineObject::Shape { story: Some(id), .. }) = p.objects.get(oi) + && let Some(o) = p.objects.get(oi) { - notes.extend(doc.notes_in_text_box(*id).into_iter().map(|n| (ci, n))); + for id in o.text_boxes() { + notes.extend(doc.notes_in_text_box(id).into_iter().map(|n| (ci, n))); + } } } } @@ -1611,10 +1631,7 @@ fn headers_footers(ctx: &mut Ctx, pages: &mut [Page], sections: &[(usize, &Secti /// Is an object floating (not laid out inline)? pub fn is_floating(o: &InlineObject) -> bool { - match o { - InlineObject::Image { float, .. } | InlineObject::Shape { float, .. } => float.wrap != Wrap::Inline, - _ => false, - } + o.is_floating() } /// Milliseconds since an arbitrary epoch (monotonic on native; the browser's clock on the web). diff --git a/crates/layout/src/para.rs b/crates/layout/src/para.rs index 9d30c22408..8003dcd5af 100644 --- a/crates/layout/src/para.rs +++ b/crates/layout/src/para.rs @@ -713,8 +713,10 @@ pub fn layout_para(p: &Paragraph, env: &ParaEnv) -> ParaLayout { let k = obj_index; obj_index += 1; match p.objects.get(k) { - Some(InlineObject::Image { w, h, float, .. }) | Some(InlineObject::Shape { w, h, float, .. }) => { - if float.wrap == wordcraft_doc::para::Wrap::Inline { + Some(o) if o.is_drawing() => { + if let Some((w, h, float)) = o.frame() + && float.wrap == wordcraft_doc::para::Wrap::Inline + { let maxw = (env.width - rp.indent_left.max(0.0) - rp.indent_right.max(0.0)).max(18.0); let (w, h) = (w.clamp(1.0, 4000.0), h.clamp(1.0, 4000.0)); let s = if w > maxw { maxw / w } else { 1.0 }; diff --git a/crates/ui-egui/src/i18n/es.tsv b/crates/ui-egui/src/i18n/es.tsv index 7427c5daac..4cf57387cd 100644 --- a/crates/ui-egui/src/i18n/es.tsv +++ b/crates/ui-egui/src/i18n/es.tsv @@ -24,6 +24,7 @@ Accept This Change Aceptar este cambio Accessibility Accesibilidad Add Añadir + Add Object to Selection Añadir objeto a la selección Add Space Before Paragraph Añadir espacio antes del párrafo Add Text Añadir texto Add a Table Añadir una tabla @@ -730,6 +731,7 @@ Two Dos Type Text Escribir texto Type a command, e.g. "insert table" Escribe un comando, p. ej. "insertar tabla" + Ungroup Desagrupar UPPERCASE MAYÚSCULAS Underline Subrayado Underline Words Only Subrayar solo las palabras diff --git a/crates/ui-egui/src/i18n/ja.tsv b/crates/ui-egui/src/i18n/ja.tsv index 1f0b0435d9..a397359587 100644 --- a/crates/ui-egui/src/i18n/ja.tsv +++ b/crates/ui-egui/src/i18n/ja.tsv @@ -12,6 +12,7 @@ Add 追加 Add a comment コメントを追加 Add a Table 表を追加 + Add Object to Selection オブジェクトを選択範囲に追加 Add Space Before Paragraph 段落前に間隔を追加 Add Text テキストの追加 Add to Dictionary 辞書に追加 @@ -735,6 +736,7 @@ Underline Words Only 単語のみ下線 Undo 元に戻す Undo {action} 元に戻す: {action} + Ungroup グループ解除 Up 上 Update Field フィールドの更新 Update Index 索引の更新 diff --git a/crates/ui-egui/src/i18n/pt-br.tsv b/crates/ui-egui/src/i18n/pt-br.tsv index 1ea724d662..91550fc9d9 100644 --- a/crates/ui-egui/src/i18n/pt-br.tsv +++ b/crates/ui-egui/src/i18n/pt-br.tsv @@ -23,6 +23,7 @@ Add Adicionar Add a comment Adicionar um comentário Add a Table Adicionar uma tabela + Add Object to Selection Adicionar objeto à seleção Add Space Before Paragraph Adicionar espaço antes do parágrafo Add Text Adicionar texto Add to Dictionary Adicionar ao dicionário @@ -735,6 +736,7 @@ Underline Words Only Sublinhar somente palavras Undo Desfazer Undo {action} Desfazer {action} + Ungroup Desagrupar Up Para cima Update Field Atualizar campo Update Index Atualizar índice diff --git a/crates/ui-egui/src/i18n/uk.tsv b/crates/ui-egui/src/i18n/uk.tsv index 39302d0abd..e391b9c416 100644 --- a/crates/ui-egui/src/i18n/uk.tsv +++ b/crates/ui-egui/src/i18n/uk.tsv @@ -23,6 +23,7 @@ Add Додати Add a comment Додати коментар Add a Table Додати таблицю + Add Object to Selection Додати об'єкт до виділення Add Space Before Paragraph Додати інтервал перед абзацом Add Text Додати текст Add to Dictionary Додати до словника @@ -735,6 +736,7 @@ Underline Words Only Підкреслити лише слова Undo Скасувати Undo {action} Скасувати {action} + Ungroup Розгрупувати Up Угору Update Field Оновити поле Update Index Оновити покажчик diff --git a/crates/ui-egui/src/i18n/zh-hans.tsv b/crates/ui-egui/src/i18n/zh-hans.tsv index efd65d7c8c..4dffc2e8e6 100644 --- a/crates/ui-egui/src/i18n/zh-hans.tsv +++ b/crates/ui-egui/src/i18n/zh-hans.tsv @@ -23,6 +23,7 @@ Add 添加 Add a comment 添加批注 Add a Table 添加表格 + Add Object to Selection 将对象添加到所选内容 Add Space Before Paragraph 在段前添加间距 Add Text 添加文字 Add to Dictionary 添加到词典 @@ -746,6 +747,7 @@ Underline Words Only 仅给字词加下划线 Undo 撤消 Undo {action} 撤消{action} + Ungroup 取消组合 Up 上 Update Field 更新域 Update Index 更新索引 diff --git a/crates/ui-egui/src/i18n/zh-hant.tsv b/crates/ui-egui/src/i18n/zh-hant.tsv index 17bb0c6c0d..9ca40e4759 100644 --- a/crates/ui-egui/src/i18n/zh-hant.tsv +++ b/crates/ui-egui/src/i18n/zh-hant.tsv @@ -13,6 +13,7 @@ Add 新增 Add a comment 新增註解 Add a Table 新增表格 + Add Object to Selection 將物件加入選取範圍 Add Space Before Paragraph 在段落前新增間距 Add Text 新增文字 Add to Dictionary 新增至字典 @@ -736,6 +737,7 @@ Underline Words Only 只在文字下加底線 Undo 復原 Undo {action} 復原{action} + Ungroup 取消群組 Up 上 Update Field 更新功能變數 Update Index 更新索引 diff --git a/crates/ui-egui/src/objects.rs b/crates/ui-egui/src/objects.rs index 3538efef70..7cd9772149 100644 --- a/crates/ui-egui/src/objects.rs +++ b/crates/ui-egui/src/objects.rs @@ -86,6 +86,12 @@ pub fn pointer(app: &mut WordApp, ui: &Ui, resp: &egui::Response, pages: &[Rect] return false; } let Some((object, grab)) = grab_at(app, layout, pages, scale, at) else { return false }; + // Shift/Ctrl+click adds an object to the selected ones (or takes it out), for Group. + let adding = ui.input(|i| i.modifiers.shift || i.modifiers.command); + if pressed && adding && grab == Grab::Move && selected(app).is_some() { + let _ = app.run("select.addObject", json!({"pos": object.pos()})); + return true; + } if pressed { let pos = object.pos(); let end = Pos { off: pos.off + OBJ.len_utf8(), ..pos.clone() }; @@ -153,6 +159,12 @@ pub fn paint(app: &WordApp, painter: &Painter, t: &Tokens, layout: &DocLayout, p frame::paint(painter, t, to, false, false); return; } + // The others selected along with it (Shift+click): their outlines. + for p in &app.session.also_selected { + if let Some(f) = layout.object(p, app.session.page_hint).and_then(|o| screen(pages, scale, o.page, o.rect)) { + frame::paint(painter, t, f, false, false); + } + } if let Some((o, editing)) = active(app, layout) && let Some(f) = screen(pages, scale, o.page, o.rect) { diff --git a/crates/ui-egui/src/ribbon.rs b/crates/ui-egui/src/ribbon.rs index 7e592dfb77..0cf2c76981 100644 --- a/crates/ui-egui/src/ribbon.rs +++ b/crates/ui-egui/src/ribbon.rs @@ -773,12 +773,20 @@ fn layout(app: &mut WordApp, ui: &mut Ui) { }); stack(ui, |ui| { small(ui, app, "align", None, "Align", "arrange.align", json!({}), false); - small(ui, app, "group", None, "Group", "arrange.group", json!({}), false); + group_menu(ui, app, None); small(ui, app, "rotate", None, "Rotate", "arrange.rotate", json!({}), false); }); }); } +/// Arrange › Group: Group (Shift+click objects to select several) and Ungroup. +fn group_menu(ui: &mut Ui, app: &mut WordApp, label: Option<&str>) { + menu_button(ui, app, "group", label, "Group", false, |ui, app| { + mi(ui, app, "Group", "arrange.group", json!({})); + mi(ui, app, "Ungroup", "arrange.ungroup", json!({})); + }); +} + fn references(app: &mut WordApp, ui: &mut Ui) { group(ui, "Table of Contents", None, app, |ui, app| { menu_button(ui, app, "toc", Some("Table of\nContents"), "Table of Contents", true, |ui, app| { @@ -1099,6 +1107,7 @@ fn picture_format(app: &mut WordApp, ui: &mut Ui) { stack(ui, |ui| { small(ui, app, "rotate", Some("Rotate"), "Rotate", "arrange.rotate", json!({}), false); small(ui, app, "align", Some("Align"), "Align", "arrange.align", json!({}), false); + group_menu(ui, app, Some("Group")); }); }); group(ui, "Size", None, app, |ui, app| { diff --git a/docs/parity.md b/docs/parity.md index afb626964c..3411fad1c0 100644 --- a/docs/parity.md +++ b/docs/parity.md @@ -2,7 +2,7 @@ Generated by `cargo xtask parity` (`wordcraft-cli parity --markdown`): the word-processor feature catalog (`crates/engine/src/catalog.rs`) compared with the live command registry. -**378 of 428 catalog features have commands (88.3%).** +**379 of 428 catalog features have commands (88.6%).** | Tab | Live | Total | |---|---|---| @@ -12,7 +12,7 @@ Generated by `cargo xtask parity` (`wordcraft-cli parity --markdown`): the word- | Insert | 42 | 53 | | Draw | 0 | 11 | | Design | 10 | 10 | -| Layout | 18 | 19 | +| Layout | 19 | 19 | | References | 24 | 24 | | Mailings | 17 | 17 | | Review | 26 | 29 | @@ -68,10 +68,6 @@ Generated by `cargo xtask parity` (`wordcraft-cli parity --markdown`): the word- - Insert › Drawing Canvas (`insert.canvas`) - Replay › Ink Replay (`draw.replay`) -### Layout - -- Arrange › Group (`arrange.group`) - ### Review - Language › Translate (`review.translate`)