use super::model::{Anchor, AnchorAlign, AnchorFrom, AnchorPos, Border, BorderStyle, Rgb, Wrap};
use crate::word::doc::fib::{plc, u16_at, u32_at};
use std::collections::HashMap;
const FSPA_LEN: usize = 26;
const FTXBXS_LEN: usize = 22;
const FTXBXS_LID: usize = 14;
const RECORD_HEADER_LEN: usize = 8;
const CONTAINER_VERSION: u16 = 0xF;
const FSP: u16 = 0xF00A;
const FOPT: u16 = 0xF00B;
const TERTIARY_FOPT: u16 = 0xF122;
const SP_CONTAINER: u16 = 0xF004;
const BSTORE_CONTAINER: u16 = 0xF001;
const FBSE: u16 = 0xF007;
const FBSE_SIZE: usize = 20;
const FBSE_DELAY: usize = 28;
const FSP_GROUP: u32 = 0x1;
const FSP_CHILD: u32 = 0x2;
const FSP_DELETED: u32 = 0x8;
const PID_TEXT_LEFT: u16 = 0x0081;
const PID_TEXT_TOP: u16 = 0x0082;
const PID_TEXT_RIGHT: u16 = 0x0083;
const PID_TEXT_BOTTOM: u16 = 0x0084;
const PID_PIB: u16 = 0x0104;
const PID_FILL_COLOR: u16 = 0x0181;
const PID_FILL_OPACITY: u16 = 0x0182;
const OPAQUE: f32 = 65_536.0;
const PID_FILL_BOOLEANS: u16 = 0x01BF;
const PID_LINE_COLOR: u16 = 0x01C0;
const PID_LINE_WIDTH: u16 = 0x01CB;
const PID_LINE_BOOLEANS: u16 = 0x01FF;
const PID_POSH: u16 = 0x038F;
const PID_POSRELH: u16 = 0x0390;
const PID_POSV: u16 = 0x0391;
const PID_POSRELV: u16 = 0x0392;
const FILLED: u32 = 0x10;
const USE_FILLED: u32 = 0x10_0000;
const LINE: u32 = 0x08;
const USE_LINE: u32 = 0x08_0000;
const COLOR_NOT_RGB: u32 = 0xFF00_0000;
const EMU_PER_PT: f32 = 12_700.0;
const TWIPS_PER_PT: f32 = 20.0;
const DEFAULT_INSET_X_PT: f32 = 7.2;
const DEFAULT_INSET_Y_PT: f32 = 3.6;
const DEFAULT_LINE_PT: f32 = 0.75;
const DEFAULT_WRAP_DIST_PT: f32 = 9.0;
#[derive(Debug, Clone)]
pub(super) struct Float {
pub(super) spid: u32,
pub(super) size: (f32, f32),
pub(super) anchor: Anchor,
pub(super) fill: Option<Rgb>,
pub(super) line: Option<Border>,
pub(super) insets: [f32; 4],
pub(super) picture: Option<Vec<u8>>,
pub(super) line_set: bool,
pub(super) order: usize,
}
#[derive(Debug, Default, Clone)]
struct ShapeProps {
grouped: bool,
order: usize,
props: HashMap<u16, u32>,
}
pub(super) fn floats(plc_spa: &[u8], dgg: &[u8], word: &[u8]) -> HashMap<u32, Float> {
let shapes = shape_props(dgg);
let pictures = picture_store(dgg);
let (cps, entries) = plc(plc_spa, FSPA_LEN);
let mut out = HashMap::new();
for (cp, fspa) in cps.iter().zip(entries) {
let Some(spid) = u32_at(fspa, 0) else { continue };
let props = shapes.get(&spid).cloned().unwrap_or_default();
if std::env::var_os("KAKEMONO_DEBUG_DOC").is_some() {
let mut list: Vec<_> = props
.props
.iter()
.map(|(pid, value)| format!("{pid:04X}={value:08X}"))
.collect();
list.sort();
eprintln!(
"FLOAT cp {cp} spid {spid} z {} flags {:04X} grouped {} {}",
props.order,
u16_at(fspa, 20).unwrap_or(0),
props.grouped,
list.join(" ")
);
}
if props.grouped {
continue;
}
let coord = |at: usize| u32_at(fspa, at).map_or(0.0, |value| value as i32 as f32 / TWIPS_PER_PT);
let (left, top, right, bottom) = (coord(4), coord(8), coord(12), coord(16));
let flags = u16_at(fspa, 20).unwrap_or(0);
let picture = props
.props
.get(&PID_PIB)
.and_then(|&index| pictures.get((index as usize).checked_sub(1)?))
.and_then(|&(at, len)| crate::word::doc::picture::find_blip(word, at, at.saturating_add(len)));
out.insert(
*cp,
Float {
spid,
size: ((right - left).max(0.0), (bottom - top).max(0.0)),
anchor: anchor(flags, left, top, &props.props),
fill: fill(&props.props),
line: line(&props.props),
insets: insets(&props.props),
picture,
line_set: props.props.contains_key(&PID_LINE_BOOLEANS),
order: props.order,
},
);
}
out
}
pub(super) fn text_boxes(plc_txbx: &[u8]) -> Vec<(u32, u32, u32)> {
let (cps, entries) = plc(plc_txbx, FTXBXS_LEN);
entries
.iter()
.enumerate()
.filter_map(|(at, entry)| {
let lid = u32_at(entry, FTXBXS_LID)?;
Some((lid, *cps.get(at)?, *cps.get(at + 1)?))
})
.collect()
}
fn anchor(flags: u16, left: f32, top: f32, props: &HashMap<u16, u32>) -> Anchor {
let bx = (flags >> 1) & 0x3;
let by = (flags >> 3) & 0x3;
let wr = (flags >> 5) & 0xF;
let below = flags & 0x4000 != 0;
let from_h = match props.get(&PID_POSRELH) {
Some(1) => AnchorFrom::Page,
Some(2) => AnchorFrom::Column,
Some(3) => AnchorFrom::Character,
Some(_) => AnchorFrom::Margin,
None => match bx {
1 => AnchorFrom::Page,
2 => AnchorFrom::Column,
_ => AnchorFrom::Margin,
},
};
let from_v = match props.get(&PID_POSRELV) {
Some(1) => AnchorFrom::Page,
Some(2) => AnchorFrom::Paragraph,
Some(3) => AnchorFrom::Line,
Some(_) => AnchorFrom::Margin,
None => match by {
1 => AnchorFrom::Page,
2 => AnchorFrom::Paragraph,
_ => AnchorFrom::Margin,
},
};
let align = |value: Option<&u32>| match value {
Some(1) => Some(AnchorAlign::Start),
Some(2) => Some(AnchorAlign::Center),
Some(3) => Some(AnchorAlign::End),
Some(4) => Some(AnchorAlign::Inside),
Some(5) => Some(AnchorAlign::Outside),
_ => None,
};
let wrap = match wr {
1 => Wrap::TopBottom,
3 => Wrap::None,
4 | 5 => Wrap::Tight,
_ => Wrap::Square,
};
let side = if wrap == Wrap::Square || wrap == Wrap::Tight {
DEFAULT_WRAP_DIST_PT
} else {
0.0
};
Anchor {
horizontal: AnchorPos {
from: from_h,
align: align(props.get(&PID_POSH)),
offset: left,
},
vertical: AnchorPos {
from: from_v,
align: align(props.get(&PID_POSV)),
offset: top,
},
wrap,
behind: below,
dist: [0.0, 0.0, side, side],
}
}
fn fill(props: &HashMap<u16, u32>) -> Option<Rgb> {
let booleans = props.get(&PID_FILL_BOOLEANS).copied().unwrap_or(0);
if booleans & USE_FILLED != 0 && booleans & FILLED == 0 {
return None;
}
let opacity = props
.get(&PID_FILL_OPACITY)
.map_or(1.0, |&value| (value as f32 / OPAQUE).clamp(0.0, 1.0));
if opacity <= 0.0 {
return None;
}
let color = props
.get(&PID_FILL_COLOR)
.map_or([255, 255, 255], |&color| rgb(color, [255, 255, 255]));
Some(color.map(|channel| (f32::from(channel) * opacity + 255.0 * (1.0 - opacity)).round() as u8))
}
fn line(props: &HashMap<u16, u32>) -> Option<Border> {
let booleans = props.get(&PID_LINE_BOOLEANS).copied().unwrap_or(0);
if booleans & USE_LINE != 0 && booleans & LINE == 0 {
return None;
}
let width = props
.get(&PID_LINE_WIDTH)
.map_or(DEFAULT_LINE_PT, |&emu| emu as f32 / EMU_PER_PT);
Some(Border {
style: BorderStyle::Single,
width,
color: props
.get(&PID_LINE_COLOR)
.map_or([0, 0, 0], |&color| rgb(color, [0, 0, 0])),
space: 0.0,
})
}
fn insets(props: &HashMap<u16, u32>) -> [f32; 4] {
let get = |pid: u16, default: f32| props.get(&pid).map_or(default, |&emu| emu as f32 / EMU_PER_PT);
[
get(PID_TEXT_LEFT, DEFAULT_INSET_X_PT),
get(PID_TEXT_TOP, DEFAULT_INSET_Y_PT),
get(PID_TEXT_RIGHT, DEFAULT_INSET_X_PT),
get(PID_TEXT_BOTTOM, DEFAULT_INSET_Y_PT),
]
}
fn rgb(color: u32, default: Rgb) -> Rgb {
if color & COLOR_NOT_RGB != 0 {
return default;
}
let [red, green, blue, _] = color.to_le_bytes();
[red, green, blue]
}
fn records(bytes: &[u8], pos: usize, end: usize) -> Vec<(u16, u16, usize, usize)> {
let mut out = Vec::new();
walk(bytes, pos, end.min(bytes.len()), &mut out);
out
}
fn walk(bytes: &[u8], mut at: usize, stop: usize, out: &mut Vec<(u16, u16, usize, usize)>) {
while at + RECORD_HEADER_LEN <= stop {
let (Some(version_instance), Some(kind), Some(len)) =
(u16_at(bytes, at), u16_at(bytes, at + 2), u32_at(bytes, at + 4))
else {
break;
};
let body = at + RECORD_HEADER_LEN;
let len = (len as usize).min(stop - body);
out.push((kind, version_instance >> 4, body, len));
if version_instance & 0xF == CONTAINER_VERSION {
walk(bytes, body, body + len, out);
}
at = body + len;
}
}
fn content_records(dgg: &[u8]) -> Vec<(u16, u16, usize, usize)> {
let mut out = Vec::new();
let Some(len) = u32_at(dgg, 4) else { return out };
let first_end = (RECORD_HEADER_LEN + len as usize).min(dgg.len());
walk(dgg, 0, first_end, &mut out);
let mut at = first_end;
while at + 1 + RECORD_HEADER_LEN <= dgg.len() {
let start = at + 1;
let Some(len) = u32_at(dgg, start + 4) else { break };
let stop = (start + RECORD_HEADER_LEN + len as usize).min(dgg.len());
walk(dgg, start, stop, &mut out);
at = stop;
}
out
}
fn shape_props(dgg: &[u8]) -> HashMap<u32, ShapeProps> {
let mut out = HashMap::new();
let all = content_records(dgg);
for &(kind, _, body, len) in &all {
if kind != SP_CONTAINER {
continue;
}
let mut shape = ShapeProps {
order: out.len(),
..ShapeProps::default()
};
let mut spid = None;
for (inner, instance, inner_body, inner_len) in records(dgg, body, body + len) {
match inner {
FSP => {
spid = u32_at(dgg, inner_body);
let flags = u32_at(dgg, inner_body + 4).unwrap_or(0);
shape.grouped = flags & (FSP_GROUP | FSP_CHILD | FSP_DELETED) != 0;
}
FOPT | TERTIARY_FOPT => {
for at in 0..usize::from(instance) {
let entry = inner_body + at * 6;
if entry + 6 > inner_body + inner_len {
break;
}
let (Some(opid), Some(value)) = (u16_at(dgg, entry), u32_at(dgg, entry + 2)) else {
break;
};
shape.props.insert(opid & 0x3FFF, value);
}
}
_ => {}
}
}
if let Some(spid) = spid {
out.entry(spid).or_insert(shape);
}
}
out
}
fn picture_store(dgg: &[u8]) -> Vec<(usize, usize)> {
let all = content_records(dgg);
let Some(&(_, _, body, len)) = all.iter().find(|record| record.0 == BSTORE_CONTAINER) else {
return Vec::new();
};
records(dgg, body, body + len)
.into_iter()
.filter(|record| record.0 == FBSE)
.map(|(_, _, fbse, _)| {
let size = u32_at(dgg, fbse + FBSE_SIZE).unwrap_or(0) as usize;
let delay = u32_at(dgg, fbse + FBSE_DELAY).unwrap_or(u32::MAX) as usize;
(delay, size)
})
.collect()
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn fill_follows_its_properties() {
let mut props = HashMap::new();
assert_eq!(fill(&props), Some([255, 255, 255]));
props.insert(PID_FILL_COLOR, 0x0066_3300);
assert_eq!(fill(&props), Some([0x00, 0x33, 0x66]));
props.insert(PID_FILL_OPACITY, 0);
assert_eq!(fill(&props), None);
props.insert(PID_FILL_OPACITY, 0x8000);
assert_eq!(fill(&props), Some([128, 153, 179]));
props.insert(PID_FILL_BOOLEANS, USE_FILLED);
assert_eq!(fill(&props), None);
}
#[test]
fn anchor_from_fspa_flags() {
let flags = (2 << 1) | (2 << 3) | (3 << 5);
let anchor = anchor(flags, 10.0, 20.0, &HashMap::new());
assert_eq!(anchor.horizontal.from, AnchorFrom::Column);
assert_eq!(anchor.vertical.from, AnchorFrom::Paragraph);
assert_eq!(anchor.wrap, Wrap::None);
assert_eq!((anchor.horizontal.offset, anchor.vertical.offset), (10.0, 20.0));
assert!(!anchor.behind);
}
#[test]
fn text_box_ranges() {
let mut plc_bytes = Vec::new();
for cp in [0u32, 12, 30] {
plc_bytes.extend_from_slice(&cp.to_le_bytes());
}
for lid in [1025u32, 1026] {
let mut entry = vec![0u8; FTXBXS_LEN];
entry[FTXBXS_LID..FTXBXS_LID + 4].copy_from_slice(&lid.to_le_bytes());
plc_bytes.extend_from_slice(&entry);
}
assert_eq!(text_boxes(&plc_bytes), vec![(1025, 0, 12), (1026, 12, 30)]);
}
}