use serde::Serialize;
use std::ops::{Deref, DerefMut};
use super::composer::{legacy_hancom_product_display_text, CharOverlapInfo};
use super::layout::CellContext;
use super::shaping_publication::{
HorizontalShapingPageSidecars, HorizontalShapingRunDecision, HorizontalShapingRunRange,
HorizontalShapingSidecarRejectReason,
};
use super::shaping_vertical::{
BoundedVerticalHwp5TableCellSidecar, VerticalShapingPageSidecars,
VerticalShapingSidecarRejectReason,
};
use super::{GradientFillInfo, LineStyle, PathCommand, ShapeStyle, TextStyle};
use crate::model::image::ImageEffect;
use crate::model::shape::{RectangleControlKind, TextWrap};
use crate::model::style::ImageFillMode;
use crate::model::{ColorRef, Rect};
pub const MIDDLE_DOT_RADIUS_EM: f64 = 0.060;
pub const MIDDLE_DOT_CY_OFFSET_EM: f64 = 0.35;
#[derive(Debug, Clone, Copy)]
pub(crate) struct PointInk {
pub center_x: f64,
pub above_baseline: f64,
pub radius_x: f64,
pub radius_y: f64,
}
pub(crate) fn fullwidth_onepoint_ink(style: &TextStyle, draw_font_size: f64) -> Option<PointInk> {
let advance = super::layout::char_width_decision(&['․'], &[1], 0, style, true);
if advance.width_source != "heuristicFullwidth" {
return None;
}
let outline = if style.bold { 0.01 } else { 0.0 };
Some(PointInk {
center_x: draw_font_size * style.ratio * 0.5,
above_baseline: draw_font_size * 0.3475,
radius_x: draw_font_size * style.ratio * (0.07575 + outline),
radius_y: draw_font_size * (0.0725 + outline),
})
}
pub fn is_vector_middle_dot(cluster: &str) -> bool {
cluster == "\u{00B7}"
}
pub const TAB_DOT_LEADER_PITCH_EM: f64 = 0.248;
pub const TAB_DOT_LEADER_DIAMETER_EM: f64 = MIDDLE_DOT_RADIUS_EM * 2.0;
pub const TAB_DOT_LEADER_DASH_PX: f64 = 0.1;
pub fn tab_dot_leader_stroke(font_size: f64) -> (f64, f64, f64) {
let width = font_size * TAB_DOT_LEADER_DIAMETER_EM;
let pitch = font_size * TAB_DOT_LEADER_PITCH_EM;
let dash = TAB_DOT_LEADER_DASH_PX.min(pitch * 0.5);
(width, dash, (pitch - dash).max(0.1))
}
pub(crate) fn tab_circle_leader_stroke() -> (f64, f64, f64) {
(1.6, 0.0, 4.0)
}
pub const REAL_PICTURE_WATERMARK_PAGE_OPACITY: f64 = 0.26;
pub const REAL_PICTURE_WATERMARK_FILL_OPACITY: f64 = 0.15;
pub const REAL_PICTURE_WATERMARK_OPACITY: f64 = REAL_PICTURE_WATERMARK_PAGE_OPACITY;
pub const REAL_PICTURE_WATERMARK_SATURATION: f64 = 0.91646104;
pub const REAL_PICTURE_WATERMARK_CONTRAST: f64 = 0.93125103;
pub const REAL_PICTURE_WATERMARK_BRIGHTNESS: f64 = 1.80;
pub const REAL_PICTURE_WATERMARK_CORRECTION_MATRIX: [[f64; 3]; 3] = [
[0.9897169325, 0.1297721480, -0.0666075849],
[0.0236280401, 1.0778421442, -0.0471323620],
[0.0002888270, -0.0075596780, 1.0728328592],
];
pub const REAL_PICTURE_WATERMARK_CORRECTION_BIAS: [f64; 3] =
[-0.0504989415, -0.0462952328, -0.0573305296];
pub const REAL_PICTURE_WATERMARK_CHROMA_GAIN: f64 = 3.0;
pub const REAL_PICTURE_WATERMARK_WHITE_BLEND: f64 = 0.0;
pub const REAL_PICTURE_WATERMARK_FILL_CHROMA_GAIN: f64 = 0.42;
pub const REAL_PICTURE_WATERMARK_FILL_WHITE_BLEND: f64 = 0.16;
pub const LEGACY_IMAGE_WATERMARK_OPACITY: f64 = 0.17;
pub fn is_real_picture_watermark_tone_preset(
effect: ImageEffect,
display_bright: i8,
display_contrast: i8,
) -> bool {
matches!(effect, ImageEffect::RealPic) && display_bright == 70 && display_contrast == -50
}
pub type NodeId = u32;
#[derive(Debug, Clone, Copy, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct RenderLayerInfo {
#[serde(skip)]
pub(crate) independent_page_paint: Option<NodeId>,
#[serde(skip_serializing_if = "Option::is_none")]
pub text_wrap: Option<TextWrap>,
pub z_order: i32,
pub stable_index: u32,
#[serde(skip_serializing_if = "std::ops::Not::not")]
pub master_page: bool,
}
impl RenderLayerInfo {
pub fn new(text_wrap: Option<TextWrap>, z_order: i32, stable_index: u32) -> Self {
Self {
independent_page_paint: None,
text_wrap,
z_order,
stable_index,
master_page: false,
}
}
pub fn for_master_page(mut self) -> Self {
self.master_page = true;
self
}
}
#[derive(Debug, Clone, Serialize)]
pub struct RenderNode {
#[serde(skip)]
pub(crate) cell_frame_paint: bool,
#[serde(skip)]
pub(crate) print_table_column_axes: Option<[bool; 2]>,
#[serde(skip)]
pub(crate) source_inline_picture: bool,
#[serde(skip)]
pub(crate) table_background_paint: bool,
#[serde(skip_serializing_if = "Option::is_none")]
pub paint_clip: Option<Vec<crate::model::text_clip::TextClipPath>>,
pub id: NodeId,
pub node_type: RenderNodeType,
pub bbox: BoundingBox,
#[serde(skip_serializing_if = "Option::is_none")]
pub layer: Option<RenderLayerInfo>,
pub children: Vec<RenderNode>,
pub visible: bool,
#[serde(skip_serializing_if = "std::ops::Not::not")]
pub editor_only: bool,
#[serde(skip)]
pub print_bbox: Option<BoundingBox>,
#[serde(skip)]
pub print_clip_bbox: Option<BoundingBox>,
#[serde(skip)]
pub control_code: ControlCode,
#[serde(skip)]
pub header_footer_source: Option<(usize, HeaderFooterImageRef)>,
#[serde(skip)]
pub(crate) textbox_source: Option<(usize, CellContext)>,
}
#[derive(Debug, Default, Clone, Copy, Serialize)]
pub enum ControlCode {
#[default]
Automatic,
Hidden,
Rectangle(RectangleControlKind),
}
impl RenderNode {
pub fn new(id: NodeId, mut node_type: RenderNodeType, bbox: BoundingBox) -> Self {
if let RenderNodeType::Image(image) = &mut node_type {
super::image_geometry::normalize_gif_crop(image);
}
Self {
cell_frame_paint: false,
print_table_column_axes: None,
source_inline_picture: false,
table_background_paint: false,
id,
node_type,
bbox,
layer: None,
children: Vec::new(),
visible: true,
editor_only: false,
print_bbox: None,
print_clip_bbox: None,
control_code: ControlCode::Automatic,
header_footer_source: None,
textbox_source: None,
paint_clip: None,
}
}
pub fn with_layer(mut self, layer: RenderLayerInfo) -> Self {
self.layer = Some(layer);
self
}
pub fn set_layer(&mut self, layer: RenderLayerInfo) {
self.layer = Some(layer);
}
pub(crate) fn translate_paint_clip_y(&mut self, dy: f64) {
if let Some(paths) = &mut self.paint_clip {
for path in paths {
*path = path.map(|x, y| (x, y + dy));
}
}
}
pub fn with_editor_only(mut self) -> Self {
self.editor_only = true;
self
}
pub fn set_rectangle_control_kind(&mut self, kind: RectangleControlKind) {
self.control_code = ControlCode::Rectangle(kind);
for child in &mut self.children {
if matches!(child.node_type, RenderNodeType::TextBox) {
child.control_code = ControlCode::Hidden;
}
}
}
pub fn control_code_label(&self) -> Option<&'static str> {
match self.control_code {
ControlCode::Hidden => return None,
ControlCode::Rectangle(RectangleControlKind::Rectangle) => return Some("[사각형]"),
ControlCode::Rectangle(RectangleControlKind::TextBox) => return Some("[글상자]"),
ControlCode::Automatic => {}
}
match self.node_type {
RenderNodeType::Table(_) => Some("[표]"),
RenderNodeType::Image(_) => Some("[그림]"),
RenderNodeType::TextBox => Some("[글상자]"),
RenderNodeType::Equation(_) => Some("[수식]"),
RenderNodeType::Header => Some("[머리말]"),
RenderNodeType::Footer => Some("[꼬리말]"),
RenderNodeType::FootnoteArea => Some("[각주]"),
_ => None,
}
}
pub fn to_json(&self) -> String {
let mut buf = String::with_capacity(4096);
self.write_json(&mut buf);
buf
}
fn write_json(&self, buf: &mut String) {
buf.push('{');
let (type_str, extra) = match &self.node_type {
RenderNodeType::Page(_) => ("Page", String::new()),
RenderNodeType::PageBackground(_) => ("PageBg", String::new()),
RenderNodeType::MasterPage => ("MasterPage", String::new()),
RenderNodeType::Header => ("Header", String::new()),
RenderNodeType::Footer => ("Footer", String::new()),
RenderNodeType::Body { .. } => ("Body", String::new()),
RenderNodeType::Column(c) => ("Column", format!(",\"col\":{}", c)),
RenderNodeType::FootnoteArea => ("FootnoteArea", String::new()),
RenderNodeType::TextLine(tl) => {
let mut extra = format!(",\"pi\":{}", tl.para_index.unwrap_or(0));
if let Some(owner) = &tl.caption_owner {
extra.push_str(",\"captionOwner\":");
extra.push_str(&serde_json::to_string(owner).expect("integer caption address"));
}
("TextLine", extra)
}
RenderNodeType::TextRun(tr) => {
let mut extra = format!(
",\"text\":{},\"pi\":{}",
json_escape(&tr.text),
tr.section_index
.map(|_| tr.para_index.unwrap_or(0))
.unwrap_or(0)
);
if let Some(display_text) = &tr.display_text {
extra.push_str(",\"displayText\":");
extra.push_str(&json_escape(display_text));
}
("TextRun", extra)
}
RenderNodeType::Table(tn) => (
"Table",
format!(
",\"rows\":{},\"cols\":{}{}{}",
tn.row_count,
tn.col_count,
tn.para_index
.map(|pi| format!(",\"pi\":{}", pi))
.unwrap_or_default(),
tn.control_index
.map(|ci| format!(",\"ci\":{}", ci))
.unwrap_or_default()
),
),
RenderNodeType::TableCell(tc) => {
("Cell", format!(",\"row\":{},\"col\":{}", tc.row, tc.col))
}
RenderNodeType::Image(image) => {
let mut extra = String::new();
if let Some(para_index) = image.para_index {
extra.push_str(&format!(",\"pi\":{para_index}"));
}
if let Some(control_index) = image.control_index {
extra.push_str(&format!(",\"ci\":{control_index}"));
}
let text_wrap = image
.text_wrap
.or_else(|| self.layer.and_then(|layer| layer.text_wrap));
if let Some(text_wrap) = text_wrap {
let name = match text_wrap {
TextWrap::Square => "Square",
TextWrap::Tight => "Tight",
TextWrap::Through => "Through",
TextWrap::TopAndBottom => "TopAndBottom",
TextWrap::BehindText => "BehindText",
TextWrap::InFrontOfText => "InFrontOfText",
};
extra.push_str(",\"textWrap\":");
extra.push_str(&json_escape(name));
}
("Image", extra)
}
RenderNodeType::TextBox => ("TextBox", String::new()),
RenderNodeType::Equation(_) => ("Equation", String::new()),
RenderNodeType::Line(_) => ("Line", String::new()),
RenderNodeType::Rectangle(_) => ("Rect", String::new()),
RenderNodeType::Ellipse(_) => ("Ellipse", String::new()),
RenderNodeType::Path(_) => ("Path", String::new()),
RenderNodeType::Group(_) => ("Group", String::new()),
RenderNodeType::FormObject(_) => ("Form", String::new()),
RenderNodeType::FootnoteMarker(_) => ("FnMarker", String::new()),
RenderNodeType::Placeholder(ph) => ("Placeholder", ph.control_ref_json_extra()),
RenderNodeType::RawSvg(raw) => ("RawSvg", raw.control_ref_json_extra()),
};
buf.push_str(&format!(
"\"type\":\"{}\",\"bbox\":{{\"x\":{:.1},\"y\":{:.1},\"w\":{:.1},\"h\":{:.1}}}",
type_str, self.bbox.x, self.bbox.y, self.bbox.width, self.bbox.height
));
buf.push_str(&extra);
if !self.children.is_empty() {
buf.push_str(",\"children\":[");
for (i, child) in self.children.iter().enumerate() {
if i > 0 {
buf.push(',');
}
child.write_json(buf);
}
buf.push(']');
}
buf.push('}');
}
}
fn json_escape(s: &str) -> String {
let mut out = String::with_capacity(s.len() + 2);
out.push('"');
for ch in s.chars() {
match ch {
'"' => out.push_str("\\\""),
'\\' => out.push_str("\\\\"),
'\n' => out.push_str("\\n"),
'\r' => out.push_str("\\r"),
'\t' => out.push_str("\\t"),
c if c < '\x20' => out.push_str(&format!("\\u{:04x}", c as u32)),
c => out.push(c),
}
}
out.push('"');
out
}
#[allow(clippy::large_enum_variant)]
#[derive(Debug, Clone, Serialize)]
pub enum RenderNodeType {
Page(PageNode),
PageBackground(PageBackgroundNode),
MasterPage,
Header,
Footer,
Body {
clip_rect: Option<BoundingBox>,
},
Column(u16),
FootnoteArea,
TextLine(TextLineNode),
TextRun(TextRunNode),
Table(TableNode),
TableCell(TableCellNode),
Line(LineNode),
Rectangle(RectangleNode),
Ellipse(EllipseNode),
Path(PathNode),
Image(ImageNode),
Group(GroupNode),
TextBox,
Equation(EquationNode),
FormObject(FormObjectNode),
FootnoteMarker(FootnoteMarkerNode),
Placeholder(PlaceholderNode),
RawSvg(RawSvgNode),
}
#[derive(Debug, Clone, Serialize)]
pub struct ObjectControlRef {
pub section_index: usize,
pub para_index: usize,
pub control_index: usize,
pub kind: &'static str,
}
impl ObjectControlRef {
pub fn ole(section_index: usize, para_index: usize, control_index: usize) -> Self {
Self {
section_index,
para_index,
control_index,
kind: "ole",
}
}
pub fn picture(section_index: usize, para_index: usize, control_index: usize) -> Self {
Self {
section_index,
para_index,
control_index,
kind: "picture",
}
}
fn json_extra(&self) -> String {
format!(
",\"kind\":\"{}\",\"si\":{},\"pi\":{},\"ci\":{}",
self.kind, self.section_index, self.para_index, self.control_index
)
}
}
#[derive(Debug, Clone, Serialize)]
pub struct RawSvgNode {
#[serde(skip)]
pub emf_source: Option<crate::emf::EmfReplaySource>,
pub svg: String,
pub control_ref: Option<ObjectControlRef>,
#[serde(skip)]
pub cell_context: Option<crate::renderer::layout::CellContext>,
}
impl RawSvgNode {
pub fn new(svg: String) -> Self {
Self {
emf_source: None,
svg,
control_ref: None,
cell_context: None,
}
}
pub fn ole(
svg: String,
section_index: usize,
para_index: usize,
control_index: usize,
cell_context: Option<crate::renderer::layout::CellContext>,
) -> Self {
Self {
emf_source: None,
svg,
control_ref: Some(ObjectControlRef::ole(
section_index,
para_index,
control_index,
)),
cell_context,
}
}
fn control_ref_json_extra(&self) -> String {
self.control_ref
.as_ref()
.map(ObjectControlRef::json_extra)
.unwrap_or_default()
}
}
#[derive(Debug, Clone, Serialize)]
pub struct PlaceholderNode {
pub fill_color: u32,
pub stroke_color: u32,
pub label: String,
pub control_ref: Option<ObjectControlRef>,
pub kind: PlaceholderKind,
#[serde(skip)]
pub cell_context: Option<crate::renderer::layout::CellContext>,
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default, Serialize)]
pub enum PlaceholderKind {
#[default]
Ole,
MissingPicture,
}
impl PlaceholderNode {
pub fn new(fill_color: u32, stroke_color: u32, label: String) -> Self {
Self {
fill_color,
stroke_color,
label,
control_ref: None,
kind: PlaceholderKind::default(),
cell_context: None,
}
}
pub fn missing_picture(
section_index: Option<usize>,
para_index: Option<usize>,
control_index: Option<usize>,
cell_context: Option<crate::renderer::layout::CellContext>,
) -> Self {
let control_ref = match (section_index, para_index, control_index) {
(Some(si), Some(pi), Some(ci)) => Some(ObjectControlRef::picture(si, pi, ci)),
_ => None,
};
Self {
fill_color: 0x00FFFFFF,
stroke_color: 0x00999999,
label: String::new(),
control_ref,
kind: PlaceholderKind::MissingPicture,
cell_context,
}
}
pub fn ole(
fill_color: u32,
stroke_color: u32,
label: String,
section_index: usize,
para_index: usize,
control_index: usize,
cell_context: Option<crate::renderer::layout::CellContext>,
) -> Self {
Self {
fill_color,
stroke_color,
label,
control_ref: Some(ObjectControlRef::ole(
section_index,
para_index,
control_index,
)),
kind: PlaceholderKind::default(),
cell_context,
}
}
fn control_ref_json_extra(&self) -> String {
self.control_ref
.as_ref()
.map(ObjectControlRef::json_extra)
.unwrap_or_default()
}
}
#[derive(Debug, Clone, Serialize)]
pub struct FootnoteMarkerNode {
pub number: u16,
pub text: String,
pub base_font_size: f64,
pub baseline: f64,
pub font_family: String,
pub color: u32,
pub section_index: usize,
pub para_index: usize,
pub control_index: usize,
}
impl FootnoteMarkerNode {
pub fn font_size(base: f64) -> f64 {
base * 0.75
}
pub fn reference_baseline(base: f64, line_baseline: f64) -> f64 {
line_baseline - base * 0.21
}
}
#[derive(Debug, Clone, Serialize)]
pub struct FormObjectNode {
pub form_type: crate::model::control::FormType,
pub caption: String,
pub text: String,
#[serde(skip_serializing_if = "Option::is_none")]
pub display_text: Option<String>,
pub appearance: super::form_appearance::FormAppearance,
pub fore_color: String,
pub back_color: String,
pub value: i32,
pub enabled: bool,
pub section_index: usize,
pub para_index: usize,
pub control_index: usize,
pub name: String,
pub cell_location: Option<(usize, usize, usize, usize)>,
}
impl FormObjectNode {
pub(crate) fn form_display_text(form: &crate::model::control::FormObject) -> Option<String> {
if form.form_type == crate::model::control::FormType::ComboBox && form.text.is_empty() {
return form.properties.get("listItem0").cloned();
}
if form.form_type != crate::model::control::FormType::Edit {
return None;
}
let first_line = form.text.split(['\r', '\n']).next().unwrap_or_default();
if let Some(mask) = form
.properties
.get("PasswordChar")
.and_then(|value| value.chars().next())
{
Some(mask.to_string().repeat(first_line.chars().count()))
} else {
(first_line.len() != form.text.len()).then(|| first_line.to_owned())
}
}
pub fn display_or_text(&self) -> &str {
self.display_text.as_deref().unwrap_or(&self.text)
}
}
#[derive(Debug, Clone, Copy, Default, Serialize)]
pub struct BoundingBox {
pub x: f64,
pub y: f64,
pub width: f64,
pub height: f64,
}
impl BoundingBox {
pub fn new(x: f64, y: f64, width: f64, height: f64) -> Self {
Self {
x,
y,
width,
height,
}
}
pub fn intersects(&self, other: &BoundingBox) -> bool {
self.x < other.x + other.width
&& self.x + self.width > other.x
&& self.y < other.y + other.height
&& self.y + self.height > other.y
}
pub fn contains(&self, other: &BoundingBox) -> bool {
self.x <= other.x
&& self.y <= other.y
&& self.x + self.width >= other.x + other.width
&& self.y + self.height >= other.y + other.height
}
pub fn from_hwpunit_rect(rect: &Rect, dpi: f64) -> Self {
let scale = dpi / super::HWPUNIT_PER_INCH;
Self {
x: rect.left as f64 * scale,
y: rect.top as f64 * scale,
width: rect.width() as f64 * scale,
height: rect.height() as f64 * scale,
}
}
}
pub fn body_clip_with_editor_marks(clip: BoundingBox, show_editor_marks: bool) -> BoundingBox {
if show_editor_marks {
BoundingBox::new(clip.x, clip.y, clip.width + 48.0, clip.height)
} else {
clip
}
}
#[derive(Debug, Clone, Serialize)]
pub struct PageNode {
pub page_index: u32,
pub width: f64,
pub height: f64,
pub section_index: usize,
}
#[derive(Debug, Clone, Serialize)]
pub struct PageBackgroundNode {
pub background_color: Option<ColorRef>,
pub border_color: Option<ColorRef>,
pub border_width: f64,
pub gradient: Option<Box<GradientFillInfo>>,
pub image: Option<PageBackgroundImage>,
}
#[derive(Debug, Clone, Serialize)]
pub struct PageBackgroundImage {
#[serde(skip)]
pub data: Vec<u8>,
pub fill_mode: ImageFillMode,
pub brightness: i8,
pub contrast: i8,
pub effect: ImageEffect,
}
impl PageBackgroundImage {
pub const fn display_brightness_contrast(&self) -> (i8, i8) {
(self.contrast, self.brightness)
}
pub fn is_watermark(&self) -> bool {
self.brightness != 0 && self.contrast != 0
}
pub fn is_real_picture_watermark_tone_preset(&self) -> bool {
let (bright, contrast) = self.display_brightness_contrast();
is_real_picture_watermark_tone_preset(self.effect, bright, contrast)
}
}
#[derive(Debug, Clone, Copy, Serialize, PartialEq, Eq)]
#[serde(rename_all = "camelCase")]
pub struct CaptionOwner {
pub sec_idx: usize,
pub para_idx: usize,
pub control_idx: usize,
pub control_kind: CaptionControlKind,
pub caption_ordinal: usize,
}
#[derive(Debug, Clone, Copy, Serialize, PartialEq, Eq)]
#[serde(rename_all = "lowercase")]
pub enum CaptionControlKind {
Table,
Image,
Shape,
}
impl CaptionOwner {
pub fn new(
section_index: Option<usize>,
para_index: Option<usize>,
control_index: Option<usize>,
control_kind: CaptionControlKind,
) -> Option<Self> {
Some(Self {
sec_idx: section_index?,
para_idx: para_index?,
control_idx: control_index?,
control_kind,
caption_ordinal: 0,
})
}
}
#[derive(Debug, Clone, Serialize)]
pub struct TextLineNode {
#[serde(rename = "captionOwner", skip_serializing_if = "Option::is_none")]
pub caption_owner: Option<CaptionOwner>,
pub line_height: f64,
pub baseline: f64,
pub section_index: Option<usize>,
pub para_index: Option<usize>,
pub line_index: Option<u32>,
pub vpos: Option<i32>,
}
impl TextLineNode {
pub fn new(line_height: f64, baseline: f64) -> Self {
Self {
caption_owner: None,
line_height,
baseline,
section_index: None,
para_index: None,
line_index: None,
vpos: None,
}
}
pub fn with_para(
line_height: f64,
baseline: f64,
section_index: usize,
para_index: usize,
) -> Self {
Self {
line_height,
baseline,
section_index: Some(section_index),
para_index: Some(para_index),
line_index: None,
vpos: None,
caption_owner: None,
}
}
pub fn with_para_vpos(
line_height: f64,
baseline: f64,
section_index: usize,
para_index: usize,
line_index: u32,
vpos: i32,
) -> Self {
Self {
line_height,
baseline,
section_index: Some(section_index),
para_index: Some(para_index),
line_index: Some(line_index),
vpos: Some(vpos),
caption_owner: None,
}
}
}
#[derive(Debug, Clone, PartialEq, Serialize)]
pub struct TextRunNode {
pub text: String,
pub style: TextStyle,
pub char_shape_id: Option<u32>,
pub para_shape_id: Option<u16>,
pub section_index: Option<usize>,
pub para_index: Option<usize>,
pub char_start: Option<usize>,
pub cell_context: Option<CellContext>,
pub is_para_end: bool,
pub is_line_break_end: bool,
pub rotation: f64,
pub is_vertical: bool,
pub char_overlap: Option<CharOverlapInfo>,
pub border_fill_id: u16,
pub baseline: f64,
pub field_marker: FieldMarkerType,
#[serde(skip_serializing_if = "Option::is_none")]
pub layout_positions: Option<Vec<f64>>,
pub display_text: Option<String>,
}
impl TextRunNode {
pub(crate) fn logical_char_count(&self) -> usize {
if self.char_overlap.is_some() {
usize::from(!self.text.is_empty())
} else {
self.text.chars().count()
}
}
pub(crate) fn ends_with_alignment_tab(text: &str) -> bool {
text.trim_end_matches([' ', '\u{2007}']).ends_with('\t')
}
pub(crate) fn resolve_trailing_tab_end(
&mut self,
requested_width: f64,
leader_limit_width: f64,
) -> Option<f64> {
let text = self.display_or_text();
if !Self::ends_with_alignment_tab(text)
|| !requested_width.is_finite()
|| requested_width < 0.0
|| !leader_limit_width.is_finite()
|| leader_limit_width < requested_width
{
return None;
}
let chars: Vec<char> = text.chars().collect();
let mut positions = self.replay_positions_for(text).into_owned();
super::validated_replay_positions(text, Some(&positions))?;
let tab = chars.iter().rposition(|character| *character == '\t')?;
let suffix = chars[tab + 1..].iter().collect::<String>();
let suffix_style = self.style.for_text_fragment(tab + 1);
let suffix_positions = super::layout::compute_char_positions(&suffix, &suffix_style);
let suffix_width = *suffix_positions.last()?;
let width = requested_width.max(positions[tab] + suffix_width);
let tab_end = width - suffix_width;
if !tab_end.is_finite() || tab_end < positions[tab] {
return None;
}
for (position, offset) in positions[tab + 1..].iter_mut().zip(&suffix_positions) {
*position = tab_end + offset;
}
super::validated_replay_positions(text, Some(&positions))?;
let leaders = super::layout::extract_tab_leaders_with_extended(
text,
&positions,
&self.style,
&self.style.inline_tabs,
);
self.layout_positions = Some(positions);
self.style.tab_leaders = leaders;
Some(width)
}
pub fn display_or_text(&self) -> &str {
self.display_text.as_deref().unwrap_or(&self.text)
}
pub(crate) fn metric_or_display_text(&self) -> &str {
super::composer::display_projection_metric_text(
&self.text,
self.display_or_text(),
self.style.literal_soft_hyphen,
)
}
pub(crate) fn validated_layout_positions_for(&self, replay_text: &str) -> Option<&[f64]> {
super::validated_replay_positions(replay_text, self.layout_positions.as_deref())
}
pub(crate) fn replay_positions_for<'a>(
&'a self,
replay_text: &str,
) -> std::borrow::Cow<'a, [f64]> {
let metric_text = super::composer::display_projection_metric_text(
&self.text,
replay_text,
self.style.literal_soft_hyphen,
);
let replay_text = super::composer::one_to_one_pua_replay_text(metric_text);
super::replay_positions_or_compute(
&replay_text,
&self.style,
self.layout_positions.as_deref(),
)
}
pub(crate) fn replay_positions_prefix_for<'a>(
&'a self,
full_replay_text: &str,
prefix_replay_text: &str,
) -> std::borrow::Cow<'a, [f64]> {
let max_scalars = super::kerning::MAX_KERNING_RUN_CODE_POINTS;
let prefix_scalar_count = prefix_replay_text.chars().take(max_scalars + 1).count();
let prefix_matches = prefix_scalar_count <= max_scalars
&& full_replay_text
.chars()
.take(prefix_scalar_count)
.eq(prefix_replay_text.chars());
if prefix_matches {
if let Some(positions) = self.validated_layout_positions_for(full_replay_text) {
if let Some(prefix) = positions.get(..=prefix_scalar_count) {
return std::borrow::Cow::Borrowed(prefix);
}
}
}
let prefix_replay_text = super::composer::one_to_one_pua_replay_text(prefix_replay_text);
std::borrow::Cow::Owned(super::layout::compute_char_positions(
&prefix_replay_text,
&self.style,
))
}
}
#[derive(Debug, Clone, Copy, PartialEq, Default, Serialize)]
pub enum FieldMarkerType {
#[default]
None,
FieldBegin,
FieldEnd,
FieldBeginEnd,
ShapeMarker(usize),
}
#[derive(Debug, Clone, Serialize)]
pub struct TableNode {
pub row_count: u16,
pub col_count: u16,
pub border_fill_id: u16,
pub section_index: Option<usize>,
pub para_index: Option<usize>,
pub control_index: Option<usize>,
#[serde(default)]
pub cell_context: Option<CellContext>,
}
#[derive(Debug, Clone, Serialize)]
pub struct TableCellNode {
pub col: u16,
pub row: u16,
pub col_span: u16,
pub row_span: u16,
pub border_fill_id: u16,
pub text_direction: u8,
pub clip: bool,
#[serde(default)]
pub closed_reflow_frame: bool,
pub page_fragment: bool,
pub model_cell_index: Option<u32>,
#[serde(skip_serializing_if = "Option::is_none")]
pub model_para_range: Option<(usize, usize)>,
}
#[derive(Debug, Clone, Copy, Default, Serialize)]
pub struct ShapeTransform {
pub rotation: f64,
pub horz_flip: bool,
pub vert_flip: bool,
#[serde(skip_serializing_if = "Option::is_none")]
pub image_frame_ratio: Option<[f64; 2]>,
}
impl ShapeTransform {
pub fn matrix_about(&self, bbox: BoundingBox) -> [f64; 6] {
let (sin, cos) = self.rotation.to_radians().sin_cos();
let sx = if self.horz_flip { -1.0 } else { 1.0 };
let sy = if self.vert_flip { -1.0 } else { 1.0 };
let (a, b, c, d) = (cos * sx, sin * sx, -sin * sy, cos * sy);
let cx = bbox.x + bbox.width / 2.0;
let cy = bbox.y + bbox.height / 2.0;
[a, b, c, d, cx - a * cx - c * cy, cy - b * cx - d * cy]
}
pub fn has_transform(&self) -> bool {
self.rotation != 0.0 || self.horz_flip || self.vert_flip
}
pub fn reflected_rotation(&self) -> f64 {
if self.horz_flip ^ self.vert_flip {
-self.rotation
} else {
self.rotation
}
}
pub fn effective_image_bbox(&self, bbox: &BoundingBox) -> BoundingBox {
if let Some([width, height]) = self.image_frame_ratio {
return BoundingBox::new(
bbox.x + bbox.width * (1.0 - width) / 2.0,
bbox.y + bbox.height * (1.0 - height) / 2.0,
bbox.width * width,
bbox.height * height,
);
}
let r = self.rotation.rem_euclid(360.0);
let is_perpendicular = (r - 90.0).abs() < 1.0 || (r - 270.0).abs() < 1.0;
if !is_perpendicular {
return *bbox;
}
let cx = bbox.x + bbox.width / 2.0;
let cy = bbox.y + bbox.height / 2.0;
let new_w = bbox.height;
let new_h = bbox.width;
BoundingBox::new(cx - new_w / 2.0, cy - new_h / 2.0, new_w, new_h)
}
}
#[derive(Debug, Clone, Serialize)]
pub struct LineNode {
pub x1: f64,
pub y1: f64,
pub x2: f64,
pub y2: f64,
pub style: LineStyle,
#[serde(skip_serializing_if = "Option::is_none")]
pub underpaint_color: Option<u32>,
pub section_index: Option<usize>,
pub para_index: Option<usize>,
pub control_index: Option<usize>,
pub transform: ShapeTransform,
#[serde(default)]
pub cell_index: Option<usize>,
#[serde(default)]
pub cell_para_index: Option<usize>,
#[serde(default)]
pub outer_table_control_index: Option<usize>,
}
impl LineNode {
pub fn new(x1: f64, y1: f64, x2: f64, y2: f64, style: LineStyle) -> Self {
Self {
x1,
y1,
x2,
y2,
style,
underpaint_color: None,
section_index: None,
para_index: None,
control_index: None,
transform: ShapeTransform::default(),
cell_index: None,
cell_para_index: None,
outer_table_control_index: None,
}
}
pub(crate) fn paint_strokes(&self) -> impl Iterator<Item = Self> {
let mut primary = self.clone();
primary.underpaint_color = None;
if self.underpaint_color.is_some() {
primary.style.compound_component = true;
}
let underpaint = self.underpaint_color.map(|color| {
let mut stroke = primary.clone();
stroke.style.color = color;
stroke
});
underpaint.into_iter().chain(std::iter::once(primary))
}
pub fn ink_bbox(&self) -> BoundingBox {
let stroke = self.style.width.max(0.0);
let half = stroke / 2.0;
let x_min = self.x1.min(self.x2);
let y_min = self.y1.min(self.y2);
let dx = (self.x2 - self.x1).abs();
let dy = (self.y2 - self.y1).abs();
if dy <= LINE_AXIS_EPSILON_PX && dx > LINE_AXIS_EPSILON_PX {
BoundingBox::new(x_min, y_min - half, dx, stroke)
} else if dx <= LINE_AXIS_EPSILON_PX && dy > LINE_AXIS_EPSILON_PX {
BoundingBox::new(x_min - half, y_min, stroke, dy)
} else {
BoundingBox::new(x_min - half, y_min - half, dx + stroke, dy + stroke)
}
}
}
const LINE_AXIS_EPSILON_PX: f64 = 0.01;
#[derive(Debug, Clone, Serialize)]
pub struct RectangleNode {
pub corner_radius: f64,
pub style: ShapeStyle,
pub gradient: Option<Box<GradientFillInfo>>,
#[serde(default, skip_serializing_if = "std::ops::Not::not")]
pub picture_border: bool,
#[serde(default, skip_serializing_if = "std::ops::Not::not")]
pub round_stroke_join: bool,
pub section_index: Option<usize>,
pub para_index: Option<usize>,
pub control_index: Option<usize>,
pub transform: ShapeTransform,
#[serde(default)]
pub cell_index: Option<usize>,
#[serde(default)]
pub cell_para_index: Option<usize>,
#[serde(default)]
pub outer_table_control_index: Option<usize>,
#[serde(skip)]
pub image_frame_owner: Option<NodeId>,
#[serde(skip)]
pub picture_border_width_hu: Option<i32>,
#[serde(skip)]
pub print_picture_pen: Option<[f64; 2]>,
#[serde(skip)]
pub drawing_border_width_hu: Option<i32>,
}
impl RectangleNode {
pub fn new(
corner_radius: f64,
style: ShapeStyle,
gradient: Option<Box<GradientFillInfo>>,
) -> Self {
Self {
corner_radius,
style,
gradient,
picture_border: false,
round_stroke_join: false,
section_index: None,
para_index: None,
control_index: None,
transform: ShapeTransform::default(),
cell_index: None,
cell_para_index: None,
outer_table_control_index: None,
image_frame_owner: None,
picture_border_width_hu: None,
print_picture_pen: None,
drawing_border_width_hu: None,
}
}
}
#[derive(Debug, Clone, Serialize)]
pub struct EllipseNode {
pub style: ShapeStyle,
pub gradient: Option<Box<GradientFillInfo>>,
pub section_index: Option<usize>,
pub para_index: Option<usize>,
pub control_index: Option<usize>,
pub transform: ShapeTransform,
#[serde(default)]
pub cell_index: Option<usize>,
#[serde(default)]
pub cell_para_index: Option<usize>,
#[serde(default)]
pub outer_table_control_index: Option<usize>,
}
impl EllipseNode {
pub fn new(style: ShapeStyle, gradient: Option<Box<GradientFillInfo>>) -> Self {
Self {
style,
gradient,
section_index: None,
para_index: None,
control_index: None,
transform: ShapeTransform::default(),
cell_index: None,
cell_para_index: None,
outer_table_control_index: None,
}
}
}
#[derive(Debug, Clone, Serialize)]
pub struct PathNode {
pub commands: Vec<PathCommand>,
pub style: ShapeStyle,
pub gradient: Option<Box<GradientFillInfo>>,
pub section_index: Option<usize>,
pub para_index: Option<usize>,
pub control_index: Option<usize>,
pub transform: ShapeTransform,
pub connector_endpoints: Option<(f64, f64, f64, f64)>,
pub line_style: Option<LineStyle>,
#[serde(default)]
pub cell_index: Option<usize>,
#[serde(default)]
pub cell_para_index: Option<usize>,
#[serde(default)]
pub outer_table_control_index: Option<usize>,
}
impl PathNode {
pub fn new(
commands: Vec<PathCommand>,
style: ShapeStyle,
gradient: Option<Box<GradientFillInfo>>,
) -> Self {
Self {
commands,
style,
gradient,
section_index: None,
para_index: None,
control_index: None,
transform: ShapeTransform::default(),
connector_endpoints: None,
line_style: None,
cell_index: None,
cell_para_index: None,
outer_table_control_index: None,
}
}
}
#[derive(Debug, Clone, Serialize)]
pub struct ImageNode {
pub bin_data_id: u16,
#[serde(skip)]
pub data: Option<Vec<u8>>,
#[serde(skip)]
pub hancom2024_print_bitmap: bool,
pub section_index: Option<usize>,
pub para_index: Option<usize>,
pub control_index: Option<usize>,
pub fill_mode: Option<ImageFillMode>,
pub original_size: Option<(f64, f64)>,
pub transform: ShapeTransform,
pub crop: Option<(i32, i32, i32, i32)>,
pub original_size_hu: Option<(u32, u32)>,
pub effect: ImageEffect,
pub brightness: i8,
pub contrast: i8,
pub opacity: f64,
pub text_wrap: Option<TextWrap>,
#[serde(default)]
pub external_path: Option<String>,
#[serde(default)]
pub header_footer_ref: Option<HeaderFooterImageRef>,
#[serde(default)]
pub cell_index: Option<usize>,
#[serde(default)]
pub cell_para_index: Option<usize>,
#[serde(default)]
pub outer_table_control_index: Option<usize>,
#[serde(default)]
pub cell_context: Option<CellContext>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub content_inset: Option<[f64; 4]>,
#[serde(skip_serializing_if = "Option::is_none")]
pub pre_rotation_ratio: Option<[f64; 2]>,
#[serde(skip_serializing_if = "Option::is_none")]
pub source_rect: Option<super::image_geometry::PictureSourceRect>,
}
#[derive(Debug, Clone, serde::Serialize, serde::Deserialize, PartialEq, Eq)]
pub struct HeaderFooterImageRef {
pub outer_para_index: usize,
pub outer_control_index: usize,
pub kind: HeaderFooterKind,
}
#[derive(Debug, Clone, Copy, serde::Serialize, serde::Deserialize, PartialEq, Eq)]
#[serde(rename_all = "lowercase")]
pub enum HeaderFooterKind {
Header,
Footer,
}
impl ImageNode {
pub fn is_watermark(&self) -> bool {
self.brightness != 0 && self.contrast != 0
}
pub fn is_real_picture_watermark_tone_preset(&self) -> bool {
is_real_picture_watermark_tone_preset(self.effect, self.brightness, self.contrast)
}
pub fn new(bin_data_id: u16, data: Option<Vec<u8>>) -> Self {
Self {
bin_data_id,
data,
hancom2024_print_bitmap: false,
section_index: None,
para_index: None,
control_index: None,
fill_mode: None,
original_size: None,
transform: ShapeTransform::default(),
crop: None,
original_size_hu: None,
effect: ImageEffect::RealPic,
brightness: 0,
contrast: 0,
opacity: 1.0,
text_wrap: None,
external_path: None,
header_footer_ref: None,
cell_index: None,
cell_para_index: None,
outer_table_control_index: None,
cell_context: None,
content_inset: None,
pre_rotation_ratio: None,
source_rect: None,
}
}
pub fn paint_bbox(&self, frame: &BoundingBox) -> BoundingBox {
let Some([left, top, right, bottom]) = self.content_inset else {
return *frame;
};
BoundingBox::new(
frame.x + frame.width * left,
frame.y + frame.height * top,
frame.width * (1.0 - left - right),
frame.height * (1.0 - top - bottom),
)
}
pub fn transformed_paint_bbox(&self, frame: &BoundingBox) -> BoundingBox {
self.paint_geometry(frame).bitmap
}
pub fn source_clip_path(&self, frame: &BoundingBox) -> Option<[[f64; 2]; 4]> {
self.paint_geometry(frame).clip
}
pub fn source_clip_bbox(&self, frame: &BoundingBox) -> Option<BoundingBox> {
let points = self.source_clip_path(frame)?;
let min_x = points.iter().map(|p| p[0]).fold(f64::INFINITY, f64::min);
let min_y = points.iter().map(|p| p[1]).fold(f64::INFINITY, f64::min);
let max_x = points
.iter()
.map(|p| p[0])
.fold(f64::NEG_INFINITY, f64::max);
let max_y = points
.iter()
.map(|p| p[1])
.fold(f64::NEG_INFINITY, f64::max);
Some(BoundingBox::new(min_x, min_y, max_x - min_x, max_y - min_y))
}
fn paint_geometry(&self, frame: &BoundingBox) -> super::image_geometry::PicturePaintGeometry {
let base = super::image_geometry::pre_rotation_bbox(
&self.paint_bbox(frame),
self.transform,
self.pre_rotation_ratio,
);
super::image_geometry::source_geometry(base, self.transform, self.source_rect)
}
}
#[derive(Debug, Clone, Serialize)]
pub struct GroupNode {
#[serde(skip_serializing_if = "Option::is_none")]
pub paint_transform: Option<[f64; 6]>,
pub section_index: Option<usize>,
pub para_index: Option<usize>,
pub control_index: Option<usize>,
}
#[derive(Debug, Clone, Serialize)]
pub struct NoteControlRef {
pub kind: String,
pub section_index: usize,
pub para_index: usize,
pub control_index: usize,
pub note_para_index: usize,
pub inner_control_index: usize,
}
#[derive(Debug, Clone, Serialize)]
pub struct EquationNode {
pub svg_content: String,
pub layout_box: crate::renderer::equation::layout::LayoutBox,
pub color_str: String,
pub color: u32,
pub font_size: f64,
#[serde(default)]
pub script: String,
pub section_index: Option<usize>,
pub para_index: Option<usize>,
pub control_index: Option<usize>,
pub cell_index: Option<usize>,
pub cell_para_index: Option<usize>,
pub note_ref: Option<NoteControlRef>,
}
pub type InlineShapeKey = (usize, usize, usize, Vec<(usize, usize, usize)>);
pub(crate) type DocPath = Vec<u32>;
fn push_cell_path(path: &mut DocPath, cell_path: &[crate::renderer::layout::CellPathEntry]) {
for entry in cell_path {
path.push(entry.control_index as u32);
path.push(entry.cell_index as u32);
path.push(entry.cell_para_index as u32);
}
}
fn doc_path_full(
section_index: Option<usize>,
para_index: Option<usize>,
cell_context: Option<&CellContext>,
control_index: Option<usize>,
) -> Option<DocPath> {
let (si, pi, ci) = (section_index?, para_index?, control_index?);
let mut path: DocPath = vec![si as u32, pi as u32];
if let Some(ctx) = cell_context {
push_cell_path(&mut path, &ctx.path);
}
path.push(ci as u32);
Some(path)
}
#[allow(clippy::too_many_arguments)]
fn doc_path_single_cell_level(
section_index: Option<usize>,
para_index: Option<usize>,
outer_table_control_index: Option<usize>,
cell_index: Option<usize>,
cell_para_index: Option<usize>,
control_index: Option<usize>,
) -> Option<DocPath> {
let (si, pi, ci) = (section_index?, para_index?, control_index?);
let mut path: DocPath = vec![si as u32, pi as u32];
if let Some(cell_idx) = cell_index {
path.push(outer_table_control_index.unwrap_or(0) as u32);
path.push(cell_idx as u32);
path.push(cell_para_index.unwrap_or(0) as u32);
}
path.push(ci as u32);
Some(path)
}
pub(crate) fn doc_path_for_node(node: &RenderNode) -> Option<DocPath> {
match &node.node_type {
RenderNodeType::Table(t) => doc_path_full(
t.section_index,
t.para_index,
t.cell_context.as_ref(),
t.control_index,
),
RenderNodeType::Image(i) => doc_path_full(
i.section_index,
i.para_index,
i.cell_context.as_ref(),
i.control_index,
),
RenderNodeType::Equation(e) => doc_path_single_cell_level(
e.section_index,
e.para_index,
None,
e.cell_index,
e.cell_para_index,
e.control_index,
),
RenderNodeType::Rectangle(r) => doc_path_single_cell_level(
r.section_index,
r.para_index,
r.outer_table_control_index,
r.cell_index,
r.cell_para_index,
r.control_index,
),
RenderNodeType::Line(l) => doc_path_single_cell_level(
l.section_index,
l.para_index,
l.outer_table_control_index,
l.cell_index,
l.cell_para_index,
l.control_index,
),
RenderNodeType::Ellipse(el) => doc_path_single_cell_level(
el.section_index,
el.para_index,
el.outer_table_control_index,
el.cell_index,
el.cell_para_index,
el.control_index,
),
RenderNodeType::Path(p) => doc_path_single_cell_level(
p.section_index,
p.para_index,
p.outer_table_control_index,
p.cell_index,
p.cell_para_index,
p.control_index,
),
RenderNodeType::Group(g) => {
doc_path_full(g.section_index, g.para_index, None, g.control_index)
}
_ => None,
}
}
#[derive(Debug, Clone)]
pub struct PageLayoutContext {
next_id: NodeId,
inline_shape_positions: std::collections::HashMap<InlineShapeKey, (f64, f64)>,
page_index: u32,
page_bbox: BoundingBox,
horizontal_shaping_sidecars: HorizontalShapingPageSidecars,
vertical_shaping_sidecars: VerticalShapingPageSidecars,
}
impl PageLayoutContext {
pub fn new(page_index: u32, width: f64, height: f64) -> Self {
Self {
next_id: 1,
inline_shape_positions: std::collections::HashMap::new(),
page_index,
page_bbox: BoundingBox::new(0.0, 0.0, width, height),
horizontal_shaping_sidecars: HorizontalShapingPageSidecars::default(),
vertical_shaping_sidecars: VerticalShapingPageSidecars::default(),
}
}
pub fn page_index(&self) -> u32 {
self.page_index
}
pub fn page_bbox(&self) -> BoundingBox {
self.page_bbox
}
pub fn page_size(&self) -> (f64, f64) {
(self.page_bbox.width, self.page_bbox.height)
}
fn cell_path_from_ctx(
cell_ctx: Option<&crate::renderer::layout::CellContext>,
) -> Vec<(usize, usize, usize)> {
cell_ctx
.map(|ctx| {
ctx.path
.iter()
.map(|e| (e.control_index, e.cell_index, e.cell_para_index))
.collect()
})
.unwrap_or_default()
}
pub fn set_inline_shape_position(
&mut self,
sec: usize,
para: usize,
ctrl: usize,
cell_ctx: Option<&crate::renderer::layout::CellContext>,
x: f64,
y: f64,
) {
let cell_path = Self::cell_path_from_ctx(cell_ctx);
let para_for_key = cell_ctx.map(|c| c.parent_para_index).unwrap_or(para);
self.inline_shape_positions
.insert((sec, para_for_key, ctrl, cell_path), (x, y));
}
pub fn get_inline_shape_position(
&self,
sec: usize,
para: usize,
ctrl: usize,
cell_ctx: Option<&crate::renderer::layout::CellContext>,
) -> Option<(f64, f64)> {
let cell_path = Self::cell_path_from_ctx(cell_ctx);
let para_for_key = cell_ctx.map(|c| c.parent_para_index).unwrap_or(para);
self.inline_shape_positions
.get(&(sec, para_for_key, ctrl, cell_path))
.copied()
}
pub fn translate_inline_shape_positions_y(
&mut self,
keep: impl Fn(&InlineShapeKey) -> bool,
dy: f64,
) {
for (key, (_, y)) in self.inline_shape_positions.iter_mut() {
if keep(key) {
*y += dy;
}
}
}
pub fn inline_shape_positions(&self) -> &std::collections::HashMap<InlineShapeKey, (f64, f64)> {
&self.inline_shape_positions
}
pub fn next_id(&mut self) -> NodeId {
let id = self.next_id;
self.next_id += 1;
id
}
pub(crate) fn preview_node_ids(
&self,
count: u32,
) -> Result<NodeId, VerticalShapingSidecarRejectReason> {
if count == 0 {
return Err(VerticalShapingSidecarRejectReason::NodeSequenceMismatch);
}
self.next_id
.checked_add(count)
.ok_or(VerticalShapingSidecarRejectReason::NodeSequenceOverflow)?;
Ok(self.next_id)
}
pub(crate) fn commit_bounded_vertical_hwp5_table_cell_frame(
&mut self,
expected_first_id: NodeId,
node_count: u32,
sidecar: std::sync::Arc<BoundedVerticalHwp5TableCellSidecar>,
) -> Result<(), VerticalShapingSidecarRejectReason> {
if expected_first_id != self.next_id || sidecar.line_node_id() != expected_first_id {
return Err(VerticalShapingSidecarRejectReason::NodeSequenceMismatch);
}
let next_id = self
.next_id
.checked_add(node_count)
.ok_or(VerticalShapingSidecarRejectReason::NodeSequenceOverflow)?;
self.vertical_shaping_sidecars
.attach_bounded_hwp5_table_cell_atomic(sidecar)?;
self.next_id = next_id;
Ok(())
}
pub(crate) fn attach_horizontal_shaping_sidecar(
&mut self,
node_id: NodeId,
expected_range: HorizontalShapingRunRange,
decision: std::sync::Arc<HorizontalShapingRunDecision>,
) -> Result<(), HorizontalShapingSidecarRejectReason> {
self.horizontal_shaping_sidecars
.attach(node_id, expected_range, decision)
}
pub(crate) fn publish_horizontal_shaping_no_lineseg_owner_transaction(
&mut self,
transaction: crate::renderer::shaping_composition::HorizontalShapingNoLineSegOwnerTransaction,
) -> Result<
crate::renderer::shaping_composition::HorizontalShapingNoLineSegPublication,
crate::renderer::shaping_composition::HorizontalShapingNoLineSegOwnerRejection,
> {
crate::renderer::shaping_composition::publish_horizontal_shaping_no_lineseg_owner_transaction(
&mut self.horizontal_shaping_sidecars,
transaction,
)
}
pub(crate) fn horizontal_shaping_sidecar(
&self,
node_id: NodeId,
) -> Option<&std::sync::Arc<HorizontalShapingRunDecision>> {
self.horizontal_shaping_sidecars.get(node_id)
}
pub(crate) fn horizontal_shaping_sidecars(&self) -> &HorizontalShapingPageSidecars {
&self.horizontal_shaping_sidecars
}
pub(crate) fn horizontal_shaping_sidecar_count(&self) -> usize {
self.horizontal_shaping_sidecars.len()
}
pub(crate) fn horizontal_shaping_sidecar_registry_generation(&self) -> Option<u64> {
self.horizontal_shaping_sidecars.registry_generation()
}
pub(crate) fn vertical_shaping_sidecar(
&self,
node_id: NodeId,
) -> Option<&std::sync::Arc<BoundedVerticalHwp5TableCellSidecar>> {
self.vertical_shaping_sidecars.get(node_id)
}
pub(crate) fn vertical_shaping_sidecar_count(&self) -> usize {
self.vertical_shaping_sidecars.len()
}
pub(crate) fn vertical_shaping_sidecar_registry_generation(&self) -> Option<u64> {
self.vertical_shaping_sidecars.registry_generation()
}
}
#[deprecated(note = "use PageLayoutContext")]
pub type LayoutFrame = PageLayoutContext;
#[derive(Debug, Clone, Serialize)]
pub struct PageRenderTree {
pub root: RenderNode,
#[serde(skip)]
pub(crate) frame: PageLayoutContext,
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
enum ClipReplayPlane {
BehindText,
Flow,
InFrontOfText,
}
impl ClipReplayPlane {
fn from_text_wrap(wrap: Option<TextWrap>) -> Self {
match wrap {
Some(TextWrap::BehindText) => Self::BehindText,
Some(TextWrap::InFrontOfText) => Self::InFrontOfText,
_ => Self::Flow,
}
}
}
impl PageRenderTree {
pub fn new(page_index: u32, width: f64, height: f64) -> Self {
let root = RenderNode::new(
0,
RenderNodeType::Page(PageNode {
page_index,
width,
height,
section_index: 0,
}),
BoundingBox::new(0.0, 0.0, width, height),
);
Self {
root,
frame: PageLayoutContext::new(page_index, width, height),
}
}
pub(crate) fn frame_mut(&mut self) -> &mut PageLayoutContext {
&mut self.frame
}
pub fn set_inline_shape_position(
&mut self,
sec: usize,
para: usize,
ctrl: usize,
cell_ctx: Option<&crate::renderer::layout::CellContext>,
x: f64,
y: f64,
) {
self.frame
.set_inline_shape_position(sec, para, ctrl, cell_ctx, x, y);
}
pub fn get_inline_shape_position(
&self,
sec: usize,
para: usize,
ctrl: usize,
cell_ctx: Option<&crate::renderer::layout::CellContext>,
) -> Option<(f64, f64)> {
self.frame
.get_inline_shape_position(sec, para, ctrl, cell_ctx)
}
pub fn inline_shape_positions(&self) -> &std::collections::HashMap<InlineShapeKey, (f64, f64)> {
self.frame.inline_shape_positions()
}
pub fn next_id(&mut self) -> NodeId {
self.frame.next_id()
}
pub(crate) fn apply_legacy_hancom_product_display_projection(&mut self) {
fn visit(node: &mut RenderNode) {
if let RenderNodeType::TextRun(run) = &mut node.node_type {
if run.char_overlap.is_none() {
if legacy_hancom_product_display_text(&run.text).is_some() {
let source = run.display_or_text();
if let Some(display) = legacy_hancom_product_display_text(source) {
run.display_text = Some(display);
}
}
}
}
for child in &mut node.children {
visit(child);
}
}
visit(&mut self.root);
}
pub fn clip_overlapping_same_bin_images(&mut self) {
let mut images: Vec<(
NodeId,
BoundingBox,
u16,
Option<(i32, i32, i32, i32)>,
ClipReplayPlane,
)> = Vec::new();
Self::collect_image_nodes(&self.root, &mut images);
if images.len() < 2 {
return;
}
let mut clips: std::collections::HashMap<NodeId, (f64, Option<(i32, i32, i32, i32)>)> =
std::collections::HashMap::new();
for i in 0..images.len() {
for j in (i + 1)..images.len() {
let (id_a, bbox_a, bin_a, crop_a, plane_a) = &images[i];
let (_id_b, bbox_b, bin_b, _crop_b, plane_b) = &images[j];
if bin_a != bin_b {
continue;
}
if plane_a != plane_b {
continue;
}
let epsilon = f64::EPSILON
* 32.0
* [
bbox_a.x.abs(),
bbox_b.x.abs(),
bbox_a.y.abs(),
bbox_b.y.abs(),
bbox_a.width,
bbox_b.width,
bbox_a.height,
bbox_b.height,
1.0,
]
.into_iter()
.fold(1.0_f64, f64::max);
let overlap_x =
(bbox_a.x + bbox_a.width).min(bbox_b.x + bbox_b.width) - bbox_a.x.max(bbox_b.x);
if overlap_x <= epsilon {
continue;
}
if (bbox_a.x - bbox_b.x).abs() > 1.0 {
continue;
}
if (bbox_a.width - bbox_b.width).abs() > 1.0 {
continue;
}
if bbox_a.y >= bbox_b.y {
continue;
}
let a_bottom = bbox_a.y + bbox_a.height;
if a_bottom - bbox_b.y <= epsilon {
continue;
}
let new_height = bbox_b.y - bbox_a.y;
if new_height <= 0.0 || new_height >= bbox_a.height {
continue;
}
let ratio = new_height / bbox_a.height;
let new_crop = crop_a.map(|(cl, ct, cr, cb)| {
let span = (cb - ct) as f64;
let new_cb = ct + (span * ratio).round() as i32;
(cl, ct, cr, new_cb)
});
let entry = clips.entry(*id_a).or_insert((new_height, new_crop));
if new_height < entry.0 {
*entry = (new_height, new_crop);
}
}
}
if clips.is_empty() {
return;
}
Self::apply_image_clips(&mut self.root, &clips);
}
fn collect_image_nodes(
node: &RenderNode,
out: &mut Vec<(
NodeId,
BoundingBox,
u16,
Option<(i32, i32, i32, i32)>,
ClipReplayPlane,
)>,
) {
if let RenderNodeType::Image(img) = &node.node_type {
out.push((
node.id,
node.bbox,
img.bin_data_id,
img.crop,
ClipReplayPlane::from_text_wrap(img.text_wrap),
));
}
for child in &node.children {
Self::collect_image_nodes(child, out);
}
}
fn apply_image_clips(
node: &mut RenderNode,
clips: &std::collections::HashMap<NodeId, (f64, Option<(i32, i32, i32, i32)>)>,
) {
if let Some((new_height, new_crop)) = clips.get(&node.id) {
node.bbox.height = *new_height;
if let RenderNodeType::Image(ref mut img) = &mut node.node_type {
if let Some(c) = new_crop {
img.crop = Some(*c);
}
}
}
for child in &mut node.children {
Self::apply_image_clips(child, clips);
}
}
}
impl Deref for PageRenderTree {
type Target = PageLayoutContext;
fn deref(&self) -> &Self::Target {
&self.frame
}
}
impl DerefMut for PageRenderTree {
fn deref_mut(&mut self) -> &mut Self::Target {
&mut self.frame
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn test_bounding_box_intersects() {
let a = BoundingBox::new(0.0, 0.0, 100.0, 100.0);
let b = BoundingBox::new(50.0, 50.0, 100.0, 100.0);
let c = BoundingBox::new(200.0, 200.0, 50.0, 50.0);
assert!(a.intersects(&b));
assert!(!a.intersects(&c));
}
#[test]
fn test_bounding_box_contains() {
let outer = BoundingBox::new(0.0, 0.0, 200.0, 200.0);
let inner = BoundingBox::new(10.0, 10.0, 50.0, 50.0);
assert!(outer.contains(&inner));
assert!(!inner.contains(&outer));
}
#[test]
fn test_page_render_tree() {
let mut tree = PageRenderTree::new(0, 793.7, 1122.5);
assert_eq!(tree.next_id(), 1);
assert_eq!(tree.next_id(), 2);
}
#[test]
fn legacy_hancom_product_projection_covers_direct_text_runs_only() {
fn text_run(id: NodeId, text: &str) -> RenderNode {
RenderNode::new(
id,
RenderNodeType::TextRun(TextRunNode {
text: text.to_owned(),
style: TextStyle::default(),
char_shape_id: None,
para_shape_id: None,
section_index: None,
para_index: None,
char_start: None,
cell_context: None,
is_para_end: false,
is_line_break_end: false,
rotation: 0.0,
is_vertical: false,
char_overlap: None,
border_fill_id: 0,
baseline: 0.0,
field_marker: FieldMarkerType::None,
layout_positions: None,
display_text: None,
}),
BoundingBox::new(0.0, 0.0, 1.0, 1.0),
)
}
let mut tree = PageRenderTree::new(0, 100.0, 100.0);
let product_id = tree.next_id();
tree.root.children.push(text_run(product_id, "ᄒᆞᆫ글 97"));
let general_old_hangul_id = tree.next_id();
tree.root
.children
.push(text_run(general_old_hangul_id, "ᄒᆞᆫ겨울은 일반 옛한글이다"));
tree.apply_legacy_hancom_product_display_projection();
let RenderNodeType::TextRun(product) = &tree.root.children[0].node_type else {
panic!("expected product text run");
};
assert_eq!(product.text, "ᄒᆞᆫ글 97", "원문/offset 공간은 보존한다");
assert_eq!(product.display_text.as_deref(), Some("한글 97"));
let RenderNodeType::TextRun(general_old_hangul) = &tree.root.children[1].node_type else {
panic!("expected general old-Hangul text run");
};
assert_eq!(general_old_hangul.display_text, None);
}
#[test]
fn legacy_hancom_product_projection_does_not_rewrite_pua_old_hangul() {
let mut tree = PageRenderTree::new(0, 100.0, 100.0);
let id = tree.next_id();
tree.root.children.push(RenderNode::new(
id,
RenderNodeType::TextRun(TextRunNode {
text: "\u{f53a}글".to_owned(),
style: TextStyle::default(),
char_shape_id: None,
para_shape_id: None,
section_index: None,
para_index: None,
char_start: None,
cell_context: None,
is_para_end: false,
is_line_break_end: false,
rotation: 0.0,
is_vertical: false,
char_overlap: None,
border_fill_id: 0,
baseline: 0.0,
field_marker: FieldMarkerType::None,
layout_positions: None,
display_text: Some("ᄒᆞᆫ글".to_owned()),
}),
BoundingBox::new(0.0, 0.0, 1.0, 1.0),
));
tree.apply_legacy_hancom_product_display_projection();
let RenderNodeType::TextRun(pua_old_hangul) = &tree.root.children[0].node_type else {
panic!("expected PUA old-Hangul text run");
};
assert_eq!(pua_old_hangul.text, "\u{f53a}글");
assert_eq!(pua_old_hangul.display_text.as_deref(), Some("ᄒᆞᆫ글"));
}
#[test]
fn test_bounding_box_from_hwpunit() {
use crate::model::Rect;
let rect = Rect {
left: 0,
top: 0,
right: 7200,
bottom: 7200,
};
let bbox = BoundingBox::from_hwpunit_rect(&rect, 96.0);
assert!((bbox.width - 96.0).abs() < 0.01);
assert!((bbox.height - 96.0).abs() < 0.01);
}
#[test]
fn render_tree_json_exposes_image_owner_and_text_wrap() {
let mut tree = PageRenderTree::new(0, 100.0, 100.0);
let mut image = ImageNode::new(9, None);
image.para_index = Some(1355);
image.control_index = Some(0);
image.text_wrap = Some(TextWrap::Square);
let image_id = tree.next_id();
tree.root.children.push(RenderNode::new(
image_id,
RenderNodeType::Image(image),
BoundingBox::new(10.0, 20.0, 30.0, 40.0),
));
let json = tree.root.to_json();
assert!(json.contains("\"type\":\"Image\""));
assert!(json.contains("\"pi\":1355"));
assert!(json.contains("\"ci\":0"));
assert!(json.contains("\"textWrap\":\"Square\""));
}
fn make_image_node(
id: NodeId,
bbox: BoundingBox,
bin_id: u16,
crop: Option<(i32, i32, i32, i32)>,
) -> RenderNode {
let img = ImageNode {
crop,
..ImageNode::new(bin_id, None)
};
RenderNode::new(id, RenderNodeType::Image(img), bbox)
}
fn image_bbox(node: &RenderNode) -> BoundingBox {
node.bbox
}
fn image_crop(node: &RenderNode) -> Option<(i32, i32, i32, i32)> {
match &node.node_type {
RenderNodeType::Image(img) => img.crop,
_ => None,
}
}
#[test]
fn test_clip_different_bin_id_no_clip() {
let mut tree = PageRenderTree::new(0, 1122.5, 1587.4);
let _id = tree.next_id();
tree.root.children.push(make_image_node(
_id,
BoundingBox::new(100.0, 100.0, 200.0, 200.0),
1,
Some((0, 0, 100, 100)),
));
let _id = tree.next_id();
tree.root.children.push(make_image_node(
_id,
BoundingBox::new(100.0, 250.0, 200.0, 100.0),
2, Some((0, 0, 100, 100)),
));
tree.clip_overlapping_same_bin_images();
assert_eq!(image_bbox(&tree.root.children[0]).height, 200.0);
assert_eq!(image_bbox(&tree.root.children[1]).height, 100.0);
}
#[test]
fn test_clip_no_vertical_overlap_no_clip() {
let mut tree = PageRenderTree::new(0, 1122.5, 1587.4);
let _id = tree.next_id();
tree.root.children.push(make_image_node(
_id,
BoundingBox::new(100.0, 100.0, 200.0, 100.0), 1,
Some((0, 0, 100, 100)),
));
let _id = tree.next_id();
tree.root.children.push(make_image_node(
_id,
BoundingBox::new(100.0, 250.0, 200.0, 100.0), 1,
Some((0, 0, 100, 100)),
));
tree.clip_overlapping_same_bin_images();
assert_eq!(image_bbox(&tree.root.children[0]).height, 100.0);
assert_eq!(image_bbox(&tree.root.children[1]).height, 100.0);
}
#[test]
fn test_clip_different_x_no_clip() {
let mut tree = PageRenderTree::new(0, 1122.5, 1587.4);
let _id = tree.next_id();
tree.root.children.push(make_image_node(
_id,
BoundingBox::new(100.0, 100.0, 200.0, 200.0),
1,
Some((0, 0, 100, 100)),
));
let _id = tree.next_id();
tree.root.children.push(make_image_node(
_id,
BoundingBox::new(108.0, 150.0, 200.0, 200.0),
1,
Some((0, 0, 100, 100)),
));
tree.clip_overlapping_same_bin_images();
assert_eq!(image_bbox(&tree.root.children[0]).height, 200.0);
assert_eq!(image_bbox(&tree.root.children[1]).height, 200.0);
}
#[test]
fn test_clip_different_width_no_clip() {
let mut tree = PageRenderTree::new(0, 1122.5, 1587.4);
let _id = tree.next_id();
tree.root.children.push(make_image_node(
_id,
BoundingBox::new(100.0, 100.0, 200.0, 200.0),
1,
Some((0, 0, 100, 100)),
));
let _id = tree.next_id();
tree.root.children.push(make_image_node(
_id,
BoundingBox::new(100.0, 150.0, 100.0, 200.0),
1,
Some((0, 0, 100, 100)),
));
tree.clip_overlapping_same_bin_images();
assert_eq!(image_bbox(&tree.root.children[0]).height, 200.0);
assert_eq!(image_bbox(&tree.root.children[1]).height, 200.0);
}
#[test]
fn test_clip_reversed_order_no_clip() {
let mut tree = PageRenderTree::new(0, 1122.5, 1587.4);
let _id = tree.next_id();
tree.root.children.push(make_image_node(
_id,
BoundingBox::new(100.0, 250.0, 200.0, 100.0),
1,
Some((0, 0, 100, 100)),
));
let _id = tree.next_id();
tree.root.children.push(make_image_node(
_id,
BoundingBox::new(100.0, 100.0, 200.0, 200.0),
1,
Some((0, 0, 100, 100)),
));
tree.clip_overlapping_same_bin_images();
assert_eq!(image_bbox(&tree.root.children[0]).height, 100.0);
assert_eq!(image_bbox(&tree.root.children[1]).height, 200.0);
}
#[test]
fn test_clip_without_crop() {
let mut tree = PageRenderTree::new(0, 1122.5, 1587.4);
let _id = tree.next_id();
tree.root.children.push(make_image_node(
_id,
BoundingBox::new(100.0, 100.0, 200.0, 200.0),
1,
None,
));
let _id = tree.next_id();
tree.root.children.push(make_image_node(
_id,
BoundingBox::new(100.0, 250.0, 200.0, 100.0),
1,
None,
));
tree.clip_overlapping_same_bin_images();
assert!((image_bbox(&tree.root.children[0]).height - 150.0).abs() < 0.01);
assert!(image_crop(&tree.root.children[0]).is_none());
assert!((image_bbox(&tree.root.children[1]).height - 100.0).abs() < 0.01);
}
#[test]
fn test_clip_three_overlapping_chain() {
let mut tree = PageRenderTree::new(0, 1122.5, 1587.4);
let _id = tree.next_id();
tree.root.children.push(make_image_node(
_id,
BoundingBox::new(100.0, 0.0, 200.0, 200.0),
1,
Some((0, 0, 1000, 2000)),
));
let _id = tree.next_id();
tree.root.children.push(make_image_node(
_id,
BoundingBox::new(100.0, 100.0, 200.0, 150.0),
1,
Some((0, 1000, 1000, 2500)),
));
let _id = tree.next_id();
tree.root.children.push(make_image_node(
_id,
BoundingBox::new(100.0, 180.0, 200.0, 100.0),
1,
Some((0, 1800, 1000, 2800)),
));
tree.clip_overlapping_same_bin_images();
assert!((image_bbox(&tree.root.children[0]).height - 100.0).abs() < 0.01);
assert!((image_bbox(&tree.root.children[1]).height - 80.0).abs() < 0.01);
assert!((image_bbox(&tree.root.children[2]).height - 100.0).abs() < 0.01);
}
#[test]
fn test_clip_nested_children() {
let mut tree = PageRenderTree::new(0, 1122.5, 1587.4);
let mut body = RenderNode::new(
tree.next_id(),
RenderNodeType::Body { clip_rect: None },
BoundingBox::new(0.0, 0.0, 1000.0, 1500.0),
);
let _id = tree.next_id();
body.children.push(make_image_node(
_id,
BoundingBox::new(597.15, 243.59, 408.19, 256.09),
5,
Some((0, 0, 189900, 120958)),
));
let _id = tree.next_id();
body.children.push(make_image_node(
_id,
BoundingBox::new(597.15, 463.17, 408.19, 70.0),
5,
Some((0, 105958, 189900, 138540)),
));
tree.root.children.push(body);
tree.clip_overlapping_same_bin_images();
let body = &tree.root.children[0];
let lower = &body.children[0];
assert!((image_bbox(lower).height - 219.58).abs() < 0.01);
}
#[test]
fn test_clip_skips_cross_plane_pairs() {
let mut tree = PageRenderTree::new(0, 1122.5, 1587.4);
let mut flow = make_image_node(
tree.next_id(),
BoundingBox::new(100.0, 100.0, 200.0, 200.0),
9,
Some((0, 0, 1000, 2000)),
);
if let RenderNodeType::Image(ref mut img) = flow.node_type {
img.text_wrap = Some(TextWrap::Square);
}
let mut behind = make_image_node(
tree.next_id(),
BoundingBox::new(100.0, 150.0, 200.0, 200.0),
9,
Some((0, 0, 1000, 2000)),
);
if let RenderNodeType::Image(ref mut img) = behind.node_type {
img.text_wrap = Some(TextWrap::BehindText);
}
tree.root.children.push(flow);
tree.root.children.push(behind);
tree.clip_overlapping_same_bin_images();
assert_eq!(image_bbox(&tree.root.children[0]).height, 200.0);
assert_eq!(image_bbox(&tree.root.children[1]).height, 200.0);
}
#[test]
fn test_clip_single_image_no_op() {
let mut tree = PageRenderTree::new(0, 1122.5, 1587.4);
let _id = tree.next_id();
tree.root.children.push(make_image_node(
_id,
BoundingBox::new(100.0, 100.0, 200.0, 200.0),
1,
Some((0, 0, 100, 100)),
));
tree.clip_overlapping_same_bin_images();
assert_eq!(image_bbox(&tree.root.children[0]).height, 200.0);
assert_eq!(image_crop(&tree.root.children[0]), Some((0, 0, 100, 100)));
}
}