mirror of
https://github.com/storytold/craft-libs.git
synced 2026-11-25 15:44:29 +00:00
craft-rtf: read text boxes and drawing shapes from \shpinst (#2059)
Ported from storytold/wordcraft#6242 (issue storytold/wordcraft#6212), written before the RTF reader moved here. Rectangles, ellipses, triangles, diamonds, block arrows and text boxes are read from the shape's properties (position, size, wrap, fill, line, text); the \defshp picture Word writes after a shape it read, also inside \shppict, is not imported as a second copy. Co-authored-by: Mauro Mazzieri <mauro.mazzieri@talete.net>
This commit is contained in:
co-authored by
Mauro Mazzieri
parent
a19d58c5f6
commit
5bd7eb9e88
+10
-3
@@ -27,9 +27,13 @@
|
||||
//! `\fldlock` locking it, and `\chpgn` is a `PAGE` field; otherwise a field is its result's text),
|
||||
//! bookmarks, pictures and
|
||||
//! tables, footnotes, endnotes (`\footnote` with `\ftnalt`) and comments (author, initials, date,
|
||||
//! text, the commented range). Group nesting, picture sizes and the number of notes and comments
|
||||
//! are capped. Not kept: custom note marks, comment replies (`\atnparent`), notes inside
|
||||
//! headers, footers and other notes, tables inside note and comment texts (flattened).
|
||||
//! text, the commented range), drawing shapes and text boxes (`\shp`: rectangles, ellipses,
|
||||
//! triangles, diamonds, block arrows and text boxes from `\shpinst`, with their place, wrapping,
|
||||
//! fill, outline and text; their `\shprslt` copy and the `\defshp` picture after them are
|
||||
//! skipped). Group nesting, picture sizes and the number of notes and comments are capped. Not
|
||||
//! kept: custom note marks, comment replies (`\atnparent`), notes inside headers, footers, text
|
||||
//! boxes and other notes, tables inside note and comment texts (flattened). Pictures, lines and
|
||||
//! shapes in a group (`\shpgrp`) are read from their `\shprslt` copy.
|
||||
|
||||
use std::collections::{HashMap, HashSet};
|
||||
use std::sync::Arc;
|
||||
@@ -44,6 +48,7 @@ mod export;
|
||||
mod field;
|
||||
mod parse;
|
||||
mod reader;
|
||||
mod shape;
|
||||
mod state;
|
||||
mod styles;
|
||||
mod text;
|
||||
@@ -64,3 +69,5 @@ use word::hyperlink;
|
||||
mod tests;
|
||||
#[cfg(test)]
|
||||
mod tests_fields;
|
||||
#[cfg(test)]
|
||||
mod tests_shapes;
|
||||
|
||||
@@ -30,7 +30,8 @@ struct Parsed {
|
||||
}
|
||||
|
||||
/// `marks`: also read footnotes, endnotes and comments (as place markers in the flow's text, for
|
||||
/// [`import`] to turn into objects); without it they are skipped.
|
||||
/// [`import`] to turn into objects), and drawing shapes and text boxes; without it they are
|
||||
/// skipped.
|
||||
fn parse_full(bytes: &[u8], marks: bool) -> Result<Parsed, String> {
|
||||
let start = bytes.iter().position(|b| !b.is_ascii_whitespace()).unwrap_or(0);
|
||||
if !bytes.get(start..).is_some_and(|b| b.starts_with(b"{\\rtf")) {
|
||||
@@ -38,6 +39,7 @@ fn parse_full(bytes: &[u8], marks: bool) -> Result<Parsed, String> {
|
||||
}
|
||||
let mut r = Reader::default();
|
||||
r.marks_on = marks;
|
||||
r.boxes_on = marks;
|
||||
let mut i = start;
|
||||
let mut first_in_group = false;
|
||||
let mut starred = false;
|
||||
@@ -236,6 +238,7 @@ fn finalize(mut r: Reader) -> Parsed {
|
||||
// truncated file.
|
||||
r.finish_multibyte();
|
||||
r.end_sub();
|
||||
r.end_shape_text();
|
||||
r.end_header_footer();
|
||||
if r.para_has || !r.para.inlines.is_empty() {
|
||||
r.end_para(false);
|
||||
|
||||
@@ -11,7 +11,7 @@ use crate::date::{dttm_to_iso, iso_date};
|
||||
pub(super) struct Reader {
|
||||
pub(super) st: St,
|
||||
stack: Vec<St>,
|
||||
overflow: usize,
|
||||
pub(super) overflow: usize,
|
||||
pub(super) fonts: HashMap<i32, Arc<str>>,
|
||||
pub(super) font_cur: i32,
|
||||
pub(super) font_name: String,
|
||||
@@ -114,6 +114,17 @@ pub(super) struct Reader {
|
||||
pub(super) range_ends: HashSet<i32>,
|
||||
pub(super) claimed: HashSet<i32>,
|
||||
pub(super) synth: i32,
|
||||
/// Drawing shapes and text boxes (only when the caller wants them), and the one being read.
|
||||
pub(super) boxes_on: bool,
|
||||
pub(super) shape: Option<Box<super::shape::ShapeSt>>,
|
||||
/// The depth of the group the last shape closed in, when it was read (the picture of it Word
|
||||
/// writes right after it is not a picture of its own); whether the picture being read follows
|
||||
/// it, and whether it is marked `\defshp`.
|
||||
pub(super) shape_read_at: Option<usize>,
|
||||
pub(super) pict_after_shape: bool,
|
||||
/// The depth of the open `\*\shppict` group: a picture in it stands where the group does.
|
||||
pub(super) shppict_at: Option<usize>,
|
||||
pub(super) pict_defshp: bool,
|
||||
}
|
||||
|
||||
impl Reader {
|
||||
@@ -123,7 +134,7 @@ impl Reader {
|
||||
|
||||
/// Set the output aside (a header or footer starts) or put it back (it ended), returning the
|
||||
/// other one.
|
||||
fn swap_output(&mut self, mut o: Output) -> Output {
|
||||
pub(super) fn swap_output(&mut self, mut o: Output) -> Output {
|
||||
std::mem::swap(&mut o.body, &mut self.body);
|
||||
std::mem::swap(&mut o.para, &mut self.para);
|
||||
std::mem::swap(&mut o.para_has, &mut self.para_has);
|
||||
@@ -177,7 +188,8 @@ impl Reader {
|
||||
|
||||
/// A footnote, endnote or comment group starts: read it into an output of its own.
|
||||
pub(super) fn start_sub(&mut self, comment: bool) {
|
||||
if self.overflow > 0 || self.notes.len() >= MAX_NOTES || self.comments.len() >= MAX_NOTES {
|
||||
// A note in a text box's text is not kept (it would have no place in the body).
|
||||
if self.overflow > 0 || self.notes.len() >= MAX_NOTES || self.comments.len() >= MAX_NOTES || self.in_shape_text() {
|
||||
self.st.dest = Dest::Skip;
|
||||
return;
|
||||
}
|
||||
@@ -348,6 +360,9 @@ impl Reader {
|
||||
if self.sub.as_ref().is_some_and(|s| s.depth == self.depth()) {
|
||||
self.end_sub();
|
||||
}
|
||||
if self.closes_shape_text() {
|
||||
self.end_shape_text();
|
||||
}
|
||||
self.close_field_group();
|
||||
let closing = self.st.dest;
|
||||
// Destination-level commits.
|
||||
@@ -368,6 +383,8 @@ impl Reader {
|
||||
self.in_creatim = false;
|
||||
}
|
||||
Dest::Atn(k) => self.commit_atn(k),
|
||||
Dest::ShpSv => self.commit_shape_prop(),
|
||||
Dest::ShpInst if self.closes_shape_inst() => self.finish_shape(),
|
||||
_ => {}
|
||||
}
|
||||
let Some(mut prev) = self.stack.pop() else { return };
|
||||
@@ -403,6 +420,7 @@ impl Reader {
|
||||
}
|
||||
}
|
||||
self.st = prev;
|
||||
self.after_shape_group();
|
||||
if self.hf.as_ref().is_some_and(|(d, _, _)| self.depth() < *d) {
|
||||
self.end_header_footer();
|
||||
}
|
||||
|
||||
@@ -0,0 +1,419 @@
|
||||
//! Drawing shapes and text boxes (`\shp`, #6212). Word describes a shape in `\shpinst`: its
|
||||
//! place (`\shpleft`… in twips, against `\shpbx…`/`\shpby…` or the `posrelh`/`posrelv`
|
||||
//! properties), its wrapping (`\shpwr`, `\shpwrk`, `\shpfblwtxt`), its `\sp` name/value
|
||||
//! properties and a text box's text (`\shptxt`); `\shprslt` holds a copy for readers without
|
||||
//! shapes. A shape whose type is known here is read from `\shpinst` and its `\shprslt` skipped;
|
||||
//! any other (pictures, lines, shapes in a group) keeps the copy, as before.
|
||||
|
||||
use craft_wordmodel::fill::Fill;
|
||||
use craft_wordmodel::para::{Anchor, Float, FloatAlign, ShapeKind, Wrap, WrapText};
|
||||
|
||||
use super::reader::Reader;
|
||||
use super::state::{Dest, MAX_NOTE_BLOCKS, Output};
|
||||
use super::{FBlock, Inline, Rgb, model};
|
||||
|
||||
/// Most characters kept of a property's name or value (hostile input).
|
||||
const MAX_PROP: usize = 64;
|
||||
|
||||
/// Twips in a point, and EMUs in a point.
|
||||
const TWIPS: f32 = 20.0;
|
||||
const EMUS: f32 = 12_700.0;
|
||||
|
||||
/// A `\shp` group being read.
|
||||
#[derive(Default)]
|
||||
pub(super) struct ShapeSt {
|
||||
/// The depths of the `\shp` group, of its `\shpinst` and of the `\shptxt` being read.
|
||||
shp_depth: usize,
|
||||
inst_depth: Option<usize>,
|
||||
txt_depth: Option<usize>,
|
||||
/// The output set aside while `\shptxt` is read, and the text read.
|
||||
saved: Option<Box<Output>>,
|
||||
blocks: Vec<FBlock>,
|
||||
/// The shape was read from `\shpinst`: its `\shprslt` copy is skipped.
|
||||
read: bool,
|
||||
/// `\shpleft`, `\shptop`, `\shpright`, `\shpbottom` (twips).
|
||||
rect: [i64; 4],
|
||||
bx: Option<Anchor>,
|
||||
by: Option<Anchor>,
|
||||
bx_ignore: bool,
|
||||
by_ignore: bool,
|
||||
wr: Option<i32>,
|
||||
wrk: i32,
|
||||
behind: bool,
|
||||
/// The `\sn` and `\sv` of the property being read.
|
||||
sn: String,
|
||||
sv: String,
|
||||
props: Props,
|
||||
}
|
||||
|
||||
/// The `\sp` properties read.
|
||||
#[derive(Default)]
|
||||
struct Props {
|
||||
shape_type: Option<i64>,
|
||||
fill: Option<Rgb>,
|
||||
filled: Option<bool>,
|
||||
opacity: Option<i64>,
|
||||
line_color: Option<Rgb>,
|
||||
line: Option<bool>,
|
||||
line_width: Option<i64>,
|
||||
posrelh: Option<i64>,
|
||||
posrelv: Option<i64>,
|
||||
posh: Option<i64>,
|
||||
posv: Option<i64>,
|
||||
pseudo_inline: bool,
|
||||
fit: bool,
|
||||
hidden: bool,
|
||||
flip_h: bool,
|
||||
flip_v: bool,
|
||||
rotation: Option<i64>,
|
||||
behind: Option<bool>,
|
||||
/// `dxTextLeft`, `dyTextTop`, `dxTextRight`, `dyTextBottom` (EMUs).
|
||||
inset: [Option<i64>; 4],
|
||||
/// `dxWrapDistLeft`, `dyWrapDistTop`, `dyWrapDistBottom` (EMUs).
|
||||
dist: [Option<i64>; 3],
|
||||
}
|
||||
|
||||
/// A colour property (a COLORREF, `0x00BBGGRR`); `None` for a scheme or system colour.
|
||||
fn colorref(v: i64) -> Option<Rgb> {
|
||||
(0..=0xFF_FFFF).contains(&v).then_some(Rgb((v & 0xFF) as u8, ((v >> 8) & 0xFF) as u8, ((v >> 16) & 0xFF) as u8))
|
||||
}
|
||||
|
||||
/// The shapes read from `\shpinst`; the others keep their `\shprslt` copy.
|
||||
fn kind(shape_type: i64) -> Option<ShapeKind> {
|
||||
Some(match shape_type {
|
||||
1 => ShapeKind::Rectangle,
|
||||
2 => ShapeKind::RoundedRectangle,
|
||||
3 => ShapeKind::Ellipse,
|
||||
4 => ShapeKind::Diamond,
|
||||
5 => ShapeKind::Triangle,
|
||||
6 => ShapeKind::RightTriangle,
|
||||
13 => ShapeKind::Arrow,
|
||||
66 => ShapeKind::ArrowLeft,
|
||||
67 => ShapeKind::ArrowDown,
|
||||
68 => ShapeKind::ArrowUp,
|
||||
202 => ShapeKind::TextBox,
|
||||
_ => return None,
|
||||
})
|
||||
}
|
||||
|
||||
/// `posh`/`posv`: 0 is an offset, then left/top, centre, right/bottom, inside, outside.
|
||||
fn align(v: Option<i64>) -> Option<FloatAlign> {
|
||||
match v? {
|
||||
1 => Some(FloatAlign::Start),
|
||||
2 => Some(FloatAlign::Center),
|
||||
3 => Some(FloatAlign::End),
|
||||
4 => Some(FloatAlign::Inside),
|
||||
5 => Some(FloatAlign::Outside),
|
||||
_ => None,
|
||||
}
|
||||
}
|
||||
|
||||
/// A length in points from `v` in `per` units to the point, held to a page's reach.
|
||||
fn points(v: i64, per: f32) -> f32 {
|
||||
(v.clamp(-31_680 * 12_700, 31_680 * 12_700) as f32 / per).clamp(-1584.0, 1584.0)
|
||||
}
|
||||
|
||||
impl Reader {
|
||||
/// A shape word, read here when it is one: true then.
|
||||
pub(super) fn shape_word(&mut self, w: &str, p: Option<i32>, first_in_group: bool) -> bool {
|
||||
match self.st.dest {
|
||||
Dest::ShpInst => {
|
||||
self.shape_inst_word(w, p, first_in_group);
|
||||
true
|
||||
}
|
||||
// A group in a name or value (a picture's `pib`) is not read.
|
||||
Dest::ShpSn | Dest::ShpSv => {
|
||||
if first_in_group {
|
||||
self.st.dest = Dest::Skip;
|
||||
}
|
||||
true
|
||||
}
|
||||
Dest::Body => self.shape_body_word(w),
|
||||
_ => false,
|
||||
}
|
||||
}
|
||||
|
||||
fn shape_body_word(&mut self, w: &str) -> bool {
|
||||
let depth = self.depth();
|
||||
match w {
|
||||
// A group's shapes are placed in the group's own coordinates: its copy is read.
|
||||
"shpgrp" => {
|
||||
self.st.in_shpgrp = true;
|
||||
false
|
||||
}
|
||||
"shp" if self.boxes_on && self.shape.is_none() && self.sub.is_none() && !self.st.in_shpgrp && self.overflow == 0 => {
|
||||
self.shape = Some(Box::new(ShapeSt { shp_depth: depth, ..Default::default() }));
|
||||
true
|
||||
}
|
||||
"shpinst" => match self.shape.as_deref_mut() {
|
||||
Some(s) if s.inst_depth.is_none() && depth == s.shp_depth + 1 => {
|
||||
s.inst_depth = Some(depth);
|
||||
self.st.dest = Dest::ShpInst;
|
||||
true
|
||||
}
|
||||
_ => false,
|
||||
},
|
||||
"shprslt" if self.shape.as_deref().is_some_and(|s| s.read && depth == s.shp_depth + 1) => {
|
||||
self.st.dest = Dest::Skip;
|
||||
true
|
||||
}
|
||||
_ => false,
|
||||
}
|
||||
}
|
||||
|
||||
fn shape_inst_word(&mut self, w: &str, p: Option<i32>, first_in_group: bool) {
|
||||
let depth = self.depth();
|
||||
let pv = p.unwrap_or(0);
|
||||
let Some(s) = self.shape.as_deref_mut() else {
|
||||
self.st.dest = Dest::Skip;
|
||||
return;
|
||||
};
|
||||
match w {
|
||||
"shpleft" => s.rect[0] = i64::from(pv),
|
||||
"shptop" => s.rect[1] = i64::from(pv),
|
||||
"shpright" => s.rect[2] = i64::from(pv),
|
||||
"shpbottom" => s.rect[3] = i64::from(pv),
|
||||
"shpbxpage" => s.bx = Some(Anchor::Page),
|
||||
"shpbxmargin" => s.bx = Some(Anchor::Margin),
|
||||
"shpbxcolumn" => s.bx = Some(Anchor::Column),
|
||||
"shpbxignore" => s.bx_ignore = true,
|
||||
"shpbypage" => s.by = Some(Anchor::Page),
|
||||
"shpbymargin" => s.by = Some(Anchor::Margin),
|
||||
"shpbypara" => s.by = Some(Anchor::Paragraph),
|
||||
"shpbyignore" => s.by_ignore = true,
|
||||
"shpwr" => s.wr = Some(pv),
|
||||
"shpwrk" => s.wrk = pv,
|
||||
"shpfblwtxt" => s.behind = p != Some(0),
|
||||
"sp" => {}
|
||||
"sn" => {
|
||||
s.sn.clear();
|
||||
self.st.dest = Dest::ShpSn;
|
||||
}
|
||||
"sv" => {
|
||||
s.sv.clear();
|
||||
self.st.dest = Dest::ShpSv;
|
||||
}
|
||||
"shptxt" if s.saved.is_none() && s.txt_depth.is_none() => {
|
||||
s.txt_depth = Some(depth);
|
||||
let saved = self.swap_output(Output::default());
|
||||
if let Some(s) = self.shape.as_deref_mut() {
|
||||
s.saved = Some(Box::new(saved));
|
||||
}
|
||||
self.st.dest = Dest::Body;
|
||||
self.st.intbl = false;
|
||||
}
|
||||
_ if first_in_group => self.st.dest = Dest::Skip,
|
||||
_ => {}
|
||||
}
|
||||
}
|
||||
|
||||
/// `\defshp` in a picture's `\picprop` (which is otherwise skipped): the picture is the one
|
||||
/// Word writes of a shape for readers without shapes.
|
||||
pub(super) fn note_defshp(&mut self, w: &str) {
|
||||
if w == "defshp" && self.pict_depth.is_some() {
|
||||
self.pict_defshp = true;
|
||||
}
|
||||
}
|
||||
|
||||
/// Text of a property's name or value.
|
||||
pub(super) fn shape_text(&mut self, t: &str) {
|
||||
let name = self.st.dest == Dest::ShpSn;
|
||||
if let Some(s) = self.shape.as_deref_mut() {
|
||||
let into = if name { &mut s.sn } else { &mut s.sv };
|
||||
for c in t.chars() {
|
||||
if into.len() >= MAX_PROP {
|
||||
break;
|
||||
}
|
||||
into.push(c);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Whether a text box's text is being read.
|
||||
pub(super) fn in_shape_text(&self) -> bool {
|
||||
self.shape.as_deref().is_some_and(|s| s.saved.is_some())
|
||||
}
|
||||
|
||||
/// Whether the group at the current depth is the `\shptxt` being read.
|
||||
pub(super) fn closes_shape_text(&self) -> bool {
|
||||
self.shape.as_deref().is_some_and(|s| s.txt_depth == Some(self.depth()))
|
||||
}
|
||||
|
||||
/// Whether the group at the current depth is the shape's `\shpinst`.
|
||||
pub(super) fn closes_shape_inst(&self) -> bool {
|
||||
self.shape.as_deref().is_some_and(|s| s.inst_depth == Some(self.depth()))
|
||||
}
|
||||
|
||||
/// `\shppict`: note where its group is, so a picture in it counts as standing in its place.
|
||||
pub(super) fn shppict_word(&mut self, w: &str) -> bool {
|
||||
if w != "shppict" {
|
||||
return false;
|
||||
}
|
||||
self.shppict_at = Some(self.depth());
|
||||
true
|
||||
}
|
||||
|
||||
/// Whether the `\pict` just opened is right after a shape read, in the same group (a
|
||||
/// `\*\shppict` around it is transparent): it may be the shape's copy.
|
||||
pub(super) fn pict_follows_shape(&mut self) -> bool {
|
||||
let depth = self.depth();
|
||||
let at = if self.shppict_at.is_some_and(|s| s.saturating_add(1) == depth) { depth.saturating_sub(1) } else { depth };
|
||||
self.shape_read_at.take().is_some_and(|d| d.saturating_add(1) == at)
|
||||
}
|
||||
|
||||
/// After a group closed: the shape whose `\shp` group it was is done.
|
||||
pub(super) fn after_shape_group(&mut self) {
|
||||
if self.shppict_at.is_some_and(|d| self.depth() < d) {
|
||||
self.shppict_at = None;
|
||||
}
|
||||
if self.shape_read_at.is_some_and(|d| self.depth() < d) {
|
||||
self.shape_read_at = None;
|
||||
}
|
||||
if self.shape.as_deref().is_some_and(|s| self.depth() < s.shp_depth) {
|
||||
self.end_shape_text();
|
||||
// Only a shape read has its picture skipped: one that wasn't keeps the next picture.
|
||||
let read = self.shape.take().is_some_and(|s| s.read);
|
||||
self.shape_read_at = read.then_some(self.depth());
|
||||
}
|
||||
}
|
||||
|
||||
/// The `\shptxt` group closed (or the file ended in it): keep its text for the shape and go
|
||||
/// back to the output it was read from.
|
||||
pub(super) fn end_shape_text(&mut self) {
|
||||
let Some(saved) = self.shape.as_deref_mut().and_then(|s| {
|
||||
s.txt_depth = None;
|
||||
s.saved.take()
|
||||
}) else {
|
||||
return;
|
||||
};
|
||||
if self.para_has || !self.para.inlines.is_empty() {
|
||||
self.end_para(false);
|
||||
}
|
||||
self.close_table();
|
||||
let mut inner = self.swap_output(*saved);
|
||||
inner.body.truncate(MAX_NOTE_BLOCKS);
|
||||
if let Some(s) = self.shape.as_deref_mut() {
|
||||
s.blocks = inner.body;
|
||||
}
|
||||
}
|
||||
|
||||
/// A `\sv` group closed: the property it gives.
|
||||
pub(super) fn commit_shape_prop(&mut self) {
|
||||
let Some(s) = self.shape.as_deref_mut() else { return };
|
||||
let v = s.sv.trim().parse::<i64>().ok();
|
||||
let on = v.map(|v| v != 0);
|
||||
let p = &mut s.props;
|
||||
match s.sn.trim() {
|
||||
"shapeType" => p.shape_type = v,
|
||||
"fillColor" => p.fill = v.and_then(colorref),
|
||||
"fFilled" => p.filled = on,
|
||||
"fillOpacity" => p.opacity = v,
|
||||
"lineColor" => p.line_color = v.and_then(colorref),
|
||||
"fLine" => p.line = on,
|
||||
"lineWidth" => p.line_width = v,
|
||||
"posrelh" => p.posrelh = v,
|
||||
"posrelv" => p.posrelv = v,
|
||||
"posh" => p.posh = v,
|
||||
"posv" => p.posv = v,
|
||||
"fPseudoInline" => p.pseudo_inline = on == Some(true),
|
||||
"fFitShapeToText" => p.fit = on == Some(true),
|
||||
"fHidden" => p.hidden = on == Some(true),
|
||||
"fFlipH" => p.flip_h = on == Some(true),
|
||||
"fFlipV" => p.flip_v = on == Some(true),
|
||||
"rotation" => p.rotation = v,
|
||||
"fBehindDocument" => p.behind = on,
|
||||
"dxTextLeft" => p.inset[0] = v,
|
||||
"dyTextTop" => p.inset[1] = v,
|
||||
"dxTextRight" => p.inset[2] = v,
|
||||
"dyTextBottom" => p.inset[3] = v,
|
||||
"dxWrapDistLeft" => p.dist[0] = v,
|
||||
"dyWrapDistTop" => p.dist[1] = v,
|
||||
"dyWrapDistBottom" => p.dist[2] = v,
|
||||
_ => {}
|
||||
}
|
||||
s.sn.clear();
|
||||
s.sv.clear();
|
||||
}
|
||||
|
||||
/// The `\shpinst` group closed: a shape of a known type goes in the paragraph, and its
|
||||
/// `\shprslt` copy will be skipped.
|
||||
pub(super) fn finish_shape(&mut self) {
|
||||
self.end_shape_text();
|
||||
let Some(s) = self.shape.as_deref_mut() else { return };
|
||||
let Some(kind) = s.props.shape_type.and_then(kind) else { return };
|
||||
let p = &s.props;
|
||||
let [l, t, r, b] = s.rect;
|
||||
let (w, h) = (points(r.saturating_sub(l), TWIPS), points(b.saturating_sub(t), TWIPS));
|
||||
let mut look = model::BoxLook::default();
|
||||
if p.filled == Some(false) {
|
||||
look.fill = None;
|
||||
} else {
|
||||
let transparency = p.opacity.map_or(0.0, |o| 1.0 - (o.clamp(0, 65_536) as f32 / 65_536.0));
|
||||
look.fill = Some(Fill::Solid { color: p.fill.unwrap_or(Rgb::WHITE), transparency });
|
||||
}
|
||||
look.line = if p.line == Some(false) {
|
||||
None
|
||||
} else {
|
||||
Some((p.line_color.unwrap_or(Rgb::BLACK), p.line_width.map_or(0.75, |w| points(w, EMUS).max(0.0))))
|
||||
};
|
||||
if p.inset.iter().any(Option::is_some) {
|
||||
let [il, it, ir, ib] = p.inset;
|
||||
let get = |v: Option<i64>, d: f32| v.map_or(d, |v| points(v, EMUS).max(0.0));
|
||||
look.inset = Some([get(il, 7.2), get(it, 3.6), get(ir, 7.2), get(ib, 3.6)]);
|
||||
}
|
||||
look.auto_fit = p.fit;
|
||||
let mut f = Float {
|
||||
flip_h: p.flip_h,
|
||||
flip_v: p.flip_v,
|
||||
rot: p.rotation.map_or(0.0, |r| (r.clamp(-360 * 65_536, 360 * 65_536) as f32 / 65_536.0).rem_euclid(360.0)),
|
||||
hidden: p.hidden,
|
||||
..Float::default()
|
||||
};
|
||||
if !p.pseudo_inline {
|
||||
let behind = p.behind.unwrap_or(s.behind);
|
||||
f.wrap = match s.wr {
|
||||
Some(1) => Wrap::TopAndBottom,
|
||||
Some(2) => Wrap::Square,
|
||||
Some(4) => Wrap::Tight,
|
||||
Some(5) => Wrap::Through,
|
||||
_ if behind => Wrap::BehindText,
|
||||
_ => Wrap::InFrontOfText,
|
||||
};
|
||||
f.wrap_text = match s.wrk {
|
||||
1 => WrapText::Left,
|
||||
2 => WrapText::Right,
|
||||
3 => WrapText::Largest,
|
||||
_ => WrapText::BothSides,
|
||||
};
|
||||
let rel_h = p.posrelh.and_then(|v| match v {
|
||||
0 => Some(Anchor::Margin),
|
||||
1 => Some(Anchor::Page),
|
||||
2 => Some(Anchor::Column),
|
||||
3 => Some(Anchor::Character),
|
||||
_ => None,
|
||||
});
|
||||
let rel_v = p.posrelv.and_then(|v| match v {
|
||||
0 => Some(Anchor::Margin),
|
||||
1 => Some(Anchor::Page),
|
||||
2 => Some(Anchor::Paragraph),
|
||||
3 => Some(Anchor::Line),
|
||||
_ => None,
|
||||
});
|
||||
// `\shpbxignore` and `\shpbyignore` hand the anchor to the properties.
|
||||
f.h_rel = if s.bx_ignore { rel_h.or(s.bx) } else { s.bx.or(rel_h) }.unwrap_or(Anchor::Column);
|
||||
f.v_rel = if s.by_ignore { rel_v.or(s.by) } else { s.by.or(rel_v) }.unwrap_or(Anchor::Paragraph);
|
||||
f.x = points(l, TWIPS);
|
||||
f.y = points(t, TWIPS);
|
||||
f.h_align = align(p.posh);
|
||||
f.v_align = align(p.posv);
|
||||
let dist = |v: Option<i64>, d: f32| v.map_or(d, |v| points(v, EMUS).max(0.0));
|
||||
f.dist = dist(p.dist[0], 9.0);
|
||||
f.dist_top = dist(p.dist[1], 0.0);
|
||||
f.dist_bottom = dist(p.dist[2], 0.0);
|
||||
}
|
||||
let blocks = std::mem::take(&mut s.blocks);
|
||||
s.read = true;
|
||||
self.para.inlines.push(Inline::Shape { kind, w, h, float: Some(Box::new(f)), blocks, look, path: None });
|
||||
self.para_has = true;
|
||||
}
|
||||
}
|
||||
@@ -42,6 +42,11 @@ pub(super) enum Dest {
|
||||
/// Formatting before a tracked change (`\oldpprops` when true, else `\oldcprops`): read
|
||||
/// into the group's own state, which the group's end keeps as the change's old formatting.
|
||||
OldProps(bool),
|
||||
/// A shape's description (`\shpinst`), and the name (`\sn`) and value (`\sv`) of one of
|
||||
/// its properties.
|
||||
ShpInst,
|
||||
ShpSn,
|
||||
ShpSv,
|
||||
}
|
||||
|
||||
/// A footnote, endnote or comment group being read into an output of its own.
|
||||
@@ -157,6 +162,8 @@ pub(super) struct St {
|
||||
pub(super) outline: Option<u8>,
|
||||
pub(super) pagebb: bool,
|
||||
pub(super) field: Option<usize>,
|
||||
/// Inside a group of shapes (`\shpgrp`), whose members are not read as shapes of their own.
|
||||
pub(super) in_shpgrp: bool,
|
||||
/// The code page of the current font's charset (`\fcharset`), when it names one.
|
||||
pub(super) cp: Option<u16>,
|
||||
/// Space before/after (`\sb`, `\sa`), line spacing (`\sl`, `\slmult`) and indents
|
||||
@@ -195,6 +202,7 @@ impl Default for St {
|
||||
outline: None,
|
||||
pagebb: false,
|
||||
field: None,
|
||||
in_shpgrp: false,
|
||||
cp: None,
|
||||
borders: Default::default(),
|
||||
border_side: None,
|
||||
|
||||
@@ -0,0 +1,198 @@
|
||||
//! Drawing shapes and text boxes read from `\shp` (#6212): the shape's own description,
|
||||
//! `\shpinst`, is read, and its `\shprslt` copy (for readers without shapes) is not.
|
||||
|
||||
use super::*;
|
||||
use craft_wordmodel::fill::Fill;
|
||||
use craft_wordmodel::para::{Anchor, FloatAlign, ShapeKind, Wrap};
|
||||
|
||||
/// The document's shapes, in order: kind, size, fill, outline, placement and text.
|
||||
/// (kind, width, height, fill, line colour, float, text) of each shape.
|
||||
type ShapeRow = (ShapeKind, f32, f32, Option<Fill>, Option<Rgb>, craft_wordmodel::para::Float, String);
|
||||
|
||||
fn shapes(d: &Document) -> Vec<ShapeRow> {
|
||||
d.body
|
||||
.iter()
|
||||
.filter_map(|b| b.as_para())
|
||||
.flat_map(|p| p.objects.iter())
|
||||
.filter_map(|o| match o {
|
||||
InlineObject::Shape { kind, w, h, fill, stroke, float, story, .. } => {
|
||||
let text = story
|
||||
.and_then(|id| d.parts.get(&id))
|
||||
.map(|p| p.blocks.iter().filter_map(|b| b.as_para()).map(|p| p.plain_text()).collect::<Vec<_>>().join("\n"))
|
||||
.unwrap_or_default();
|
||||
Some((*kind, *w, *h, fill.clone(), *stroke, float.clone(), text))
|
||||
}
|
||||
_ => None,
|
||||
})
|
||||
.collect()
|
||||
}
|
||||
|
||||
fn images(d: &Document) -> usize {
|
||||
d.body.iter().filter_map(|b| b.as_para()).flat_map(|p| p.objects.iter()).filter(|o| matches!(o, InlineObject::Image { .. })).count()
|
||||
}
|
||||
|
||||
/// A text box as Word writes one: shape type 202 with its text in `\shptxt`, and an old-style
|
||||
/// drawing object holding the same text in `\shprslt`.
|
||||
const TEXT_BOX: &str = r"{\rtf1\ansi Before\par
|
||||
{\shp{\*\shpinst\shpleft0\shptop0\shpright5000\shpbottom1400\shpbxcolumn\shpbxignore\shpbypara\shpbyignore\shpwr1\shpwrk0\shpfblwtxt0\shpz2
|
||||
{\sp{\sn shapeType}{\sv 202}}{\sp{\sn fillColor}{\sv 16445672}}
|
||||
{\shptxt \pard\plain Boxed note\par}}
|
||||
{\shprslt{\*\do\dobxcolumn\dobypara\dptxbx{\dptxbxtext \pard\plain Boxed note\par}\dpx0\dpy0\dpxsize5000\dpysize1400}}}
|
||||
After\par}";
|
||||
|
||||
#[test]
|
||||
fn a_text_box_is_read_with_its_text_fill_and_wrapping() {
|
||||
let d = import(TEXT_BOX.as_bytes()).unwrap();
|
||||
let s = shapes(&d);
|
||||
assert_eq!(s.len(), 1, "{s:?}");
|
||||
let (kind, w, h, fill, stroke, float, text) = &s[0];
|
||||
assert_eq!(*kind, ShapeKind::TextBox);
|
||||
// Twips to points.
|
||||
assert_eq!((*w, *h), (250.0, 70.0));
|
||||
// `fillColor` is 0x00BBGGRR.
|
||||
assert_eq!(*fill, Some(Fill::solid(Rgb(232, 240, 250))));
|
||||
// A line unless `fLine` turns it off: Word's black hairline.
|
||||
assert_eq!(*stroke, Some(Rgb::BLACK));
|
||||
assert_eq!(float.wrap, Wrap::TopAndBottom);
|
||||
assert_eq!((float.h_rel, float.v_rel), (Anchor::Column, Anchor::Paragraph));
|
||||
assert_eq!((float.x, float.y), (0.0, 0.0));
|
||||
assert_eq!(text, "Boxed note");
|
||||
// Its text is in the box, once: not also in the body.
|
||||
assert!(!d.plain_text(craft_wordmodel::StoryRef::Body).contains("Boxed"), "{}", d.plain_text(craft_wordmodel::StoryRef::Body));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn an_arrow_in_a_shape_field_is_read_in_line() {
|
||||
// Word writes a shape in line with text as a SHAPE field whose result is the shape, then a
|
||||
// picture of it for readers without shapes.
|
||||
let rtf = r"{\rtf1\ansi {\field\fldedit\fldlock{\*\fldinst SHAPE \\* MERGEFORMAT }{\fldrslt
|
||||
{\shp{\*\shpinst\shpleft0\shptop0\shpright2400\shpbottom800\shpbxcolumn\shpbxignore\shpbypara\shpbyignore\shpwr3\shpwrk0\shpfblwtxt0
|
||||
{\sp{\sn shapeType}{\sv 13}}{\sp{\sn fillColor}{\sv 42495}}{\sp{\sn posrelh}{\sv 3}}{\sp{\sn posrelv}{\sv 3}}{\sp{\sn fPseudoInline}{\sv 1}}
|
||||
{\sp{\sn fLine}{\sv 0}}}
|
||||
{\shprslt{\*\do\dobxcolumn\dobypara\dppolygon\dppolycount3\dpptx0\dppty0\dpptx2400\dppty400\dpptx0\dppty800\dpx0\dpy0\dpxsize2400\dpysize800}}}}}
|
||||
caption\par}";
|
||||
let d = import(rtf.as_bytes()).unwrap();
|
||||
let s = shapes(&d);
|
||||
assert_eq!(s.len(), 1, "{s:?}");
|
||||
let (kind, w, h, fill, stroke, float, _) = &s[0];
|
||||
assert_eq!(*kind, ShapeKind::Arrow);
|
||||
assert_eq!((*w, *h), (120.0, 40.0));
|
||||
assert_eq!(*fill, Some(Fill::solid(Rgb(255, 165, 0))));
|
||||
assert_eq!(*stroke, None);
|
||||
assert_eq!(float.wrap, Wrap::Inline);
|
||||
assert!(d.plain_text(craft_wordmodel::StoryRef::Body).contains("caption"));
|
||||
}
|
||||
|
||||
/// A placeable WMF: the 9-word header (type 1, version 0x300, 12 words, max record 3), then EOF.
|
||||
fn wmf_hex() -> String {
|
||||
[1u16, 9, 0x300, 12, 0, 0, 3, 0, 0, 3, 0, 0].iter().flat_map(|w| w.to_le_bytes()).map(|b| format!("{b:02x}")).collect()
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_picture_after_a_shape_read_is_not_a_second_copy() {
|
||||
// After the shape, Word writes a picture of it marked `\defshp` for readers without shapes.
|
||||
let pict = format!(r"{{\pict{{\*\picprop\defshp{{\sp{{\sn shapeType}}{{\sv 75}}}}}}\picwgoal2400\pichgoal800\wmetafile8 {}}}", wmf_hex());
|
||||
let shape =
|
||||
|t: u32| format!(r"{{\shp{{\*\shpinst\shpright2400\shpbottom800{{\sp{{\sn shapeType}}{{\sv {t}}}}}{{\sp{{\sn fPseudoInline}}{{\sv 1}}}}}}}}");
|
||||
let field = |t: u32| format!(r"{{\rtf1\ansi {{\field{{\*\fldinst SHAPE }}{{\fldrslt {}{pict}}}}} caption\par}}", shape(t));
|
||||
let d = import(field(13).as_bytes()).unwrap();
|
||||
assert_eq!((shapes(&d).len(), images(&d)), (1, 0));
|
||||
// A shape not read here (a line) keeps its picture.
|
||||
let d = import(field(20).as_bytes()).unwrap();
|
||||
assert_eq!((shapes(&d).len(), images(&d)), (0, 1));
|
||||
// A `\defshp` picture with no shape read before it is kept.
|
||||
let d = import(format!(r"{{\rtf1\ansi {pict} caption\par}}").as_bytes()).unwrap();
|
||||
assert_eq!(images(&d), 1);
|
||||
// Only the picture right after a shape read is its copy: a line read earlier in the same
|
||||
// group doesn't take the picture of a later shape not read here.
|
||||
let d = import(format!(r"{{\rtf1\ansi {}{}{pict} caption\par}}", shape(13), shape(20)).as_bytes()).unwrap();
|
||||
assert_eq!((shapes(&d).len(), images(&d)), (1, 1));
|
||||
let d = import(format!(r"{{\rtf1\ansi {}{pict}{pict} caption\par}}", shape(13)).as_bytes()).unwrap();
|
||||
assert_eq!((shapes(&d).len(), images(&d)), (1, 1));
|
||||
// The picture may come wrapped in `\*\shppict`: still the shape's copy.
|
||||
let d = import(format!(r"{{\rtf1\ansi {}{{\*\shppict{pict}}} caption\par}}", shape(13)).as_bytes()).unwrap();
|
||||
assert_eq!((shapes(&d).len(), images(&d)), (1, 0));
|
||||
let d = import(format!(r"{{\rtf1\ansi {}{{\*\shppict{pict}}} caption\par}}", shape(20)).as_bytes()).unwrap();
|
||||
assert_eq!((shapes(&d).len(), images(&d)), (0, 1));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_shape_behind_text_is_placed_on_the_page() {
|
||||
let rtf = r"{\rtf1\ansi {\shp{\*\shpinst\shpleft1440\shptop2880\shpright4320\shpbottom4320\shpbxpage\shpbypage\shpwr3\shpfblwtxt1
|
||||
{\sp{\sn shapeType}{\sv 3}}{\sp{\sn posh}{\sv 2}}{\sp{\sn fFilled}{\sv 0}}{\sp{\sn lineColor}{\sv 255}}{\sp{\sn lineWidth}{\sv 25400}}
|
||||
{\sp{\sn fFlipH}{\sv 1}}}}Text\par}";
|
||||
let d = import(rtf.as_bytes()).unwrap();
|
||||
let s = shapes(&d);
|
||||
assert_eq!(s.len(), 1, "{s:?}");
|
||||
let (kind, w, h, fill, stroke, float, _) = &s[0];
|
||||
assert_eq!(*kind, ShapeKind::Ellipse);
|
||||
assert_eq!((*w, *h), (144.0, 72.0));
|
||||
assert_eq!(*fill, None);
|
||||
assert_eq!(*stroke, Some(Rgb(255, 0, 0)));
|
||||
assert_eq!(float.wrap, Wrap::BehindText);
|
||||
assert_eq!((float.h_rel, float.v_rel), (Anchor::Page, Anchor::Page));
|
||||
assert_eq!((float.x, float.y), (72.0, 144.0));
|
||||
assert_eq!(float.h_align, Some(FloatAlign::Center));
|
||||
assert!(float.flip_h);
|
||||
let width = d.body.iter().filter_map(|b| b.as_para()).flat_map(|p| p.objects.iter()).find_map(|o| match o {
|
||||
InlineObject::Shape { stroke_width, .. } => Some(*stroke_width),
|
||||
_ => None,
|
||||
});
|
||||
assert_eq!(width, Some(2.0));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_picture_shape_keeps_one_picture() {
|
||||
// Shape type 75 (a picture frame) stays on its `\shprslt` copy: its `pib` picture isn't
|
||||
// read a second time.
|
||||
let png = "89504e470d0a1a0a0000000d4948445200000001000000010806000000";
|
||||
let rtf = format!(
|
||||
r"{{\rtf1\ansi {{\shp{{\*\shpinst\shpleft0\shptop0\shpright1440\shpbottom1440\shpbxcolumn\shpbypara\shpwr2
|
||||
{{\sp{{\sn shapeType}}{{\sv 75}}}}{{\sp{{\sn pib}}{{\sv {{\pict\pngblip\picwgoal1440\pichgoal1440 {png}}}}}}}}}}}
|
||||
{{\shprslt\par\pard{{\pict\pngblip\picwgoal1440\pichgoal1440 {png}}}\par}}}}Text\par}}"
|
||||
);
|
||||
let d = import(rtf.as_bytes()).unwrap();
|
||||
assert!(shapes(&d).is_empty());
|
||||
assert_eq!(images(&d), 1);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn shapes_inside_a_group_are_left_to_the_groups_copy() {
|
||||
// A group's members are placed in the group's own coordinates: they stay on the group's
|
||||
// `\shprslt` copy rather than being read at the wrong place.
|
||||
let rtf = r"{\rtf1\ansi {\shpgrp{\*\shpinst\shpleft0\shptop0\shpright2000\shpbottom2000\shpbxcolumn\shpbypara\shpwr3}
|
||||
{\shp{\*\shpinst\shpleft0\shptop0\shpright1000\shpbottom1000{\sp{\sn shapeType}{\sv 1}}}}
|
||||
{\shprslt kept}}Text\par}";
|
||||
let d = import(rtf.as_bytes()).unwrap();
|
||||
assert!(shapes(&d).is_empty());
|
||||
assert!(d.plain_text(craft_wordmodel::StoryRef::Body).contains("kept"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn truncated_and_hostile_shapes_do_not_crash() {
|
||||
for rtf in [
|
||||
r"{\rtf1 Before\par{\shp{\*\shpinst{\shptxt Inside",
|
||||
r"{\rtf1 Before\par{\shp{\*\shpinst\shpleft-2147483648\shpright2147483647{\sp{\sn shapeType}{\sv 202}}{\shptxt A\par}}}}",
|
||||
r"{\rtf1 Before\par{\shp{\*\shpinst{\sp{\sn shapeType}{\sv 99999999999999999999}}{\sp{\sn fillColor}{\sv -5}}}}}",
|
||||
r"{\rtf1 Before\par{\shp{\*\shpinst{\sp{\sn shapeType}{\sv 202}}{\shptxt {\shp{\*\shpinst{\sp{\sn shapeType}{\sv 202}}{\shptxt deeper\par}}}\par}}}}",
|
||||
r"{\rtf1 Before\par{\footnote{\shp{\*\shpinst{\sp{\sn shapeType}{\sv 202}}{\shptxt in a note\par}}}}}",
|
||||
] {
|
||||
let d = import(rtf.as_bytes()).unwrap();
|
||||
assert!(d.plain_text(craft_wordmodel::StoryRef::Body).contains("Before"), "{rtf}");
|
||||
}
|
||||
// A shape too large for a page is held to Word's largest.
|
||||
let d = import(r"{\rtf1 {\shp{\*\shpinst\shpleft-2147483648\shpright2147483647\shpbottom100{\sp{\sn shapeType}{\sv 1}}}}}".as_bytes()).unwrap();
|
||||
assert!(shapes(&d).iter().all(|s| s.1 <= 1584.0 && s.2 >= 1.0));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_flow_reader_is_unchanged() {
|
||||
// The public flow reader, `parse`, asks for no shapes: the box's text is left out as before.
|
||||
let f = parse(TEXT_BOX.as_bytes()).unwrap();
|
||||
let all: String = f.blocks.iter().filter_map(|b| if let FBlock::Para(p) = b { Some(p.text()) } else { None }).collect();
|
||||
assert!(!all.contains("Boxed"), "{all}");
|
||||
assert!(f.blocks.iter().all(|b| match b {
|
||||
FBlock::Para(p) => p.inlines.iter().all(|i| !matches!(i, Inline::Shape { .. })),
|
||||
FBlock::Table(_) => true,
|
||||
}));
|
||||
}
|
||||
@@ -155,6 +155,11 @@ impl Reader {
|
||||
// Odd hex digit count: drop the dangling nibble.
|
||||
}
|
||||
let data = std::mem::take(&mut self.pict_hex);
|
||||
// The picture Word writes of a shape just read (`\defshp`), for readers without shapes.
|
||||
let after_shape = std::mem::take(&mut self.pict_after_shape);
|
||||
if std::mem::take(&mut self.pict_defshp) && after_shape {
|
||||
return;
|
||||
}
|
||||
if self.pict_kind == 0 || data.is_empty() {
|
||||
return;
|
||||
}
|
||||
@@ -304,7 +309,8 @@ impl Reader {
|
||||
}
|
||||
}
|
||||
}
|
||||
Dest::Skip | Dest::ListTable | Dest::ListOverride | Dest::OldProps(_) => {}
|
||||
Dest::ShpSn | Dest::ShpSv => self.shape_text(s),
|
||||
Dest::Skip | Dest::ListTable | Dest::ListOverride | Dest::OldProps(_) | Dest::ShpInst => {}
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -21,10 +21,14 @@ impl Reader {
|
||||
self.finish_multibyte();
|
||||
let on = p != Some(0);
|
||||
let pv = p.unwrap_or(0);
|
||||
self.note_defshp(w);
|
||||
if self.skip_destination_word(w, pv) {
|
||||
return;
|
||||
}
|
||||
if w == "shppict" || self.start_header_footer_word(w) {
|
||||
if self.shape_word(w, p, first_in_group) {
|
||||
return;
|
||||
}
|
||||
if self.shppict_word(w) || self.start_header_footer_word(w) {
|
||||
return;
|
||||
}
|
||||
if self.start_note_word(w) {
|
||||
@@ -38,6 +42,8 @@ impl Reader {
|
||||
}
|
||||
Dest::Pict => {
|
||||
self.pict_depth = Some(self.depth());
|
||||
self.pict_defshp = false;
|
||||
self.pict_after_shape = self.pict_follows_shape();
|
||||
self.pict_hex.clear();
|
||||
self.pict_half = None;
|
||||
self.pict_kind = 0;
|
||||
@@ -465,6 +471,8 @@ impl Reader {
|
||||
}
|
||||
Dest::RevTbl if !matches!(word, "u" | "uc") => true,
|
||||
Dest::RevTbl => false,
|
||||
// Read by `shape_word`, which takes every word there.
|
||||
Dest::ShpInst | Dest::ShpSn | Dest::ShpSv => true,
|
||||
Dest::Pict => {
|
||||
self.picture_word(word, value);
|
||||
true
|
||||
|
||||
Reference in New Issue
Block a user