use super::super::page_layout::LayoutRect;
use super::super::render_tree::*;
use super::super::{format_number, ArrowStyle, LineStyle, NumberFormat as NumFmt, ShapeStyle};
use crate::model::bin_data::BinDataContent;
use crate::model::image::Picture;
use crate::model::style::{HeadType, Numbering, NUMBERING_LEVELS};
pub(crate) fn find_bin_data<'a>(
bin_data_content: &'a [BinDataContent],
bin_data_id: u16,
) -> Option<&'a BinDataContent> {
find_bin_data_index(bin_data_content, bin_data_id).map(|i| &bin_data_content[i])
}
pub(crate) fn find_bin_data_index(
bin_data_content: &[BinDataContent],
bin_data_id: u16,
) -> Option<usize> {
crate::model::bin_data::content_index(bin_data_content, bin_data_id)
}
pub(crate) fn find_bin_data_bytes(
bin_data_content: &[BinDataContent],
bin_data_id: u16,
) -> Option<Vec<u8>> {
find_bin_data(bin_data_content, bin_data_id).and_then(|c| {
c.data
.load_limited(crate::model::bin_data::MAX_BIN_DATA_BYTES)
})
}
pub(crate) fn picture_data_is_unusable(data: Option<&[u8]>) -> bool {
match data {
None => true,
Some(bytes) => {
bytes.is_empty() || !crate::renderer::image_resolver::is_displayable_image_data(bytes)
}
}
}
pub(crate) fn picture_display_size_hu(picture: &Picture) -> (i32, i32) {
let attr = &picture.shape_attr;
if picture.common.width > 0
&& picture.common.height > 0
&& attr.original_width > 0
&& attr.original_height > 0
&& !attr.raw_rendering.is_empty()
&& attr.render_b == 0.0
&& attr.render_c == 0.0
&& attr.rotation_angle.rem_euclid(360) == 0
{
let transformed_width = f64::from(attr.original_width) * attr.render_sx.abs();
let transformed_height = f64::from(attr.original_height) * attr.render_sy.abs();
if (transformed_width - f64::from(picture.common.width)).abs() <= 2.0
&& (transformed_height - f64::from(picture.common.height)).abs() <= 2.0
{
return (picture.common.width as i32, picture.common.height as i32);
}
}
if picture.shape_attr.rotation_angle.rem_euclid(360) != 0
&& picture.common.width > 0
&& picture.common.height > 0
&& picture.shape_attr.current_width > 0
&& picture.shape_attr.current_height > 0
{
return (picture.common.width as i32, picture.common.height as i32);
}
let mut width = picture.common.width as i32;
let mut height = picture.common.height as i32;
let current_width = picture.shape_attr.current_width as i32;
if current_width > 0 && current_width > width {
width = current_width;
}
let current_height = picture.shape_attr.current_height as i32;
if current_height > 0 && current_height > height {
height = current_height;
}
(width, height)
}
pub(crate) fn picture_flow_frame_size_hu(picture: &Picture) -> (i32, i32) {
let flows_beside = !picture.common.treat_as_char
&& matches!(
picture.common.text_wrap,
crate::model::shape::TextWrap::Square
| crate::model::shape::TextWrap::Tight
| crate::model::shape::TextWrap::Through
);
let saved_float_transform = !picture.common.treat_as_char
&& picture.shape_attr.group_level == 0
&& picture.shape_attr.has_saved_affine_geometry();
if (flows_beside || saved_float_transform)
&& picture.common.width > 0
&& picture.common.height > 0
{
crate::renderer::stored_picture_metrics::stored_picture_size_hu(picture)
} else {
picture_display_size_hu(picture)
}
}
pub(crate) fn picture_content_inset(picture: &Picture) -> Option<[f64; 4]> {
let p = &picture.padding;
if p.left == 0 && p.right == 0 && p.top == 0 && p.bottom == 0 {
return None;
}
let (w, h) = (picture.common.width as f64, picture.common.height as f64);
if w <= 0.0 || h <= 0.0 || picture.shape_attr.rotation_angle.rem_euclid(360) != 0 {
return None;
}
let inset = [
f64::from(p.left.max(0)) / w,
f64::from(p.top.max(0)) / h,
f64::from(p.right.max(0)) / w,
f64::from(p.bottom.max(0)) / h,
];
(inset[0] + inset[2] < 1.0 && inset[1] + inset[3] < 1.0).then_some(inset)
}
pub fn resolve_numbering_id(
head_type: HeadType,
para_numbering_id: u16,
outline_numbering_id: u16,
) -> u16 {
if para_numbering_id == 0 && head_type == HeadType::Outline {
outline_numbering_id
} else {
para_numbering_id
}
}
pub(crate) fn default_outline_numbering() -> Numbering {
let mut n = Numbering::default();
for f in n.level_formats.iter_mut() {
*f = "^N".to_string();
}
for head in n.heads.iter_mut() {
head.attr = DEFAULT_OUTLINE_HEAD_AUTO_INDENT;
head.width_adjust = 0;
head.text_distance = DEFAULT_OUTLINE_HEAD_TEXT_DISTANCE_PERCENT;
head.char_shape_id = u32::MAX;
}
n.start_number = 1;
n.level_start_numbers = [1; NUMBERING_LEVELS];
n
}
const DEFAULT_OUTLINE_HEAD_AUTO_INDENT: u32 = 1 << 3;
const DEFAULT_OUTLINE_HEAD_TEXT_DISTANCE_PERCENT: i16 = 50;
pub(crate) fn expand_numbering_format(
format_str: &str,
counters: &[u32; NUMBERING_LEVELS],
numbering: &Numbering,
start_numbers: &[u32; NUMBERING_LEVELS],
current_level: usize,
) -> String {
let format_level = |idx: usize| -> String {
let counter_val = counters[idx];
let start = start_numbers[idx];
let num = if counter_val > 0 {
start.saturating_sub(1) + counter_val
} else {
start
};
let fmt_code = numbering.heads[idx].number_format;
let num_fmt = NumFmt::from_hwp_format(fmt_code);
format_number(num as u16, num_fmt)
};
let mut result = String::new();
let mut chars = format_str.chars().peekable();
while let Some(ch) = chars.next() {
if ch == '^' {
match chars.peek() {
Some(&digit @ '0'..=':') => {
chars.next();
let level_ref = (digit as u8 - b'0') as usize;
if (1..=NUMBERING_LEVELS).contains(&level_ref) {
result.push_str(&format_level(level_ref - 1));
}
continue;
}
Some(&code @ ('n' | 'N')) => {
chars.next();
for idx in 0..=current_level.min(NUMBERING_LEVELS - 1) {
if idx > 0 {
result.push('.');
}
result.push_str(&format_level(idx));
}
if code == 'N' {
result.push('.');
}
continue;
}
_ => {}
}
}
result.push(ch);
}
result
}
pub(crate) fn format_page_number(
page_num: u32,
format: u8,
prefix_char: char,
suffix_char: char,
dash_char: char,
user_symbol: char,
) -> String {
let formatted = crate::renderer::note_marker::number_text(page_num as u16, format, user_symbol);
let prefix = if prefix_char != '\0' {
prefix_char.to_string()
} else {
String::new()
};
let suffix = if suffix_char != '\0' {
suffix_char.to_string()
} else {
String::new()
};
let dash = if dash_char != '\0' {
dash_char.to_string()
} else {
String::new()
};
if prefix.is_empty() && suffix.is_empty() && dash.is_empty() {
formatted
} else if dash.is_empty() {
format!("{}{}{}", prefix, formatted, suffix)
} else {
format!("{} {}{}{} {}", dash, prefix, formatted, suffix, dash)
}
}
pub(crate) fn extract_shape_transform(
sa: &crate::model::shape::ShapeComponentAttr,
) -> ShapeTransform {
ShapeTransform {
rotation: sa.rotation_angle as f64,
horz_flip: sa.horz_flip,
vert_flip: sa.vert_flip,
image_frame_ratio: None,
}
}
pub(crate) fn extract_picture_transform(picture: &Picture) -> ShapeTransform {
let mut transform = extract_shape_transform(&picture.shape_attr);
let shape = &picture.shape_attr;
if shape.rotation_angle.rem_euclid(360) != 0
&& shape.current_width > 0
&& shape.current_height > 0
&& picture.common.width > 0
&& picture.common.height > 0
{
transform.image_frame_ratio = Some([
f64::from(shape.current_width) / f64::from(picture.common.width),
f64::from(shape.current_height) / f64::from(picture.common.height),
]);
}
transform
}
pub(crate) fn drawing_to_shape_style(
drawing: &crate::model::shape::DrawingObjAttr,
dpi: f64,
) -> (ShapeStyle, Option<Box<super::super::GradientFillInfo>>) {
use super::super::GradientFillInfo;
use crate::model::style::FillType;
let fill_color = drawing.fill.solid.and_then(|s| {
if s.pattern_type > 0 || (s.background_color >> 24) != 0 {
None
} else {
Some(s.background_color)
}
});
let gradient = match drawing.fill.fill_type {
FillType::Gradient => drawing.fill.gradient.as_ref().map(|g| {
let positions: Vec<f64> = if g.positions.is_empty() {
let n = g.colors.len();
(0..n)
.map(|i| i as f64 / (n.max(2) - 1).max(1) as f64)
.collect()
} else {
g.positions.iter().map(|&p| p as f64 / 100.0).collect()
};
let (colors, positions) =
super::super::expand_gradient_steps(&g.colors, &positions, g.blur, g.step_center);
Box::new(GradientFillInfo {
gradient_type: g.gradient_type,
angle: g.angle,
center_x: g.center_x,
center_y: g.center_y,
colors,
positions,
})
}),
_ => None,
};
let border = &drawing.border_line;
let shape_line_type = border.attr & 0x3F;
let (mut stroke_width, mut stroke_color) = if shape_line_type == 0 {
(0.0, None)
} else {
let sw = crate::renderer::stroke_pattern::shape_pen_width_to_px(
border.width,
shape_line_type as u8,
);
let sc = if sw > 0.0 { Some(border.color) } else { None };
(sw, sc)
};
if shape_line_type > 0 && stroke_width == 0.0 {
stroke_width = 0.5; stroke_color = Some(border.color);
}
let stroke_dash = crate::renderer::line_style::hwp_shape_line_type(shape_line_type as u8).0;
let opacity = if drawing.fill.alpha > 0 {
1.0 - (drawing.fill.alpha as f64 / 255.0)
} else {
1.0
};
let pattern = drawing.fill.solid.and_then(|s| {
if s.pattern_type > 0 {
Some(super::super::PatternFillInfo {
pattern_type: s.pattern_type,
tile_size: super::super::hwpunit_to_px(576, dpi),
pattern_color: s.pattern_color,
background_color: s.background_color,
})
} else {
None
}
});
let shadow = if drawing.shadow_type > 0 {
Some(super::super::ShadowStyle {
shadow_type: drawing.shadow_type,
color: drawing.shadow_color,
offset_x: super::super::hwpunit_to_px(drawing.shadow_offset_x, 96.0),
offset_y: super::super::hwpunit_to_px(drawing.shadow_offset_y, 96.0),
alpha: drawing.shadow_alpha,
})
} else {
None
};
let style = ShapeStyle {
fill_color,
pattern,
stroke_color,
stroke_width,
stroke_dash,
opacity,
shadow,
};
(style, gradient)
}
pub(crate) fn drawing_to_line_style(drawing: &crate::model::shape::DrawingObjAttr) -> LineStyle {
let border = &drawing.border_line;
let attr = border.attr;
let shape_line_type = attr & 0x3F;
let width =
crate::renderer::stroke_pattern::shape_pen_width_to_px(border.width, shape_line_type as u8);
let (dash, line_render_type) =
crate::renderer::line_style::hwp_shape_line_type(shape_line_type as u8);
let start_arrow_val = (attr >> 10) & 0x3F;
let start_fill = (attr >> 30) & 1 != 0;
let start_arrow = arrow_type_from_hwp(start_arrow_val, start_fill);
let end_arrow_val = (attr >> 16) & 0x3F;
let end_fill = (attr >> 31) & 1 != 0;
let end_arrow = arrow_type_from_hwp(end_arrow_val, end_fill);
let start_arrow_size = ((attr >> 22) & 0x0F) as u8;
let end_arrow_size = ((attr >> 26) & 0x0F) as u8;
let shadow = if drawing.shadow_type > 0 {
Some(super::super::ShadowStyle {
shadow_type: drawing.shadow_type,
color: drawing.shadow_color,
offset_x: super::super::hwpunit_to_px(drawing.shadow_offset_x, 96.0),
offset_y: super::super::hwpunit_to_px(drawing.shadow_offset_y, 96.0),
alpha: drawing.shadow_alpha,
})
} else {
None
};
LineStyle {
color: border.color,
width: if width > 0.0 { width } else { 0.5 },
dash,
dash_pattern: None,
line_type: line_render_type,
compound_component: false,
preserve_fractional_position: false,
start_arrow,
end_arrow,
start_arrow_size,
end_arrow_size,
shadow,
}
}
fn arrow_type_from_hwp(hwp_type: u32, fill: bool) -> ArrowStyle {
match hwp_type {
0 => ArrowStyle::None,
1 => ArrowStyle::Arrow,
2 => ArrowStyle::OpenArrow, 3 => ArrowStyle::ConcaveArrow,
4 => {
if fill {
ArrowStyle::Diamond
} else {
ArrowStyle::OpenDiamond
}
}
5 => {
if fill {
ArrowStyle::Circle
} else {
ArrowStyle::OpenCircle
}
}
6 => {
if fill {
ArrowStyle::Square
} else {
ArrowStyle::OpenSquare
}
}
_ => ArrowStyle::None,
}
}
pub(crate) fn layout_rect_to_bbox(rect: &LayoutRect) -> BoundingBox {
BoundingBox::new(rect.x, rect.y, rect.width, rect.height)
}
#[cfg(test)]
mod tests {
use super::{find_bin_data, picture_display_size_hu};
use crate::model::bin_data::BinDataContent;
use crate::model::image::Picture;
fn mk(id: u16, ext: &str) -> BinDataContent {
BinDataContent {
id,
data: vec![].into(),
extension: ext.to_string(),
}
}
#[test]
fn find_bin_data_returns_none_for_zero() {
let v = vec![mk(1, "png")];
assert!(find_bin_data(&v, 0).is_none());
}
#[test]
fn picture_display_size_uses_larger_current_axis() {
let mut picture = Picture::default();
picture.common.width = 3365;
picture.common.height = 9446;
picture.shape_attr.current_width = 9014;
picture.shape_attr.current_height = 9446;
assert_eq!(picture_display_size_hu(&picture), (9014, 9446));
}
#[test]
fn picture_display_size_keeps_common_when_current_is_smaller() {
let mut picture = Picture::default();
picture.common.width = 9000;
picture.common.height = 8000;
picture.shape_attr.current_width = 3000;
picture.shape_attr.current_height = 4000;
assert_eq!(picture_display_size_hu(&picture), (9000, 8000));
}
#[test]
fn picture_flow_frame_uses_common_for_square_wrap_float() {
use super::picture_flow_frame_size_hu;
let mut picture = Picture::default();
picture.common.treat_as_char = false;
picture.common.text_wrap = crate::model::shape::TextWrap::Square;
picture.common.width = 14847; picture.common.height = 10230;
picture.shape_attr.current_width = 27494; picture.shape_attr.current_height = 18956;
assert_eq!(picture_flow_frame_size_hu(&picture), (14847, 10230));
let mut picture = Picture::default();
picture.common.treat_as_char = false;
picture.common.text_wrap = crate::model::shape::TextWrap::BehindText;
picture.common.width = 6000;
picture.common.height = 5000;
picture.shape_attr.current_width = 12000;
picture.shape_attr.current_height = 10000;
picture.shape_attr.raw_rendering = vec![1];
picture.shape_attr.render_sx = 0.5;
picture.shape_attr.render_sy = 0.5;
assert_eq!(picture_flow_frame_size_hu(&picture), (6000, 5000));
}
#[test]
fn picture_flow_frame_keeps_display_size_for_tac_inline() {
use super::picture_flow_frame_size_hu;
let mut picture = Picture::default();
picture.common.treat_as_char = true;
picture.common.text_wrap = crate::model::shape::TextWrap::Square;
picture.common.width = 3365; picture.common.height = 9446;
picture.shape_attr.current_width = 9014;
picture.shape_attr.current_height = 9446;
assert_eq!(picture_flow_frame_size_hu(&picture), (9014, 9446));
}
#[test]
fn picture_flow_frame_keeps_display_size_for_topbottom_float() {
use super::picture_flow_frame_size_hu;
let mut picture = Picture::default();
picture.common.treat_as_char = false;
picture.common.text_wrap = crate::model::shape::TextWrap::TopAndBottom;
picture.common.width = 3365;
picture.common.height = 9446;
picture.shape_attr.current_width = 9014;
picture.shape_attr.current_height = 9446;
assert_eq!(picture_flow_frame_size_hu(&picture), (9014, 9446));
}
#[test]
fn picture_flow_frame_falls_back_when_common_is_zero() {
use super::picture_flow_frame_size_hu;
let mut picture = Picture::default();
picture.common.treat_as_char = false;
picture.common.text_wrap = crate::model::shape::TextWrap::Square;
picture.common.width = 0;
picture.common.height = 0;
picture.shape_attr.current_width = 9014;
picture.shape_attr.current_height = 9446;
assert_eq!(picture_flow_frame_size_hu(&picture), (9014, 9446));
}
#[test]
fn find_bin_data_indexed_match_storage_id_differs() {
let v = vec![
mk(12, "png"), mk(1, "bmp"), mk(2, "bmp"), ];
let c = find_bin_data(&v, 1).expect("매칭 성공");
assert_eq!(c.id, 12);
assert_eq!(c.extension, "png");
}
#[test]
fn find_bin_data_indexed_match_storage_id_matches() {
let v = vec![mk(1, "jpg"), mk(2, "png"), mk(3, "bmp")];
for i in 1..=3u16 {
let c = find_bin_data(&v, i).expect("매칭 성공");
assert_eq!(c.id, i);
}
}
#[test]
fn find_bin_data_sparse_id_for_hwpx_chart() {
let v = vec![
mk(1, "png"),
mk(2, "png"),
mk(60001, "ooxml_chart"),
mk(60002, "ooxml_chart"),
];
let c = find_bin_data(&v, 60001).expect("차트 매칭");
assert_eq!(c.id, 60001);
assert_eq!(c.extension, "ooxml_chart");
let c2 = find_bin_data(&v, 60002).expect("차트 매칭");
assert_eq!(c2.id, 60002);
}
#[test]
fn find_bin_data_out_of_range_returns_none() {
let v = vec![mk(1, "png"), mk(2, "png")];
assert!(find_bin_data(&v, 99).is_none());
}
#[test]
fn find_bin_data_hwpx_realistic_layout_with_chart() {
let v = vec![
mk(1, "png"), mk(2, "png"), mk(3, "jpg"), mk(60001, "ooxml_chart"), mk(60002, "ooxml_chart"), ];
for i in 1..=3u16 {
let c = find_bin_data(&v, i).expect("그림 매칭");
assert_eq!(c.id, i);
assert!(c.extension == "png" || c.extension == "jpg");
}
let chart1 = find_bin_data(&v, 60001).expect("차트 1");
assert_eq!(chart1.id, 60001);
assert_eq!(chart1.extension, "ooxml_chart");
let chart2 = find_bin_data(&v, 60002).expect("차트 2");
assert_eq!(chart2.id, 60002);
}
#[test]
fn find_bin_data_hwp_hwpspec_page_bg_pattern() {
let v = vec![
mk(0x000C, "png"), mk(0x0001, "bmp"), mk(0x0002, "bmp"), mk(0x0003, "bmp"), mk(0x0004, "bmp"), mk(0x0005, "bmp"), mk(0x0006, "bmp"), mk(0x0007, "bmp"), mk(0x0008, "bmp"), mk(0x0009, "bmp"), mk(0x000A, "bmp"), mk(0x000B, "bmp"), mk(0x002B, "png"), mk(0x000D, "bmp"), ];
let bg = find_bin_data(&v, 1).expect("페이지 표지");
assert_eq!(
bg.id, 0x000C,
"회귀: bin_data_id=1 이 storage_id=12 가 아님 (가드가 정상 매칭을 거짓 실패시킴)"
);
assert_eq!(bg.extension, "png");
let p2 = find_bin_data(&v, 14).expect("두 번째 표지");
assert_eq!(p2.id, 0x000D);
assert_eq!(p2.extension, "bmp");
}
}