use super::ids::{page_self, spread_self};
use crate::coord::{fmt_pt, item_transform, local_rect_path, pt_val, SpreadSpace, DOM, NS};
use crate::ir::{LineDash, PictureBox, ShapeBox, TextBox};
use crate::xml::escape_xml;
use base64::Engine;
const XML_DECL: &str = r#"<?xml version="1.0" encoding="UTF-8" standalone="yes"?>"#;
pub fn spread_xml(i: usize, space: &SpreadSpace, items: &str) -> String {
let bounds = space.page_geometric_bounds();
let page_name = i + 1;
format!(
r#"{XML_DECL}
<idPkg:Spread xmlns:idPkg="{NS}" DOMVersion="{DOM}">
<Spread Self="{spread}" PageCount="1" BindingLocation="0" ItemTransform="1 0 0 1 0 0" FlattenerOverride="Default">
<Page Self="{page}" AppliedMaster="kMaster" GeometricBounds="{bounds}" ItemTransform="1 0 0 1 0 0" Name="{page_name}"/>
{items} </Spread>
</idPkg:Spread>
"#,
spread = spread_self(i),
page = page_self(i),
)
}
pub fn textframe_xml(tb: &TextBox, space: &SpreadSpace, tf_self: &str, story_self: &str) -> String {
textframe_xml_on(tb, space, tf_self, story_self, false)
}
pub(crate) fn textframe_xml_on(
tb: &TextBox,
space: &SpreadSpace,
tf_self: &str,
story_self: &str,
on_master: bool,
) -> String {
let (tx, ty) = if on_master {
space.box_center_master(&tb.rect)
} else {
space.box_center(&tb.rect)
};
let tf = item_transform(tx, ty);
let w = pt_val(tb.rect.width);
let h = pt_val(tb.rect.height);
let geo = path_geometry_xml(w, h);
let name = escape_xml(&tb.node_id);
let vert = if tb.vert_center {
"CenterAlign"
} else {
"TopAlign"
};
let baseline = if tb.first_baseline_leading_offset {
"LeadingOffset"
} else {
"Ascent"
};
let autosize = if tb.autosize_width {
let no_wrap = if tb.autosize_no_wrap {
r#" UseNoLineBreaksForAutoSizing="true""#
} else {
r#" UseNoLineBreaksForAutoSizing="false""#
};
format!(
r#" AutoSizingType="WidthOnly" AutoSizingReferencePoint="{}"{no_wrap}"#,
tb.autosize_refer
)
} else if tb.autosize_height {
let refer = match tb.align {
crate::ir::TextAlign::Center => "TopCenterPoint",
crate::ir::TextAlign::Right => "TopRightPoint",
crate::ir::TextAlign::Left | crate::ir::TextAlign::Justify => "TopLeftPoint",
};
format!(r#" AutoSizingType="HeightOnly" AutoSizingReferencePoint="{refer}""#)
} else {
String::new()
};
let insets = inset_spacing_xml(
tb.inset_top,
tb.inset_left,
tb.inset_bottom,
tb.inset_right,
);
format!(
r#" <TextFrame Self="{tf_self}" ParentStory="{story_self}" ContentType="TextType" ItemLayer="kLayer" FillColor="Swatch/None" StrokeWeight="0" ItemTransform="{tf}" Name="{name}" NextTextFrame="n" PreviousTextFrame="n">
{geo}
<TextFramePreference TextColumnCount="1" VerticalJustification="{vert}" FirstBaselineOffset="{baseline}"{autosize}>
{insets}
</TextFramePreference>
</TextFrame>
"#
)
}
fn inset_spacing_xml(top: f64, left: f64, bottom: f64, right: f64) -> String {
format!(
r#" <Properties>
<InsetSpacing type="list">
<ListItem type="unit">{}</ListItem>
<ListItem type="unit">{}</ListItem>
<ListItem type="unit">{}</ListItem>
<ListItem type="unit">{}</ListItem>
</InsetSpacing>
</Properties>"#,
fmt_pt(top),
fmt_pt(left),
fmt_pt(bottom),
fmt_pt(right),
)
}
#[allow(dead_code)]
pub fn rectangle_xml(shape: &ShapeBox, space: &SpreadSpace, self_id: &str) -> String {
rectangle_xml_on(shape, space, self_id, false)
}
pub(crate) fn rectangle_xml_on(
shape: &ShapeBox,
space: &SpreadSpace,
self_id: &str,
on_master: bool,
) -> String {
let (tx, ty) = if on_master {
space.box_center_master(&shape.rect)
} else {
space.box_center(&shape.rect)
};
let tf = item_transform(tx, ty);
let w = pt_val(shape.rect.width);
let h = pt_val(shape.rect.height);
let name = escape_xml(&shape.node_id);
let (fill, geo) = if let Some(name) = shape.gradient_swatch_name() {
let g = shape.gradient.as_ref().expect("swatch name implies gradient");
let (sx, sy, len) = gradient_aabb_start_length(&shape.rect, g.angle_degrees);
(
format!(
"FillColor=\"Gradient/{name}\" GradientFillAngle=\"{}\" GradientFillLength=\"{}\" GradientFillStart=\"{} {}\"",
idml_gradient_angle(g.angle_degrees),
fmt_pt(len),
fmt_pt(sx),
fmt_pt(sy),
),
path_geometry_xml_with_gradient_start(w, h, sx, sy),
)
} else {
let fill = match &shape.fill_hex {
Some(hex) => format!("FillColor=\"Color/k2f_{hex}\""),
None => "FillColor=\"Swatch/None\"".into(),
};
(fill, path_geometry_xml(w, h))
};
let stroke = stroke_attrs(shape);
let corners = if shape.corner_pt > 0.0 {
let r = fmt_pt(shape.corner_pt);
format!(
" CornerOption=\"RoundedCorner\" CornerRadius=\"{r}\" \
TopLeftCornerOption=\"RoundedCorner\" TopLeftCornerRadius=\"{r}\" \
TopRightCornerOption=\"RoundedCorner\" TopRightCornerRadius=\"{r}\" \
BottomLeftCornerOption=\"RoundedCorner\" BottomLeftCornerRadius=\"{r}\" \
BottomRightCornerOption=\"RoundedCorner\" BottomRightCornerRadius=\"{r}\""
)
} else {
String::new()
};
let transparency = transparency_xml(shape);
format!(
r#" <Rectangle Self="{self_id}" ContentType="Unassigned" ItemLayer="kLayer" {fill}{stroke}{corners} ItemTransform="{tf}" Name="{name}">
{geo}
{transparency} </Rectangle>
"#
)
}
#[allow(dead_code)]
pub fn picture_xml(pic: &PictureBox, space: &SpreadSpace, rect_id: &str, img_id: &str) -> String {
framed_image_xml(pic, space, rect_id, img_id, &pic.node_id, false)
}
#[allow(dead_code)]
pub fn raster_xml(pic: &PictureBox, space: &SpreadSpace, rect_id: &str, img_id: &str) -> String {
framed_image_xml(
pic,
space,
rect_id,
img_id,
&format!("k2f-raster:{}", pic.node_id),
false,
)
}
pub(crate) fn picture_xml_on(
pic: &PictureBox,
space: &SpreadSpace,
rect_id: &str,
img_id: &str,
on_master: bool,
) -> String {
framed_image_xml(pic, space, rect_id, img_id, &pic.node_id, on_master)
}
pub(crate) fn raster_xml_on(
pic: &PictureBox,
space: &SpreadSpace,
rect_id: &str,
img_id: &str,
on_master: bool,
) -> String {
framed_image_xml(
pic,
space,
rect_id,
img_id,
&format!("k2f-raster:{}", pic.node_id),
on_master,
)
}
fn framed_image_xml(
pic: &PictureBox,
space: &SpreadSpace,
rect_id: &str,
img_id: &str,
name: &str,
on_master: bool,
) -> String {
let (tx, ty) = if on_master {
space.box_center_master(&pic.rect)
} else {
space.box_center(&pic.rect)
};
let tf = item_transform(tx, ty);
let w = pt_val(pic.rect.width);
let h = pt_val(pic.rect.height);
let geo = path_geometry_xml(w, h);
let name = escape_xml(name);
let type_name = image_type_name(&pic.ext);
let b64 = b64_76(&pic.bytes);
let (gw, gh) = image_graphic_size(pic, w, h);
let left = fmt_pt(-gw / 2.0);
let top = fmt_pt(-gh / 2.0);
let right = fmt_pt(gw / 2.0);
let bottom = fmt_pt(gh / 2.0);
let corners = if pic.corner_pt > 0.0 {
let r = fmt_pt(pic.corner_pt);
format!(
" CornerOption=\"RoundedCorner\" CornerRadius=\"{r}\" \
TopLeftCornerOption=\"RoundedCorner\" TopLeftCornerRadius=\"{r}\" \
TopRightCornerOption=\"RoundedCorner\" TopRightCornerRadius=\"{r}\" \
BottomLeftCornerOption=\"RoundedCorner\" BottomLeftCornerRadius=\"{r}\" \
BottomRightCornerOption=\"RoundedCorner\" BottomRightCornerRadius=\"{r}\""
)
} else {
String::new()
};
let fitting = if pic.fill_proportionally {
" <FrameFittingOption FittingOnEmptyFrame=\"FillProportionally\" FittingAlignment=\"CenterAlignment\"/>\n"
} else {
""
};
format!(
r#" <Rectangle Self="{rect_id}" ContentType="GraphicType" ItemLayer="kLayer" FillColor="Swatch/None" StrokeWeight="0"{corners} ItemTransform="{tf}" Name="{name}">
{geo}{fitting} <Image Self="{img_id}" ImageTypeName="{type_name}" Space="RGB" ItemTransform="1 0 0 1 0 0">
<Properties>
<GraphicBounds Left="{left}" Top="{top}" Right="{right}" Bottom="{bottom}"/>
<Contents>
<![CDATA[{b64}]]>
</Contents>
</Properties>
</Image>
</Rectangle>
"#
)
}
fn image_graphic_size(pic: &PictureBox, frame_w: f64, frame_h: f64) -> (f64, f64) {
if pic.fill_proportionally {
if let Ok(img) = k2f_paint::decode_raster(&pic.bytes) {
return (img.width() as f64, img.height() as f64);
}
}
(frame_w, frame_h)
}
fn stroke_attrs(shape: &ShapeBox) -> String {
match &shape.line_hex {
Some(hex) => {
let alignment = if shape.fill_hex.is_some() || shape.gradient.is_some() {
" StrokeAlignment=\"InsideAlignment\""
} else {
""
};
format!(
" StrokeColor=\"Color/k2f_{hex}\" StrokeWeight=\"{}\" StrokeType=\"{}\"{alignment}",
fmt_pt(shape.line_w_pt),
stroke_type(shape.line_dash),
)
}
None => " StrokeWeight=\"0\"".into(),
}
}
fn stroke_type(dash: LineDash) -> &'static str {
match dash {
LineDash::Solid => "$ID/Solid",
LineDash::Dash => "$ID/Dashed",
LineDash::Dot => "$ID/Dotted",
}
}
fn idml_gradient_angle(k2f_deg: i64) -> i64 {
let mut a = -k2f_deg % 360;
if a > 180 {
a -= 360;
}
if a < -180 {
a += 360;
}
a
}
fn gradient_aabb_start_length(rect: &k2f_core::Rect, angle_degrees: i64) -> (f64, f64, f64) {
let w = pt_val(rect.width).max(0.0);
let h = pt_val(rect.height).max(0.0);
let cx = pt_val(rect.x) + w * 0.5;
let cy = pt_val(rect.y) + h * 0.5;
let theta = (angle_degrees as f64).to_radians();
let dir_x = theta.cos();
let dir_y = theta.sin();
let hw = w * 0.5;
let hh = h * 0.5;
let corners = [(-hw, -hh), (hw, -hh), (-hw, hh), (hw, hh)];
let mut min_t = f64::INFINITY;
let mut max_t = f64::NEG_INFINITY;
for (dx, dy) in corners {
let t = dx * dir_x + dy * dir_y;
min_t = min_t.min(t);
max_t = max_t.max(t);
}
(
cx + dir_x * min_t,
cy + dir_y * min_t,
(max_t - min_t).max(0.0),
)
}
fn transparency_xml(shape: &ShapeBox) -> String {
let mut out = String::new();
if shape.fill_hex.is_some() && shape.fill_alpha < 255 {
out.push_str(&blending_xml("FillTransparencySetting", shape.fill_alpha));
}
if shape.line_hex.is_some() && shape.line_alpha < 255 {
out.push_str(&blending_xml("StrokeTransparencySetting", shape.line_alpha));
}
out
}
fn blending_xml(tag: &str, alpha: u8) -> String {
let opacity = (f64::from(alpha) * 100.0 / 255.0).clamp(0.0, 100.0);
format!(
" <{tag}>\n <BlendingSetting BlendMode=\"Normal\" Opacity=\"{}\" KnockoutGroup=\"false\" IsolateBlending=\"false\"/>\n </{tag}>\n",
fmt_pt(opacity)
)
}
fn image_type_name(ext: &str) -> &'static str {
match ext {
"jpg" | "jpeg" => "$ID/JPEG",
_ => "$ID/PNG",
}
}
fn b64_76(bytes: &[u8]) -> String {
let s = base64::engine::general_purpose::STANDARD.encode(bytes);
let mut out = String::with_capacity(s.len() + s.len() / 76);
for (i, chunk) in s.as_bytes().chunks(76).enumerate() {
if i > 0 {
out.push('\n');
}
out.push_str(std::str::from_utf8(chunk).unwrap());
}
out
}
pub(crate) fn path_geometry_xml(w: f64, h: f64) -> String {
path_geometry_properties(w, h, None)
}
fn path_geometry_xml_with_gradient_start(w: f64, h: f64, sx: f64, sy: f64) -> String {
path_geometry_properties(w, h, Some((sx, sy)))
}
fn path_geometry_properties(w: f64, h: f64, gradient_start: Option<(f64, f64)>) -> String {
let [tl, tr, br, bl] = local_rect_path(w, h);
let start = if let Some((sx, sy)) = gradient_start {
format!(
"\n <GradientFillStart type=\"list\">\n <ListItem type=\"unit\">{}</ListItem>\n <ListItem type=\"unit\">{}</ListItem>\n </GradientFillStart>",
fmt_pt(sx),
fmt_pt(sy),
)
} else {
String::new()
};
format!(
r#" <Properties>
<PathGeometry>
<GeometryPathType PathOpen="false">
<PathPointArray>
<PathPointType Anchor="{tl}" LeftDirection="{tl}" RightDirection="{tl}"/>
<PathPointType Anchor="{tr}" LeftDirection="{tr}" RightDirection="{tr}"/>
<PathPointType Anchor="{br}" LeftDirection="{br}" RightDirection="{br}"/>
<PathPointType Anchor="{bl}" LeftDirection="{bl}" RightDirection="{bl}"/>
</PathPointArray>
</GeometryPathType>
</PathGeometry>{start}
</Properties>"#
)
}
#[cfg(test)]
mod tests {
use super::*;
use crate::ir::{LineDash, ShapeBox};
use k2f_core::{Pt, Rect};
#[test]
fn filled_stroke_uses_inside_alignment() {
let shape = ShapeBox {
node_id: "shell".into(),
rect: Rect {
x: Pt(20_000),
y: Pt(20_000),
width: Pt(320_000),
height: Pt(464_000),
},
fill_hex: Some("FAF8F3".into()),
fill_alpha: 255,
gradient: None,
corner_pt: 0.0,
line_hex: Some("D2C8B4".into()),
line_alpha: 255,
line_w_pt: 0.65,
line_dash: LineDash::Solid,
};
let space = SpreadSpace {
page_w: 360.0,
page_h: 504.0,
};
let xml = rectangle_xml(&shape, &space, "kRect0");
assert!(
xml.contains("StrokeAlignment=\"InsideAlignment\""),
"filled rim must align inside, got {xml}"
);
}
#[test]
fn stroke_only_bar_omits_inside_alignment() {
let shape = ShapeBox {
node_id: "rule".into(),
rect: Rect {
x: Pt(0),
y: Pt(150_000),
width: Pt(360_000),
height: Pt(1_000),
},
fill_hex: Some("D5CCBA".into()),
fill_alpha: 255,
gradient: None,
corner_pt: 0.0,
line_hex: None,
line_alpha: 255,
line_w_pt: 0.0,
line_dash: LineDash::Solid,
};
let space = SpreadSpace {
page_w: 360.0,
page_h: 504.0,
};
let xml = rectangle_xml(&shape, &space, "kRect0");
assert!(
!xml.contains("StrokeAlignment"),
"fill-only bar must not set stroke alignment, got {xml}"
);
}
#[test]
fn rounded_rect_emits_live_corner_attrs() {
let shape = ShapeBox {
node_id: "pill".into(),
rect: Rect {
x: Pt(0),
y: Pt(0),
width: Pt(80_000),
height: Pt(20_000),
},
fill_hex: Some("E05A47".into()),
fill_alpha: 255,
gradient: None,
corner_pt: 20.0,
line_hex: None,
line_alpha: 255,
line_w_pt: 0.0,
line_dash: LineDash::Solid,
};
let space = SpreadSpace {
page_w: 960.0,
page_h: 540.0,
};
let xml = rectangle_xml(&shape, &space, "kRect0");
for attr in [
"TopLeftCornerOption=\"RoundedCorner\"",
"TopRightCornerOption=\"RoundedCorner\"",
"BottomLeftCornerOption=\"RoundedCorner\"",
"BottomRightCornerOption=\"RoundedCorner\"",
"TopLeftCornerRadius=\"20.000\"",
"TopRightCornerRadius=\"20.000\"",
"BottomLeftCornerRadius=\"20.000\"",
"BottomRightCornerRadius=\"20.000\"",
] {
assert!(xml.contains(attr), "missing {attr} in {xml}");
}
}
#[test]
fn gradient_rect_emits_gradient_fill_and_corners() {
use crate::ir::{GradientFill, GradientStopFill};
let shape = ShapeBox {
node_id: "hero.right.labels.pptx".into(),
rect: Rect {
x: Pt(0),
y: Pt(0),
width: Pt(58_794),
height: Pt(26_800),
},
fill_hex: None,
fill_alpha: 255,
gradient: Some(GradientFill {
angle_degrees: 135,
stops: vec![
GradientStopFill {
pos: 0,
hex: "FF8A00".into(),
},
GradientStopFill {
pos: 1000,
hex: "FF5E00".into(),
},
],
}),
corner_pt: 26.8,
line_hex: None,
line_alpha: 255,
line_w_pt: 0.0,
line_dash: LineDash::Solid,
};
let space = SpreadSpace {
page_w: 960.0,
page_h: 540.0,
};
let xml = rectangle_xml(&shape, &space, "kRect0");
assert!(
xml.contains("FillColor=\"Gradient/k2f_g_hero_right_labels_pptx\""),
"{xml}"
);
assert!(xml.contains("GradientFillAngle=\"-135\""), "{xml}");
let (sx, sy, len) = gradient_aabb_start_length(&shape.rect, 135);
assert!(
xml.contains(&format!("GradientFillLength=\"{}\"", fmt_pt(len))),
"{xml}"
);
assert!(
xml.contains(&format!("GradientFillStart=\"{} {}\"", fmt_pt(sx), fmt_pt(sy))),
"{xml}"
);
assert!(
xml.contains(&format!(
"<ListItem type=\"unit\">{}</ListItem>",
fmt_pt(sx)
)),
"{xml}"
);
assert!(
xml.contains(&format!(
"<ListItem type=\"unit\">{}</ListItem>",
fmt_pt(sy)
)),
"{xml}"
);
assert!(xml.contains("TopRightCornerOption=\"RoundedCorner\""), "{xml}");
assert!(!xml.contains("k2f-raster"), "{xml}");
}
#[test]
fn gradient_aabb_puts_135_end_stop_on_square_bottom_left() {
let rect = Rect {
x: Pt(0),
y: Pt(0),
width: Pt(600_000),
height: Pt(600_000),
};
let (sx, sy, len) = gradient_aabb_start_length(&rect, 135);
assert!((sx - 600.0).abs() < 0.01, "sx={sx}");
assert!(sy.abs() < 0.01, "sy={sy}");
assert!((len - 600.0 * 2.0_f64.sqrt()).abs() < 0.01, "len={len}");
let (sx0, sy0, len0) = gradient_aabb_start_length(&rect, 0);
assert!(sx0.abs() < 0.01, "sx0={sx0}");
assert!((sy0 - 300.0).abs() < 0.01, "sy0={sy0}");
assert!((len0 - 600.0).abs() < 0.01, "len0={len0}");
}
#[test]
fn k2f_down_angle_flips_for_indesign() {
assert_eq!(idml_gradient_angle(0), 0);
assert_eq!(idml_gradient_angle(90), -90);
assert_eq!(idml_gradient_angle(135), -135);
assert_eq!(idml_gradient_angle(-45), 45);
}
#[test]
fn translucent_fill_emits_fill_transparency() {
let shape = ShapeBox {
node_id: "top_hero.scrim".into(),
rect: Rect {
x: Pt(80_000),
y: Pt(40_000),
width: Pt(200_000),
height: Pt(80_000),
},
fill_hex: Some("000000".into()),
fill_alpha: 0x44,
gradient: None,
corner_pt: 7.0,
line_hex: None,
line_alpha: 255,
line_w_pt: 0.0,
line_dash: LineDash::Solid,
};
let space = SpreadSpace {
page_w: 595.0,
page_h: 842.0,
};
let xml = rectangle_xml(&shape, &space, "kRect0");
assert!(
xml.contains("<FillTransparencySetting>"),
"{xml}"
);
assert!(
xml.contains("Opacity=\"26.667\""),
"0x44 / 255 = 26.667%, got {xml}"
);
assert!(!xml.contains("k2f-raster"), "{xml}");
assert!(!xml.contains("StrokeTransparencySetting"), "{xml}");
}
#[test]
fn translucent_stroke_emits_stroke_transparency() {
let shape = ShapeBox {
node_id: "glass_card".into(),
rect: Rect {
x: Pt(40_000),
y: Pt(40_000),
width: Pt(200_000),
height: Pt(80_000),
},
fill_hex: Some("FFFFFF".into()),
fill_alpha: 0x24,
gradient: None,
corner_pt: 16.0,
line_hex: Some("FFFFFF".into()),
line_alpha: 0x59,
line_w_pt: 1.0,
line_dash: LineDash::Solid,
};
let space = SpreadSpace {
page_w: 600.0,
page_h: 600.0,
};
let xml = rectangle_xml(&shape, &space, "kRect0");
assert!(xml.contains("<FillTransparencySetting>"), "{xml}");
assert!(xml.contains("<StrokeTransparencySetting>"), "{xml}");
assert!(xml.contains("Opacity=\"14.118\""), "fill 0x24, got {xml}");
assert!(xml.contains("Opacity=\"34.902\""), "stroke 0x59, got {xml}");
}
#[test]
fn text_frame_insets_use_idml_list_not_attribute() {
use crate::ir::{TextAlign, TextBox, TextRun};
let tb = TextBox {
node_id: "sec.banner".into(),
rect: Rect {
x: Pt(40_000),
y: Pt(100_000),
width: Pt(515_000),
height: Pt(21_600),
},
runs: vec![TextRun {
text: "TITLE".into(),
font_name: "Roboto".into(),
size_pt: 10.5,
bold: true,
italic: false,
underline: false,
strike: false,
color_hex: "000000".into(),
hyperlink: None,
script: crate::ir::ScriptPos::Baseline,
leading_pt: None,
auto_page_number: false,
tracking: 0,
face_style: "Regular".into(),
}],
align: TextAlign::Left,
inset_top: 0.0,
inset_left: 10.0,
inset_bottom: 0.0,
inset_right: 0.0,
first_line_indent_pt: 0.0,
left_indent_pt: 0.0,
vert_center: true,
autosize_width: false,
autosize_refer: "CenterLeftPoint",
autosize_no_wrap: false,
autosize_height: false,
no_break: true,
semantic_newlines: false,
lock_line_count: 1,
first_baseline_leading_offset: false,
full_width_lock_line: false,
};
let space = SpreadSpace {
page_w: 595.0,
page_h: 842.0,
};
let xml = textframe_xml(&tb, &space, "kTf0", "kSt0");
assert!(
!xml.contains("InsetSpacing=\""),
"attribute form is ignored by InDesign, got {xml}"
);
assert!(
xml.contains(r#"<InsetSpacing type="list">"#),
"must write IDML inset list, got {xml}"
);
let items: Vec<_> = xml
.split("<ListItem type=\"unit\">")
.skip(1)
.map(|s| s.split('<').next().unwrap_or(""))
.collect();
assert_eq!(items, ["0.000", "10.000", "0.000", "0.000"], "{xml}");
}
}