mirror of
https://github.com/storytold/craft-libs.git
synced 2026-11-17 15:55:14 +00:00
craft-docx: a frame preset shape is a border with a hole
Moves the format part of storytold/wordcraft#6162 into craft-wordmodel, craft-docx, craft-flow and craft-odf, where WordCraft's DOCX and ODT I/O now live (#778). A DrawingML `prstGeom frame` (a letterhead's page border) was read as a rectangle, so its fill covered the whole page behind the text. It is now ShapeKind::Frame, its border width read from `adj1` (capped, as a rounded rectangle's corner is) and written back as the same preset. connector::frame_width gives the border in points. Formats with no frame shape (ODT and the other flow formats) get the freeform it draws: its outline and, wound the other way, its hole, so the hole stays empty under either fill rule.
This commit is contained in:
1 parent
44d83fa8f6
commit
8b876291a1
10 files changed
+130
-9
No files matched your search
@@ -47,6 +47,7 @@ pub(crate) fn preset_kind(prst: &str) -> ShapeKind {
|
||||
"downArrow" => ShapeKind::ArrowDown,
|
||||
"star4" | "star5" | "star6" | "star7" | "star8" | "star10" | "star12" | "star16" | "star24" | "star32" => ShapeKind::Star,
|
||||
"heart" => ShapeKind::Heart,
|
||||
"frame" => ShapeKind::Frame,
|
||||
_ => ShapeKind::Rectangle,
|
||||
}
|
||||
}
|
||||
|
||||
@@ -526,12 +526,17 @@ impl Reader<'_> {
|
||||
outline_fill: paint.outline_fill,
|
||||
..ShapeExtra::default()
|
||||
};
|
||||
// A rounded rectangle's own corner (`adj`, ECMA-376 §20.1.10.56); other presets drawn as
|
||||
// rounded rectangles keep the default.
|
||||
if prst == "roundRect" {
|
||||
// A rounded rectangle's own corner (`adj`, ECMA-376 §20.1.10.56), a frame's own border
|
||||
// width (`adj1`); other presets drawn as rounded rectangles keep the default.
|
||||
let adj = match prst {
|
||||
"roundRect" => Some("adj"),
|
||||
"frame" => Some("adj1"),
|
||||
_ => None,
|
||||
};
|
||||
if let Some(adj) = adj {
|
||||
extra.corner = sppr
|
||||
.and_then(|s| s.child("a:prstGeom"))
|
||||
.and_then(|g| preset_adj(g, "adj"))
|
||||
.and_then(|g| preset_adj(g, adj))
|
||||
.and_then(|v| u32::try_from(v.clamp(0, i64::from(craft_wordmodel::connector::MAX_CORNER))).ok());
|
||||
}
|
||||
// Arrowheads: any end type but `none` (ECMA-376 §20.1.10.33) is drawn as a triangle of its
|
||||
|
||||
@@ -117,16 +117,22 @@ impl Writer<'_> {
|
||||
ShapeKind::ArrowDown => "downArrow",
|
||||
ShapeKind::Star => "star5",
|
||||
ShapeKind::Heart => "heart",
|
||||
ShapeKind::Frame => "frame",
|
||||
};
|
||||
match geom {
|
||||
Some(f) => cust_geom(w, f, *sw, *sh),
|
||||
None => {
|
||||
w.open("a:prstGeom", &[("prst", prst)]);
|
||||
match extra.corner.filter(|_| *kind == ShapeKind::RoundedRectangle) {
|
||||
Some(c) => {
|
||||
let adj = match kind {
|
||||
ShapeKind::RoundedRectangle => Some("adj"),
|
||||
ShapeKind::Frame => Some("adj1"),
|
||||
_ => None,
|
||||
};
|
||||
match adj.zip(extra.corner) {
|
||||
Some((name, c)) => {
|
||||
w.open("a:avLst", &[]);
|
||||
let fmla = format!("val {}", c.min(craft_wordmodel::connector::MAX_CORNER));
|
||||
w.empty("a:gd", &[("name", "adj"), ("fmla", &fmla)]);
|
||||
w.empty("a:gd", &[("name", name), ("fmla", &fmla)]);
|
||||
w.close("a:avLst");
|
||||
}
|
||||
None => w.empty("a:avLst", &[]),
|
||||
|
||||
@@ -2729,6 +2729,39 @@ fn rounded_rectangle_corners_are_read_and_saved() {
|
||||
assert_eq!(corners(&craft_docx::read(&bytes).unwrap()), expected);
|
||||
}
|
||||
|
||||
/// A `frame` preset (a letterhead's page border) is a frame, not a filled rectangle: its border
|
||||
/// width is its `adj1`, read, capped and written back as the same preset.
|
||||
#[test]
|
||||
fn frame_presets_keep_their_hole_and_border_width() {
|
||||
let geom =
|
||||
|av: &str| format!(r#"<a:prstGeom prst="frame"><a:avLst>{av}</a:avLst></a:prstGeom><a:solidFill><a:srgbClr val="E3AB48"/></a:solidFill>"#);
|
||||
let gd = |fmla: &str| format!(r#"<a:gd name="adj1" fmla="{fmla}"/>"#);
|
||||
let body = [geom(&gd("val 2604")), geom(""), geom(&gd("val 90000")), geom(r#"<a:gd name="adj" fmla="val 100"/>"#)]
|
||||
.iter()
|
||||
.map(|sppr| anchored_wsp("Frame", 2540000, 1270000, sppr, "", "<wps:cNvSpPr/>"))
|
||||
.collect::<String>();
|
||||
let frames = |d: &Document| -> Vec<(ShapeKind, Option<u32>)> {
|
||||
paras(d)[0]
|
||||
.objects
|
||||
.iter()
|
||||
.filter_map(|o| match o {
|
||||
InlineObject::Shape { kind, extra, .. } => Some((*kind, extra.corner)),
|
||||
_ => None,
|
||||
})
|
||||
.collect()
|
||||
};
|
||||
let f = ShapeKind::Frame;
|
||||
let expected = vec![(f, Some(2604)), (f, None), (f, Some(50_000)), (f, None)];
|
||||
let d = read_body(&format!("<w:p>{body}</w:p>"));
|
||||
assert_eq!(frames(&d), expected);
|
||||
let bytes = craft_docx::write(&d).unwrap();
|
||||
let mut xml = String::new();
|
||||
let mut zip = zip::ZipArchive::new(std::io::Cursor::new(bytes.as_slice())).unwrap();
|
||||
std::io::Read::read_to_string(&mut zip.by_name("word/document.xml").unwrap(), &mut xml).unwrap();
|
||||
assert!(xml.contains(r#"<a:prstGeom prst="frame"><a:avLst><a:gd name="adj1" fmla="val 2604"/></a:avLst></a:prstGeom>"#), "{xml}");
|
||||
assert_eq!(frames(&craft_docx::read(&bytes).unwrap()), expected);
|
||||
}
|
||||
|
||||
/// #611: legacy VML lines and rectangles (documents without DrawingML).
|
||||
#[test]
|
||||
fn vml_lines_and_rectangles() {
|
||||
|
||||
@@ -342,6 +342,20 @@ fn rich_inlines(doc: &Document, o: &InlineObject, f: &Fmt, opts: FlowOpts) -> Op
|
||||
})
|
||||
}
|
||||
|
||||
/// The freeform a `w` × `h` frame shape with border `corner` (see
|
||||
/// [`craft_wordmodel::connector::frame_width`]) draws: its outline clockwise and its hole the
|
||||
/// other way, so the hole stays empty under either fill rule.
|
||||
fn frame_freeform(corner: Option<u32>, w: f32, h: f32) -> craft_wordmodel::freeform::Freeform {
|
||||
use craft_wordmodel::freeform::{FreePath, Freeform};
|
||||
let (w, h) = (craft_wordmodel::geom::finite(w).max(0.0), craft_wordmodel::geom::finite(h).max(0.0));
|
||||
let t = craft_wordmodel::connector::frame_width(corner, w, h);
|
||||
let mut paths = vec![FreePath { pts: vec![[0.0, 0.0], [w, 0.0], [w, h], [0.0, h]], closed: true }];
|
||||
if w - 2.0 * t > 0.0 && h - 2.0 * t > 0.0 {
|
||||
paths.push(FreePath { pts: vec![[t, t], [t, h - t], [w - t, h - t], [w - t, t]], closed: true });
|
||||
}
|
||||
Freeform { w, h, paths, ..Default::default() }
|
||||
}
|
||||
|
||||
/// Comment `c` (a reply to `parent`) of `doc` as a flow comment: its text holds no comments or
|
||||
/// notes of its own.
|
||||
/// The flow inline for picture, shape or group `o` of `doc` (a member of groups `depth` deep),
|
||||
@@ -358,8 +372,12 @@ fn drawing_inline(doc: &Document, o: &InlineObject, opts: FlowOpts, depth: usize
|
||||
{
|
||||
// A connector stays one in formats that glue them (ODT, with boxes); elsewhere it is a
|
||||
// straight line.
|
||||
// A frame (a border with a hole), which the other formats have no shape for, is the
|
||||
// freeform it draws: its outline and, wound the other way, its hole.
|
||||
let frame = (*kind == ShapeKind::Frame).then(|| std::sync::Arc::new(frame_freeform(extra.corner, *w, *h)));
|
||||
let kind = match kind {
|
||||
ShapeKind::StraightConnector | ShapeKind::ElbowConnector | ShapeKind::CurvedConnector if !opts.boxes => ShapeKind::Line,
|
||||
ShapeKind::Frame => ShapeKind::Freeform,
|
||||
k => *k,
|
||||
};
|
||||
let inner = FlowOpts { notes: false, comments: false, boxes: false, ..opts };
|
||||
@@ -383,7 +401,7 @@ fn drawing_inline(doc: &Document, o: &InlineObject, opts: FlowOpts, depth: usize
|
||||
Box::new(crate::Chain { name: format!("Frame{id}"), next })
|
||||
}),
|
||||
};
|
||||
let path = freeform.clone().filter(|_| kind == ShapeKind::Freeform);
|
||||
let path = frame.or_else(|| freeform.clone()).filter(|_| kind == ShapeKind::Freeform);
|
||||
Some(Inline::Shape { kind, w: w * sx, h: h * sy, float: kept_float(float), blocks, look, path })
|
||||
}
|
||||
InlineObject::Image { media, w, h, alt, float, ole, crop, .. } => {
|
||||
|
||||
@@ -124,7 +124,8 @@ pub(super) fn element_of(kind: ShapeKind) -> (&'static str, Option<&'static str>
|
||||
ShapeKind::ArrowDown => custom("down-arrow"),
|
||||
ShapeKind::Star => custom("star5"),
|
||||
ShapeKind::Heart => custom("heart"),
|
||||
ShapeKind::Freeform => ("draw:path", None),
|
||||
// A frame reaches the writer as the freeform it draws (see `model::from_doc`).
|
||||
ShapeKind::Freeform | ShapeKind::Frame => ("draw:path", None),
|
||||
ShapeKind::Rectangle | ShapeKind::TextBox => ("draw:rect", None),
|
||||
}
|
||||
}
|
||||
|
||||
@@ -188,3 +188,44 @@ fn a_shape_with_only_an_empty_paragraph_has_no_text() {
|
||||
let stories: Vec<bool> = d.body.iter().filter_map(|b| b.as_para()).flat_map(|p| p.objects.iter()).map(|o| o.text_box().is_some()).collect();
|
||||
assert_eq!(stories, [false, false, true, false, false, false]);
|
||||
}
|
||||
|
||||
/// A frame shape (a letterhead's page border, from DOCX `frame`), which ODT has no shape for,
|
||||
/// is written as the outline it draws: its outer edge and its hole, so LibreOffice doesn't fill
|
||||
/// the whole box; read back, it is that freeform, hole and all.
|
||||
#[test]
|
||||
fn a_frame_shape_is_written_as_a_border_with_a_hole() {
|
||||
let mut p = Paragraph::new();
|
||||
p.text.push(OBJ);
|
||||
p.objects.push(InlineObject::Shape {
|
||||
kind: ShapeKind::Frame,
|
||||
w: 200.0,
|
||||
h: 100.0,
|
||||
fill: Some(craft_wordmodel::fill::Fill::solid(Rgb(1, 2, 3))),
|
||||
stroke: None,
|
||||
stroke_width: 0.0,
|
||||
float: Default::default(),
|
||||
story: None,
|
||||
freeform: None,
|
||||
effects: Default::default(),
|
||||
// A border a tenth of the shorter side: 10 pt.
|
||||
extra: craft_wordmodel::connector::ShapeExtra { corner: Some(10_000), ..Default::default() },
|
||||
});
|
||||
p.runs = vec![craft_wordmodel::para::Run { len: p.text.len(), props: Default::default() }];
|
||||
let mut d = Document::new();
|
||||
d.body = vec![para_block(p)];
|
||||
let odt = export(&d).unwrap();
|
||||
let content = content_of(&odt);
|
||||
assert!(content.contains("<draw:path"), "{content}");
|
||||
let back = import(&odt).unwrap();
|
||||
let Some(InlineObject::Shape { kind, freeform, fill, .. }) = back.body[0].as_para().and_then(|p| p.objects.first()) else {
|
||||
panic!("the frame comes back as a shape");
|
||||
};
|
||||
assert_eq!(*kind, ShapeKind::Freeform);
|
||||
assert!(fill.is_some(), "it stays filled");
|
||||
let f = freeform.as_deref().unwrap();
|
||||
assert_eq!(f.paths.len(), 2, "its outline and its hole: {f:?}");
|
||||
// The hole starts 10 pt in, in the freeform's own coordinates.
|
||||
let hole = &f.paths[1];
|
||||
let (sx, sy) = (f.w / 200.0, f.h / 100.0);
|
||||
assert!(hole.pts.iter().all(|[x, y]| *x >= 9.5 * sx && *x <= 190.5 * sx && *y >= 9.5 * sy && *y <= 90.5 * sy), "{hole:?}");
|
||||
}
|
||||
@@ -201,6 +201,8 @@ pub struct ShapeExtra {
|
||||
pub end_style: ArrowStyle,
|
||||
/// A rounded rectangle's corner radius (`roundRect`'s `adj`, ECMA-376 §20.1.10.56): in
|
||||
/// 100000ths of the shorter side, at most [`MAX_CORNER`]; `None` draws [`DEFAULT_CORNER`].
|
||||
/// A [`ShapeKind::Frame`]'s border width (`frame`'s `adj1`), in the same units; `None`
|
||||
/// draws [`DEFAULT_FRAME`].
|
||||
#[serde(skip_serializing_if = "Option::is_none")]
|
||||
pub corner: Option<u32>,
|
||||
/// The outline dash pattern; absent in older saved documents means solid.
|
||||
@@ -273,6 +275,16 @@ pub const MAX_CORNER: u32 = 50_000;
|
||||
/// A rounded rectangle's corner radius without its own: 16% of the shorter side.
|
||||
pub const DEFAULT_CORNER: f32 = 0.16;
|
||||
|
||||
/// A frame's border width without its own: `frame`'s default `adj1`, 12.5% of the shorter side.
|
||||
pub const DEFAULT_FRAME: f32 = 0.125;
|
||||
|
||||
/// The border width, in points, of a `w` × `h` [`ShapeKind::Frame`] with `corner` (see
|
||||
/// [`ShapeExtra::corner`]): at most half the shorter side, which leaves no hole.
|
||||
pub fn frame_width(corner: Option<u32>, w: f32, h: f32) -> f32 {
|
||||
let side = crate::geom::finite(w).min(crate::geom::finite(h)).max(0.0);
|
||||
side * corner.map_or(DEFAULT_FRAME, |c| c.min(MAX_CORNER) as f32 / 100_000.0)
|
||||
}
|
||||
|
||||
/// The corner radius, in points, of a `w` × `h` rounded rectangle with `corner` (see
|
||||
/// [`ShapeExtra::corner`]).
|
||||
pub fn corner_radius(corner: Option<u32>, w: f32, h: f32) -> f32 {
|
||||
|
||||
@@ -24,6 +24,9 @@ pub enum ShapeKind {
|
||||
ArrowDown,
|
||||
Star,
|
||||
Heart,
|
||||
/// A picture frame (DrawingML's `frame`): a rectangle with a rectangular hole, its border as
|
||||
/// wide as [`crate::connector::frame_width`] says.
|
||||
Frame,
|
||||
/// A text box (rectangle with a text story).
|
||||
TextBox,
|
||||
/// A shape drawn point by point, such as ink (its geometry is the shape's `freeform`).
|
||||
|
||||
@@ -70,6 +70,7 @@ pub fn shape_outline(kind: ShapeKind, w: f32, h: f32, corner: Option<u32>) -> Op
|
||||
| ShapeKind::TextBox
|
||||
| ShapeKind::Line
|
||||
| ShapeKind::Freeform
|
||||
| ShapeKind::Frame
|
||||
| ShapeKind::StraightConnector
|
||||
| ShapeKind::ElbowConnector
|
||||
| ShapeKind::CurvedConnector => return None,
|
||||
|
||||
Reference in new issue
Block a user