Skip to main content

rhwp/renderer/
mod.rs

1//! 렌더링 엔진 모듈
2//!
3//! IR(Document Model) → 렌더 트리 → 백엔드 렌더링 파이프라인을 구현한다.
4//! Renderer Trait으로 추상화하여 Canvas/SVG/HTML 백엔드를 선택할 수 있다.
5
6use serde::Serialize;
7
8use crate::model::control::Control;
9use crate::model::paragraph::LineSeg;
10use crate::model::style::{LineSpacingType, UnderlineType};
11
12pub(crate) mod arabic_context;
13pub(crate) mod arrow;
14#[cfg(any(feature = "native-skia", target_arch = "wasm32"))]
15pub(crate) mod bitmap_raster;
16pub(crate) mod blank_band;
17pub mod canvas;
18pub mod canvas_text_font;
19pub mod canvaskit_policy;
20pub(crate) mod cell_grid;
21pub(crate) mod cell_paragraph_spacing;
22pub mod char_overlap;
23pub mod composer;
24mod conjoining_jamo;
25pub(crate) mod footnote_frames;
26#[cfg(target_arch = "wasm32")]
27pub(crate) mod mipmap_sampling;
28pub use conjoining_jamo::IsolatedJamoFont;
29pub(crate) mod emphasis;
30pub(crate) mod enclosed_pua_geometry;
31pub(crate) mod endnote_spacing;
32pub mod equation;
33pub(crate) mod equation_tac_flow;
34pub(crate) mod filled_path_bounds;
35pub mod float_placement;
36pub(crate) mod font_decision;
37pub mod font_environment;
38mod font_fallback;
39pub mod font_metrics_data;
40#[cfg(not(target_arch = "wasm32"))]
41pub mod font_paths;
42#[path = "font_rule_projections/layout_metric.rs"]
43pub(crate) mod font_rule_layout_metric_projection;
44#[path = "font_rule_projections/layout_name.rs"]
45pub(crate) mod font_rule_layout_name_projection;
46pub mod font_symbol_coverage;
47pub mod form_appearance;
48pub(crate) mod form_caption;
49pub(crate) mod glyph_fit;
50pub(crate) mod gradient_geometry;
51pub(crate) mod hancom_pua;
52pub mod height_cursor;
53pub mod height_measurer;
54pub(crate) mod hft_ascii_evidence;
55pub(crate) mod hft_outline;
56pub mod html;
57pub(crate) mod hwp3_caption_host;
58pub mod hyperlinks;
59pub(crate) mod image_geometry;
60pub(crate) mod image_header;
61pub mod image_resolver;
62mod implicit_symbol;
63pub mod inline_flow;
64pub(crate) mod kerning;
65#[cfg(all(not(target_arch = "wasm32"), feature = "native-skia"))]
66pub mod kitty;
67pub mod layer_renderer;
68pub mod layout;
69pub(crate) mod layout_frame;
70pub(crate) mod legacy_font_advances;
71pub(crate) mod line_style;
72mod measured_glyph_supplier;
73pub(crate) mod metafile_geometry;
74#[cfg(not(target_arch = "wasm32"))]
75pub mod native_webfonts;
76pub(crate) mod note_marker;
77pub(crate) mod note_separator;
78pub(crate) mod object_alignment;
79pub mod page_layout;
80pub mod page_number;
81pub mod pagination;
82pub(crate) mod paint_order;
83#[cfg(any(target_arch = "wasm32", test))]
84pub(crate) mod partial_replay;
85#[cfg(not(target_arch = "wasm32"))]
86pub mod pdf;
87#[cfg(not(target_arch = "wasm32"))]
88pub mod pdf_raster_fidelity;
89mod physical_units;
90pub(crate) mod print_picture_pen;
91pub(crate) mod pua_glyph;
92pub mod pua_oldhangul;
93pub mod raster_pixels;
94pub(crate) mod raster_stroke;
95pub(crate) mod reflow_float_host_line;
96pub(crate) mod reflow_spacing;
97pub mod render_normalization;
98pub mod render_tree;
99pub mod scheduler;
100pub mod script_metrics;
101pub(crate) mod shaping;
102pub(crate) mod shaping_composition;
103pub(crate) mod shaping_context;
104pub(crate) mod shaping_paragraph;
105pub(crate) mod shaping_publication;
106#[cfg(all(not(target_arch = "wasm32"), feature = "native-skia"))]
107pub mod sixel;
108pub(crate) mod stored_frame_boundary;
109pub(crate) mod stored_picture_metrics;
110mod stroke_pattern;
111pub(crate) use stroke_pattern::char_outline_stroke;
112pub(crate) mod table_row_frame;
113pub(crate) mod text_font_coverage;
114pub mod text_font_presentation;
115pub(crate) mod text_glyph_visibility;
116pub(crate) mod text_ink;
117pub(crate) mod text_italic;
118// Q4-D1 registers the exact-source-bound vertical owner while all product
119// layout/publication callers remain closed until their own approved slices.
120pub(crate) mod anisotropic_sampling;
121pub(crate) mod contextual_text;
122pub(crate) mod cubic_sampling;
123pub mod native_pua_fonts;
124pub(crate) mod pdf_stroke;
125pub(crate) mod print_image_sampling;
126pub(crate) mod print_raster;
127#[allow(dead_code)]
128pub(crate) mod shaping_vertical;
129#[cfg(all(not(target_arch = "wasm32"), feature = "native-skia"))]
130pub mod skia;
131pub mod space_compression;
132pub(crate) mod static_svg;
133#[cfg(any(feature = "native-skia", target_arch = "wasm32"))]
134pub(crate) mod static_svg_raster;
135pub(crate) mod stored_control_frame;
136pub(crate) mod stored_float_anchor;
137mod stored_line_ladder;
138pub(crate) mod stored_page_origin;
139pub mod style_resolver;
140pub mod supplemental_metrics;
141pub mod svg;
142mod svg_buffer;
143pub mod svg_fragment;
144pub mod svg_layer;
145pub(crate) mod tab_leader;
146pub(crate) mod text_decoration;
147pub(crate) mod text_direction;
148pub(crate) mod text_transform;
149pub use text_direction::{BidiLayout, BidiVisualRun};
150pub mod typeset;
151#[cfg(target_arch = "wasm32")]
152pub mod web_canvas;
153
154use crate::model::ColorRef;
155
156/// 렌더링 백엔드 종류
157#[derive(Debug, Clone, Copy, PartialEq)]
158pub enum RenderBackend {
159    /// Canvas 2D API (1차)
160    Canvas,
161    /// SVG 엘리먼트 생성 (2차)
162    Svg,
163    /// HTML DOM 생성 (3차)
164    Html,
165}
166
167impl RenderBackend {
168    /// 문자열로부터 백엔드 파싱
169    pub fn from_str(s: &str) -> Option<Self> {
170        match s {
171            "canvas" => Some(RenderBackend::Canvas),
172            "svg" => Some(RenderBackend::Svg),
173            "html" => Some(RenderBackend::Html),
174            _ => None,
175        }
176    }
177}
178
179/// 탭 정지 (렌더링용)
180#[derive(Debug, Clone, PartialEq, Serialize)]
181pub struct TabStop {
182    /// 절대 위치 (px, 단 시작 기준)
183    pub position: f64,
184    /// 탭 종류 (0=왼쪽, 1=오른쪽, 2=가운데, 3=소수점)
185    pub tab_type: u8,
186    /// 채움 종류 (0=없음, 1=실선, 2=파선, 3=점선)
187    pub fill_type: u8,
188}
189crate::storage::clone_fields!(TabStop, {position, tab_type, fill_type});
190
191/// 탭 리더(채움 기호) 렌더링 정보
192#[derive(Debug, Clone, PartialEq, Serialize)]
193pub struct TabLeaderInfo {
194    /// 리더 시작 x (run 내 상대 좌표)
195    pub start_x: f64,
196    /// 리더 끝 x (run 내 상대 좌표)
197    pub end_x: f64,
198    /// 채움 종류 (1=실선, 2=파선, 3=점선)
199    pub fill_type: u8,
200}
201crate::storage::clone_fields!(TabLeaderInfo, {start_x, end_x, fill_type});
202
203pub(crate) fn clamp_tab_leader_end_x(
204    text: &str,
205    char_positions: &[f64],
206    leader: &TabLeaderInfo,
207    font_size: f64,
208) -> f64 {
209    let content_stop = text.chars().enumerate().find_map(|(i, ch)| {
210        if ch != '\t'
211            && !ch.is_whitespace()
212            && i < char_positions.len()
213            && char_positions[i] > leader.start_x + 0.5
214        {
215            Some(char_positions[i] - font_size * 0.25)
216        } else {
217            None
218        }
219    });
220    content_stop
221        .map(|stop| stop.min(leader.end_x).max(leader.start_x))
222        .unwrap_or(leader.end_x)
223}
224
225/// 글꼴 원래 하이픈 폭이 저장 글자 간격보다 커서 연속 하이픈이 실선으로
226/// 겹칠 때만, 각 글자의 짧은 획을 그릴 공통 기하를 돌려준다.
227/// 글자마다 별도 획을 남겨 한컴 출력의 파선과 문자 소유를 보존한다.
228pub(crate) fn overlapping_dash_leader_segment(
229    text: &str,
230    style: &TextStyle,
231    char_index: usize,
232    positions: &[f64],
233    font_size: f64,
234) -> Option<(f64, f64, f64, f64)> {
235    if style.shadow_type > 0 || style.outline_type > 0 || style.emboss || style.engrave {
236        return None;
237    }
238    let face = style
239        .font_family
240        .split(',')
241        .next()?
242        .trim()
243        .trim_matches(['\'', '"']);
244    if face != "한양신명조" || positions.len() <= char_index + 1 {
245        return None;
246    }
247    let chars: Vec<char> = text.chars().collect();
248    if chars.get(char_index) != Some(&'-') {
249        return None;
250    }
251    let left = chars[..char_index]
252        .iter()
253        .rev()
254        .take_while(|ch| **ch == '-')
255        .count();
256    let right = chars[char_index + 1..]
257        .iter()
258        .take_while(|ch| **ch == '-')
259        .count();
260    if left + right + 1 < 3 {
261        return None;
262    }
263    let advance = positions[char_index + 1] - positions[char_index];
264    // 저장 폭 표는 좁은 획(588/1024em)을 쓰지만 실제 SVG 글꼴은
265    // H2MJSM의 넓은 하이픈(853/1024em)을 칠한다. 겹침 판정은 칠할
266    // 글꼴의 폭으로 해야 한다.
267    let metric =
268        font_metrics_data::find_metric_decision("HYSinMyeongJo-Medium", style.bold, style.italic)?;
269    let natural_width =
270        f64::from(metric.metric.get_width('-')?) * font_size / f64::from(metric.metric.em_size);
271    if advance <= 0.0 || natural_width <= advance + 0.25 {
272        return None;
273    }
274    // 두 한컴 Print 원본의 실제 선분은 일반 서체 기준선에서 약 0.36em 위다.
275    // 굵게·기울임은 별도 잉크 근거가 없으므로 기존 위치를 유지한다.
276    // 길이는 저장 advance 안에서만 남긴다.
277    let end = (font_size * 0.38).min(advance * 0.7);
278    let rise = if style.bold || style.italic {
279        0.43
280    } else {
281        0.36
282    };
283    Some((0.0, end, -font_size * rise, font_size * 0.054))
284}
285
286/// Backend replay 직전의 optional scalar positions를 한 번 더 검증한다.
287///
288/// `TextRunNode` accessor와 positioned `Renderer` 직접 호출이 같은 bounded
289/// 계약을 소비하도록 하는 단일 판정이다. 문자열 projection으로 scalar 수가
290/// 달라지거나 payload가 손상되면 해당 run 전체를 K0로 되돌린다.
291pub(crate) fn validated_replay_positions<'a>(
292    replay_text: &str,
293    positions: Option<&'a [f64]>,
294) -> Option<&'a [f64]> {
295    let positions = positions?;
296    let max_scalars = kerning::MAX_KERNING_RUN_CODE_POINTS;
297    if positions.len() > max_scalars.saturating_add(1) {
298        return None;
299    }
300    let scalar_count = replay_text.chars().take(max_scalars + 1).count();
301    if scalar_count > max_scalars || positions.len() != scalar_count.saturating_add(1) {
302        return None;
303    }
304    if positions.first().copied() != Some(0.0)
305        || positions
306            .iter()
307            .any(|position| !position.is_finite() || *position < 0.0)
308        || positions.windows(2).any(|pair| pair[0] > pair[1])
309    {
310        return None;
311    }
312    Some(positions)
313}
314
315pub(crate) fn replay_positions_or_compute<'a>(
316    replay_text: &str,
317    style: &TextStyle,
318    positions: Option<&'a [f64]>,
319) -> std::borrow::Cow<'a, [f64]> {
320    validated_replay_positions(replay_text, positions)
321        .map(std::borrow::Cow::Borrowed)
322        .unwrap_or_else(|| {
323            std::borrow::Cow::Owned(layout::compute_char_positions(replay_text, style))
324        })
325}
326
327pub(crate) use glyph_fit::glyph_fit_positions;
328
329// 출력 backend와 기존 unit 검사의 공통 진입점은 유지한다.
330pub(crate) fn canvas_cluster_fit(
331    style: &TextStyle,
332    cluster: &str,
333    layout_cluster_advance: f64,
334    visual_width: f64,
335    ink_width: Option<f64>,
336    pin_ascii_advance: bool,
337) -> Option<(f64, f64)> {
338    glyph_fit::canvas_cluster_fit(
339        style,
340        cluster,
341        layout_cluster_advance,
342        visual_width,
343        ink_width,
344        pin_ascii_advance,
345    )
346}
347
348fn has_no_unjustified_leading_spaces(count: &usize) -> bool {
349    *count == 0
350}
351
352/// 텍스트 렌더링 스타일
353#[derive(Debug, Clone, PartialEq, Serialize)]
354pub struct TextStyle {
355    /// 리터럴 U+00AD는 표시 글리프와 원문 전진을 분리한다.
356    #[serde(skip)]
357    pub literal_soft_hyphen: bool,
358    #[serde(skip_serializing_if = "Option::is_none")]
359    pub text_paint: Option<crate::model::text_paint::TextPaintStyle>,
360    /// 리터럴 숫자 폭 공백. HWP 고정폭 빈칸 제어 문자와 구분한다.
361    #[serde(skip_serializing_if = "std::ops::Not::not")]
362    pub literal_figure_space: bool,
363    /// 리터럴 공백에 선택한 실제 슬롯 프로그램의 전진폭(em).
364    #[serde(skip_serializing_if = "Option::is_none")]
365    pub literal_figure_space_em: Option<f64>,
366    /// 원본과 분리된 세션의 첨자 조판 계약이다.
367    #[serde(skip)]
368    pub script_metrics: script_metrics::ScriptMetricsContract,
369    /// 원본 표 33의 signed 그림자 간격. 세션 paint에서만 사용한다.
370    #[serde(skip)]
371    pub shadow_offset_percent: Option<[i8; 2]>,
372    /// 공통 paint가 실제 공급 글꼴로 해소한 연속 그림자다.
373    #[serde(skip)]
374    pub continuous_shadow: Option<crate::paint::text_shadow::ContinuousTextShadow>,
375    /// 호스트가 실제 paint에 준비한 글꼴의 원 PUA 표시·전진 계약이다.
376    #[serde(skip)]
377    pub native_pua_metrics: Option<std::sync::Arc<native_pua_fonts::NativePuaMetrics>>,
378    /// Native paint가 실제 공급한 OTF의 세션 전진폭.
379    #[serde(skip)]
380    pub native_otf_metrics: Option<std::sync::Arc<native_pua_fonts::NativeOtfMetrics>>,
381    /// 글줄 전체에서 계산한 표시 방향. 모델/저장 스타일과 논리 전진은 바꾸지 않는다.
382    #[serde(skip_serializing_if = "Option::is_none")]
383    pub bidi_layout: Option<BidiLayout>,
384    /// 앞 run에서 시작한 같은 원문 자소의 첫 조각에는 강조점을 중복하지 않는다.
385    pub emphasis_skip_first_cluster: bool,
386    /// 실제 글줄의 최대 글꼴 크기. 위 밑줄은 비장식 글자도 포함한 이 크기를 따른다.
387    #[serde(skip_serializing_if = "Option::is_none")]
388    pub top_underline_font_size: Option<f64>,
389    /// 같은 원본 글자 모양 구간의 위 밑줄·아래 일점쇄선에서 이미 소비한 가로 길이.
390    #[serde(skip_serializing_if = "Option::is_none")]
391    pub top_underline_phase: Option<f64>,
392    /// Session-only glyph metrics; never part of document/style serialization.
393    #[serde(skip)]
394    pub supplemental_metrics:
395        Option<std::sync::Arc<supplemental_metrics::SupplementalMetricSnapshot>>,
396    /// 출력 세대가 독립 중성·종성에 선택한 무전진 프로그램. 세션 속성이다.
397    #[serde(skip)]
398    pub isolated_jamo_font: Option<IsolatedJamoFont>,
399    /// 같은 줄의 측정·배치가 공유하는 세션 한정 공백 결과다.
400    #[serde(skip)]
401    pub space_compression: Option<space_compression::SpaceCompression>,
402    /// 글꼴 이름
403    pub font_family: String,
404    /// 글꼴 크기 (px)
405    pub font_size: f64,
406    /// 저장 글줄 없이 생성한 텍스트의 원본 글자 폭을 paint에도 적용한다.
407    /// HFT 자동 쪽번호는 HFT 메트릭으로 정렬하므로 대체 TTF의 자연 폭을
408    /// 그대로 그리면 숫자·장식의 점유 폭이 달라진다. 본문은 기존 계약을 쓴다.
409    #[serde(skip_serializing)]
410    pub fixed_glyph_advances: bool,
411    /// 표시용 대체 face와 구분한 원본 언어 슬롯의 HFT 선언이다.
412    #[serde(skip_serializing)]
413    pub source_font_is_hft: bool,
414    /// 유형 미상과 구별한 원본 언어 슬롯의 명시적 TTF 선언이다.
415    #[serde(skip_serializing)]
416    pub source_font_is_ttf: bool,
417    /// 실제 원본 주 프로그램 선택. 같은 글리프의 실제 공급자와 대조한다.
418    #[serde(skip)]
419    pub selected_primary_font_program: Option<font_environment::FontProgramIdentity>,
420    /// 독립 출력에서 굵기 전진이 확인된 원본 글꼴 프로그램 선언이다.
421    #[serde(skip_serializing)]
422    pub source_verified_hft_bold_tracking: bool,
423    /// HWP3 원본의 HFT 굵기 전진 계약을 적용한다.
424    #[serde(skip_serializing)]
425    pub source_hwp3_hft_bold: bool,
426    /// 원본 글자 스타일에서 크기를 해소했는지. 명시적인 0과 미지정을 구별한다.
427    #[serde(skip_serializing)]
428    pub resolved_font_size: bool,
429    /// 공통 Print paint가 확정한 표시 em. 원본 크기·조판 전진은 유지한다.
430    #[serde(skip)]
431    pub print_ink_font_size: Option<f64>,
432    /// 원본 언어 슬롯의 글자 위치(%). 0은 기존 직렬화와 같이 생략한다.
433    #[serde(skip_serializing_if = "Option::is_none")]
434    pub font_position: Option<i8>,
435    /// 유지된 원본 HFT의 인쇄 paint 좌표 계약. 논리 조판/전진 폭과 별개다.
436    #[serde(skip_serializing)]
437    pub hft_print_frame: bool,
438    /// 명시적 원본 TTF 또는 검증된 세션 TTF의 text device 좌표 계약.
439    /// 원문 유형을 추정하지 않으며 Type3 그래픽의 fill 상태와 구분한다.
440    #[serde(skip_serializing)]
441    pub print_text_device_frame: bool,
442    /// 명시적으로 선택한 실제 프로그램의 잉크 폭. 논리 전진과 구분한다.
443    #[serde(skip_serializing)]
444    pub preserve_glyph_ink: bool,
445    /// 자연 프로그램의 전진을 명시적으로 선택했는지. 윤곽 폭 보존과 별개다.
446    #[serde(skip)]
447    pub natural_program_metrics: bool,
448    /// 글자 색상
449    pub color: ColorRef,
450    /// 진하게
451    pub bold: bool,
452    /// 기울임
453    pub italic: bool,
454    /// 밑줄 위치 (None/Bottom/Top)
455    pub underline: UnderlineType,
456    /// 취소선
457    pub strikethrough: bool,
458    /// 문서가 kerning pair positioning을 요청했는지 여부.
459    ///
460    /// `false`는 기존 layer-tree 직렬화에서 생략해 kerning-off schema와
461    /// byte baseline을 보존한다. 실제 pair adjustment는 공통 measurement
462    /// decision이 exact font capability를 확인한 뒤 별도로 결정한다.
463    #[serde(skip_serializing_if = "std::ops::Not::not")]
464    pub kerning: bool,
465    /// 자간 (px)
466    pub letter_spacing: f64,
467    /// 장평 비율 (1.0 = 100%, 0.8 = 80%)
468    pub ratio: f64,
469    /// 기본 탭 간격 (px, 0이면 font_size 기반 fallback)
470    pub default_tab_width: f64,
471    /// 커스텀 탭 정지 목록 (position 오름차순)
472    pub tab_stops: Vec<TabStop>,
473    /// 문단 오른쪽 끝 자동 탭 여부
474    pub auto_tab_right: bool,
475    /// 문단 왼쪽 자동 탭의 단 기준 위치. 저장 hint와 줄 채움이 같은 정지를 쓴다.
476    #[serde(default, skip_serializing_if = "Option::is_none")]
477    pub auto_left_tab_position: Option<f64>,
478    /// 사용 가능 너비 (px, auto_tab_right 계산용)
479    pub available_width: f64,
480    /// 단 시작으로부터 run 시작 위치 (탭 절대좌표 변환용)
481    pub line_x_offset: f64,
482    /// 단 시작으로부터 텍스트 영역 시작 위치 (effective_margin_left, px).
483    /// auto_tab_right 의 col-relative 위치 = text_start_offset + available_width.
484    /// [Task #874] 종전 find_next_tab_stop 의 auto_right 반환값(=available_width) 은
485    /// 텍스트-시작-상대 좌표였으나, 호출자(compute_char_positions / pending_right_tab)
486    /// 가 col-relative 로 해석해 effective_margin_left 만큼 좌측으로 밀린 정렬 발생.
487    /// 본 필드로 변환 보정.
488    pub text_start_offset: f64,
489    /// auto_tab_right + 다음 run-경계 cross 시 우측 정렬 블록의 총 폭 (px).
490    /// composer 가 lang/script 경계로 run 을 쪼개면 (예: "F3→Alt+I" → "F3"/"→"/"Alt+I")
491    /// `measure_segment_from` 이 현재 run 의 post-tab chars 만 측정하여 seg_w 가
492    /// 과소되고, 우측 정렬이 무너진다. paragraph_layout 에서 line 내 후속 runs 합산
493    /// 을 미리 계산해 주입한다. None 이면 기존 동작 (현재 run 내부 측정).
494    pub right_tab_block_width_override: Option<f64>,
495    /// 탭 리더 정보 (compute_char_positions 후 채움)
496    pub tab_leaders: Vec<TabLeaderInfo>,
497    /// HWPX 인라인 탭 확장 데이터 ([width, leader, type, ...])
498    pub inline_tabs: Vec<[u16; 7]>,
499    /// 양쪽 정렬용: 공백 문자당 추가 간격 (px)
500    pub extra_word_spacing: f64,
501    /// 이 런 앞부분의 분배 제외 문자 수. 선행 공백과 자동 탭 앞 항목 번호는
502    /// 원래 전진 폭을 보존하며 뒤 본문의 양쪽 정렬 여분을 받지 않는다.
503    #[serde(skip_serializing_if = "has_no_unjustified_leading_spaces")]
504    pub unjustified_leading_spaces: usize,
505    /// 배분/나눔 정렬용: 글자당 추가 간격 (px)
506    pub extra_char_spacing: f64,
507    /// Task #352: dash leader (3+ 연속 '-') 시퀀스의 글자당 추가 간격 (px).
508    /// PDF 와 같이 라인 슬랙을 dash leader 가 흡수하도록 하여, 공백 분배
509    /// 부담을 줄이고 자연스러운 단어 간격을 유지한다. 0 이면 미적용.
510    pub extra_dash_advance: f64,
511    /// 외곽선 종류 (0=없음, 1~6=종류)
512    pub outline_type: u8,
513    /// 그림자 종류 (0=없음, 1=비연속, 2=연속)
514    pub shadow_type: u8,
515    /// 그림자 색
516    pub shadow_color: ColorRef,
517    /// 그림자 X 오프셋 (px)
518    pub shadow_offset_x: f64,
519    /// 그림자 Y 오프셋 (px)
520    pub shadow_offset_y: f64,
521    /// 양각
522    pub emboss: bool,
523    /// 음각
524    pub engrave: bool,
525    /// 위 첨자
526    pub superscript: bool,
527    /// 아래 첨자
528    pub subscript: bool,
529    /// 강조점 종류 (0=없음, 1~6)
530    pub emphasis_dot: u8,
531    /// 밑줄 모양 (표 27 선 종류, 0=실선 ~ 10=삼중선)
532    pub underline_shape: u8,
533    /// 취소선 모양 (표 27 선 종류, 0=실선 ~ 10=삼중선)
534    pub strike_shape: u8,
535    /// 밑줄 색상
536    pub underline_color: ColorRef,
537    /// 취소선 색상
538    pub strike_color: ColorRef,
539    /// 음영 색 (형광펜, 0xFFFFFF = 없음)
540    pub shade_color: ColorRef,
541    /// [#7092] 이 run 의 메트릭 표를 그 글꼴 자신의 폭으로 믿을 수 있는지
542    /// (TTF 선언 · 대체 없음). 모르면 거짓 — 종전의 보수적 측정을 따른다.
543    ///
544    /// 측정 결정에만 쓴다 — 레이어 트리 직렬화 바이트를 보존하려고 직렬화에서 뺀다.
545    #[serde(skip_serializing)]
546    pub font_metric_trusted: bool,
547    /// 명시된 glyphFallbacks의 자연 전진폭 선택. 기본 paint 공급은 해당하지 않는다.
548    #[serde(skip_serializing)]
549    pub glyph_fallback_advance_explicit: bool,
550    /// [#7391] 폭을 잴 때만 `font_family` 대신 쓸 face 이름.
551    ///
552    /// legacy-latin 폴백은 표시할 글꼴이 없는 환경을 위해 라틴 face 를 한글 face 로
553    /// 보낸다(`AmeriGarmnd BT` → `HY견명조`). 표시로는 뜻이 있어도 폭은 범주가 다르다.
554    /// rhwp 가 선언 face 자신의 표를 이미 가진 경우에만 그 이름이 들어오며, 근거는
555    /// [`crate::renderer::style_resolver::ResolvedCharStyle::font_families_metric_face`] 에 있다.
556    ///
557    /// 측정 결정에만 쓴다 — 레이어 트리 직렬화 바이트를 보존하려고 직렬화에서 뺀다.
558    #[serde(skip_serializing)]
559    pub metric_font_family: Option<String>,
560    /// 확인된 원본 글리프만 사용하는 부분 메트릭. 미확인 글자는 표시 face에 남는다.
561    /// 불변 이름을 공유하여 런 복제와 enum의 인라인 메모리를 줄인다.
562    #[serde(skip_serializing)]
563    pub original_glyph_metric_family: Option<std::sync::Arc<String>>,
564    /// [#7387] 명시적으로 확인한 공백 전진폭(em). 주로
565    /// `CharShape.use_font_space`가 켜진 run의 **영문 슬롯** 글꼴 폭이며,
566    /// 저장 문서의 독립 출력에서 다른 폭이 확인되면 프로필이 덮어쓸 수 있다.
567    /// `None`이면 아래 일반 글꼴 측정 규칙을 따른다.
568    ///
569    /// 한/글은 이 속성이 켜지면 공백을 반각이 아니라 영문 슬롯 글꼴의 제 공백
570    /// 글리프 전진폭으로 전진시킨다. `1382000_domestic_violence_survey` 정본
571    /// (`Hwp 2018 11.0.0.1623`)의 같은 문서·같은 쪽 대조가 값을 말한다 —
572    /// 미정렬 줄만 골라 charPr 에 붙여 재면:
573    ///
574    /// ```text
575    ///   ufs=0  charPr 12  자간 0   n=37   0.500 em   (반각 그대로)
576    ///   ufs=0  charPr 6·33 자간 -5 n=729  0.469 em   (0.5 x 0.95)
577    ///   ufs=1  charPr 65·54·53·59  자간 0 n=763  0.337 em
578    ///   ufs=1  charPr 24  자간 0   n=18   0.337 em
579    ///   ufs=1  charPr 26  자간 0   n=38   0.489 em  <- 영문 슬롯이 휴먼명조
580    /// ```
581    ///
582    /// 마지막 줄이 상수가 아님을 말한다: 같은 `ufs=1` 이라도 영문 슬롯이 대체 없이
583    /// 쓰인 휴먼명조면 그 글꼴의 제 공백 0.5 em 이 나오고, Batang 으로 대체된
584    /// 슬롯이면 0.333 em(341/1024)이 나온다.
585    ///
586    /// 영문 슬롯 `KoPub바탕체 Light`(charPr 53·54·59·65 …)는 KoPub 을 **설치한**
587    /// 환경의 같은 문서 정본(`Hwp 2020`, KoPub 서브셋 내장)에서는 연속 공백 덩어리가
588    /// 0.312 em 으로, 그 글꼴의 공백 312/1000 그대로다. 위 0.337 은 KoPub 이 없는
589    /// 환경의 대체 결과로 보이며, rhwp 는 선언 face 의 표를 쓴다(KoPub 전용 표).
590    ///
591    /// 측정 결정에만 쓴다 — 레이어 트리 직렬화 바이트를 보존하려고 직렬화에서 뺀다.
592    #[serde(skip_serializing)]
593    pub font_space_em: Option<f64>,
594    /// 공백 전진값이 글꼴 폭이 아니라 상속 언어의 반각 환산값인지 구분한다.
595    #[serde(skip_serializing)]
596    pub inherited_half_space_em: bool,
597    /// 줄 구성에서 선택한 반각 공백 규칙. 원문의 useFontSpace와 구별한다.
598    #[serde(skip_serializing)]
599    pub layout_half_space: bool,
600    /// 반각 공백의 기준 em을 현재 언어 슬롯의 em으로 환산한 비율.
601    /// 영문 상대 크기를 바꾸어도 한글 슬롯의 반각 전진은 유지한다.
602    #[serde(skip_serializing)]
603    pub layout_half_space_em: Option<f64>,
604    /// 실제 새 줄 구성의 메트릭인지. 공백 규칙과 별도로 측정·배치가 공유한다.
605    #[serde(skip_serializing)]
606    pub regenerated_font_metrics: bool,
607    /// [#7051] 이 run 의 글꼴이 **HFT 한글 전용 face** 라서 대체됐는지
608    /// (`FontSubstitutionBoundary::Hft`). 그런 글꼴의 ASCII 는 한컴이 반각(`em/2`)으로
609    /// 전진시키므로 대체 글꼴의 비례 폭을 그대로 쓰면 안 된다. 진짜 영문 HFT
610    /// (`LegacyLatin` 경계 — HCI Poppy·BT 계열·영문 안상수체)는 여기 들어오지 않는다.
611    ///
612    /// 측정 결정에만 쓴다 — 레이어 트리 직렬화 바이트를 보존하려고 직렬화에서 뺀다.
613    #[serde(skip_serializing)]
614    pub hft_hangul_face: bool,
615    /// 현재 언어 슬롯의 표시 face가 한글 HFT에서 치환됐는지.
616    /// ASCII 반각 폭의 문서별 수용 조건과 무관한 원본 글꼴 출처다.
617    /// 그리기 변환은 이 값을 쓰고, 폭 측정은 위 hft_hangul_face를 유지한다.
618    #[serde(skip_serializing)]
619    pub hft_font_face: bool,
620    /// 원본 한글 HFT 기호 슬롯의 전각 폭 보존 여부. ASCII 반각 판정과 별개다.
621    #[serde(skip_serializing)]
622    pub hft_fullwidth_dot: bool,
623    /// [#7418] 이 run 이 한글 슬롯이고 글자 모양이 `ascii_punct_latin_slot` 이면, ASCII
624    /// 구두점을 잴 때 쓸 **영문 슬롯**의 기본 메트릭. run 을 쪼개지 않고 글자 단위로 폭만
625    /// 영문 슬롯으로 잰다(#7051 HFT 반각 ASCII 와 같은 자리). 양쪽 정렬 여분 등 배치가 얹는
626    /// 값은 run 의 것을 그대로 쓴다.
627    ///
628    /// 측정 결정에만 쓴다 — 레이어 트리 직렬화 바이트를 보존하려고 직렬화에서 뺀다.
629    #[serde(skip_serializing)]
630    pub ascii_punct_latin: Option<Box<LatinSlotMetrics>>,
631}
632crate::storage::clone_fields!(TextStyle, {literal_soft_hyphen, text_paint, continuous_shadow, inherited_half_space_em, script_metrics, shadow_offset_percent, space_compression, literal_figure_space, literal_figure_space_em, native_pua_metrics, native_otf_metrics, bidi_layout, emphasis_skip_first_cluster, top_underline_font_size, top_underline_phase, supplemental_metrics, isolated_jamo_font, font_family, font_size, fixed_glyph_advances, source_font_is_hft, source_font_is_ttf, selected_primary_font_program, source_verified_hft_bold_tracking, source_hwp3_hft_bold, resolved_font_size, print_ink_font_size, font_position, hft_print_frame, print_text_device_frame, preserve_glyph_ink, natural_program_metrics, color, bold, italic, underline, strikethrough, kerning, letter_spacing, ratio, default_tab_width, tab_stops, auto_tab_right, auto_left_tab_position, available_width, line_x_offset, text_start_offset, right_tab_block_width_override, tab_leaders, inline_tabs, extra_word_spacing, unjustified_leading_spaces, extra_char_spacing, extra_dash_advance, outline_type, shadow_type, shadow_color, shadow_offset_x, shadow_offset_y, emboss, engrave, superscript, subscript, emphasis_dot, underline_shape, strike_shape, underline_color, strike_color, shade_color, font_metric_trusted, glyph_fallback_advance_explicit, metric_font_family, original_glyph_metric_family, font_space_em, layout_half_space, layout_half_space_em, regenerated_font_metrics, hft_hangul_face, hft_font_face, hft_fullwidth_dot, ascii_punct_latin});
633
634/// [#7418] 영문 슬롯의 기본 메트릭 — [`TextStyle::ascii_punct_latin`] 참조.
635#[derive(Debug, Clone, PartialEq)]
636pub struct LatinSlotMetrics {
637    pub font_family: String,
638    /// 영문 슬롯이 실제 선택한 OTF의 글리프별 전진.
639    pub native_otf_metrics: Option<std::sync::Arc<native_pua_fonts::NativeOtfMetrics>>,
640    pub metric_font_family: Option<String>,
641    /// 확인된 원본 글리프만 사용하는 부분 메트릭. 미확인 글자는 표시 face에 남는다.
642    /// 불변 이름을 공유하여 런 복제와 enum의 인라인 메모리를 줄인다.
643    pub original_glyph_metric_family: Option<std::sync::Arc<String>>,
644    pub font_metric_trusted: bool,
645    /// [#8079] 영문 슬롯의 선언 face 가 HFT 프로그램인지 — [`TextStyle::source_font_is_hft`] 와 같은 뜻.
646    pub source_font_is_hft: bool,
647    /// 영문 슬롯의 명시적 TTF 선언이다.
648    pub source_font_is_ttf: bool,
649    pub selected_primary_font_program: Option<font_environment::FontProgramIdentity>,
650    pub source_verified_hft_bold_tracking: bool,
651    pub letter_spacing: f64,
652    pub ratio: f64,
653}
654
655crate::storage::clone_fields!(LatinSlotMetrics, {font_family, native_otf_metrics, metric_font_family, original_glyph_metric_family, font_metric_trusted, source_font_is_hft, source_font_is_ttf, selected_primary_font_program, source_verified_hft_bold_tracking, letter_spacing, ratio});
656crate::storage::clone_copy!(crate::model::style::UnderlineType);
657
658/// 위첨자/아래첨자 글리프를 그릴 때 적용하는 본문 대비 글꼴 크기 배율.
659pub const SCRIPT_FONT_SCALE: f64 = 0.7;
660/// 위첨자 baseline 상향 이동량 (본문 글꼴 크기 대비 em).
661pub const SUPERSCRIPT_RISE_EM: f64 = 0.3;
662/// 아래첨자 baseline 하향 이동량 (본문 글꼴 크기 대비 em).
663pub const SUBSCRIPT_DROP_EM: f64 = 0.15;
664
665/// 독립 한/글 Print의 합성 굵기 `w / Tf`; Native와 Canvas가 같은 값을 소비한다.
666pub(crate) const HANCOM_FAUX_BOLD_STROKE_EM: f64 = 0.02;
667
668/// 합성 볼드 획 굵기(px) — 실제 Bold 메트릭이 없는 face 의 볼드 요청에만.
669///
670/// 한/글 2022 는 Bold face 가 없는 face 의 볼드를 PDF `2 Tr`(fill+stroke)로
671/// 내보내고 선 굵기를 **글꼴·크기 불문 `0.02 em`** 으로 준다. 표본
672/// `pdf/issue2470/36382471_masked-2022.pdf` 1쪽의 `Tr 2` run 은 전부
673/// `w / Tf` 가 0.0200 이다 — 굴림체 `1.66/83`, HY헤드라인M `3.50/175`,
674/// HY견명조 `4.34/217`. `font-weight="bold"` 만 넘기면 굵히는 양이 받는 쪽
675/// 몫이라 Chromium 은 이보다 굵게 만든다(#7151).
676///
677/// 메트릭 DB 에 Bold 항목이 있는 face 는 배치 advance 도 Bold 메트릭으로
678/// 잡았으므로 종전대로 그 face 를 요청한다. DB 에 없는 face 는 어느 쪽인지
679/// 알 근거가 없어 건드리지 않는다.
680pub(crate) fn faux_bold_stroke_width(style: &TextStyle, font_size: f64) -> Option<f64> {
681    if !style.bold {
682        return None;
683    }
684    let primary = style_resolver::primary_font_name(&style.font_family);
685    font_metrics_data::find_metric(primary, true, style.italic)?
686        .bold_fallback
687        .then_some(font_size * HANCOM_FAUX_BOLD_STROKE_EM)
688}
689
690impl TextStyle {
691    /// 원본의 0 크기를 보존한다. 해소되지 않은 기본 스타일에만 기존 폴백을 쓴다.
692    pub(crate) fn effective_font_size(&self) -> f64 {
693        if let Some(size) = self.print_ink_font_size {
694            return size;
695        }
696        if self.resolved_font_size || self.font_size > 0.0 {
697            self.font_size
698        } else {
699            12.0
700        }
701    }
702
703    /// 런을 각주·인라인 개체 경계에서 나눠도 같은 공백 구간을 이어받는다.
704    pub(crate) fn for_text_fragment(&self, scalar_start: usize) -> Self {
705        let mut style = self.clone();
706        style.space_compression = self
707            .space_compression
708            .as_ref()
709            .map(|plan| plan.for_fragment(scalar_start));
710        style.unjustified_leading_spaces =
711            self.unjustified_leading_spaces.saturating_sub(scalar_start);
712        style
713    }
714
715    /// 원문 앞 조각이 소비한 저장 탭을 건너뛰고 남은 조각의 스타일을 만든다.
716    pub(crate) fn for_source_text_fragment(&self, scalar_start: usize, source: &[char]) -> Self {
717        let mut style = self.for_text_fragment(scalar_start);
718        let prior_tabs = source
719            .iter()
720            .take(scalar_start)
721            .filter(|c| **c == '\t')
722            .count();
723        style.inline_tabs = self.inline_tabs.iter().skip(prior_tabs).copied().collect();
724        style
725    }
726
727    /// 위첨자/아래첨자 run 의 **그리기** 글꼴 크기와 baseline 을 계산한다.
728    ///
729    /// SVG·Canvas·HTML·Skia·paint JSON 이 각자 하드코딩하던 동일 상수를 한곳으로
730    /// 모은 것이다 (#2771). 레이아웃 advance 는 본문 run 기준을 유지하고 실제
731    /// 글리프 크기와 baseline 만 조정한다는 계약은 종전과 같다.
732    ///
733    /// 원본의 글자 위치는 줄 기준선에 한 번만 적용한다.
734    pub fn script_draw_metrics(&self, base_font_size: f64, baseline_y: f64) -> (f64, f64) {
735        self.script_metrics.draw_metrics(
736            base_font_size,
737            baseline_y,
738            self.superscript,
739            self.subscript,
740            self.font_position,
741        )
742    }
743
744    /// 글자폭 맞춤(fit) 대상 advance 에 적용할 배율 (#2771, #5756).
745    ///
746    /// SVG `textLength` 와 Canvas `fit_scale` 은 "레이아웃 advance 에 글리프 폭을
747    /// 맞춘다". [#5756] 이후 첨자 run 의 **레이아웃 advance 자체**가 그리기
748    /// 배율로 측정되므로(`text_measurement::style_params`), 대상 advance 는
749    /// 이미 축소 글리프의 자연 폭과 일치한다 — 여기서 또 줄이면 이중 축소로
750    /// 글리프가 0.49 배까지 눌린다. 항상 1.0(항등)을 돌려준다.
751    pub fn script_advance_scale(&self) -> f64 {
752        1.0
753    }
754
755    /// 브라우저 렌더러가 실제 glyph 폭을 맞출 때 사용할 advance 를 반환한다.
756    ///
757    /// `extra_char_spacing` 의 양수 값은 배분/나눔 정렬에서 다음 cluster 의 시작
758    /// 위치를 옮기는 간격이다. 이를 SVG `textLength` 또는 Canvas `scaleX`의 목표
759    /// 폭에 포함하면 영문·숫자 glyph 자체가 가로로 늘어난다. 문자 위치 계산은
760    /// 그대로 두고, glyph 맞춤 단계에서만 이 간격을 제외한다.
761    ///
762    /// 음수 간격은 `glyph_fit_positions`에서 간격 전의 폭을 다시 측정한다.
763    /// 그 결과를 이곳에서 다시 늘리지 않는다. 양수 간격만 여기서 제외한다.
764    pub(crate) fn glyph_fit_advance(&self, layout_cluster_advance: f64) -> Option<f64> {
765        if !layout_cluster_advance.is_finite() || !self.extra_char_spacing.is_finite() {
766            return None;
767        }
768        if self.extra_char_spacing > 0.0 {
769            Some((layout_cluster_advance - self.extra_char_spacing).max(0.0))
770        } else {
771            Some(layout_cluster_advance)
772        }
773    }
774
775    /// 장평은 가로 그리기 축만 바꾸며 선언 크기와 배치 전진폭은 보존한다.
776    /// 한컴 Print의 Tf·세로 CTM과 Tz를 각각 대조한 계약이다.
777    /// PDF 추출기가 행렬 행렬식의 제곱근으로 보고한 크기를 세로 크기로 쓰지 않는다.
778    pub fn ratio_draw_params(&self, font_size: f64) -> (f64, f64) {
779        condensed_ratio_draw_params(font_size, self.ratio)
780    }
781
782    /// 공식 장평은 정수 백분율이다. 99·101%도 항등 변환으로 생략하지 않는다.
783    /// 각 paint가 정밀도 변환 전에 같은 정규화 결과로 가로 변환을 선택한다.
784    pub fn has_horizontal_ratio(&self) -> bool {
785        self.ratio_draw_params(1.0).1 != 1.0
786    }
787
788    /// 시각적 bold 여부.
789    ///
790    /// CharShape.bold=true 외에도 HY헤드라인M 같은 heavy display face 를
791    /// 사용할 때 true 를 반환. 해당 face 가 fallback 으로 대체될 때 발생하는
792    /// 시각 bold 소실을 보완하기 위해 SVG 출력 시 font-weight="bold" 강제에
793    /// 사용된다.
794    pub fn is_visually_bold(&self) -> bool {
795        self.bold
796            || crate::renderer::style_resolver::is_heavy_display_face(&self.font_family)
797            || crate::renderer::style_resolver::is_bold_weight_face(&self.font_family)
798    }
799
800    /// 중고딕 계열(font-weight 500) 여부. SVG/HTML 출력 시 `font-weight: 500` 힌트 삽입에 사용.
801    pub fn is_medium_weight(&self) -> bool {
802        !self.bold && crate::renderer::style_resolver::is_medium_weight_face(&self.font_family)
803    }
804
805    /// CSS/SVG font-weight hint for fallback rendering.
806    pub fn css_font_weight(&self) -> Option<&'static str> {
807        if self.is_visually_bold() {
808            Some("bold")
809        } else if crate::renderer::style_resolver::is_light_weight_face(&self.font_family) {
810            Some("300")
811        } else if self.is_medium_weight() {
812            Some("500")
813        } else {
814            None
815        }
816    }
817}
818
819/// 반각 강제 구두점(`U+2018..=U+2027`, 반각 낫표)을 그릴 때의 가로 배율.
820///
821/// 대체 글꼴의 글리프가 전진폭보다 넓을 때만 전진폭에 맞춰 누른다. 종전에는
822/// 글리프 폭과 무관하게 0.5배로 눌러, 이미 좁은 대체 글리프(곡선 따옴표 등)가
823/// 실선처럼 가늘어지고 전진폭 안에 빈칸이 남았다.
824pub fn halfwidth_punct_paint_scale(advance: f64, glyph_width: f64) -> f64 {
825    if !(advance > 0.0 && glyph_width > 0.0) {
826        return 0.5;
827    }
828    (advance / glyph_width).min(1.0)
829}
830
831impl Default for TextStyle {
832    fn default() -> Self {
833        Self {
834            literal_soft_hyphen: false,
835            bidi_layout: None,
836            emphasis_skip_first_cluster: false,
837            top_underline_font_size: None,
838            top_underline_phase: None,
839            script_metrics: Default::default(),
840            supplemental_metrics: None,
841            isolated_jamo_font: None,
842            shadow_offset_percent: None,
843            continuous_shadow: None,
844            space_compression: None,
845            font_family: String::new(),
846            font_size: 0.0,
847            fixed_glyph_advances: false,
848            source_font_is_hft: false,
849            source_font_is_ttf: false,
850            selected_primary_font_program: None,
851            source_verified_hft_bold_tracking: false,
852            source_hwp3_hft_bold: false,
853            resolved_font_size: false,
854            print_ink_font_size: None,
855            font_position: None,
856            hft_print_frame: false,
857            print_text_device_frame: false,
858            preserve_glyph_ink: false,
859            natural_program_metrics: false,
860            color: 0,
861            bold: false,
862            italic: false,
863            underline: UnderlineType::None,
864            strikethrough: false,
865            kerning: false,
866            letter_spacing: 0.0,
867            ratio: 1.0,
868            default_tab_width: 0.0,
869            tab_stops: Vec::new(),
870            auto_tab_right: false,
871            auto_left_tab_position: None,
872            available_width: 0.0,
873            line_x_offset: 0.0,
874            text_start_offset: 0.0,
875            right_tab_block_width_override: None,
876            tab_leaders: Vec::new(),
877            inline_tabs: Vec::new(),
878            extra_word_spacing: 0.0,
879            unjustified_leading_spaces: 0,
880            extra_char_spacing: 0.0,
881            extra_dash_advance: 0.0,
882            text_paint: None,
883            outline_type: 0,
884            shadow_type: 0,
885            shadow_color: 0x00B2B2B2,
886            shadow_offset_x: 0.0,
887            shadow_offset_y: 0.0,
888            emboss: false,
889            engrave: false,
890            superscript: false,
891            subscript: false,
892            emphasis_dot: 0,
893            underline_shape: 0,
894            strike_shape: 0,
895            underline_color: 0,
896            strike_color: 0,
897            shade_color: 0x00FFFFFF,
898            font_metric_trusted: false,
899            native_pua_metrics: None,
900            native_otf_metrics: None,
901            glyph_fallback_advance_explicit: false,
902            metric_font_family: None,
903            original_glyph_metric_family: None,
904            font_space_em: None,
905            inherited_half_space_em: false,
906            layout_half_space: false,
907            layout_half_space_em: None,
908            regenerated_font_metrics: false,
909            literal_figure_space: false,
910            literal_figure_space_em: None,
911            hft_hangul_face: false,
912            hft_font_face: false,
913            hft_fullwidth_dot: false,
914            ascii_punct_latin: None,
915        }
916    }
917}
918
919/// 패턴 채우기 정보
920#[derive(Debug, Clone, Copy, Serialize)]
921pub struct PatternFillInfo {
922    /// HWP 무늬 종류 0~5 (`crate::model::style::HatchStyle`). 0=─, 1=│, 2=\, 3=/, 4=+, 5=×
923    pub pattern_type: i32,
924    /// 한컴 인쇄 무늬의 576HU 반복 주기를 현재 출력 DPI로 변환한 값.
925    pub tile_size: f64,
926    /// 무늬색
927    pub pattern_color: ColorRef,
928    /// 배경색
929    pub background_color: ColorRef,
930}
931
932/// 도형 렌더링 스타일
933#[derive(Debug, Clone, Serialize)]
934pub struct ShapeStyle {
935    /// 채우기 색상 (None이면 채우기 없음)
936    pub fill_color: Option<ColorRef>,
937    /// 패턴 채우기 (무늬 0~5일 때)
938    pub pattern: Option<PatternFillInfo>,
939    /// 테두리 색상
940    pub stroke_color: Option<ColorRef>,
941    /// 테두리 두께 (px)
942    pub stroke_width: f64,
943    /// 테두리 종류
944    pub stroke_dash: StrokeDash,
945    /// 투명도 (0.0=완전투명, 1.0=불투명)
946    pub opacity: f64,
947    /// 그림자 (None이면 그림자 없음)
948    pub shadow: Option<ShadowStyle>,
949}
950
951/// 도형 그림자 스타일
952#[derive(Debug, Clone, Serialize)]
953pub struct ShadowStyle {
954    /// HWP 도형 그림자 종류 (1~14, HWPX SHADOWTYPE과 대응)
955    pub shadow_type: u32,
956    /// 그림자 색상
957    pub color: ColorRef,
958    /// X 오프셋 (px)
959    pub offset_x: f64,
960    /// Y 오프셋 (px)
961    pub offset_y: f64,
962    /// 투명도 (0~255, 0=불투명)
963    pub alpha: u8,
964}
965
966impl Default for ShapeStyle {
967    fn default() -> Self {
968        Self {
969            fill_color: None,
970            pattern: None,
971            stroke_color: None,
972            stroke_width: 0.0,
973            stroke_dash: StrokeDash::default(),
974            opacity: 1.0,
975            shadow: None,
976        }
977    }
978}
979
980/// 그라데이션 채우기 렌더링 정보
981#[derive(Debug, Clone, Serialize)]
982pub struct GradientFillInfo {
983    /// 유형 (1: 줄무늬/선형, 2: 원형, 3: 원뿔형, 4: 사각형)
984    pub gradient_type: i16,
985    /// 기울임 각도 (도)
986    pub angle: i16,
987    /// 가로 중심 (%)
988    pub center_x: i16,
989    /// 세로 중심 (%)
990    pub center_y: i16,
991    /// 색상 목록 (ColorRef)
992    ///
993    /// [`expand_gradient_steps`] 가 편 **띠 단위 stop** 이다 — 모델의 색 목록과 1:1 이
994    /// 아니다. `positions` 와 길이가 같고, 같은 offset 이 두 번 나오면 하드 경계다.
995    pub colors: Vec<ColorRef>,
996    /// 색상 위치 (0.0~1.0 정규화)
997    pub positions: Vec<f64>,
998}
999
1000/// 두 색 사이를 채널별로 선형 보간한다.
1001fn lerp_color(from: ColorRef, to: ColorRef, t: f64) -> ColorRef {
1002    let t = t.clamp(0.0, 1.0);
1003    let mut out = 0u32;
1004    for shift in [0, 8, 16] {
1005        let a = ((from >> shift) & 0xff) as f64;
1006        let b = ((to >> shift) & 0xff) as f64;
1007        // 독립 한컴 Print의 양방향 RGB 대조군은 최종값 반올림이 아니라
1008        // 시작색에 대한 signed 변화량의 소수부를 버린 뒤 더한다.
1009        // 예: 210→40의 1/6은182, 40→210의 1/6은68이다.
1010        let v = (a + ((b - a) * t).trunc()).clamp(0.0, 255.0) as u32;
1011        out |= v << shift;
1012    }
1013    out
1014}
1015
1016/// `(colors, positions)` 가 이루는 색 램프를 `t`(0~1) 에서 표집한다.
1017fn sample_ramp(colors: &[ColorRef], positions: &[f64], t: f64) -> ColorRef {
1018    match colors.len() {
1019        0 => 0,
1020        1 => colors[0],
1021        n => {
1022            let at = |i: usize| -> f64 {
1023                positions
1024                    .get(i)
1025                    .copied()
1026                    .unwrap_or(i as f64 / (n - 1) as f64)
1027            };
1028            let t = t.clamp(0.0, 1.0);
1029            for i in 1..n {
1030                let (p0, p1) = (at(i - 1), at(i));
1031                if t <= p1 || i == n - 1 {
1032                    let span = p1 - p0;
1033                    let local = if span.abs() < f64::EPSILON {
1034                        0.0
1035                    } else {
1036                        (t - p0) / span
1037                    };
1038                    return lerp_color(colors[i - 1], colors[i], local);
1039                }
1040            }
1041            colors[n - 1]
1042        }
1043    }
1044}
1045
1046/// HWP 그러데이션의 `step`(띠 개수)·`step_center`(전이 위치 %)를 렌더 stop 목록으로 편다.
1047///
1048/// [#6822] 한/글은 그러데이션 축을 **`step` 개의 띠**로 잘라 각 띠를 단색으로 칠하고,
1049/// 띠 경계들의 가운데를 `step_center`% 지점에 놓는다. 렌더 IR 은 이 두 값을 담지 않아
1050/// 전이가 언제나 50% 에 고정됐다.
1051///
1052/// 실측(`samples/issue6551/113424_evaluation_guideline.hwpx`, 한/글 2024 정본):
1053///
1054/// ```text
1055///   step=2  stepCenter=8   장 제목 막대  초록→흰색 하드 경계가 축의 8% 지점
1056///   step=50 stepCenter=50  구분 막대     균등한 50개 띠 (사실상 매끄러운 램프)
1057/// ```
1058///
1059/// `step <= 1` 이거나 색이 둘 미만이면 띠를 만들지 않고 원본을 그대로 돌려준다 —
1060/// 값이 없는 문서의 현행 동작을 바꾸지 않기 위해서다.
1061pub fn expand_gradient_steps(
1062    colors: &[ColorRef],
1063    positions: &[f64],
1064    step: i16,
1065    step_center: u8,
1066) -> (Vec<ColorRef>, Vec<f64>) {
1067    match try_expand_gradient_steps(
1068        colors,
1069        positions,
1070        step,
1071        step_center,
1072        &style_resolver::storage::Unbounded,
1073    ) {
1074        Ok(stops) => stops,
1075        Err(never) => match never {},
1076    }
1077}
1078
1079pub(crate) fn try_expand_gradient_steps<S: style_resolver::storage::Storage>(
1080    colors: &[ColorRef],
1081    positions: &[f64],
1082    step: i16,
1083    step_center: u8,
1084    storage: &S,
1085) -> Result<(Vec<ColorRef>, Vec<f64>), S::Error> {
1086    let bands = step.max(0) as usize;
1087    if bands <= 1 || colors.len() < 2 {
1088        return Ok((storage.copy_slice(colors)?, storage.copy_slice(positions)?));
1089    }
1090
1091    // 띠 경계는 균등 위치 `m` 을 두 구간 선형으로 옮겨 가운데(m=0.5)가 `c` 에 오게 한다.
1092    // `c == 0.5` 면 항등이므로 기본값 문서는 지금 그리는 것과 같은 균등 띠가 된다.
1093    let c = (step_center as f64 / 100.0).clamp(0.0, 1.0);
1094    let warp = |m: f64| -> f64 {
1095        if m <= 0.5 {
1096            2.0 * m * c
1097        } else {
1098            c + (m - 0.5) * 2.0 * (1.0 - c)
1099        }
1100    };
1101
1102    let mut out_colors = storage.vec(bands * 2)?;
1103    let mut out_positions = storage.vec(bands * 2)?;
1104    for i in 0..bands {
1105        let color = sample_ramp(colors, positions, i as f64 / (bands - 1) as f64);
1106        let start = warp(i as f64 / bands as f64);
1107        let end = warp((i + 1) as f64 / bands as f64);
1108        out_colors.push(color);
1109        out_positions.push(start.clamp(0.0, 1.0));
1110        out_colors.push(color);
1111        out_positions.push(end.clamp(0.0, 1.0));
1112    }
1113    Ok((out_colors, out_positions))
1114}
1115
1116/// [#6845] HWP 그러데이션 각도를 **사용자 좌표계**의 축 양 끝점으로 옮긴다.
1117///
1118/// 종전 두 렌더러는 각도를 상자 정규화 공간에서 다뤄 **가로세로비만큼 축이 눕는** 결함이
1119/// 있었다 — SVG 는 `objectBoundingBox` 백분율을 그대로 냈고, canvas 는 방향을
1120/// `(sin·w/2, cos·h/2)` 로 축별 배율했다. 둘 다 정사각형 상자에서만 옳다.
1121///
1122/// ## 축 방향은 `(sin a, −cos a)` 다
1123///
1124/// 한/글 2024 정본(`pdf/113424_evaluation_guideline-2024.pdf`)에서 두 각도로 확정했다.
1125///
1126/// ```text
1127///   angle=0    5쪽 목차 막대 `#C8EDFF → #FFFFFF`
1128///              정본은 아래가 `#C8EDFF`, 위가 흰색 → 축은 **위쪽**       (0, −1)
1129///   angle=90   29쪽 구분 막대 `#000080 → #99CCFF`  → 축은 오른쪽        (1, 0)
1130///   angle=110  7쪽 장 제목 막대, 등색선 기울기 dx/dy = −0.365
1131///              → 축 (0.939, 0.343) = (sin 110°, −cos 110°)
1132/// ```
1133///
1134/// SVG·canvas 는 y 가 아래로 자라므로 `cos` 의 부호를 뒤집어야 한다. 종전 코드는 `+cos`
1135/// 라 `angle=0` 에서 위아래가 반대였다.
1136///
1137/// ## 끝점은 상자를 덮도록 잡는다
1138///
1139/// 상자를 축 방향으로 정사영한 길이의 절반이 `(|dx|·w + |dy|·h) / 2` 이므로, 중심에서
1140/// 그만큼 양쪽으로 벌리면 어떤 각도에서도 상자 전체가 램프 안에 들어온다.
1141pub fn linear_gradient_axis(angle: i16, x: f64, y: f64, w: f64, h: f64) -> (f64, f64, f64, f64) {
1142    let a = ((angle % 360 + 360) % 360) as f64;
1143    let rad = a.to_radians();
1144    let (dx, dy) = (rad.sin(), -rad.cos());
1145    let (cx, cy) = (x + w / 2.0, y + h / 2.0);
1146    let half = (dx.abs() * w + dy.abs() * h) / 2.0;
1147    (
1148        cx - dx * half,
1149        cy - dy * half,
1150        cx + dx * half,
1151        cy + dy * half,
1152    )
1153}
1154
1155/// 선형 그러데이션의 첫 색은 원본 중심에, 마지막 색은 양쪽 끝에 놓인다.
1156/// 한컴 Print의 0/50/100% 중심 대조군에서 50%는 두 방향, 끝 중심은 한 방향 램프다.
1157/// step/stepCenter로 이미 편 stop의 순서·불연속도 함께 보존한다.
1158pub(crate) fn linear_gradient_color_stops(
1159    gradient: &GradientFillInfo,
1160    x: f64,
1161    y: f64,
1162    width: f64,
1163    height: f64,
1164) -> (Vec<ColorRef>, Vec<f64>) {
1165    let positions: Vec<_> =
1166        (0..gradient.colors.len())
1167            .map(|i| {
1168                gradient.positions.get(i).copied().unwrap_or_else(|| {
1169                    i as f64 / gradient.colors.len().saturating_sub(1).max(1) as f64
1170                })
1171            })
1172            .collect();
1173    if gradient.gradient_type != 1
1174        || gradient.colors.len() < 2
1175        || !(0..=100).contains(&gradient.center_x)
1176        || !(0..=100).contains(&gradient.center_y)
1177        || width <= 0.0
1178        || height <= 0.0
1179    {
1180        return (gradient.colors.clone(), positions);
1181    }
1182    let (x0, y0, x1, y1) = linear_gradient_axis(gradient.angle, x, y, width, height);
1183    let dx = x1 - x0;
1184    let dy = y1 - y0;
1185    let length_squared = dx * dx + dy * dy;
1186    if length_squared <= 0.0 {
1187        return (gradient.colors.clone(), positions);
1188    }
1189    let cx = x + width * f64::from(gradient.center_x) / 100.0;
1190    let cy = y + height * f64::from(gradient.center_y) / 100.0;
1191    // 유효한 0..100% 중심은 상자 안이다. 정사영의 끝자리 부동소수 오차만 정규화한다.
1192    let center = (((cx - x0) * dx + (cy - y0) * dy) / length_squared).clamp(0.0, 1.0);
1193    let mut colors = Vec::with_capacity(gradient.colors.len() * 2);
1194    let mut stops = Vec::with_capacity(gradient.colors.len() * 2);
1195    if center > 0.0 {
1196        for (&color, &position) in gradient.colors.iter().zip(&positions).rev() {
1197            colors.push(color);
1198            stops.push(center * (1.0 - position));
1199        }
1200    }
1201    if center < 1.0 {
1202        for (&color, &position) in gradient.colors.iter().zip(&positions) {
1203            colors.push(color);
1204            stops.push(center + (1.0 - center) * position);
1205        }
1206    }
1207    (colors, stops)
1208}
1209
1210/// 원본 중심은 공통 색상 스톱에서 반영한다. 축을 다시 뒤집지 않는다.
1211pub fn linear_gradient_axis_for_fill(
1212    grad: &GradientFillInfo,
1213    x: f64,
1214    y: f64,
1215    w: f64,
1216    h: f64,
1217) -> (f64, f64, f64, f64) {
1218    linear_gradient_axis(grad.angle, x, y, w, h)
1219}
1220
1221/// 원형 채우기를 상자의 가장 먼 모서리까지 펼친다.
1222/// 상자 정규화 좌표로 원을 만들면 비정사각형 도형에서 타원으로 왜곡된다.
1223pub fn radial_gradient_geometry(
1224    grad: &GradientFillInfo,
1225    x: f64,
1226    y: f64,
1227    w: f64,
1228    h: f64,
1229) -> (f64, f64, f64) {
1230    let cx = x + w * f64::from(grad.center_x) / 100.0;
1231    let cy = y + h * f64::from(grad.center_y) / 100.0;
1232    let dx = (cx - x).abs().max((x + w - cx).abs());
1233    let dy = (cy - y).abs().max((y + h - cy).abs());
1234    (cx, cy, dx.hypot(dy))
1235}
1236
1237/// 사각 채우기의 중심·회전축·반변 길이. 중심에서 원본 상자 네 변까지의
1238/// 가장 긴 거리를 회전 전의 정사각형 반변으로 쓴다. 회전 후 모서리를 덮도록
1239/// 반변을 다시 늘리면 원본의 색 띠 폭이 달라진다. 정사각형 밖은 마지막 색이다.
1240pub fn square_gradient_geometry(
1241    grad: &GradientFillInfo,
1242    x: f64,
1243    y: f64,
1244    w: f64,
1245    h: f64,
1246) -> (f64, f64, f64, f64, f64) {
1247    let cx = x + w * f64::from(grad.center_x) / 100.0;
1248    let cy = y + h * f64::from(grad.center_y) / 100.0;
1249    let radius = (cx - x)
1250        .abs()
1251        .max((x + w - cx).abs())
1252        .max((cy - y).abs())
1253        .max((y + h - cy).abs());
1254    let angle = f64::from(grad.angle).to_radians();
1255    (cx, cy, radius, angle.cos(), angle.sin())
1256}
1257
1258/// 선 렌더링 스타일
1259#[derive(Debug, Clone, Default, Serialize)]
1260pub struct LineStyle {
1261    /// 선 색상
1262    pub color: ColorRef,
1263    /// 선 두께 (px)
1264    pub width: f64,
1265    /// 선 종류
1266    pub dash: StrokeDash,
1267    /// Explicit physical on/off lengths in scene coordinates. A native border
1268    /// can have metrics different from the generic shape dash preset.
1269    #[serde(skip_serializing_if = "Option::is_none")]
1270    pub dash_pattern: Option<Vec<f64>>,
1271    /// 선 렌더링 종류 (이중선/삼중선 등)
1272    pub line_type: LineRenderType,
1273    /// 부모의 다중선 기하 또는 겹쳐 칠하는 순서를 분해한 구성 획이다.
1274    /// 각 획을 다시 픽셀 중심에 옮기면 공통 간격과 복합 coverage가 바뀐다.
1275    #[serde(skip_serializing_if = "std::ops::Not::not")]
1276    pub compound_component: bool,
1277    /// 원본 프레임의 분수 장치 좌표를 유지한다. 최소 획 폭과 별개이며,
1278    /// 용지 테두리를 표 격자처럼 화소 중심에 옮기지 않는다.
1279    #[serde(skip_serializing_if = "std::ops::Not::not")]
1280    pub preserve_fractional_position: bool,
1281    /// 시작 화살표
1282    pub start_arrow: ArrowStyle,
1283    /// 끝 화살표
1284    pub end_arrow: ArrowStyle,
1285    /// 시작 화살표 크기 (HWP bits 22-25: 0=작은-작은 ~ 8=큰-큰)
1286    pub start_arrow_size: u8,
1287    /// 끝 화살표 크기 (HWP bits 26-29)
1288    pub end_arrow_size: u8,
1289    /// 그림자
1290    pub shadow: Option<ShadowStyle>,
1291}
1292
1293/// 테두리 점선 종류
1294#[derive(Debug, Clone, Copy, Default, PartialEq, Serialize)]
1295pub enum StrokeDash {
1296    #[default]
1297    Solid,
1298    Dash,
1299    Dot,
1300    DashDot,
1301    DashDotDot,
1302    /// HWP5 도형의 파선. 반복 구간은 선 굵기에 비례한다.
1303    HwpDash,
1304    HwpDot,
1305    HwpDashDot,
1306    HwpDashDotDot,
1307    HwpLongDash,
1308    HwpCircle,
1309    /// 생산 단계에서 확정한 출력 좌표의 반복 구간. 끝의 0은 미사용 구간이다.
1310    Explicit([f64; 6]),
1311}
1312
1313/// 선 렌더링 종류 (이중선/삼중선)
1314#[derive(Debug, Clone, Copy, Default, PartialEq, Serialize)]
1315pub enum LineRenderType {
1316    #[default]
1317    Single,
1318    /// 이중선 (같은 굵기)
1319    Double,
1320    /// 가는선-굵은선 이중선
1321    ThinThickDouble,
1322    /// 굵은선-가는선 이중선
1323    ThickThinDouble,
1324    /// 가는선-굵은선-가는선 삼중선
1325    ThinThickThinTriple,
1326}
1327
1328/// 화살표 스타일
1329#[derive(Debug, Clone, Copy, Default, PartialEq, Serialize)]
1330pub enum ArrowStyle {
1331    #[default]
1332    None,
1333    /// 화살 모양 (채움)
1334    Arrow,
1335    /// 오목한 화살 모양 (채움)
1336    ConcaveArrow,
1337    /// 속이 빈 다이아몬드
1338    OpenDiamond,
1339    /// 속이 빈 원
1340    OpenCircle,
1341    /// 속이 빈 사각
1342    OpenSquare,
1343    /// 속이 채운 다이아몬드
1344    Diamond,
1345    /// 속이 채운 원
1346    Circle,
1347    /// 속이 채운 사각
1348    Square,
1349    /// 선형 화살촉(SPEAR): 두 사선을 잇고 바닥은 닫지 않는다.
1350    OpenArrow,
1351}
1352
1353/// 패스 커맨드 (벡터 도형용)
1354#[derive(Debug, Clone, Copy, Serialize)]
1355pub enum PathCommand {
1356    MoveTo(f64, f64),
1357    LineTo(f64, f64),
1358    CurveTo(f64, f64, f64, f64, f64, f64),
1359    /// SVG arc: (rx, ry, x_rotation, large_arc_flag, sweep_flag, x, y)
1360    ArcTo(f64, f64, f64, bool, bool, f64, f64),
1361    ClosePath,
1362}
1363
1364/// SVG arc(endpoint parameterization)를 cubic bezier 곡선으로 변환
1365///
1366/// SVG spec: Implementation Notes - Arc Conversion
1367/// (x1, y1): 시작점, (x2, y2): 끝점, rx/ry: 반지름,
1368/// phi: x축 회전(도), large_arc/sweep: 플래그
1369pub fn svg_arc_to_beziers(
1370    x1: f64,
1371    y1: f64,
1372    mut rx: f64,
1373    mut ry: f64,
1374    phi_deg: f64,
1375    large_arc: bool,
1376    sweep: bool,
1377    x2: f64,
1378    y2: f64,
1379) -> Vec<PathCommand> {
1380    use std::f64::consts::PI;
1381
1382    let mut result = Vec::new();
1383
1384    // 퇴화 케이스: 시작점 == 끝점
1385    if (x1 - x2).abs() < 1e-6 && (y1 - y2).abs() < 1e-6 {
1386        return result;
1387    }
1388    // 퇴화 케이스: 반지름 0
1389    rx = rx.abs();
1390    ry = ry.abs();
1391    if rx < 1e-6 || ry < 1e-6 {
1392        result.push(PathCommand::LineTo(x2, y2));
1393        return result;
1394    }
1395
1396    let phi = phi_deg.to_radians();
1397    let cos_phi = phi.cos();
1398    let sin_phi = phi.sin();
1399
1400    // Step 1: (x1', y1') 계산
1401    let dx = (x1 - x2) / 2.0;
1402    let dy = (y1 - y2) / 2.0;
1403    let x1p = cos_phi * dx + sin_phi * dy;
1404    let y1p = -sin_phi * dx + cos_phi * dy;
1405
1406    // Step 2: 반지름 보정 (너무 작은 경우 확대)
1407    let x1p2 = x1p * x1p;
1408    let y1p2 = y1p * y1p;
1409    let lambda = x1p2 / (rx * rx) + y1p2 / (ry * ry);
1410    if lambda > 1.0 {
1411        let s = lambda.sqrt();
1412        rx *= s;
1413        ry *= s;
1414    }
1415    let rx2 = rx * rx;
1416    let ry2 = ry * ry;
1417
1418    // Step 3: 중심점' (cx', cy') 계산
1419    let num = (rx2 * ry2 - rx2 * y1p2 - ry2 * x1p2).max(0.0);
1420    let den = rx2 * y1p2 + ry2 * x1p2;
1421    let sq = if den > 1e-10 { (num / den).sqrt() } else { 0.0 };
1422    let sign = if large_arc == sweep { -1.0 } else { 1.0 };
1423    let cxp = sign * sq * rx * y1p / ry;
1424    let cyp = sign * sq * (-ry * x1p) / rx;
1425
1426    // Step 4: 중심점 (cx, cy) 계산
1427    let cx = cos_phi * cxp - sin_phi * cyp + (x1 + x2) / 2.0;
1428    let cy = sin_phi * cxp + cos_phi * cyp + (y1 + y2) / 2.0;
1429
1430    // Step 5: θ1 (시작 각도), dθ (호 각도) 계산
1431    let theta1 = ((y1p - cyp) / ry).atan2((x1p - cxp) / rx);
1432    let theta2 = ((-y1p - cyp) / ry).atan2((-x1p - cxp) / rx);
1433    let mut dtheta = theta2 - theta1;
1434
1435    if !sweep && dtheta > 0.0 {
1436        dtheta -= 2.0 * PI;
1437    }
1438    if sweep && dtheta < 0.0 {
1439        dtheta += 2.0 * PI;
1440    }
1441
1442    // 호를 최대 90° 세그먼트로 분할하여 bezier 근사
1443    let n_segs = (dtheta.abs() / (PI / 2.0 + 0.001)).ceil().max(1.0) as usize;
1444    let seg_angle = dtheta / n_segs as f64;
1445
1446    for i in 0..n_segs {
1447        let t1 = theta1 + seg_angle * i as f64;
1448        let t2 = theta1 + seg_angle * (i + 1) as f64;
1449
1450        // 호 세그먼트의 bezier 제어점 계산
1451        // alpha = 4/3 * tan(segment_angle / 4)
1452        let alpha = 4.0 / 3.0 * (seg_angle / 4.0).tan();
1453
1454        let cos_t1 = t1.cos();
1455        let sin_t1 = t1.sin();
1456        let cos_t2 = t2.cos();
1457        let sin_t2 = t2.sin();
1458
1459        // 단위 원 위의 제어점 (반지름 적용 전)
1460        let ep1x = cos_t1 - alpha * sin_t1;
1461        let ep1y = sin_t1 + alpha * cos_t1;
1462        let ep2x = cos_t2 + alpha * sin_t2;
1463        let ep2y = sin_t2 - alpha * cos_t2;
1464
1465        // 반지름 적용
1466        let cp1x = rx * ep1x;
1467        let cp1y = ry * ep1y;
1468        let cp2x = rx * ep2x;
1469        let cp2y = ry * ep2y;
1470        let endx = rx * cos_t2;
1471        let endy = ry * sin_t2;
1472
1473        // 회전(phi) + 이동(cx, cy) 적용
1474        result.push(PathCommand::CurveTo(
1475            cos_phi * cp1x - sin_phi * cp1y + cx,
1476            sin_phi * cp1x + cos_phi * cp1y + cy,
1477            cos_phi * cp2x - sin_phi * cp2y + cx,
1478            sin_phi * cp2x + cos_phi * cp2y + cy,
1479            cos_phi * endx - sin_phi * endy + cx,
1480            sin_phi * endx + cos_phi * endy + cy,
1481        ));
1482    }
1483
1484    result
1485}
1486
1487/// 한양 HFT 불릿과 비어 있는 대체 TTF 원 기호의 실제 원 윤곽을 보존한다.
1488/// 한컴 PDF Type3 /HFT8: 중심 (500,352), 가로 반지름123.75, 세로123 /1000em.
1489/// U+26AB는 한컴 Print의 SegoeUIEmoji: bbox (256,-431)..(2556,1869), 2048em.
1490/// 명시적으로 검증된 TrueType face와 다른 기호·글꼴은 원 글리프를 유지한다.
1491pub(crate) fn legacy_hft_bullet_geometry(
1492    text: &str,
1493    style: &TextStyle,
1494) -> Option<(f64, f64, f64, f64)> {
1495    let face = style.font_family.split(',').next().unwrap_or("").trim();
1496    if style.font_metric_trusted || !matches!(face, "한양신명조" | "HanyangSinMyeongJo") {
1497        return None;
1498    }
1499    let (cx, cy, rx, ry) = match text {
1500        "∙" => (0.5, -0.352, 0.12375, 0.123),
1501        // HBATANG의 cmap hit는 있지만 uni26AB 윤곽은 비어 있다. 글자 전진·소유는
1502        // 유지하고, 한컴이 선택한 실제 fallback의 원을 같은 em 좌표계로 그린다.
1503        "⚫" => (
1504            1406.0 / 2048.0,
1505            -719.0 / 2048.0,
1506            1150.0 / 2048.0,
1507            1150.0 / 2048.0,
1508        ),
1509        _ => return None,
1510    };
1511    let size = style.script_font_size(style.font_size);
1512    let ratio = if style.ratio > 0.0 { style.ratio } else { 1.0 };
1513    Some((size * ratio * cx, size * cy, size * ratio * rx, size * ry))
1514}
1515
1516/// 렌더러 트레이트 (모든 백엔드가 구현)
1517pub trait Renderer {
1518    /// 페이지 렌더링 시작
1519    fn begin_page(&mut self, width: f64, height: f64);
1520    /// 페이지 렌더링 종료
1521    fn end_page(&mut self);
1522
1523    /// 텍스트 그리기
1524    fn draw_text(&mut self, text: &str, x: f64, y: f64, style: &TextStyle);
1525    /// Layout owner가 확정한 run-relative 문자 경계값으로 텍스트를 그린다.
1526    ///
1527    /// K0와 positioned replay를 지원하지 않는 보조 renderer는 기존 `draw_text`를
1528    /// 그대로 쓴다. K1 visual backend만 이 메서드를 override하며 font lookup이나
1529    /// shaping을 다시 수행하지 않는다.
1530    fn draw_text_positioned(
1531        &mut self,
1532        text: &str,
1533        x: f64,
1534        y: f64,
1535        style: &TextStyle,
1536        _positions: Option<&[f64]>,
1537    ) {
1538        self.draw_text(text, x, y, style);
1539    }
1540    /// 사각형 그리기 (corner_radius > 0이면 둥근 모서리)
1541    fn draw_rect(&mut self, x: f64, y: f64, w: f64, h: f64, corner_radius: f64, style: &ShapeStyle);
1542    /// 선 그리기
1543    fn draw_line(&mut self, x1: f64, y1: f64, x2: f64, y2: f64, style: &LineStyle);
1544    /// 타원 그리기
1545    fn draw_ellipse(&mut self, cx: f64, cy: f64, rx: f64, ry: f64, style: &ShapeStyle);
1546    /// 이미지 그리기
1547    fn draw_image(&mut self, data: &[u8], x: f64, y: f64, w: f64, h: f64);
1548    /// 패스 그리기 (벡터 도형)
1549    fn draw_path(&mut self, commands: &[PathCommand], style: &ShapeStyle);
1550}
1551
1552/// HWPUNIT → 픽셀 변환 (96 DPI 기준)
1553pub const DEFAULT_DPI: f64 = 96.0;
1554pub const HWPUNIT_PER_INCH: f64 = 7200.0;
1555
1556/// LINE_SEG line_height가 줄의 최대 글자 크기보다 작으면
1557/// ParaShape의 줄간격 설정으로 재계산한다.
1558/// height_measurer와 layout 양쪽에서 동일 로직을 사용해야 한다.
1559#[inline]
1560pub fn corrected_line_height(
1561    raw_lh: f64,
1562    max_fs: f64,
1563    ls_type: LineSpacingType,
1564    ls_val: f64,
1565) -> f64 {
1566    if max_fs > 0.0 && raw_lh < max_fs {
1567        match ls_type {
1568            LineSpacingType::Percent => max_fs * ls_val / 100.0,
1569            LineSpacingType::Fixed => ls_val.max(max_fs),
1570            LineSpacingType::SpaceOnly => max_fs + ls_val,
1571            LineSpacingType::Minimum => ls_val.max(max_fs),
1572        }
1573    } else {
1574        raw_lh
1575    }
1576}
1577
1578/// LINE_SEG의 line_height/line_spacing 의미를 보존하면서 폴백 line_height를 보정한다.
1579///
1580/// raw line_height가 글자 크기보다 작은 합성 줄은 한컴의
1581/// `(line_height=base, line_spacing=extra)` 모델에 맞춰 분해한다.
1582#[inline]
1583pub fn corrected_line_metrics(
1584    raw_lh: f64,
1585    raw_ls: f64,
1586    max_fs: f64,
1587    ls_type: LineSpacingType,
1588    ls_val: f64,
1589) -> (f64, f64) {
1590    if max_fs > 0.0 && raw_lh < max_fs {
1591        match ls_type {
1592            LineSpacingType::Percent => {
1593                // [#2279] sub-100% 퍼센트 음수 gap 존중 (line_breaking 정합)
1594                // 0% 는 실값이다 — line_breaking 과 같은 계약(>=)으로 맞춘다.
1595                let extra = if ls_val >= 0.0 {
1596                    max_fs * (ls_val - 100.0) / 100.0
1597                } else {
1598                    0.0
1599                };
1600                (max_fs, extra)
1601            }
1602            LineSpacingType::Fixed => (ls_val.max(max_fs), 0.0),
1603            LineSpacingType::SpaceOnly => (max_fs, ls_val.max(0.0)),
1604            LineSpacingType::Minimum => (ls_val.max(max_fs), 0.0),
1605        }
1606    } else {
1607        (raw_lh, raw_ls)
1608    }
1609}
1610
1611/// 구역 첫 문단의 저장 줄 metrics를 재조판할 수 있는 구조인가.
1612///
1613/// `SectionDef`와 `ColumnDef`가 함께 들어 있는 문단은 본문 첫 줄을 선언하는
1614/// HWPX 구조다. task2093처럼 해당 첫 줄의 저장 좌표계 전체가 오래된 경우에만
1615/// 줄 높이와 baseline을 글꼴 기준으로 다시 계산한다. 일반 본문/미주 문단의 큰
1616/// 줄 높이는 의도된 조판일 수 있으므로 이 보정 대상이 아니다.
1617#[inline]
1618pub(crate) fn controls_mark_section_start(controls: &[Control]) -> bool {
1619    let mut has_section_def = false;
1620    let mut has_column_def = false;
1621
1622    for control in controls {
1623        match control {
1624            Control::SectionDef(_) => has_section_def = true,
1625            Control::ColumnDef(_) => has_column_def = true,
1626            Control::Bookmark(_) => {}
1627            _ => return false,
1628        }
1629    }
1630
1631    has_section_def && has_column_def
1632}
1633
1634const STALE_SOURCE_LINE_ADVANCE_MULTIPLIER: f64 = 40.0;
1635
1636/// 조합 줄의 최대 글꼴 크기를 구한다.
1637///
1638/// 문단 선두의 구역/단 정의처럼 가시 문자가 아닌 control이 UTF-16 stream offset을
1639/// 앞당기면, 조합 과정에서 줄 run의 글자 모양을 해소하지 못하는 문서가 있다. 이때도
1640/// 해당 줄 시작 위치의 `CharShapeRef`는 원본 문단에 남아 있으므로 이를 보조 근거로
1641/// 사용한다. run에서 얻은 유효한 크기가 있으면 그것을 항상 우선한다.
1642pub(crate) fn composed_line_max_font_size(
1643    line: &composer::ComposedLine,
1644    para: &crate::model::paragraph::Paragraph,
1645    styles: &style_resolver::ResolvedStyleSet,
1646) -> f64 {
1647    let run_max = line
1648        .runs
1649        .iter()
1650        .filter(|run| composed_run_reserves_font_height(run))
1651        .filter_map(|run| {
1652            styles
1653                .char_styles
1654                .get(run.char_style_id as usize)
1655                .map(|style| style.font_size)
1656        })
1657        .fold(0.0f64, f64::max);
1658
1659    let reference_max = composed_line_reference_font_size(line, para, styles);
1660    let run_max = run_max.max(reference_max);
1661    if run_max > 0.0 {
1662        return run_max;
1663    }
1664
1665    // 개체 마커만 있는 줄은 개체/저장 줄 상자가 높이를 소유한다.
1666    // 빈 문단의 글꼴 폴백과 달리 U+FFFC 자체의 글자 크기를 예약하지 않는다.
1667    if !line.runs.is_empty()
1668        && line
1669            .runs
1670            .iter()
1671            .all(|run| !composed_run_reserves_font_height(run))
1672    {
1673        return 0.0;
1674    }
1675
1676    para.char_shape_id_at(line.char_start)
1677        .or_else(|| para.char_shapes.first().map(|shape| shape.char_shape_id))
1678        .and_then(|shape_id| styles.char_styles.get(shape_id as usize))
1679        .map(|style| style.font_size)
1680        .unwrap_or(0.0)
1681}
1682
1683/// 참조 번호의 명목 글자 크기도 소유 줄의 상자에 참여한다. 표시 글리프가
1684/// 3/4 크기여도 그 제어 슬롯의 저장 글자모양을 본문 문자 모양으로 대체하지 않는다.
1685pub(crate) fn composed_line_reference_font_size(
1686    line: &composer::ComposedLine,
1687    para: &crate::model::paragraph::Paragraph,
1688    styles: &style_resolver::ResolvedStyleSet,
1689) -> f64 {
1690    let end = line.char_start
1691        + line
1692            .runs
1693            .iter()
1694            .map(|run| run.text.chars().count())
1695            .sum::<usize>();
1696    let paragraph_end = para.text.chars().count();
1697    let positions = para.control_text_positions();
1698    let raw_positions = para.control_utf16_positions();
1699    para.controls
1700        .iter()
1701        .enumerate()
1702        .filter_map(|(index, control)| {
1703            if !matches!(
1704                control,
1705                crate::model::control::Control::Footnote(_)
1706                    | crate::model::control::Control::Endnote(_)
1707            ) {
1708                return None;
1709            }
1710            let position = *positions.get(index)?;
1711            if position < line.char_start
1712                || (position >= end && !(position == end && end == paragraph_end))
1713            {
1714                return None;
1715            }
1716            let raw = raw_positions.get(index)?;
1717            let shape = para
1718                .char_shapes
1719                .iter()
1720                .rev()
1721                .find(|shape| shape.start_pos <= *raw)?;
1722            styles
1723                .char_styles
1724                .get(shape.char_shape_id as usize)
1725                .map(|style| style.font_size)
1726        })
1727        .fold(0.0_f64, f64::max)
1728}
1729
1730/// 외곽선과 같은 채움 상자는 후행 줄간격을 감싼다. 측정·마지막 흐름 경계와
1731/// 실제 paragraph border painter가 같은 점유 조건을 소비한다.
1732pub(crate) fn paragraph_outline_reserves_line_spacing(
1733    border_fill_id: u16,
1734    styles: &style_resolver::ResolvedStyleSet,
1735) -> bool {
1736    border_fill_id
1737        .checked_sub(1)
1738        .and_then(|index| styles.border_styles.get(usize::from(index)))
1739        .is_some_and(|style| {
1740            style.borders.iter().any(|border| {
1741                !matches!(border.line_type, crate::model::style::BorderLineType::None)
1742            })
1743        })
1744}
1745
1746/// 공백도 글꼴 줄 상자를 가지지만 개체 대체 문자와 제어 문자에는 가시 글꼴이 없다.
1747pub(crate) fn composed_run_reserves_font_height(run: &composer::ComposedTextRun) -> bool {
1748    run.text.chars().any(|c| c != '\u{FFFC}' && !c.is_control())
1749}
1750
1751/// 유효 저장 빈 문단 하나만 가진 각주는 본문 없는 인라인 참조다.
1752/// 공백·개체·명시 번호와 무효/합성 줄은 기존 각주 본문 계약으로 남긴다.
1753pub(crate) fn stored_footnote_is_bodyless(footnote: &crate::model::footnote::Footnote) -> bool {
1754    let [paragraph] = footnote.paragraphs.as_slice() else {
1755        return false;
1756    };
1757    let [line] = paragraph.line_segs.as_slice() else {
1758        return false;
1759    };
1760    paragraph.text.is_empty()
1761        && paragraph.controls.is_empty()
1762        && line.tag & crate::model::paragraph::LineSeg::TAG_IMPLEMENTATION_PROPERTY == 0
1763        && line.vertical_pos == 0
1764        && line.line_height > 0
1765        && line.segment_width > 0
1766}
1767
1768/// 순수 텍스트 줄의 저장 metrics가 글자와 문단 스타일로부터 가능한 줄 advance보다
1769/// 현저히 크면 한컴처럼 재조판한다. 개체가 없는 줄에서 `line_height`와
1770/// `text_height`가 모두 비정상적으로 큰 값이면 저장 조판 정보가 현재 텍스트와 맞지
1771/// 않는다. 원본 IR은 보존하고 렌더/조판용 metrics만 바꾼다.
1772///
1773/// 40배는 10pt/160% 줄이 A4 본문 한 쪽에 가까운 높이를 단일 줄에 기록한 경우만
1774/// 잡는다. 이보다 작은 큰 줄은 하단 고정 틀의 fit 경계처럼 의도된 저장 조판일 수 있다.
1775#[inline]
1776pub(crate) fn source_line_metrics_need_reflow(
1777    raw_lh: f64,
1778    raw_text_height: f64,
1779    max_fs: f64,
1780    ls_type: LineSpacingType,
1781    ls_val: f64,
1782    source_metrics_reflow_eligible: bool,
1783) -> bool {
1784    if !source_metrics_reflow_eligible || max_fs <= 0.0 || raw_lh <= 0.0 || raw_text_height <= 0.0 {
1785        return false;
1786    }
1787
1788    let (expected_lh, expected_ls) = corrected_line_metrics(0.0, 0.0, max_fs, ls_type, ls_val);
1789    let expected_advance = (expected_lh + expected_ls).max(max_fs);
1790
1791    raw_lh > expected_advance * STALE_SOURCE_LINE_ADVANCE_MULTIPLIER
1792        && raw_text_height > expected_advance * STALE_SOURCE_LINE_ADVANCE_MULTIPLIER
1793}
1794
1795/// 저장된 다음 줄 좌표를 현재 줄의 흐름 높이로 쓸 수 있으면 그 콘텐츠 높이를 반환한다.
1796///
1797/// `LINE_SEG.line_height`는 그림·표를 덮는 상자일 수 있지만, 한/글의 다음 줄 위치는
1798/// 저장 사다리(`next.vertical_pos - current.vertical_pos`)가 정한다. 다만 재조판된
1799/// 상자, 역행·동일 좌표, 글자 또는 글자처럼 취급되는 개체보다 작은 advance에는 저장
1800/// 좌표를 섞지 않는다. layout과 fallback measurement가 이 판별자를 공유한다.
1801#[inline]
1802pub(crate) fn stored_line_flow_height(
1803    current: &LineSeg,
1804    next: &LineSeg,
1805    rendered_line_height: f64,
1806    line_spacing: f64,
1807    flow_floor: f64,
1808    dpi: f64,
1809    source_metrics_reflowed: bool,
1810) -> Option<f64> {
1811    if source_metrics_reflowed
1812        || (hwpunit_to_px(current.line_height, dpi) - rendered_line_height).abs() >= 0.5
1813        || current.vertical_pos < 0
1814        || next.vertical_pos <= current.vertical_pos
1815    {
1816        return None;
1817    }
1818
1819    let step = hwpunit_to_px(next.vertical_pos - current.vertical_pos, dpi) - line_spacing;
1820    (step > 0.0 && step < rendered_line_height && (flow_floor <= 0.0 || step + 0.5 >= flow_floor))
1821        .then_some(step)
1822}
1823
1824/// 장평은 가로 축에 적용하고 원본 글자 크기의 세로 축은 보존한다.
1825/// PDF 추출 span의 size는 가로 변환까지 포함하므로 실제 Tf·CTM과 구분한다.
1826/// 독립 Print의 원시 연산은 세로 크기를 유지하고 Tz로 장평을 적용한다.
1827#[inline]
1828pub(crate) fn condensed_ratio_draw_params(font_size: f64, ratio: f64) -> (f64, f64) {
1829    (font_size, if ratio > 0.0 { ratio } else { 1.0 })
1830}
1831
1832/// 저장 줄 metrics를 재조판하는 경우의 baseline을 글꼴 기준으로 복원한다.
1833///
1834/// 원본 `baseline_distance`도 손상된 `line_height` 좌표계에 기록되므로, 줄 높이만
1835/// 낮추고 baseline을 그대로 두면 SVG/Canvas 텍스트가 페이지 하단으로 이탈한다.
1836#[inline]
1837pub(crate) fn corrected_line_baseline_for_source(
1838    raw_baseline: f64,
1839    max_fs: f64,
1840    source_metrics_reflowed: bool,
1841) -> f64 {
1842    if source_metrics_reflowed {
1843        max_fs * 0.85
1844    } else {
1845        raw_baseline
1846    }
1847}
1848
1849/// 문단의 단일 저장 줄이 현재 글꼴/문단 스타일 기준으로 재조판 대상인지 판별한다.
1850///
1851/// 이 판정은 HWPX의 손상된 첫 줄이 이후 문단의 `vertical_pos`까지 크게 밀어 둔
1852/// 경우에만 사용한다. 원본 줄 배열은 바꾸지 않고, 페이지네이터와 렌더러가 같은
1853/// 조판 커서 보정 여부를 결정하는 데 쓴다.
1854pub(crate) fn paragraph_source_line_metrics_need_reflow(
1855    para: &crate::model::paragraph::Paragraph,
1856    styles: &style_resolver::ResolvedStyleSet,
1857    dpi: f64,
1858) -> bool {
1859    if !controls_mark_section_start(&para.controls)
1860        || !para
1861            .text
1862            .chars()
1863            .any(|ch| ch > '\u{001F}' && ch != '\u{FFFC}')
1864    {
1865        return false;
1866    }
1867
1868    let [line] = para.line_segs.as_slice() else {
1869        return false;
1870    };
1871    let max_fs = para
1872        .char_shape_id_at(0)
1873        .or_else(|| para.char_shapes.first().map(|shape| shape.char_shape_id))
1874        .and_then(|shape_id| styles.char_styles.get(shape_id as usize))
1875        .map(|style| style.font_size)
1876        .unwrap_or(0.0);
1877    let (ls_type, ls_val) = styles
1878        .para_styles
1879        .get(para.para_shape_id as usize)
1880        .map(|style| (style.line_spacing_type, style.line_spacing))
1881        .unwrap_or((LineSpacingType::Percent, 160.0));
1882
1883    source_line_metrics_need_reflow(
1884        hwpunit_to_px(line.line_height, dpi),
1885        hwpunit_to_px(line.text_height, dpi),
1886        max_fs,
1887        ls_type,
1888        ls_val,
1889        true,
1890    )
1891}
1892
1893/// 구역의 저장 LINE_SEG 사다리가 "통짜 합성값"인지 판정한다 (#5854).
1894///
1895/// 한컴이 실제로 조판한 문서의 LINE_SEG 는 줄마다 그 줄의 글자 크기·줄간격을
1896/// 담고, 여러 줄로 접힌 문단은 줄 수만큼 세그먼트를 갖는다. 반면 일부 생성기는
1897/// 그 자리에 **문단 하나당 세그먼트 하나 · 전 문단 동일 튜플 · `vertical_pos` 는
1898/// 그 튜플의 advance 만큼 일정하게 증가**하는 사다리를 채워 넣는다. 그런 사다리는
1899/// 문서의 실제 글자 크기와 무관한 상수라서 조판 근거가 될 수 없다.
1900///
1901/// 실측 (`samples/hwpx/hwpx-02.hwpx`): 122 문단 전부
1902/// `vertsize=1000 textheight=1000 baseline=850 spacing=600`,
1903/// `vertpos` 는 처음부터 끝까지 정확히 1600 씩 증가한다. 그런데 문단들의 실제
1904/// 글자 크기는 2pt~15pt 로 갈려 82 문단이 저장 `vertsize`(10pt) 와 어긋난다.
1905///
1906/// 판정이 참이면 호출자는 (1) 줄 metrics 를 저장값이 아니라 글꼴·문단 스타일에서
1907/// 다시 뽑고, (2) `vertical_pos` 앵커 스냅을 끈다. 원본 IR 은 건드리지 않는다.
1908pub(crate) use stored_line_ladder::stored_line_ladder_is_uniform_filler;
1909
1910/// 저장된 순수 텍스트 줄은 `vertsize`에 내부 여백이 포함되어도 한컴의 줄 진행이
1911/// `textheight + spacing`에 맞춰지는 사례가 있다. IR 값은 보존하고 렌더/조판용
1912/// line height만 낮춘다.
1913#[inline]
1914pub fn corrected_line_metrics_for_source(
1915    raw_lh: f64,
1916    raw_text_height: f64,
1917    raw_ls: f64,
1918    max_fs: f64,
1919    ls_type: LineSpacingType,
1920    ls_val: f64,
1921    use_stored_text_height: bool,
1922    source_metrics_reflow_eligible: bool,
1923) -> (f64, f64) {
1924    if source_line_metrics_need_reflow(
1925        raw_lh,
1926        raw_text_height,
1927        max_fs,
1928        ls_type,
1929        ls_val,
1930        source_metrics_reflow_eligible,
1931    ) {
1932        return corrected_line_metrics(0.0, 0.0, max_fs, ls_type, ls_val);
1933    }
1934
1935    let (lh, ls) = corrected_line_metrics(raw_lh, raw_ls, max_fs, ls_type, ls_val);
1936    if use_stored_text_height
1937        && raw_text_height > 0.0
1938        && raw_text_height < lh
1939        && (max_fs <= 0.0 || raw_text_height + 0.5 >= max_fs * 0.8)
1940    {
1941        (raw_text_height, ls)
1942    } else {
1943        (lh, ls)
1944    }
1945}
1946
1947/// HWP3-origin HWP5 conversions may omit PARA_LINE_SEG for body paragraphs.
1948/// The composer then emits synthetic lines with a tiny raw line height. For
1949/// those synthetic lines, applying ParaShape's percent line spacing again makes
1950/// the paragraph too tall compared with Hancom's converted layout.
1951#[inline]
1952pub fn corrected_line_height_for_variant_synthetic(
1953    raw_lh: f64,
1954    max_fs: f64,
1955    ls_type: LineSpacingType,
1956    ls_val: f64,
1957    hwp3_variant_synthetic: bool,
1958) -> f64 {
1959    if hwp3_variant_synthetic && max_fs > 0.0 && raw_lh < max_fs {
1960        max_fs
1961    } else {
1962        corrected_line_height(raw_lh, max_fs, ls_type, ls_val)
1963    }
1964}
1965
1966/// 해소된 문단 앞 간격을 측정·배치·편집 호출에 그대로 전달한다.
1967///
1968/// HWP5 원시 간격을 parser에서 반감한 뒤 배치만 다시 두 배로 늘리던
1969/// 보정은 제거했다. 계보와 관계없이 공통 style resolver의 물리 값을 한 번 소비한다.
1970/// 기존 내부 호출의 인자 형태는 유지하지만 추가 스케일은 적용하지 않는다.
1971#[inline]
1972pub(crate) fn hwp3_variant_flow_spacing_before(base: f64, _is_hwp3_variant: bool) -> f64 {
1973    base
1974}
1975
1976/// [#6630] 셀 첫 문단의 위 여백(px) — 저장 첫 줄 `LINE_SEG.vertical_pos` 를 상한으로 둔 값.
1977///
1978/// 한/글은 셀 맨 위 문단의 "문단 위 여백"을 저장 vpos 만큼 둔다 (exam_eng 바탕쪽 머리 표:
1979/// 위 여백 1136HU 인데 vpos=568HU=7.57px, 그림이 그만큼 아래·셀 내용 높이도 그만큼 큼).
1980/// 본문 column-top 문단의 증거 기반 클램프(#853·#1811)와 같은 규칙을 셀 첫 문단에 쓴다.
1981/// 내용 높이 측정(`calc_para_lines_height`·`height_measurer`)과 셀 배치가 같은 값을 써야
1982/// 세로 정렬이 어긋나지 않는다. 저장 줄이 없거나 vpos ≤ 0 이면 0 (종전과 같다).
1983pub(crate) fn cell_first_para_stored_lead(
1984    para: &crate::model::paragraph::Paragraph,
1985    spacing_before_px: f64,
1986    dpi: f64,
1987) -> f64 {
1988    if spacing_before_px <= 0.0 {
1989        return 0.0;
1990    }
1991    let vpos = para
1992        .line_segs
1993        .first()
1994        .map(|ls| hwpunit_to_px(ls.vertical_pos, dpi))
1995        .unwrap_or(0.0);
1996    if vpos <= 0.0 {
1997        return 0.0;
1998    }
1999    spacing_before_px.min(vpos)
2000}
2001
2002/// 셀 안의 단일 단 정의는 글자·개체를 그리거나 세로 흐름을 전진하지 않는다.
2003/// 원본 셀의 단 정의와 필드/링크 표식은 본문 글줄에 별도 상자를 추가하지 않는다.
2004/// 필드 결과는 문단 텍스트가 소유하며, 원본 제어 주소는 그대로 보존한다.
2005/// 여러 단 정의와 실제 개체 컨트롤은 일반 텍스트 글줄로 재분류하지 않는다.
2006pub(crate) fn cell_control_is_text_metadata(control: &crate::model::control::Control) -> bool {
2007    match control {
2008        crate::model::control::Control::ColumnDef(columns) => columns.column_count == 1,
2009        crate::model::control::Control::Field(_) | crate::model::control::Control::Hyperlink(_) => {
2010            composer::control_is_width_neutral_marker(control)
2011        }
2012        _ => false,
2013    }
2014}
2015
2016pub(crate) fn cell_paragraph_has_only_text_metadata(
2017    para: &crate::model::paragraph::Paragraph,
2018) -> bool {
2019    para.controls.iter().all(cell_control_is_text_metadata)
2020}
2021
2022/// Stored cell starts already express their lead in the saved frame. Reflow
2023/// starts have no such frame and own the paragraph's declared before-space.
2024/// Later paragraphs own that space in both paths.
2025pub(crate) fn cell_paragraph_spacing_before(
2026    para: &crate::model::paragraph::Paragraph,
2027    para_index: usize,
2028    spacing_before: f64,
2029) -> f64 {
2030    if para_index > 0 || para_has_no_stored_line_segs(para) {
2031        spacing_before
2032    } else {
2033        0.0
2034    }
2035}
2036
2037/// [#2169] 저장 LINE_SEG 부재 판별 — 원본 NO_LS 와 자기-export HWPX 재파싱본
2038/// (전부 synthetic, tag 0x8000_0000)을 동일 취급해 왕복 시멘틱을 정합한다
2039/// (#1770 계열: 국소 문맥 판별).
2040#[inline]
2041pub(crate) fn para_has_no_stored_line_segs(p: &crate::model::paragraph::Paragraph) -> bool {
2042    p.line_segs.is_empty() || p.line_segs.iter().all(|s| s.tag & 0x8000_0000 != 0)
2043}
2044
2045/// [#8810] 저장 줄 없는 **글** 문단 — 저장 뒤 글을 고치고 줄 정보를 지운 문단이다.
2046///
2047/// 같은 사다리의 뒤 저장 vpos 와 되감김은 이 문단의 저장 당시 높이로 정해졌으므로, 이
2048/// 문단을 지난 저장 좌표는 현재 글의 조판이 아니다. 개체를 가진 문단은 본문 규칙
2049/// (`stored_page_boundary_invalidated_by_reflow`)과 같이 독립 소유자로 본다 — 쪽을 넘는
2050/// TAC 표 host 는 저장 줄 없이도 정상 저장본이다.
2051pub(crate) fn para_is_unstored_text(p: &crate::model::paragraph::Paragraph) -> bool {
2052    p.controls.is_empty() && !p.text.trim().is_empty() && para_has_no_stored_line_segs(p)
2053}
2054
2055/// [#8507] 글자 없는 host(텍스트 스트림이 비어 있는 문단)의 개체 줄을 rhwp 가 여러 줄로 재조판했는지.
2056///
2057/// 줄 재조판은 필드 시작 뒤 줄 폭에 들지 않는 글자처럼 취급 개체를 다음 줄로 넘기고 필드
2058/// 줄을 빈 줄로 남긴다(한/글 2020 합성 field_over19). 이 줄들은 저장 사다리가 아니라 한 번
2059/// 정한 줄 구성이라, 조판과 배치가 개체를 자기 줄(`control_line_seg_index`)에 두고 앞 줄을
2060/// 문단 높이에 센다. 저장 줄은 각자의 저장 계약을 따른다.
2061pub(crate) fn para_has_composed_object_rows(p: &crate::model::paragraph::Paragraph) -> bool {
2062    p.text.is_empty() && p.line_segs.len() >= 2 && para_has_no_stored_line_segs(p)
2063}
2064
2065/// 본문 글자가 없는 표 host 문단에서 표 줄(`table_line`) 뒤의 저장 줄들이 차지하는 높이(HU).
2066///
2067/// 쪽 번호 감추기 같은 컨트롤만 남은 줄도 한/글은 줄 상자(높이+간격)를 쌓는다.
2068/// 본문 줄이 없어 post-text 로 나가지 않으므로 조판과 그리기가 이 값을 함께 더한다.
2069/// 한/글이 계산한 저장 줄이 같은 쪽에서 끊김 없이 이어질 때만 값을 돌려준다.
2070pub(crate) fn tac_host_control_only_tail_hu(
2071    p: &crate::model::paragraph::Paragraph,
2072    table_line: usize,
2073) -> Option<i32> {
2074    tac_host_control_only_tail(p, table_line)
2075        .filter(|tail| tail.same_frame)
2076        .map(|tail| {
2077            tail.lines
2078                .iter()
2079                .map(|s| s.line_height + s.line_spacing)
2080                .sum()
2081        })
2082}
2083
2084/// 표 줄 뒤 컨트롤 전용 저장 줄들.
2085pub(crate) struct TacHostControlOnlyTail<'a> {
2086    /// 표 줄 다음 줄부터 문단 끝까지의 저장 줄.
2087    pub lines: &'a [crate::model::paragraph::LineSeg],
2088    /// 모든 줄이 앞 줄의 `vpos + 줄 높이 + 줄간격` 에서 이어진다(같은 저장 쪽).
2089    pub same_frame: bool,
2090}
2091
2092/// 본문 글자가 없는 표 host 문단의 표 줄 뒤 컨트롤 전용 저장 줄들.
2093///
2094/// 한/글은 이 줄도 보통 줄처럼 `앞 줄 vpos + 줄 높이 + 줄간격` 에 놓고, 그 자리가 쪽에
2095/// 들어가지 않으면 다음 쪽 맨 위에서 다시 시작한다(저장 vpos 가 앞 줄보다 작아진다).
2096/// 각 줄은 앞 줄에서 끊김 없이 잇거나 저장 쪽 재시작이어야 한다.
2097pub(crate) fn tac_host_control_only_tail(
2098    p: &crate::model::paragraph::Paragraph,
2099    table_line: usize,
2100) -> Option<TacHostControlOnlyTail<'_>> {
2101    use crate::model::{control::Control, paragraph::LineSeg};
2102    let tail = p
2103        .line_segs
2104        .get(table_line + 1..)
2105        .filter(|t| !t.is_empty())?;
2106    let steps = p.line_segs[table_line..].windows(2);
2107    let continues = |w: &[LineSeg]| {
2108        w[1].vertical_pos == w[0].vertical_pos + w[0].line_height + w[0].line_spacing
2109    };
2110    let same_frame = steps.clone().all(continues);
2111    let stored_flow = steps
2112        .clone()
2113        .all(|w| continues(w) || w[1].vertical_pos < w[0].vertical_pos);
2114    // 표 말고 다른 개체가 있으면 뒤 줄은 그 개체의 줄이다(개체 배치가 높이를 쌓는다).
2115    let only_one_object = p
2116        .controls
2117        .iter()
2118        .filter(|c| {
2119            matches!(
2120                c,
2121                Control::Table(_)
2122                    | Control::Shape(_)
2123                    | Control::Picture(_)
2124                    | Control::Equation(_)
2125                    | Control::Form(_)
2126            )
2127        })
2128        .count()
2129        == 1;
2130    (stored_flow
2131        && only_one_object
2132        && p.text.is_empty()
2133        && p.line_segs
2134            .iter()
2135            .all(|s| s.tag & LineSeg::TAG_IMPLEMENTATION_PROPERTY == 0))
2136    .then_some(TacHostControlOnlyTail {
2137        lines: tail,
2138        same_frame,
2139    })
2140}
2141
2142/// These controls do not replace the empty host paragraph's own text line.
2143/// Square tables have a separate exclusion/flow owner and are not included.
2144/// 별도 머리말/꼬리말 프레임의 표지는 본문 줄의 폭·높이를 소유하지 않는다.
2145/// 각주·미주는 본문 슬롯/예약을 가지므로 같은 marker로 취급하지 않는다.
2146pub(crate) fn control_is_body_flow_neutral_marker(
2147    control: &crate::model::control::Control,
2148) -> bool {
2149    matches!(
2150        control,
2151        crate::model::control::Control::Header(_) | crate::model::control::Control::Footer(_)
2152    ) || composer::control_is_width_neutral_marker(control)
2153}
2154
2155pub(crate) fn empty_host_controls_are_flow_neutral(
2156    para: &crate::model::paragraph::Paragraph,
2157) -> bool {
2158    use crate::model::{control::Control, shape::TextWrap};
2159    para.controls.iter().all(|control| {
2160        let common = match control {
2161            Control::Picture(picture) => &picture.common,
2162            Control::Shape(shape) => shape.common(),
2163            Control::Table(table) => {
2164                return !table.common.treat_as_char
2165                    && matches!(
2166                        table.common.text_wrap,
2167                        TextWrap::InFrontOfText | TextWrap::BehindText
2168                    );
2169            }
2170            marker => return control_is_body_flow_neutral_marker(marker),
2171        };
2172        !common.treat_as_char
2173            && matches!(
2174                common.text_wrap,
2175                TextWrap::InFrontOfText | TextWrap::BehindText | TextWrap::Square
2176            )
2177    })
2178}
2179
2180/// 저장 LINE_SEG 가 없는 문단이 글자 없이(공백뿐) 글앞/글뒤 표를 host 하는지.
2181///
2182/// 작은 표나 제목 표를 얹은 서식 머리 문단이다. 한/글은 이 문단에도 자기 글자 모양의
2183/// 줄 하나(줄높이 + 줄간격)를 주고, 글앞/글뒤 개체는 그 줄을 밀지도 지우지도 않는다.
2184/// 이 줄이 없으면 뒤 문단에 묶인 표가 em 줄만큼 위로 올라 앞 표와 겹친다. 구역 첫
2185/// 문단만의 규칙이 아니다 — 구역 중간의 host 도 같은 줄을 가진다.
2186///
2187/// 판별은 문단만 보므로 셀 문단도 해당될 수 있다. 셀 높이 측정은 별도 경로라 이
2188/// em 줄을 모른다 — 본문 흐름(typeset·본문 layout) 호출부에서만 쓴다.
2189pub(crate) fn para_is_unstored_empty_overlay_table_host(
2190    p: &crate::model::paragraph::Paragraph,
2191) -> bool {
2192    p.text.trim().is_empty() && para_is_unstored_overlay_table_host(p)
2193}
2194
2195/// 저장 LINE_SEG 가 없는 문단이 글앞/글뒤 개체만 갖고 그중 표가 하나 이상인지(글자 유무 무관).
2196pub(crate) fn para_is_unstored_overlay_table_host(p: &crate::model::paragraph::Paragraph) -> bool {
2197    use crate::model::control::Control;
2198    use crate::model::shape::{CommonObjAttr, TextWrap};
2199    let overlay = |c: &CommonObjAttr| {
2200        !c.treat_as_char && matches!(c.text_wrap, TextWrap::InFrontOfText | TextWrap::BehindText)
2201    };
2202    p.line_segs.is_empty()
2203        && p.controls
2204            .iter()
2205            .any(|c| matches!(c, Control::Table(t) if overlay(&t.common)))
2206        && p.controls.iter().all(|c| match c {
2207            Control::Table(t) => overlay(&t.common),
2208            Control::Picture(pic) => overlay(&pic.common),
2209            Control::Shape(s) => overlay(s.common()),
2210            // 머리말/꼬리말은 자기 영역의 별도 흐름이라 이 줄을 차지하지 않는다.
2211            Control::SectionDef(_)
2212            | Control::ColumnDef(_)
2213            | Control::Header(_)
2214            | Control::Footer(_) => true,
2215            _ => false,
2216        })
2217}
2218
2219/// [`para_is_unstored_empty_overlay_table_host`] 문단의 em 줄 `(줄높이, 줄간격, 글꼴 크기)` px.
2220/// typeset(빈 문단 줄박스)과 본문 layout(흐름 전진)이 같은 값을 쓴다.
2221pub(crate) fn unstored_overlay_table_host_line_metrics(
2222    p: &crate::model::paragraph::Paragraph,
2223    styles: &style_resolver::ResolvedStyleSet,
2224    para_style: Option<&style_resolver::ResolvedParaStyle>,
2225) -> Option<(f64, f64, f64)> {
2226    let font_size = section_head_overlay_host_font_size(p, styles)?;
2227    if font_size <= 0.0 {
2228        return None;
2229    }
2230    let (height, leading) = corrected_line_metrics(
2231        0.0,
2232        0.0,
2233        font_size,
2234        para_style.map_or(crate::model::style::LineSpacingType::Percent, |s| {
2235            s.line_spacing_type
2236        }),
2237        para_style.map_or(160.0, |s| s.line_spacing),
2238    );
2239    Some((height, leading, font_size))
2240}
2241
2242/// 저장 줄 없는 host 의 글줄이 같은 문단의 자리차지 표 **아래**에서 시작하는지.
2243///
2244/// 자리차지 표는 자기 세로 구간에 글줄을 두지 않는다. 표 컨트롤이 글자보다 앞에 있고
2245/// 표 상자(오프셋 + 바깥여백 위)가 첫 줄 높이 안에서 시작하면, 그 줄은 표 위에 들어갈
2246/// 자리가 없어 표 아래로 내려간다.
2247/// 표가 글자 뒤에 있거나 오프셋이 첫 줄보다 깊으면 글줄은 표 위(앵커)에 남는다(#1549).
2248pub(crate) fn unstored_host_text_follows_topbottom_table(
2249    p: &crate::model::paragraph::Paragraph,
2250    styles: &style_resolver::ResolvedStyleSet,
2251    dpi: f64,
2252) -> bool {
2253    use crate::model::control::Control;
2254    use crate::model::shape::{TextWrap, VertAlign, VertRelTo};
2255    if !para_has_no_stored_line_segs(p) {
2256        return false;
2257    }
2258    let Some(first_ink) = p.text.chars().position(|c| !c.is_whitespace()) else {
2259        return false;
2260    };
2261    let mut tables = p.controls.iter().enumerate().filter_map(|(i, c)| match c {
2262        Control::Table(t) => Some((i, t)),
2263        _ => None,
2264    });
2265    let (Some((table_index, t)), None) = (tables.next(), tables.next()) else {
2266        return false;
2267    };
2268    let v_off = t.common.vertical_offset as i32;
2269    if t.common.treat_as_char
2270        || !matches!(t.common.text_wrap, TextWrap::TopAndBottom)
2271        || !matches!(t.common.vert_rel_to, VertRelTo::Para)
2272        || !matches!(t.common.vert_align, VertAlign::Top)
2273        || v_off <= 0
2274        || p.control_text_positions()
2275            .get(table_index)
2276            .is_none_or(|&pos| pos > first_ink)
2277    {
2278        return false;
2279    }
2280    section_head_overlay_host_font_size(p, styles)
2281        .is_some_and(|font_size| hwpunit_to_px(v_off + t.outer_margin_top as i32, dpi) < font_size)
2282}
2283
2284/// 저장 줄 없는 **빈** host 의 단독 어울림(Square) 표 기하 `(표 상단, 표 아래 추가분)` px.
2285///
2286/// 표 상단은 host 시작에서 `세로 오프셋 + 바깥여백 위` 아래다(오프셋은 바깥여백 상자의
2287/// 모서리). 표만 가진 빈 host 는 개체 앵커라 자기 빈 줄이 없어 표 바닥 뒤 흐름이
2288/// `바깥여백 아래` 만큼만 전진한다. 글앞·글뒤 장식을 함께 가진 host 는 빈 줄을 갖고,
2289/// 표가 단 폭을 채워 옆에 글자 띠가 없으면 그 줄은 표 밴드와 겹치는 자리에 들어갈 수
2290/// 없어 표 **아래**로 내려가므로, 표 바닥 뒤 흐름은 `바깥여백 아래 + host 줄(lh+ls)`
2291/// 만큼 더 전진한다.
2292///
2293/// 줄이 오프셋 위 틈에 들어가는 경우(오프셋 ≥ 줄 높이)와 옆 띠가 있는 경우는 None 으로
2294/// 일반 어울림 표 경로에 남긴다. typeset(흐름 전진)과 layout(표 위치·뒤 흐름)이
2295/// 같은 값을 쓴다.
2296pub(crate) fn unstored_empty_square_table_host_geometry_px(
2297    p: &crate::model::paragraph::Paragraph,
2298    t: &crate::model::table::Table,
2299    column_width_px: f64,
2300    styles: &style_resolver::ResolvedStyleSet,
2301    para_style: Option<&style_resolver::ResolvedParaStyle>,
2302    dpi: f64,
2303) -> Option<(f64, f64)> {
2304    use crate::model::control::Control;
2305    use crate::model::shape::{
2306        CommonObjAttr, HorzAlign, HorzRelTo, TextWrap, VertAlign, VertRelTo,
2307    };
2308    // 글자 하나가 들어갈 최소 띠 — `no_lineseg_square_table_host_band` 와 같은 값.
2309    const MIN_BAND_HU: i32 = 2000;
2310
2311    let is_square_float =
2312        |c: &CommonObjAttr| !c.treat_as_char && matches!(c.text_wrap, TextWrap::Square);
2313    let is_overlay = |c: &CommonObjAttr| {
2314        !c.treat_as_char && matches!(c.text_wrap, TextWrap::InFrontOfText | TextWrap::BehindText)
2315    };
2316    if !para_has_no_stored_line_segs(p)
2317        || !p.text.trim().is_empty()
2318        || !is_square_float(&t.common)
2319        || !matches!(t.common.vert_rel_to, VertRelTo::Para)
2320        || !matches!(t.common.vert_align, VertAlign::Top)
2321        || !matches!(t.common.horz_rel_to, HorzRelTo::Column | HorzRelTo::Para)
2322        || !matches!(t.common.horz_align, HorzAlign::Left)
2323        || (t.common.vertical_offset as i32) < 0
2324    {
2325        return None;
2326    }
2327    let mut square_floats = 0usize;
2328    let mut has_overlay = false;
2329    for control in &p.controls {
2330        let common = match control {
2331            Control::Table(table) => &table.common,
2332            Control::Picture(pic) => &pic.common,
2333            Control::Shape(shape) => shape.common(),
2334            _ => return None,
2335        };
2336        if is_square_float(common) {
2337            square_floats += 1;
2338        } else if is_overlay(common) {
2339            has_overlay = true;
2340        } else {
2341            return None;
2342        }
2343    }
2344    if square_floats != 1 {
2345        return None;
2346    }
2347
2348    let column_width_hu = px_to_hwpunit(column_width_px, dpi);
2349    let offset = t.common.horizontal_offset as i32;
2350    let obj_left = offset - t.outer_margin_left as i32;
2351    let obj_right = offset + t.common.width as i32 + t.outer_margin_right as i32;
2352    if obj_left.max(0) >= MIN_BAND_HU || column_width_hu - obj_right >= MIN_BAND_HU {
2353        return None;
2354    }
2355
2356    let char_shape_id =
2357        p.char_shape_id_at(0)
2358            .or_else(|| p.char_shapes.first().map(|cs| cs.char_shape_id))? as usize;
2359    let font_size = styles.char_styles.get(char_shape_id)?.font_size;
2360    if font_size <= 0.0 {
2361        return None;
2362    }
2363    let (line_height, line_spacing) = corrected_line_metrics(
2364        0.0,
2365        0.0,
2366        font_size,
2367        para_style.map_or(crate::model::style::LineSpacingType::Percent, |s| {
2368            s.line_spacing_type
2369        }),
2370        para_style.map_or(160.0, |s| s.line_spacing),
2371    );
2372    let line_advance = line_height + line_spacing;
2373    let v_off = hwpunit_to_px(t.common.vertical_offset as i32, dpi);
2374    if v_off >= line_advance {
2375        return None;
2376    }
2377    let table_top = v_off + hwpunit_to_px(t.outer_margin_top as i32, dpi);
2378    let outer_bottom = hwpunit_to_px(t.outer_margin_bottom as i32, dpi);
2379    if !has_overlay {
2380        return Some((table_top, outer_bottom));
2381    }
2382    Some((table_top, outer_bottom + line_advance))
2383}
2384
2385/// [`para_is_unstored_empty_overlay_table_host`] 문단의 em 줄 글자 크기.
2386///
2387/// 이 문단의 한 줄에는 컨트롤 문자(구역·단 정의, 표)와 공백이 함께 놓인다. 줄 높이는
2388/// 그 줄 글자들의 최대 글자 크기다 — 첫 글자(공백)의 모양만 보면 컨트롤 문자 구간의
2389/// 더 큰 모양이 빠진다.
2390fn section_head_overlay_host_font_size(
2391    p: &crate::model::paragraph::Paragraph,
2392    styles: &style_resolver::ResolvedStyleSet,
2393) -> Option<f64> {
2394    p.char_shapes
2395        .iter()
2396        .filter_map(|r| styles.char_styles.get(r.char_shape_id as usize))
2397        .map(|s| s.font_size)
2398        .fold(None, |acc: Option<f64>, size| {
2399            Some(acc.map_or(size, |a| a.max(size)))
2400        })
2401}
2402
2403/// 합성 Square 구간은 시작 위치까지의 왼쪽 여백을 이미 차지한다.
2404/// 이를 본문 상자의 폭으로 환산해 측정과 배치가 같은 프레임을 사용하게 하며,
2405/// 글꼴별 임의 허용 폭은 더하지 않는다.
2406pub(crate) fn synthetic_wrap_column_width(
2407    column_width: f64,
2408    margin_left: f64,
2409    anchor: Option<&pagination::WrapAnchorRef>,
2410    dpi: f64,
2411) -> f64 {
2412    let Some(anchor) = anchor.filter(|a| a.band_y_range.is_none() && a.anchor_sw > 0) else {
2413        return column_width;
2414    };
2415    let start = hwpunit_to_px(anchor.anchor_cs, dpi);
2416    let width = hwpunit_to_px(anchor.anchor_sw.max(0), dpi);
2417    column_width.min(width + margin_left.min(start))
2418}
2419
2420/// 셀 문단의 저장 `LINE_SEG.vertical_pos` 를 절대 앵커로 신뢰할 수 있는지 판정한다.
2421///
2422/// `vertical_pos == 0` 은 "셀 상단"이라는 유효한 값이면서 동시에 "앵커 없음"의
2423/// 센티널이기도 하다. 첫 문단은 0 이 곧 셀 상단이라 그대로 신뢰하고, 두 번째 이후
2424/// 문단은 양수 vpos 가 저장돼 있을 때만 앵커로 쓴다.
2425#[inline]
2426pub(crate) fn first_seg_vpos_is_anchor(
2427    para: &crate::model::paragraph::Paragraph,
2428    cell_para_index: usize,
2429) -> bool {
2430    para.line_segs.first().is_some_and(|seg| {
2431        // 재조판 줄의 vpos는 현재 문단 안의 로컬 원점이다. 저장된 셀 절대
2432        // 앵커로 승격하면 첫 줄의 앞 간격을 선차감한 뒤 다시 잃게 된다.
2433        seg.tag & crate::model::paragraph::LineSeg::TAG_IMPLEMENTATION_PROPERTY == 0
2434            && (cell_para_index == 0 || seg.vertical_pos > 0)
2435    })
2436}
2437
2438/// 글자처럼 취급되는(`treat_as_char`) 그림·도형이 줄 흐름에서 차지하는 높이(px).
2439///
2440/// 조판(`typeset`)과 렌더(`layout`)가 각자 이 식을 들고 있었고, 도형 쪽 정의가
2441/// 서로 달랐다 — 렌더는 [`ShapeObject::flow_height_hu`], 조판은 저장 프레임만.
2442/// 같은 속성의 정의는 하나여야 하므로(#4333) 두 경로가 이 함수를 공유한다.
2443#[inline]
2444pub(crate) fn tac_object_flow_height_px(
2445    ctrl: &crate::model::control::Control,
2446    dpi: f64,
2447) -> Option<f64> {
2448    tac_object_flow_height_hu(ctrl).map(|height_hu| hwpunit_to_px(height_hu, dpi))
2449}
2450
2451/// [`tac_object_flow_height_px`] 와 같은 값의 HWPUNIT 판. 저장 `LineSeg.line_height`
2452/// 와 직접 견주는 자리는 dpi 를 거치지 않아야 반올림 없이 같은 줄을 짚는다.
2453#[inline]
2454pub(crate) fn tac_object_flow_height_hu(ctrl: &crate::model::control::Control) -> Option<i32> {
2455    use crate::model::control::Control;
2456    match ctrl {
2457        Control::Picture(pic) if pic.common.treat_as_char => {
2458            Some(composer::inline_picture_size_hu(pic).1)
2459        }
2460        Control::Shape(shape) if shape.common().treat_as_char => Some(shape.flow_height_hu()),
2461        _ => None,
2462    }
2463}
2464
2465/// 저장 줄 높이가 문단의 인라인 개체 하나로 설명될 때, 그 개체의 흐름 높이(px).
2466///
2467/// "이 줄은 인라인 개체가 소유한 줄인가" 를 묻는 술어다. 조판과 렌더가 같은 줄에
2468/// 같은 답을 내지 않으면 그 줄의 예약 높이가 갈리므로(#4333) 정의는 하나다.
2469pub(crate) fn line_owning_tac_object_height_px(
2470    para: &crate::model::paragraph::Paragraph,
2471    raw_line_height: f64,
2472    dpi: f64,
2473) -> Option<f64> {
2474    para.controls
2475        .iter()
2476        .filter_map(|ctrl| tac_object_flow_height_px(ctrl, dpi))
2477        .find(|height| {
2478            *height > 8.0 && raw_line_height + 4.0 >= *height && raw_line_height <= *height + 8.0
2479        })
2480}
2481
2482fn para_text_is_picture_only_host(para: &crate::model::paragraph::Paragraph) -> bool {
2483    para.text.chars().all(|ch| {
2484        ch.is_whitespace()
2485            || ch == '\u{FFFC}'
2486            || ch <= '\u{001F}'
2487            || ('\u{E000}'..='\u{F8FF}').contains(&ch)
2488    })
2489}
2490
2491/// 원본의 다음 줄 원점이 닫는 안내 줄 슬롯. 문단 전체 그림 높이를
2492/// 앞 안내 줄의 소유로 취급하지 않는다. 같은 text_start의 그림 줄과
2493/// 재조판 줄은 이 계약으로 축소하지 않는다.
2494pub(crate) fn stored_picture_guide_line_height_px(
2495    para: &crate::model::paragraph::Paragraph,
2496    composed: &composer::ComposedParagraph,
2497    line_index: usize,
2498    dpi: f64,
2499) -> Option<f64> {
2500    use crate::model::{control::Control, paragraph::LineSeg};
2501
2502    if para.stored_text_partition_is_dirty()
2503        || para.cell_format_vpos_dirty
2504        || composed.lines.len() != para.line_segs.len()
2505    {
2506        return None;
2507    }
2508    let line = para.line_segs.get(line_index)?;
2509    let next = para.line_segs.get(line_index + 1)?;
2510    if (line.tag | next.tag) & LineSeg::TAG_IMPLEMENTATION_PROPERTY != 0
2511        || line.vertical_pos < 0
2512        || line.text_height <= 0
2513        || line.text_height >= line.line_height
2514        || line.line_spacing < 0
2515        || next.text_start <= line.text_start
2516        || line
2517            .vertical_pos
2518            .checked_add(line.text_height)?
2519            .checked_add(line.line_spacing)?
2520            != next.vertical_pos
2521    {
2522        return None;
2523    }
2524    let mut next_picture_owns_height = false;
2525    for (index, control) in para.controls.iter().enumerate() {
2526        let owner = layout::control_line_seg_index(para, index);
2527        let inline = match control {
2528            Control::Picture(picture) => picture.common.treat_as_char,
2529            Control::Shape(shape) => shape.common().treat_as_char,
2530            Control::Table(table) => table.common.treat_as_char,
2531            _ => false,
2532        };
2533        if inline && owner == Some(line_index) {
2534            return None;
2535        }
2536        if let Control::Picture(picture) = control {
2537            next_picture_owns_height |= picture.common.treat_as_char
2538                && owner == Some(line_index + 1)
2539                && i64::from(picture.common.height) == i64::from(line.line_height)
2540                && next.line_height == line.line_height;
2541        }
2542    }
2543    next_picture_owns_height.then(|| hwpunit_to_px(line.text_height, dpi))
2544}
2545
2546/// 쪽 분할 칸의 그림-only 문단에서, 합성 줄이 담은 TAC 그림의 흐름 높이.
2547///
2548/// 저장 LINE_SEG 가 글줄만 담아도 그 줄의 TAC 그림은 자기 높이만큼 칸 조각
2549/// 회계에 들어가야 한다 (#6114: 312px 차트가 26px 만 전진해 아래 표가 겹침).
2550/// 본문과 섞인 줄에는 쓰지 않는다 — 일반 칸 글줄까지 그림 높이로 키우면
2551/// 칸 상자 밖으로 글이 밀려 text-overlap 이 는다.
2552pub(crate) fn composed_line_tac_object_height_px(
2553    para: &crate::model::paragraph::Paragraph,
2554    composed: &composer::ComposedParagraph,
2555    line_idx: usize,
2556    dpi: f64,
2557) -> Option<f64> {
2558    if !para_text_is_picture_only_host(para) {
2559        return None;
2560    }
2561    let line = composed.lines.get(line_idx)?;
2562    let start = line.char_start;
2563    let end = composed
2564        .lines
2565        .get(line_idx + 1)
2566        .map(|next| next.char_start)
2567        .unwrap_or_else(|| para.text.chars().count().saturating_add(1))
2568        .max(start.saturating_add(1));
2569
2570    let mut max_h = 0.0f64;
2571    for &(pos, _, ci) in &composed.tac_controls {
2572        if pos < start || pos >= end {
2573            continue;
2574        }
2575        if let Some(height) = para
2576            .controls
2577            .get(ci)
2578            .and_then(|ctrl| tac_object_flow_height_px(ctrl, dpi))
2579        {
2580            max_h = max_h.max(height);
2581        }
2582    }
2583
2584    if max_h <= 0.5 && para_text_is_picture_only_host(para) {
2585        let heights: Vec<f64> = para
2586            .controls
2587            .iter()
2588            .filter_map(|ctrl| tac_object_flow_height_px(ctrl, dpi))
2589            .filter(|height| *height > 0.5)
2590            .collect();
2591        if heights.len() == 1 && line_idx == 0 {
2592            max_h = heights[0];
2593        } else if heights.len() > 1
2594            && line_idx < heights.len()
2595            && composed.lines.len() == heights.len()
2596        {
2597            max_h = heights[line_idx];
2598        } else if line_idx == 0 && composed.lines.len() <= 1 {
2599            max_h = heights.into_iter().fold(0.0, f64::max);
2600        }
2601    }
2602
2603    (max_h > 0.5).then_some(max_h)
2604}
2605
2606/// 셀의 저장 vpos 흐름이 문단 위치를 구분해 담고 있는지 ("사다리" 온전성).
2607///
2608/// 셀 안 문단이 전부 `vpos == 0` 으로 저장된 문서(중첩 표 안쪽 셀에서 흔하다)에서는
2609/// 저장 흐름이 문단 위치를 구분하지 못한다. 이 경우 다음 세 가지가 모두 성립하지
2610/// 않으므로 저장 지오메트리를 신뢰해선 안 된다.
2611///
2612/// - 문단별 절대 배치 — 전 문단이 셀 상단 한 y 로 리셋된다
2613/// - `max(vpos + lh)` 기반 셀 높이 — 1문단분으로 붕괴한다
2614/// - `para_top + 중첩표 높이` 의 max 합성 — 텍스트와 중첩 표가 서로를 가린다
2615#[inline]
2616pub(crate) fn cell_vpos_ladder_is_intact(
2617    paragraphs: &[crate::model::paragraph::Paragraph],
2618) -> bool {
2619    paragraphs.iter().enumerate().all(|(idx, para)| {
2620        // 0 위치 자체는 유효하다. 텍스트가 전진하는 연속 줄의 위치가 모두 0이고
2621        // 같은 줄의 가로 조각이나 page/column 전환이 아닐 때만 앵커 부재로 본다.
2622        // 같은 text_start의 중복과 양수 위치에서 0으로 돌아오는 저장 리셋은 보존한다.
2623        first_seg_vpos_is_anchor(para, idx)
2624            && !para.line_segs.windows(2).enumerate().any(|(i, pair)| {
2625                let (prev, seg) = (&pair[0], &pair[1]);
2626                prev.vertical_pos == 0
2627                    && seg.vertical_pos == 0
2628                    && seg.text_start > prev.text_start
2629                    && !seg.is_first_line_of_page()
2630                    && !seg.is_first_line_of_column()
2631                    && !height_measurer::stored_seg_is_row_fragment(para, i + 1)
2632            })
2633    })
2634}
2635
2636/// [#6923] 이 칸의 저장 사다리가 **줄 상자를 계통적으로 겹쳐** 적었는가.
2637///
2638/// 줄 전진(`다음 vpos − 이 vpos`)이 줄 높이보다 작은 걸음이 셋 이상이면 그 사다리의
2639/// 서명이다(한두 건은 우연). `line_spacing` 이 음수인 옛 문서에서 나온다 —
2640/// `148738070` 1쪽 감싼 칸: `p2 vpos 9800 lh 1400 ls −560 → p3 vpos 10640`.
2641pub(crate) fn cell_uses_overlapping_line_boxes(
2642    paragraphs: &[crate::model::paragraph::Paragraph],
2643) -> bool {
2644    let segs: Vec<&crate::model::paragraph::LineSeg> = paragraphs
2645        .iter()
2646        .flat_map(|para| para.line_segs.iter())
2647        .filter(|seg| seg.tag & crate::model::paragraph::LineSeg::TAG_IMPLEMENTATION_PROPERTY == 0)
2648        .collect();
2649    segs.windows(2)
2650        .filter(|w| {
2651            let prev_end = w[0].vertical_pos.saturating_add(w[0].line_height);
2652            w[1].vertical_pos >= w[0].vertical_pos && w[1].vertical_pos < prev_end
2653        })
2654        .count()
2655        >= 3
2656}
2657
2658/// [#6923] 겹침 걸음 사다리에서 **빈 줄 문단이 실제로 점유하는 전진(HWPUNIT)**.
2659///
2660/// 저장 사다리가 이 줄의 점유를 직접 말한다 — 다음 문단의 저장 `vpos` 까지의 거리다.
2661/// 겹침 사다리에서는 줄 높이(`lh`)가 점유가 아니다. 접어서 0 으로 두면 뒤따르는 내용이
2662/// 그만큼 위로 올라가고(`148738070` 1쪽 중첩 표 −15.9px), 반대로 `lh` 를 쓰면 아래로
2663/// 내려간다. 측정(`cell_units`)과 배치(`layout_horizontal_cell_paragraphs`)가 이 한
2664/// 결과를 함께 소비한다.
2665///
2666/// 전진이 줄 높이를 넘으면 겹침 걸음이 아니라 평범한 줄이므로 기존 보존 경로가 판정한다.
2667/// 되감김(전진 ≤ 0)도 이 규칙의 대상이 아니다.
2668///
2669/// [#8981] 저장 차이는 이 줄의 위끝에서 다음 문단 줄의 위끝까지이므로 이 문단의 뒤 간격과
2670/// 다음 문단의 앞 간격 띠를 함께 담는다. 두 소비자는 다음 문단에서 앞 간격을 다시 더하고,
2671/// 이 문단의 앞 간격을 적용하기 전 커서에 결과를 더한다. 그래서 돌려주는 값(px)은
2672/// `stored_empty_successor_geometry` 와 같이 `현재 앞 간격 + 저장 차이 − 다음 앞 간격` 이다
2673/// (평가결과서 칸: 6456 → 7536HU 에 다음 앞 간격 300HU 포함).
2674pub(crate) fn stored_overlap_spacer_advance(
2675    paragraphs: &[crate::model::paragraph::Paragraph],
2676    para_idx: usize,
2677    styles: &crate::renderer::style_resolver::ResolvedStyleSet,
2678    dpi: f64,
2679) -> Option<f64> {
2680    let synthetic = |seg: &crate::model::paragraph::LineSeg| {
2681        seg.tag & crate::model::paragraph::LineSeg::TAG_IMPLEMENTATION_PROPERTY != 0
2682    };
2683    let para = paragraphs.get(para_idx)?;
2684    if !para.text.trim().is_empty() || !para.controls.is_empty() {
2685        return None;
2686    }
2687    let seg = match para.line_segs.as_slice() {
2688        [seg] if !synthetic(seg) && seg.line_height > 0 => seg,
2689        _ => return None,
2690    };
2691    let next_para = paragraphs.get(para_idx + 1)?;
2692    let next = next_para.line_segs.first()?;
2693    if synthetic(next) {
2694        return None;
2695    }
2696    let forward = i64::from(next.vertical_pos) - i64::from(seg.vertical_pos);
2697    if forward <= 0 || forward > i64::from(seg.line_height) {
2698        return None;
2699    }
2700    let spacing_before = |p: &crate::model::paragraph::Paragraph| {
2701        styles
2702            .para_styles
2703            .get(p.para_shape_id as usize)
2704            .map_or(0.0, |style| style.spacing_before)
2705    };
2706    let current_before = cell_paragraph_spacing_before(para, para_idx, spacing_before(para));
2707    let advance = current_before + hwpunit_to_px(forward as i32, dpi) - spacing_before(next_para);
2708    (advance >= 0.0).then_some(advance)
2709}
2710
2711/// [#2287] 저장 LINE_SEG 없는 빈 anchor 문단의 TAC(글자처럼) 그림/도형 플로우
2712/// 줄 메트릭 합성. 컨트롤 폭을 가용 폭에 greedy wrap 하여 줄별
2713/// (최대 높이, leading) 을 돌려준다.
2714///
2715/// 한글은 글자처럼 개체를 줄박스로 취급해 그림 높이만큼 본문 흐름을 전진시키나,
2716/// rhwp 는 composed lines 가 비면(빈 텍스트 + 컨트롤) 문단 높이가 0 으로 붕괴해
2717/// 차트/스캔 그림 수십 장이 한 쪽에 응축된다 (미래부 정서분석 88 vs 한글 129쪽,
2718/// 농촌 S-OJT 꼬리 26쪽 응축 — 10k 서베이 r14 대형 음수 델타 지배 성분).
2719/// 호출부는 pairs 가 빈 경우(합성 폴백 실패 후)에만 사용한다.
2720///
2721/// [#7079] 두 번째 값(leading)은 **개체 높이가 아니라 호스트 문단의 글자모양·줄간격**에서
2722/// 나온다 — `tac_object_stack_line_leading_px` 를 본다. 문단 전진은 `높이 + leading` 이며,
2723/// 개체 잉크 위치는 유지하고 leading 을 줄 **뒤** 간격으로 소비한다. 렌더·측정·조판은
2724/// 같은 높이와 간격의 합으로 다음 줄을 전진시킨다.
2725pub(crate) fn tac_object_stack_line_metrics(
2726    para: &crate::model::paragraph::Paragraph,
2727    dpi: f64,
2728    available_width_px: Option<f64>,
2729    styles: &crate::renderer::style_resolver::ResolvedStyleSet,
2730    para_style: Option<&crate::renderer::style_resolver::ResolvedParaStyle>,
2731) -> Option<Vec<(f64, f64)>> {
2732    match tac_object_stack_line_metrics_with_storage(
2733        para,
2734        dpi,
2735        available_width_px,
2736        styles,
2737        para_style,
2738        &crate::storage::Unbounded,
2739    ) {
2740        Ok(value) => value,
2741        Err(never) => match never {},
2742    }
2743}
2744
2745pub(crate) fn tac_object_stack_line_metrics_with_storage<S: crate::storage::Storage>(
2746    para: &crate::model::paragraph::Paragraph,
2747    dpi: f64,
2748    available_width_px: Option<f64>,
2749    styles: &crate::renderer::style_resolver::ResolvedStyleSet,
2750    para_style: Option<&crate::renderer::style_resolver::ResolvedParaStyle>,
2751    storage: &S,
2752) -> Result<Option<Vec<(f64, f64)>>, S::Error> {
2753    use crate::model::control::Control;
2754    if !para_has_no_stored_line_segs(para) {
2755        return Ok(None);
2756    }
2757    let objs: Vec<(f64, f64)> = storage.collect(para.controls.iter().filter_map(|c| {
2758        let common = match c {
2759            Control::Picture(pic) if pic.common.treat_as_char => &pic.common,
2760            Control::Shape(s) if s.common().treat_as_char => s.common(),
2761            _ => return None,
2762        };
2763        let w = hwpunit_to_px(common.width as i32, dpi);
2764        let h = hwpunit_to_px(common.height as i32, dpi);
2765        (h > 0.5).then_some((w, h))
2766    }))?;
2767    if objs.is_empty() {
2768        return Ok(None);
2769    }
2770    let leading = tac_object_stack_line_leading_px(para, styles, para_style);
2771    let avail = available_width_px.unwrap_or(f64::INFINITY).max(1.0);
2772    let mut lines: Vec<(f64, f64)> = Vec::new();
2773    let mut line_w = 0.0f64;
2774    let mut line_h = 0.0f64;
2775    for (w, h) in objs {
2776        if line_w > 0.0 && line_w + w > avail + 0.5 {
2777            storage.push(&mut lines, (line_h, leading))?;
2778            line_w = 0.0;
2779            line_h = 0.0;
2780        }
2781        line_w += w;
2782        line_h = line_h.max(h);
2783    }
2784    if line_h > 0.0 {
2785        storage.push(&mut lines, (line_h, leading))?;
2786    }
2787    Ok((!lines.is_empty()).then_some(lines))
2788}
2789
2790/// 저장 줄이 없는 문단의 텍스트가 줄을 따로 만들지 않는지 — 비었거나, 줄 머리의 글자처럼
2791/// 취급 표 하나 **뒤의 공백뿐**이다.
2792///
2793/// 한/글은 말미 공백에 줄상자를 주지 않는다(#7500·#7160 `absorb_whitespace_only_rows`).
2794/// 표가 줄 머리에서 줄을 소유하고 그 뒤 공백은 표 줄 끝에 걸리므로, 텍스트가 빈 문단과
2795/// 같은 표 줄 하나만 남는다. 공백 줄을 따로 두면 표 아래에 em 줄 하나가 더 생겨 뒤 내용을
2796/// 그만큼 밀어낸다(`samples/issue8574`: 한/글 저장본은 표 줄 하나만
2797/// 저장하고, 줄을 지운 파일도 한/글 2020·2024 Print 가 같은 자리에 뒤 문단을 둔다).
2798/// 표 앞에 공백이 있거나, 가시 글자나 다른 글자처럼 취급 개체가 있으면 줄 구성이 달라지므로
2799/// 대상이 아니다 — 그 줄들은 줄 나눔이 정한다.
2800pub(crate) fn tac_table_host_text_is_line_tail(para: &crate::model::paragraph::Paragraph) -> bool {
2801    use crate::model::control::Control;
2802    if para.text.is_empty() {
2803        return true;
2804    }
2805    if !para
2806        .text
2807        .chars()
2808        .all(|c| matches!(c, ' ' | '\t' | '\u{3000}'))
2809    {
2810        return false;
2811    }
2812    let mut inline_objects = para
2813        .controls
2814        .iter()
2815        .zip(para.control_text_positions())
2816        .filter(|(control, _)| match control {
2817            Control::Table(t) => t.common.treat_as_char,
2818            Control::Picture(p) => p.common.treat_as_char,
2819            Control::Shape(s) => s.common().treat_as_char,
2820            Control::Equation(_) | Control::Form(_) => true,
2821            _ => false,
2822        });
2823    matches!(
2824        (inline_objects.next(), inline_objects.next()),
2825        (Some((Control::Table(_), 0)), None)
2826    )
2827}
2828
2829/// [#7418] 저장 줄 없는 문단의 글자처럼 취급 **표** 줄 — `(표 높이, 줄 뒤 leading)`.
2830///
2831/// 조성기는 글자 없이 표 하나만 든 문단에 줄을 만들지 않는다. 표 높이는 표 배치
2832/// (`place_table_with_text` 의 `table_total_height`, 바깥 여백 포함)가 따로 계상하지만, 그 줄의
2833/// **줄간격**은 문단 형식 높이에만 실리므로 줄이 없으면 통째로 빠졌다. 한/글 2024 합성 문서
2834/// (`samples/issue7418/tac_host_line_synthetic`, 글자 10·17pt × 줄간격 100·160·200% × 표 높이
2835/// 1716·3014)의 저장 줄은 12조합 모두 `vertsize = 표 높이 + 바깥 여백`,
2836/// `spacing = 글자 크기 × (줄간격 − 100%)` 이다 — 그림·도형 줄(`#7079`)과 같은 leading 이다.
2837/// 높이는 바깥 여백을 뺀 표 높이다(여백은 `tac_outer_margin_v_px` 가 예산에 더한다).
2838pub(crate) fn tac_table_host_line_metrics(
2839    para: &crate::model::paragraph::Paragraph,
2840    dpi: f64,
2841    styles: &crate::renderer::style_resolver::ResolvedStyleSet,
2842    para_style: Option<&crate::renderer::style_resolver::ResolvedParaStyle>,
2843) -> Option<(f64, f64)> {
2844    use crate::model::control::Control;
2845    if !para_has_no_stored_line_segs(para) || !tac_table_host_text_is_line_tail(para) {
2846        return None;
2847    }
2848    let height = para
2849        .controls
2850        .iter()
2851        .filter_map(|c| match c {
2852            Control::Table(t) if t.common.treat_as_char => {
2853                Some(hwpunit_to_px(t.common.height as i32, dpi))
2854            }
2855            _ => None,
2856        })
2857        .fold(None, |acc: Option<f64>, h| {
2858            Some(acc.map_or(h, |a| a.max(h)))
2859        })?;
2860    Some((
2861        height,
2862        tac_object_stack_line_leading_px(para, styles, para_style),
2863    ))
2864}
2865
2866/// [#7079] 합성 TAC 줄의 leading — 호스트 문단의 글자 크기와 문단 줄간격에서 나온다.
2867///
2868/// 저장 사다리 둘이 그 값을 못박는다. 156060125 2쪽은 `p[11] vpos=30525 lh=600 ls=0`
2869/// 다음 `p[13] vpos=61874` 라 그림 문단이 30749HU 를 차지하는데 그림은 29997HU 다 —
2870/// 남는 752HU 는 글자 20.0px · 150% 의 `20.0 * 0.5 = 10.0px(750HU)` 다. 156596828
2871/// 1쪽은 남는 값이 720HU 이고 글자 16.0px · 160% → `16.0 * 0.6 = 9.6px(720HU)` 로
2872/// 정확히 같다. 개체 높이는 29997 vs 2023 으로 14배 다른데 이 몫은 글자에서만 나온다.
2873///
2874/// 그 몫의 위치는 같은 96dpi 래스터에서 비교한다. 156060125 2쪽 한컴 engine 2020
2875/// 출력은 앞 본문줄→도해 잉크 84px, 도해→뒤 상자 360px 이다. leading 을 개체 뒤에
2876/// 두면 86px/360px, 앞에 두면 96px/350px 이므로 개체 잉크는 그대로 두고 뒤 간격에
2877/// 반영한다. 서로 다른 glyph bbox·TextLine 좌표를 섞은 초기 실측은 사용하지 않는다.
2878///
2879/// 빈 문단 폴백(`empty_no_lineseg_paragraph_metrics`)과 같은 `corrected_line_metrics`
2880/// 계약을 쓰되 줄 높이는 개체가 정하므로 간격 몫만 취한다. 글자모양·문단모양을 못 찾거나
2881/// Percent 가 아닌 종류(그 계약에서 간격이 0 이거나 줄 높이에 흡수된다)는 0 이다.
2882pub(crate) fn tac_object_stack_line_leading_px(
2883    para: &crate::model::paragraph::Paragraph,
2884    styles: &crate::renderer::style_resolver::ResolvedStyleSet,
2885    para_style: Option<&crate::renderer::style_resolver::ResolvedParaStyle>,
2886) -> f64 {
2887    // 합성 tag(`0x8000_0000`) seg 라도 **저장된 seg 가 있으면** 그 줄의 높이·baseline 이
2888    // 개체 배치의 근거다 — 거기에 leading 을 얹으면 baseline 정렬 위로 개체가 밀린다
2889    // (#6708 tac-img-02: 글자 264px → 158px 이동). leading 은 seg 가 아예 없어 줄을
2890    // 통째로 합성한 문단에서만 나온다. `#2287` 의 높이 합성 범위는 그대로 둔다.
2891    if !para.line_segs.is_empty() {
2892        return 0.0;
2893    }
2894    let Some(char_shape_id) = para
2895        .char_shape_id_at(0)
2896        .or_else(|| para.char_shapes.first().map(|shape| shape.char_shape_id))
2897    else {
2898        return 0.0;
2899    };
2900    let Some(char_style) = styles.char_styles.get(char_shape_id as usize) else {
2901        return 0.0;
2902    };
2903    let font_size = char_style.font_size;
2904    if font_size <= 0.0 {
2905        return 0.0;
2906    }
2907    let Some(style) = para_style else {
2908        return 0.0;
2909    };
2910    corrected_line_metrics(
2911        0.0,
2912        0.0,
2913        font_size,
2914        style.line_spacing_type,
2915        style.line_spacing,
2916    )
2917    .1
2918}
2919
2920/// HWPUNIT을 픽셀로 변환
2921#[inline]
2922pub fn hwpunit_to_px(hwpunit: i32, dpi: f64) -> f64 {
2923    hwpunit as f64 * dpi / HWPUNIT_PER_INCH
2924}
2925
2926/// 해당 문단까지 명시한 마지막 단 종류를 읽는다. 정의가 없거나 주소가 잘못되면 추정하지 않는다.
2927pub(crate) fn declared_column_type_at(
2928    paragraphs: &[crate::model::paragraph::Paragraph],
2929    index: usize,
2930) -> Option<crate::model::page::ColumnType> {
2931    paragraphs.get(..=index)?.iter().rev().find_map(|para| {
2932        para.controls.iter().find_map(|control| match control {
2933            crate::model::control::Control::ColumnDef(definition) => Some(definition.column_type),
2934            _ => None,
2935        })
2936    })
2937}
2938
2939/// 개체와 문단 묶음 제약이 없는 일반 단 사이에서만 실제 첫 줄 높이로 수용한다.
2940pub(crate) fn plain_text_column_zone(
2941    paragraphs: &[crate::model::paragraph::Paragraph],
2942    start: usize,
2943    closing_column_type: Option<crate::model::page::ColumnType>,
2944    styles: &style_resolver::ResolvedStyleSet,
2945) -> bool {
2946    // 닫히는 배분·평행 밴드도 기존 여유를 예약해야 다음 소제목이 실제 배치에서 넘치지 않는다.
2947    if closing_column_type != Some(crate::model::page::ColumnType::Normal)
2948        || declared_column_type_at(paragraphs, start)
2949            != Some(crate::model::page::ColumnType::Normal)
2950    {
2951        return false;
2952    }
2953    paragraphs[start..]
2954        .iter()
2955        .enumerate()
2956        .take_while(|(offset, para)| {
2957            *offset == 0
2958                || (para.column_type != crate::model::paragraph::ColumnBreakType::MultiColumn
2959                    && !para
2960                        .controls
2961                        .iter()
2962                        .any(|ctrl| matches!(ctrl, crate::model::control::Control::ColumnDef(_))))
2963        })
2964        .all(|(_, para)| {
2965            para.controls.iter().all(|ctrl| {
2966                matches!(
2967                    ctrl,
2968                    crate::model::control::Control::ColumnDef(_)
2969                        | crate::model::control::Control::SectionDef(_)
2970                )
2971            }) && styles
2972                .para_styles
2973                .get(para.para_shape_id as usize)
2974                .is_some_and(|style| {
2975                    !style.keep_with_next && !style.keep_lines && !style.widow_orphan
2976                })
2977        })
2978}
2979
2980/// 같은 쪽의 단일 단 뒤에는 구역에 저장된 단 사이 간격을 쓴다.
2981/// 구역 정보 없는 직접 호출과 다단 뒤의 전환은 기존 간격 계약을 유지한다.
2982pub(crate) fn solo_zone_pad_px(
2983    entering_solo: bool,
2984    prior_multicol: bool,
2985    section_spacing_hu: Option<i32>,
2986    dpi: f64,
2987) -> f64 {
2988    let spacing = section_spacing_hu
2989        .filter(|spacing| !prior_multicol && *spacing >= 0)
2990        .unwrap_or(if entering_solo && prior_multicol {
2991            1500
2992        } else {
2993            1200
2994        });
2995    hwpunit_to_px(spacing, dpi)
2996}
2997
2998/// 명시 단나누기가 다단에서 다음 다단 밴드를 시작할 때 저장 한 줄 간격.
2999pub(crate) fn multicol_band_break_pad_px(dpi: f64) -> f64 {
3000    hwpunit_to_px(1500, dpi)
3001}
3002
3003/// 큰 디자인 간격의 한 줄 표 헤더 앞뒤에 나누어 예약할 직전 제목의 줄간격.
3004pub(crate) fn solo_header_gap_half_px(
3005    title: &crate::model::paragraph::Paragraph,
3006    header: &crate::model::paragraph::Paragraph,
3007    dpi: f64,
3008) -> Option<f64> {
3009    use crate::model::control::Control;
3010    if title.line_segs.len() != 1
3011        || title.text.trim().is_empty()
3012        || header.line_segs.len() != 1
3013        || !title.controls.iter().any(|control| {
3014            matches!(control, Control::ColumnDef(cd) if cd.column_count.max(1) <= 1 && cd.spacing <= 283)
3015        })
3016        || title.controls.iter().any(|control| matches!(control, Control::Table(_)))
3017        || !header.controls.iter().any(|control| {
3018            matches!(control, Control::ColumnDef(cd) if cd.column_count.max(1) <= 1 && cd.spacing > 283)
3019        })
3020        || !header.controls.iter().any(|control| {
3021            matches!(control, Control::Table(table) if table.common.treat_as_char
3022                && matches!(table.common.text_wrap, crate::model::shape::TextWrap::TopAndBottom))
3023        })
3024    {
3025        return None;
3026    }
3027    let spacing = title.line_segs.first()?.line_spacing;
3028    (spacing > 0).then(|| hwpunit_to_px(spacing, dpi) / 2.0)
3029}
3030
3031/// 저장 한 줄 소제목에서 다단 본문으로 넘어갈 때 본문 두 줄 진행을 확보한다.
3032/// 제목에서 이미 소비한 줄 상자와 별도로 더할 디자인 간격은 예약에서 제외한다.
3033pub(crate) fn solo_title_exit_pad_px(
3034    title: &crate::model::paragraph::Paragraph,
3035    body: &crate::model::paragraph::Paragraph,
3036    title_design_px: f64,
3037    body_design_px: f64,
3038    dpi: f64,
3039) -> Option<f64> {
3040    use crate::model::control::Control;
3041    if title.line_segs.len() != 1
3042        || !title.text.trim_start().starts_with('<')
3043        || !title.controls.iter().any(|control| {
3044            matches!(control, Control::ColumnDef(cd) if cd.column_count.max(1) <= 1 && cd.spacing <= 283)
3045        })
3046        || !body.controls.iter().any(|control| {
3047            matches!(control, Control::ColumnDef(cd) if cd.column_count.max(1) > 1)
3048        })
3049    {
3050        return None;
3051    }
3052    let title_line = title.line_segs.first()?;
3053    let body_line = body.line_segs.first()?;
3054    let title_advance = title_line
3055        .line_height
3056        .saturating_add(title_line.line_spacing);
3057    let body_advance = body_line.line_height.saturating_add(body_line.line_spacing);
3058    if title_advance <= 0 || body_advance <= 0 {
3059        return None;
3060    }
3061    Some(
3062        (2.0 * hwpunit_to_px(body_advance, dpi)
3063            - hwpunit_to_px(title_advance, dpi)
3064            - title_design_px / 2.0
3065            - body_design_px / 2.0)
3066            .max(0.0),
3067    )
3068}
3069
3070/// 일반 텍스트 영역 끝의 줄 수와 후행 간격을 같은 확정 구성에서 읽는다.
3071/// 저장 줄이 없으면 수용과 배치가 공유하는 재조판 결과만 근거로 사용한다.
3072/// 개체·편집 중인 줄·배치용 채움 줄은 영역 간격을 줄일 근거가 아니다.
3073pub(crate) fn closing_text_zone_line_metrics(
3074    paragraph: &crate::model::paragraph::Paragraph,
3075    computed: Option<&composer::ComposedParagraph>,
3076    dpi: f64,
3077) -> Option<(usize, f64)> {
3078    if !paragraph.controls.is_empty() {
3079        return None;
3080    }
3081    if para_has_no_stored_line_segs(paragraph) {
3082        if paragraph.stored_text_partition_is_dirty()
3083            || paragraph.cell_format_vpos_dirty
3084            || paragraph.layout_only_fill_lines > 0
3085        {
3086            return None;
3087        }
3088        let computed = computed?;
3089        let last = computed.lines.last()?;
3090        (last.line_height > 0 && last.line_spacing >= 0)
3091            .then_some((computed.lines.len(), hwpunit_to_px(last.line_spacing, dpi)))
3092    } else {
3093        let last = paragraph.line_segs.last()?;
3094        Some((
3095            paragraph.line_segs.len(),
3096            hwpunit_to_px(last.line_spacing, dpi),
3097        ))
3098    }
3099}
3100
3101/// 단일 단 구간의 확정 텍스트 끝에서 다음 구간 간격과 중복되는 후행 줄간격.
3102/// 구조 제어만 가진 빈 줄도 줄 상자는 보존하며, 개체·부분 문단·재조판 줄은 제외한다.
3103pub(crate) fn solo_zone_trailing_spacing_px(
3104    items: &[pagination::PageItem],
3105    paragraphs: &[crate::model::paragraph::Paragraph],
3106    column_count: usize,
3107    dpi: f64,
3108) -> f64 {
3109    use crate::model::control::Control;
3110    if column_count != 1 {
3111        return 0.0;
3112    }
3113    let Some(pagination::PageItem::FullParagraph { para_index }) = items.last() else {
3114        return 0.0;
3115    };
3116    let Some(para) = paragraphs.get(*para_index) else {
3117        return 0.0;
3118    };
3119    if para.stored_text_partition_is_dirty()
3120        || para.layout_only_fill_lines > 0
3121        || para.controls.iter().any(|control| {
3122            matches!(
3123                control,
3124                Control::Table(_)
3125                    | Control::Shape(_)
3126                    | Control::Picture(_)
3127                    | Control::Equation(_)
3128                    | Control::Form(_)
3129                    | Control::Unknown(_)
3130            )
3131        })
3132        || (para.text.trim_start().starts_with('<')
3133            && para.controls.iter().any(|control| {
3134                matches!(control, Control::ColumnDef(cd)
3135                    if cd.column_count.max(1) <= 1 && cd.spacing <= 283)
3136            }))
3137    {
3138        return 0.0;
3139    }
3140    para.line_segs
3141        .last()
3142        .filter(|line| line.line_height > 0 && line.line_spacing > 0)
3143        .map_or(0.0, |line| hwpunit_to_px(line.line_spacing, dpi))
3144}
3145
3146/// 같은 저장 줄을 끝으로 갖는 다단에서 빈 마지막 문단의 추가 줄간격.
3147/// 글자가 있는 다른 단의 줄 상자는 유지하고, 빈 단의 뒤쪽 여백만 다음 구역에서 제외한다.
3148pub(crate) fn parallel_blank_tail_spacing_excess_px(
3149    columns: &[pagination::ColumnContent],
3150    paragraphs: &[crate::model::paragraph::Paragraph],
3151    dpi: f64,
3152) -> f64 {
3153    let Some(last_col) = columns.last() else {
3154        return 0.0;
3155    };
3156    if last_col
3157        .zone_layout
3158        .as_ref()
3159        .is_none_or(|layout| layout.column_areas.len() < 2)
3160    {
3161        return 0.0;
3162    }
3163    let mut visible = Vec::new();
3164    let mut blank = Vec::new();
3165    for col in columns
3166        .iter()
3167        .rev()
3168        .take_while(|col| (col.zone_y_offset - last_col.zone_y_offset).abs() < 0.1)
3169    {
3170        let Some(pagination::PageItem::FullParagraph { para_index }) = col.items.last() else {
3171            continue;
3172        };
3173        let Some(para) = paragraphs.get(*para_index) else {
3174            continue;
3175        };
3176        let Some(line) = para.line_segs.last() else {
3177            continue;
3178        };
3179        let key = (line.vertical_pos, line.line_height);
3180        if para.text.trim().is_empty() && para.controls.is_empty() {
3181            blank.push((key, line.line_spacing));
3182        } else if !para.text.trim().is_empty() {
3183            visible.push((key, line.line_spacing));
3184        }
3185    }
3186    let excess_hu = blank
3187        .iter()
3188        .flat_map(|(blank_key, blank_spacing)| {
3189            visible
3190                .iter()
3191                .filter(move |(visible_key, _)| visible_key == blank_key)
3192                .map(move |(_, visible_spacing)| blank_spacing - visible_spacing)
3193        })
3194        .max()
3195        .unwrap_or(0)
3196        .max(0);
3197    hwpunit_to_px(excess_hu, dpi)
3198}
3199
3200/// 한 줄 표 헤더 뒤의 예약 높이. 아래 바깥여백은 저장 줄에서 이미 소비했다.
3201pub(crate) fn single_tac_header_tail_px(table_height_hu: u32, margin_top_hu: i16, dpi: f64) -> f64 {
3202    (hwpunit_to_px(table_height_hu.min(i32::MAX as u32) as i32, dpi)
3203        + hwpunit_to_px(i32::from(margin_top_hu), dpi))
3204    .max(0.0)
3205}
3206
3207/// 저장 줄을 먼저 소비한 헤더 띠 뒤의 잔여 높이.
3208/// 표 본체와 아래 여백은 남고, 선행 줄의 마지막 줄간격 절반은 이미 소비됐다.
3209pub(crate) fn partial_tac_header_tail_px(
3210    table_height_hu: u32,
3211    margin_bottom_hu: i16,
3212    line_spacing_hu: i32,
3213    dpi: f64,
3214) -> f64 {
3215    (hwpunit_to_px(table_height_hu.min(i32::MAX as u32) as i32, dpi)
3216        + hwpunit_to_px(i32::from(margin_bottom_hu), dpi)
3217        - hwpunit_to_px(line_spacing_hu, dpi) / 2.0)
3218        .max(0.0)
3219}
3220
3221/// 픽셀을 HWPUNIT으로 변환
3222#[inline]
3223pub fn px_to_hwpunit(px: f64, dpi: f64) -> i32 {
3224    physical_units::px_to_hwpunit(px, dpi)
3225}
3226
3227/// TAC(글자처럼 취급) 표 한 칸의 유효 높이 — 저장된 line_seg 높이와 실측 표 높이 중
3228/// 큰 쪽을 쓴다.
3229///
3230/// [#4627] 같은 식(`seg_lh.max(mt_h)`)이 `typeset.rs`(레이아웃 확정)와
3231/// `pagination/engine.rs`(`RHWP_USE_PAGINATOR=1` 대안 경로)에 각각 따로 있었다 —
3232/// 표 높이가 페이지 경계를 정하므로 두 사본이 갈리면 쪽수가 움직인다. 두 소비자
3233/// 모두 이 함수를 불러 사본을 없앤다(행동 변경 없음, 순수 NFC).
3234#[inline]
3235pub fn tac_table_effective_height(seg_lh: f64, mt_h: f64) -> f64 {
3236    seg_lh.max(mt_h)
3237}
3238
3239/// [Task #1745] 텍스트 혼합 anchor 문단의 Square wrap 표 우측 wrap 띠 (cs, sw) HU 도출.
3240///
3241/// Square wrap(어울림) 표가 텍스트 문단(예: 별표 제목)에 anchor 되면 anchor 문단의
3242/// 첫 LINE_SEG 는 전폭 텍스트 줄(cs=0)이라 wrap 띠를 인코딩하지 않는다. 이때 표
3243/// geometry(가로 오프셋 + 바깥여백 좌 + 폭 + 바깥여백 우)로 띠 시작 cs 를 계산하고,
3244/// 띠 폭은 전폭 줄 너비에서 뺀 나머지로 잡는다 (한글 저장 LINE_SEG 와 정확 일치 —
3245/// samples/task1745 cs=45568=45002+283×2, sw=2620=48188−45568).
3246///
3247/// 기존 케이스(표 단독 anchor — 첫 LINE_SEG 가 이미 띠, cs>0)나 텍스트 없는 anchor,
3248/// 좌측 정렬이 아닌 표, 띠 폭이 남지 않는 표는 None (기존 경로 유지).
3249pub(crate) fn text_anchor_square_table_strip(
3250    para: &crate::model::paragraph::Paragraph,
3251) -> Option<(i32, i32)> {
3252    let first = para.line_segs.first()?;
3253    if first.column_start != 0 {
3254        return None;
3255    }
3256    let full_sw = first.segment_width;
3257    if full_sw <= 0 {
3258        return None;
3259    }
3260    let has_real_text = para.text.chars().any(|c| c > '\u{001F}' && c != '\u{FFFC}');
3261    if !has_real_text {
3262        return None;
3263    }
3264    let cm = para.controls.iter().find_map(|c| match c {
3265        crate::model::control::Control::Table(t)
3266            if !t.common.treat_as_char
3267                && matches!(t.common.text_wrap, crate::model::shape::TextWrap::Square)
3268                && matches!(t.common.horz_align, crate::model::shape::HorzAlign::Left) =>
3269        {
3270            Some(&t.common)
3271        }
3272        _ => None,
3273    })?;
3274    let strip_cs = cm.horizontal_offset as i32
3275        + cm.margin.left as i32
3276        + cm.width as i32
3277        + cm.margin.right as i32;
3278    let strip_sw = full_sw - strip_cs;
3279    (strip_cs > 0 && strip_sw > 0).then_some((strip_cs, strip_sw))
3280}
3281
3282/// 빈 호스트 문단의 우측 Square 표가 남긴 좌측 본문 띠를 복원한다.
3283///
3284/// 한글은 표를 실제 수평 오프셋에 두면서 호스트 문단에는 전폭 LINE_SEG만 저장할 수
3285/// 있다. 이 경우 다음 문단의 `cs=0, sw=horizontal_offset`가 표 왼쪽 띠를 직접
3286/// 가리킨다. 호스트에 가시 텍스트가 있으면 기존 `text_anchor_square_table_strip`이
3287/// 담당하므로, 이 함수는 빈 호스트와 우측으로 밀린 표에만 한정한다.
3288pub(crate) fn empty_host_square_table_left_strip(
3289    para: &crate::model::paragraph::Paragraph,
3290    column_width_hu: i32,
3291) -> Option<(i32, i32)> {
3292    let first = para.line_segs.first()?;
3293    if first.column_start != 0
3294        || (first.segment_width as i32 - column_width_hu).abs() >= 3000
3295        || para
3296            .text
3297            .chars()
3298            .any(|ch| ch > '\u{001F}' && ch != '\u{FFFC}' && !ch.is_whitespace())
3299    {
3300        return None;
3301    }
3302
3303    let left_width = para.controls.iter().find_map(|control| match control {
3304        crate::model::control::Control::Table(table)
3305            if !table.common.treat_as_char
3306                && matches!(
3307                    table.common.text_wrap,
3308                    crate::model::shape::TextWrap::Square
3309                )
3310                && matches!(
3311                    table.common.horz_align,
3312                    crate::model::shape::HorzAlign::Left
3313                ) =>
3314        {
3315            Some(table.common.horizontal_offset as i32)
3316        }
3317        _ => None,
3318    })?;
3319
3320    (left_width > 0 && left_width < column_width_hu).then_some((0, left_width))
3321}
3322
3323/// A full-width empty anchor does not itself describe the usable side lane.
3324/// Authenticate the successor against the object's complete outer width and
3325/// its vertical band before exposing the saved strip to composition and paint.
3326pub(crate) fn stored_empty_square_successor_strip(
3327    host: &crate::model::paragraph::Paragraph,
3328    next: Option<&crate::model::paragraph::Paragraph>,
3329    column_width_hu: i32,
3330) -> Option<(i32, i32)> {
3331    use crate::model::{
3332        control::Control,
3333        paragraph::LineSeg,
3334        shape::{HorzAlign, HorzRelTo, TextWrap, VertAlign, VertRelTo},
3335    };
3336    let [Control::Table(table)] = host.controls.as_slice() else {
3337        return None;
3338    };
3339    let [anchor] = host.line_segs.as_slice() else {
3340        return None;
3341    };
3342    let next = next?;
3343    let first = next.line_segs.first()?;
3344    if table.common.treat_as_char
3345        || table.common.text_wrap != TextWrap::Square
3346        || table.common.vert_rel_to != VertRelTo::Para
3347        || table.common.vert_align != VertAlign::Top
3348        || table.common.horz_align != HorzAlign::Left
3349        || !matches!(
3350            table.common.horz_rel_to,
3351            HorzRelTo::Para | HorzRelTo::Column
3352        )
3353        || !host.text.trim().is_empty()
3354        || !next.controls.is_empty()
3355        || host.stored_text_partition_is_dirty()
3356        || next.stored_text_partition_is_dirty()
3357        || host.cell_format_vpos_dirty
3358        || next.cell_format_vpos_dirty
3359        || anchor.tag & LineSeg::TAG_IMPLEMENTATION_PROPERTY != 0
3360        || first.tag & LineSeg::TAG_IMPLEMENTATION_PROPERTY != 0
3361        || anchor.column_start != 0
3362        || anchor.segment_width <= 0
3363        || anchor.segment_width > column_width_hu
3364        || first.segment_width <= 0
3365    {
3366        return None;
3367    }
3368    let object_right =
3369        crate::renderer::float_placement::signed_hwpunit(table.common.horizontal_offset)
3370            .checked_add(i32::try_from(table.common.width).ok()?)?
3371            .checked_add(i32::from(table.outer_margin_left))?
3372            .checked_add(i32::from(table.outer_margin_right))?;
3373    let top = anchor
3374        .vertical_pos
3375        .checked_add(crate::renderer::float_placement::signed_hwpunit(
3376            table.common.vertical_offset,
3377        ))?
3378        .checked_add(i32::from(table.outer_margin_top))?;
3379    let bottom = top
3380        .checked_add(i32::try_from(table.common.height).ok()?)?
3381        .checked_add(i32::from(table.outer_margin_bottom))?;
3382    (object_right > 0
3383        && object_right < column_width_hu
3384        && first.column_start == object_right
3385        && first.column_start.checked_add(first.segment_width) == Some(anchor.segment_width)
3386        && first.vertical_pos >= anchor.vertical_pos
3387        && first.vertical_pos < bottom
3388        && first
3389            .vertical_pos
3390            .checked_add(first.line_height)
3391            .is_some_and(|end| end > top))
3392    .then_some((first.column_start, first.segment_width))
3393}
3394
3395/// 저장 LINE_SEG 가 없는 공백 host 문단을 글자 있는 host 와 같게 다룰지.
3396///
3397/// 한/글(웹기안기)은 저장 줄이 없는 host 를 다시 조판할 때 공백만 든 host 줄도 글자 있는
3398/// host 줄과 똑같이 놓는다(공백 7칸 host 와 "X" host 의 다음 문단 위치가 같다). 글자처럼
3399/// 취급하지 않는 표·그림 하나를 가진 host 에만 적용한다. 글앞·글뒤 개체는 흐름을 차지하지
3400/// 않아 함께 있어도 된다. 흐름 개체가 둘 이상인 공백 host(표 두 개를 공동 앵커로 둔 제목
3401/// 띠 등)는 기존 공백 host 경로에 남긴다. 세로 오프셋이 음수인 자리차지 개체도 기존 경로에
3402/// 남긴다(웹기안기: 공백 host·"X" host 모두 음수 오프셋 자리차지 표를 문단 위끝에 놓는다.
3403/// 글자 host 경로는 오프셋을 그대로 써 표를 쪽 위 밖으로 보낸다).
3404pub(crate) fn is_unstored_whitespace_object_host(
3405    para: &crate::model::paragraph::Paragraph,
3406) -> bool {
3407    use crate::model::control::Control;
3408    use crate::model::shape::TextWrap;
3409    if para
3410        .line_segs
3411        .iter()
3412        .any(|seg| seg.tag & crate::model::paragraph::LineSeg::TAG_IMPLEMENTATION_PROPERTY == 0)
3413        || !para
3414            .text
3415            .chars()
3416            .any(|ch| ch > '\u{001F}' && ch != '\u{FFFC}')
3417    {
3418        return false;
3419    }
3420    let mut flow_objects = 0usize;
3421    let mut table_or_picture = false;
3422    for control in &para.controls {
3423        let (common, is_table_or_picture) = match control {
3424            Control::Table(t) => (&t.common, true),
3425            Control::Picture(p) => (&p.common, true),
3426            Control::Shape(s) => (s.common(), false),
3427            _ => continue,
3428        };
3429        if common.treat_as_char
3430            || matches!(
3431                common.text_wrap,
3432                TextWrap::InFrontOfText | TextWrap::BehindText
3433            )
3434        {
3435            continue;
3436        }
3437        if matches!(common.text_wrap, TextWrap::TopAndBottom)
3438            && crate::renderer::float_placement::signed_hwpunit(common.vertical_offset) < 0
3439        {
3440            return false;
3441        }
3442        flow_objects += 1;
3443        table_or_picture |= is_table_or_picture;
3444    }
3445    flow_objects == 1 && table_or_picture
3446}
3447
3448/// 저장 LINE_SEG 가 하나도 없고 가시 글자가 있는 문단인지. 저장 줄이 없으면 host 글자의
3449/// 띠·높이 증거가 없어 표 기하로 판단해야 한다(`no_lineseg_square_table_host_band`).
3450pub(crate) fn is_no_lineseg_visible_text_host(para: &crate::model::paragraph::Paragraph) -> bool {
3451    !para
3452        .line_segs
3453        .iter()
3454        .any(|seg| seg.tag & crate::model::paragraph::LineSeg::TAG_IMPLEMENTATION_PROPERTY == 0)
3455        && para
3456            .text
3457            .chars()
3458            .any(|ch| ch > '\u{001F}' && ch != '\u{FFFC}' && !ch.is_whitespace())
3459        || is_unstored_whitespace_object_host(para)
3460}
3461
3462/// 저장 LINE_SEG 가 없는 host 의 글자가 Square 표 **아래**로 흐르는지.
3463///
3464/// 문단·단 기준 표가 단 폭을 채워 옆 띠가 없으면 host 글자는 표 아래로 간다. 쪽·종이
3465/// 기준 표는 host 흐름 밖의 절대 위치라(#7548) host 글자는 제자리에 남고, 표 상자와
3466/// 겹치는 뒤 줄만 배제 영역으로 피한다 — 저장 host 와 같은 순서(글자 → 표)를 쓴다.
3467/// typeset(표 앞/뒤 글자 분류)과 layout(host 줄 페인트 소유자)이 같은 판정을 쓴다.
3468pub(crate) fn no_lineseg_host_text_flows_below_square_table(
3469    para: &crate::model::paragraph::Paragraph,
3470    column_width_hu: i32,
3471) -> bool {
3472    use crate::model::shape::{TextWrap, VertRelTo};
3473    is_no_lineseg_visible_text_host(para)
3474        && !para.controls.iter().any(|control| {
3475            matches!(control, crate::model::control::Control::Table(t)
3476                if !t.common.treat_as_char
3477                    && matches!(t.common.text_wrap, TextWrap::Square)
3478                    && matches!(t.common.vert_rel_to, VertRelTo::Page | VertRelTo::Paper))
3479        })
3480        && no_lineseg_square_table_host_band(para, column_width_hu).is_none()
3481}
3482
3483/// 저장 LINE_SEG 가 없는 host 문단의 Square 표 옆 글자 띠 (cs, sw) HU 도출.
3484///
3485/// 저장 줄이 있으면 첫 줄의 `column_start`/`segment_width` 가 한글이 흘린 띠를 그대로
3486/// 인코딩하지만, 저장 줄이 없는 문서(기계 생성 서식)는 그 증거가 없다. 이때 띠는 표
3487/// 자신의 기하(가로 기준·정렬·오프셋·폭·바깥여백)와 글자 흐름 방향으로 정해진다.
3488/// typeset(흐름 전진)과 layout(host 글자 페인트)이 같은 띠를 써야 두 장부가 갈리지
3489/// 않는다.
3490///
3491/// 표 하나만 앵커하고 가시 글자가 있는 host 에 한정한다. 가운데 놓여 양쪽 띠가 모두
3492/// 넓은 형상이나 쪽/용지 기준 표는 기존 경로에 남긴다(None).
3493pub(crate) fn no_lineseg_square_table_host_band(
3494    para: &crate::model::paragraph::Paragraph,
3495    column_width_hu: i32,
3496) -> Option<(i32, i32)> {
3497    use crate::model::shape::{HorzAlign, HorzRelTo, TextFlow, TextWrap};
3498    const MIN_BAND_HU: i32 = 2000;
3499
3500    if !is_no_lineseg_visible_text_host(para) || column_width_hu <= 0 {
3501        return None;
3502    }
3503
3504    let is_square_float = |common: &crate::model::shape::CommonObjAttr| {
3505        !common.treat_as_char && matches!(common.text_wrap, TextWrap::Square)
3506    };
3507    let square_float_count = para
3508        .controls
3509        .iter()
3510        .filter(|control| match control {
3511            crate::model::control::Control::Table(t) => is_square_float(&t.common),
3512            crate::model::control::Control::Picture(p) => is_square_float(&p.common),
3513            crate::model::control::Control::Shape(s) => is_square_float(s.common()),
3514            _ => false,
3515        })
3516        .count();
3517    let common = para.controls.iter().find_map(|control| match control {
3518        crate::model::control::Control::Table(t) if is_square_float(&t.common) => Some(&t.common),
3519        _ => None,
3520    })?;
3521    if square_float_count != 1 || !matches!(common.horz_rel_to, HorzRelTo::Column | HorzRelTo::Para)
3522    {
3523        return None;
3524    }
3525
3526    let width = common.width as i32;
3527    let offset = common.horizontal_offset as i32;
3528    let left = match common.horz_align {
3529        HorzAlign::Left => offset,
3530        HorzAlign::Right => column_width_hu - width - offset,
3531        _ => return None,
3532    };
3533    let obj_left = left - common.margin.left as i32;
3534    let obj_right = left + width + common.margin.right as i32;
3535    let left_gap = obj_left.clamp(0, column_width_hu);
3536    let right_gap = (column_width_hu - obj_right).clamp(0, column_width_hu);
3537    let left_band = (0, left_gap);
3538    let right_band = (obj_right.clamp(0, column_width_hu), right_gap);
3539
3540    let band = match common.text_flow {
3541        TextFlow::LeftOnly => left_band,
3542        TextFlow::RightOnly => right_band,
3543        TextFlow::LargestOnly => {
3544            if left_gap >= right_gap {
3545                left_band
3546            } else {
3547                right_band
3548            }
3549        }
3550        // 양쪽 흐름은 한쪽 띠가 글자 하나도 못 들어갈 만큼 좁을 때만 한 띠로 본다.
3551        TextFlow::BothSides => {
3552            if right_gap < MIN_BAND_HU {
3553                left_band
3554            } else if left_gap < MIN_BAND_HU {
3555                right_band
3556            } else {
3557                return None;
3558            }
3559        }
3560    };
3561    (band.1 >= MIN_BAND_HU).then_some(band)
3562}
3563
3564/// [#3314] 요청 face 의 굵기/폭 접미사를 벗긴 base family.
3565///
3566/// `"Noto Serif KR Black"` → `Some("Noto Serif KR")`, 접미사가 없으면 `None`.
3567/// 폴백 체인은 요청 face 바로 뒤에 이 base 를 끼워 넣는다 — 접미사 face 가
3568/// 미설치일 때 같은 family 의 base face 가 generic 체인(Batang 등)보다 먼저
3569/// 구제한다(1.hwpx: 한컴 NotoSerifKR vs rhwp Batang, 제목 잉크 −31%).
3570/// 요청 face 가 실존하면 체인 선두라 무영향. **렌더 경로 전용** — 측정 경로
3571/// (`text_measurement`)는 쓰지 않아 조판(쪽수)이 불변이다.
3572pub fn base_family_without_weight_suffix(font_family: &str) -> Option<String> {
3573    // 뒤에서부터 제거되는 토큰들. "Extra Bold" 처럼 두 토큰으로 쪼개진 경우를
3574    // 위해 수식 접두 토큰(extra/ultra/semi/demi)도 포함한다.
3575    const WEIGHT_TOKENS: &[&str] = &[
3576        "black",
3577        "heavy",
3578        "extrabold",
3579        "ultrabold",
3580        "semibold",
3581        "demibold",
3582        "bold",
3583        "medium",
3584        "regular",
3585        "normal",
3586        "extralight",
3587        "ultralight",
3588        "demilight",
3589        "light",
3590        "thin",
3591        "extra",
3592        "ultra",
3593        "semi",
3594        "demi",
3595    ];
3596    let mut tokens: Vec<&str> = font_family.split_whitespace().collect();
3597    let original_len = tokens.len();
3598    while tokens.len() > 1 {
3599        let last = tokens.last().expect("len > 1").to_ascii_lowercase();
3600        if WEIGHT_TOKENS.contains(&last.as_str()) {
3601            tokens.pop();
3602        } else {
3603            break;
3604        }
3605    }
3606    (tokens.len() < original_len).then(|| tokens.join(" "))
3607}
3608
3609/// 현재 설치된 글꼴로 보완 가능한 legacy face 의 대체명.
3610///
3611/// HWPX 는 `한양중고딕`이라는 legacy name을 보존하지만 실제 한양 face의 family는
3612/// `HY중고딕`(fontconfig full name: `HYGothic-Medium`)이다. 두 이름을 모두
3613/// 체인에 넣어 원 font가 설치된 호스트에서는 해당 glyph를 먼저 선택한다.
3614/// 원 font가 없는 호스트에서는 `Malgun Gothic`이 종전과 같은 마지막 대체다.
3615///
3616/// 다만 이름을 그대로 넣는 것만으로는 Windows(DirectWrite/Chrome)에서 안 잡히는
3617/// face 가 있다. 아래 중고딕 arm 의 주석을 볼 것.
3618/// 확인한 원본 글꼴의 설치 이름을 제공한다. 별도 글꼴의 호환 대체·generic·successor는 제외한다.
3619fn installed_font_program_aliases(name: &str) -> &'static [&'static str] {
3620    match name {
3621        // 같은 SFNT의 name 1/4에는 굵기가 붙지만 fontdb는 name 16의
3622        // typographic family만 노출할 수 있다. name 6으로 같은 face를
3623        // 확인하지 않으면 설치된 원본 대신 문서의 HCR 대체를 선택한다.
3624        // 서로 다른 굵기나 KoPubWorld 프로그램을 이 별칭으로 합치지 않는다.
3625        "KoPub돋움체 Light" | "KoPubDotum Light" | "KoPub Dotum Light" => &["KoPubDotumLight"],
3626        "KoPub돋움체 Medium" | "KoPubDotum Medium" | "KoPub Dotum Medium" => {
3627            &["KoPubDotumMedium"]
3628        }
3629        "KoPub돋움체 Bold" | "KoPubDotum Bold" | "KoPub Dotum Bold" => &["KoPubDotumBold"],
3630        "KoPub바탕체 Light" | "KoPubBatang Light" | "KoPub Batang Light" => {
3631            &["KoPubBatangLight"]
3632        }
3633        "KoPub바탕체 Medium" | "KoPubBatang Medium" | "KoPub Batang Medium" => {
3634            &["KoPubBatangMedium"]
3635        }
3636        "KoPub바탕체 Bold" | "KoPubBatang Bold" | "KoPub Batang Bold" => &["KoPubBatangBold"],
3637        // World는 KoPub와 별도 SFNT다. 같은 파일의 전체 이름과 name 6만
3638        // 연결하며, 다른 굵기·기존 KoPub·별도 Pro 프로그램으로 대체하지 않는다.
3639        "KoPubWorld돋움체 Light" | "KoPubWorldDotum Light" | "KoPubWorld Dotum Light" => {
3640            &["KoPubWorldDotumLight"]
3641        }
3642        "KoPubWorld돋움체 Medium" | "KoPubWorldDotum Medium" | "KoPubWorld Dotum Medium" => {
3643            &["KoPubWorldDotumMedium"]
3644        }
3645        "KoPubWorld돋움체 Bold" | "KoPubWorldDotum Bold" | "KoPubWorld Dotum Bold" => {
3646            &["KoPubWorldDotumBold"]
3647        }
3648        "KoPubWorld바탕체 Light" | "KoPubWorldBatang Light" | "KoPubWorld Batang Light" => {
3649            &["KoPubWorldBatangLight"]
3650        }
3651        "KoPubWorld바탕체 Medium" | "KoPubWorldBatang Medium" | "KoPubWorld Batang Medium" => {
3652            &["KoPubWorldBatangMedium"]
3653        }
3654        "KoPubWorld바탕체 Bold" | "KoPubWorldBatang Bold" | "KoPubWorld Batang Bold" => {
3655            &["KoPubWorldBatangBold"]
3656        }
3657        "나눔고딕" => &["NanumGothic"],
3658        "NanumGothic" => &["나눔고딕"],
3659        "한컴바탕" => &["Haansoft Batang"],
3660        "함초롬바탕" => &["HCR Batang"],
3661        "함초롬돋움" => &["HCR Dotum"],
3662        "맑은 고딕" => &["Malgun Gothic"],
3663        "바탕" => &["Batang"],
3664        "바탕체" => &["BatangChe"],
3665        "돋움" => &["Dotum"],
3666        "돋움체" => &["DotumChe"],
3667        "굴림" => &["Gulim"],
3668        "굴림체" => &["GulimChe"],
3669        "궁서" => &["Gungsuh"],
3670        "궁서체" => &["GungsuhChe"],
3671        "HY신명조" => &["HYSinMyeongJo", "HYSinMyeongJo-Medium"],
3672        // 한양중고딕의 TTF 설치본 H2GTRM은 HY중고딕/HYGothic-Medium으로 등록된다.
3673        // 원본 이름에서 이 후보를 누락하면 TTF가 있어도 HFT 변환 CFF만 선택한다.
3674        // 형식 우선순위는 호출자의 공통 TTF → TTC → OpenType 선택에 맡긴다.
3675        "한양중고딕" => &["HY중고딕", "HYGothic", "HYGothic-Medium", "HY Junggothic"],
3676        "HY중고딕" => &["HYGothic", "HYGothic-Medium"],
3677        "HY견고딕" => &["HYGothic-Extra"],
3678        "HY견명조" => &["HYMyeongJo-Extra"],
3679        "HY헤드라인M" => &["HYHeadLine", "HYHeadLine-Medium"],
3680        "HY그래픽M" => &["HYGraphic", "HYGraphic-Medium"],
3681        "휴먼명조" => &["HumanMyeongJo"],
3682        "한컴 고딕" => &["Hancom Gothic", "Hancom Gothic Regular"],
3683        "한컴 윤고딕 240" => &["Haan YGodic 240"],
3684        "한컴 윤고딕 250" => &["Haan YGodic 250"],
3685        _ => &[],
3686    }
3687}
3688
3689pub(crate) fn installed_render_font_aliases(font_family: &str) -> &'static [&'static str] {
3690    match font_family {
3691        // 같은 gulim.TTC의 face 2도 한국어/영문 family 이름이 공존한다.
3692        // 이 별칭이 빠지면 Native는 설치된 돋움 대신 맑은 고딕을 선택한다.
3693        "돋움" => &["Dotum"],
3694        "Dotum" => &["돋움"],
3695        // gulim.TTC collection face 3의 name ID 1은 같은 프로그램을
3696        // 한국어 '돋움체'와 영문 'DotumChe'로 등록한다. 영문 이름만 노출하는
3697        // Native fontdb에서도 원 face를 선언 glyph 대체보다 먼저 공급한다.
3698        "돋움체" => &["DotumChe"],
3699        "DotumChe" => &["돋움체"],
3700        "나눔고딕" => &["NanumGothic"],
3701        "NanumGothic" => &["나눔고딕"],
3702        "한컴바탕" => &["Haansoft Batang"],
3703        // 같은 SFNT의 PostScript 이름(name 6)과 실제 family 이름(name 1)이다.
3704        "HCRBatang" => &["HCR Batang"],
3705        "HCRDotum" => &["HCR Dotum"],
3706        // 공식 설치 글꼴의 한국어 이름과 영문 family 이름을 함께 조회한다.
3707        "굴림" => &["Gulim"],
3708        "굴림체" => &["GulimChe"],
3709        "바탕" => &["Batang"],
3710        "바탕체" => &["BatangChe"],
3711        // [#6171] 이름 셋 중 `HYGothic` 만 Windows 에서 해석된다. headless Chrome
3712        // 통제 실측(`'X',serif` 를 없는 글꼴 기준선과 픽셀 차분):
3713        // `HY중고딕` 0px · `HYGothic-Medium` 0px · **`HYGothic` 3,287px**.
3714        // DirectWrite 가 영문 family 끝의 스타일 접미사를 떼어 family 를 구성하기
3715        // 때문이다 — `-Medium` 은 떼어지므로 원문 이름이 남지 않고, 한국어 이름도 그
3716        // family 로 이관되지 않아 같이 실패한다. 아래 견고딕/견명조의 `-Extra` 는
3717        // 스타일 토큰이 아니라 안 떼어져 원문 그대로 잡히는 것이라 이 arm 과 다르다
3718        // (`H2GTRM`/`H2GTRE` 의 name 테이블 구조는 동일한데 결과만 갈린다).
3719        // `HYGothic` 이 실제로 `H2GTRM.TTF` 임은 Chrome 렌더 ↔ TTF 직접 렌더의 잉크
3720        // IoU 0.724 로 확인했다(대조군 `H2GTRE.TTF` 는 0.405).
3721        // 이 arm 이 없으면 3146683 1쪽 `『별표 7』`의 `『`(중고딕 run)만 Malgun 으로
3722        // 떨어져 뒤 글자와의 틈이 8.88pt 가 된다 — 한글 오라클 2.50pt, rhwp PDF 2.38pt.
3723        // (체인에서 이 이름만 뺀 통제 렌더로 잰 값. 이 arm 을 넣으면 2.25pt.)
3724        "한양중고딕" => &[
3725            "HY중고딕",
3726            "HYGothic",
3727            "HYGothic-Medium",
3728            "HCR Dotum",
3729            "함초롬돋움",
3730        ],
3731        "HY중고딕" => &[
3732            "HYGothic",
3733            "HYGothic-Medium",
3734            "HCR Dotum",
3735            "함초롬돋움",
3736            "Malgun Gothic",
3737        ],
3738        // [#6171] 견고딕/견명조도 같은 legacy ↔ 설치 face 짝이다. 이 arm 이 없으면
3739        // 체인이 `'한양견고딕'` 하나 뒤에 바로 generic(=Malgun Gothic)으로 떨어져,
3740        // `HY견고딕`이 설치된 호스트에서도 Malgun Regular 로 그려진다 — 3146683 1쪽
3741        // `『별표 7』`의 `별표` 획이 견고딕(Extra)보다 가늘어지는 원인.
3742        // Windows 글꼴 레지스트리 실측: `HY견고딕`=H2GTRE.TTF(family `HYGothic-Extra`),
3743        // `HY견명조`=H2MJRE.TTF(family `HYMyeongJo-Extra`).
3744        "한양견고딕" => &["HY견고딕", "HYGothic-Extra", "HCR Dotum", "함초롬돋움"],
3745        "한양견명조" => &["HY견명조", "HYMyeongJo-Extra", "HCR Batang", "함초롬바탕"],
3746        // 신명조도 같은 짝인데 이 arm 만 빠져 있었다. `svg.rs` 의 local()·embed 두 표는
3747        // 이미 `한양신명조 → HY신명조 / HYSinMyeongJo-Medium / H2MJSM.TTF` 를 알고 있는데,
3748        // 정작 체인을 만드는 여기가 몰라서 `'한양신명조','Batang',…` 로 바로 떨어졌다.
3749        // 156573118 8쪽 실측: 그 쪽 텍스트 런 600개가 이 체인을 쓰고, `HY신명조`가 설치된
3750        // 호스트에서도 Batang 으로 그려졌다(형제 `한양중고딕` 은 `'한양중고딕','HY중고딕',…`).
3751        // 이름 순서가 중요하다. `H2MJSM.TTF` 의 name 테이블은 family(ko) `HY신명조`,
3752        // family(en) `HYSinMyeongJo-Medium` 인데, headless Chrome 실측으로는 **둘 다
3753        // 매칭되지 않고** 스타일 접미사를 뗀 `HYSinMyeongJo` 만 잡힌다(각각 serif 로
3754        // 떨어지는 것을 통제 SVG 로 확인). 그래서 실제로 해석되는 이름을 앞에 둔다.
3755        // 형제 항목과 다른 점이라 주의 — `HY견고딕`·`HYGothic-Extra` 는 둘 다 잡힌다.
3756        "한양신명조" => &["HYSinMyeongJo", "HY신명조", "HYSinMyeongJo-Medium"],
3757        // [#6263] 같은 접미사 절단 규칙의 나머지 한컴 face 다. 문서가 한국어 이름을
3758        // 그대로 들고 있는데 Windows 는 그 이름으로 face 를 못 찾는다. 위 `한양신명조`
3759        // arm 은 legacy 이름으로 들어오는 경우고, 이 셋은 문서가 `HY…` 이름을 직접
3760        // 쓰는 경우라 별도 arm 이 필요하다(#6263 신고 7문서 실측).
3761        //
3762        // headless Chrome 통제 실측(`'X',serif` 를 없는 글꼴 기준선과 픽셀 차분):
3763        //   `HY신명조` 0px · `HYSinMyeongJo-Medium` 0px · `HYSinMyeongJo` 3,295px
3764        //   `HY헤드라인M` 0px · `HYHeadLine-Medium` 0px · `HYHeadLine` 4,785px
3765        //   `HY그래픽M` 0px · `HYGraphic-Medium` 0px · `HYGraphic` 3,687px
3766        // 셋 다 한국어 이름과 `-Medium` 원문이 모두 안 잡히고 접미사를 뗀 이름만
3767        // 잡힌다 — `한양신명조` arm 이 이미 적어 둔 규칙이 그대로 성립한다.
3768        //
3769        // name 테이블 실측 — family(ko)/family(en):
3770        //   H2MJSM.TTF `HY신명조`/`HYSinMyeongJo-Medium`
3771        //   H2HDRM.TTF `HY헤드라인M`/`HYHeadLine-Medium`
3772        //   H2GPRM.TTF `HY그래픽M`/`HYGraphic-Medium`
3773        // 해석되는 이름을 앞에 두고, 원문 en 이름은 다른 매칭 규칙을 쓰는 호스트를
3774        // 위해 뒤에 남긴다(형제 arm 과 같은 순서 규약).
3775        "HY신명조" => &[
3776            "HYSinMyeongJo",
3777            "HYSinMyeongJo-Medium",
3778            "HCR Batang",
3779            "함초롬바탕",
3780        ],
3781        "HY헤드라인M" => &[
3782            "HYHeadLine",
3783            "HYHeadLine M",
3784            "HYHeadLine-Medium",
3785            "HCR Dotum",
3786            "함초롬돋움",
3787        ],
3788        "HY그래픽M" => &["HYGraphic", "HYGraphic-Medium", "HCR Dotum", "함초롬돋움"],
3789        // [#8575] 설치본 HANYGO250.ttf 의 영문 family. Native 글꼴 목록은 이 이름만
3790        // 노출해 한국어 이름으로는 같은 face 를 찾지 못하고 대체 글꼴로 그렸다.
3791        "한컴 윤고딕 250" => &["Haan YGodic 250"],
3792        // #4739: 구형 정부상징 부처명 face가 없을 때 현재 공식 배포 face를 찾는다.
3793        // 동일 alias가 아니라 availability 기반 successor이므로 exact legacy 뒤에만 둔다.
3794        "정부상징 부처명_16040911" | "Government_16040911" => &[
3795            "ROKG",
3796            "ROKG R",
3797            "대한민국정부상징체",
3798            "대한민국정부상징체 R",
3799            "ROKGR",
3800        ],
3801        _ => &[],
3802    }
3803}
3804
3805/// Native paint와 진단이 같은 요청 사다리를 사용한다.
3806/// 저장 줄이 없는 HFT 번호는 원 face의 설치 별칭을 함께 찾는다.
3807pub(crate) fn native_font_family_for_style(style: &TextStyle) -> std::borrow::Cow<'_, str> {
3808    if !style.fixed_glyph_advances {
3809        return std::borrow::Cow::Borrowed(&style.font_family);
3810    }
3811    std::borrow::Cow::Owned(
3812        style
3813            .font_family
3814            .split(',')
3815            .flat_map(|family| {
3816                let family = family.trim();
3817                std::iter::once(family).chain(installed_render_font_aliases(family).iter().copied())
3818            })
3819            .collect::<Vec<_>>()
3820            .join(","),
3821    )
3822}
3823
3824pub(crate) fn internal_font_family_members(font_family: &str) -> Vec<&str> {
3825    font_family
3826        .split(',')
3827        .map(str::trim)
3828        .filter(|family| !family.is_empty())
3829        .collect()
3830}
3831
3832fn push_unique_family<'a>(
3833    families: &mut Vec<std::borrow::Cow<'a, str>>,
3834    family: impl Into<std::borrow::Cow<'a, str>>,
3835) {
3836    let family = family.into();
3837    if !families.iter().any(|existing| existing == &family) {
3838        families.push(family);
3839    }
3840}
3841
3842/// SVG/CSS `font-family`에서 쓸 단일 인용 family 이름.
3843///
3844/// font name 자체에 작은따옴표나 역슬래시가 들어갈 수 있으므로 단순히 `'{}'`로
3845/// 감싸면 `Tom's Handwriting` 같은 이름이 중간에서 끝나 잘못된 CSS가 된다.
3846fn css_single_quoted_font_family(font_family: &str) -> String {
3847    let escaped = font_family.replace('\\', "\\\\").replace('\'', "\\'");
3848    format!("'{escaped}'")
3849}
3850
3851/// Task #1224 ExtraLight family. regular 본문 획 두께용이며 bold 체인에서는 뺀다 (#3772).
3852pub(crate) const NOTO_SANS_KR_EXTRALIGHT: &str = "Noto Sans KR ExtraLight";
3853
3854/// 폴백 체인에서 `Noto Sans KR ExtraLight` 항목만 제거한다.
3855///
3856/// ExtraLight 는 별도 family 이름이라 `font-weight="bold"` 가 Bold/Regular 로
3857/// 넘어가지 않는다. svg2pdf 는 faux-bold 를 합성하지 않으므로 bold run 이
3858/// ExtraLight(200) 에 떨어지면 PDF 굵기가 사라진다 (#3772).
3859pub(crate) fn drop_noto_sans_kr_extralight(chain: &str) -> String {
3860    let quoted = [
3861        format!("'{NOTO_SANS_KR_EXTRALIGHT}',"),
3862        format!("&apos;{NOTO_SANS_KR_EXTRALIGHT}&apos;,"),
3863        format!("\"{NOTO_SANS_KR_EXTRALIGHT}\","),
3864        format!("'{NOTO_SANS_KR_EXTRALIGHT}'"),
3865        format!("&apos;{NOTO_SANS_KR_EXTRALIGHT}&apos;"),
3866        format!("\"{NOTO_SANS_KR_EXTRALIGHT}\""),
3867    ];
3868    let mut out = chain.to_string();
3869    for token in &quoted {
3870        out = out.replace(token, "");
3871    }
3872    if out.trim().is_empty() {
3873        "'Noto Sans KR'".to_string()
3874    } else {
3875        out
3876    }
3877}
3878
3879/// 렌더용 폴백 체인 문자열:
3880/// `요청 face → 설치 successor/alias → base family → 문서 substFont → generic 체인`.
3881pub fn render_font_family_chain(font_family: &str) -> String {
3882    render_font_family_chain_for_weight(font_family, false)
3883}
3884
3885/// `bold` 이면 ExtraLight 를 빼서 Noto Sans KR Regular/Bold 가 매칭되게 한다 (#3772).
3886pub fn render_font_family_chain_for_weight(font_family: &str, bold: bool) -> String {
3887    render_font_family_names_for_weight(font_family, bold)
3888        .into_iter()
3889        .map(|family| {
3890            if family == "serif" || family == "sans-serif" || family == "monospace" {
3891                family
3892            } else {
3893                css_single_quoted_font_family(&family)
3894            }
3895        })
3896        .collect::<Vec<_>>()
3897        .join(",")
3898}
3899
3900/// 호스트의 실제 face 준비 요청도 paint와 같은 별칭·fallback 순서를 소비한다.
3901/// CSS 인용 전 이름을 공유해 호스트의 실제 family 조회에 인용부호가 섞이지 않게 한다.
3902pub(crate) fn render_font_family_names_for_weight(font_family: &str, bold: bool) -> Vec<String> {
3903    let requested = internal_font_family_members(font_family);
3904    let Some(primary) = requested.first().copied() else {
3905        return internal_font_family_members(&generic_fallback_for_weight("", bold))
3906            .into_iter()
3907            .map(|family| family.trim_matches('\'').to_owned())
3908            .collect();
3909    };
3910    let fb = generic_fallback_for_weight(primary, bold);
3911    let mut family_names = Vec::new();
3912    push_unique_family(&mut family_names, primary);
3913    for alias in installed_render_font_aliases(primary) {
3914        push_unique_family(&mut family_names, *alias);
3915    }
3916    if let Some(base) = base_family_without_weight_suffix(primary) {
3917        push_unique_family(&mut family_names, base);
3918    }
3919    for declared_fallback in requested.into_iter().skip(1) {
3920        push_unique_family(&mut family_names, declared_fallback);
3921    }
3922    let mut families: Vec<String> = family_names
3923        .iter()
3924        .map(|family| family.to_string())
3925        .collect();
3926    families.extend(
3927        internal_font_family_members(&fb)
3928            .into_iter()
3929            .map(|family| family.trim_matches('\'').to_owned()),
3930    );
3931    families
3932}
3933
3934/// Canvas 2D 렌더용 인용 font-family 체인.
3935///
3936/// [#3314] Canvas API가 요구하는 인용 형식을 유지하면서, 굵기 접미사 face
3937/// 바로 뒤에 base family를 넣어 generic 폴백보다 먼저 선택되게 한다.
3938/// 정적 DB 조회의 family key와는 다르다. Canvas 실측은 paint와 이 체인을 공유한다.
3939pub fn canvas_font_family_chain(font_family: &str) -> String {
3940    canvas_font_family_chain_for_selection(font_family, false)
3941}
3942
3943/// 명시된 글리프 공급자는 주 face 뒤에서 미선택 OS 별칭보다 먼저 소비한다.
3944/// 일반 설치 글꼴의 별칭 조회 순서는 바꾸지 않는다.
3945pub(crate) fn canvas_font_family_chain_for_selection(
3946    font_family: &str,
3947    explicit_glyph_fallbacks: bool,
3948) -> String {
3949    let requested = internal_font_family_members(font_family);
3950    let Some(primary) = requested.first().copied() else {
3951        return "sans-serif".to_string();
3952    };
3953
3954    let fallback = generic_fallback(primary);
3955    let mut family_names = Vec::new();
3956    push_unique_family(&mut family_names, primary);
3957    if explicit_glyph_fallbacks {
3958        for declared_fallback in requested.iter().skip(1) {
3959            push_unique_family(&mut family_names, *declared_fallback);
3960        }
3961    }
3962    for alias in installed_render_font_aliases(primary) {
3963        push_unique_family(&mut family_names, *alias);
3964    }
3965    if let Some(base) = base_family_without_weight_suffix(primary) {
3966        push_unique_family(&mut family_names, base);
3967    }
3968    for declared_fallback in requested.into_iter().skip(1) {
3969        push_unique_family(&mut family_names, declared_fallback);
3970    }
3971    let mut families: Vec<String> = family_names
3972        .iter()
3973        .map(|family| format!("\"{}\"", family.replace('"', "\\\"")))
3974        .collect();
3975    families.push(fallback.to_string());
3976    families.join(", ")
3977}
3978
3979pub use font_fallback::{generic_fallback, generic_fallback_for_weight};
3980
3981pub(crate) fn contains_old_hangul_jamo(text: &str) -> bool {
3982    text.chars().any(|ch| {
3983        let code = ch as u32;
3984        matches!(
3985            code,
3986            0x1100..=0x11FF | 0xA960..=0xA97F | 0xD7B0..=0xD7FF
3987        )
3988    })
3989}
3990
3991/// 한컴 Supplementary PUA-A의 사각 안 숫자 값을 반환한다.
3992///
3993/// IR은 원문 PUA를 보존하고, 렌더러는 이 값을 사용해 backend/font와 무관한 사각형+숫자를
3994/// 합성한다.
3995pub(crate) fn boxed_pua_number(ch: char) -> Option<u32> {
3996    let code_point = ch as u32;
3997    // [#6127] U+F02B0 = 네모 안 0 — 한글 2020 실측(2599643 "②⓪⓪" 신청 번호란).
3998    (0xF02B0..=0xF02C4)
3999        .contains(&code_point)
4000        .then(|| code_point - 0xF02B0)
4001}
4002
4003/// 렌더러가 테두리와 안쪽 글자로 합성하는 한컴 PUA 기호.
4004///
4005/// 평문 흐름에서 1em 전진을 받고, paint는 `enclosed_pua_geometry`의 동봉 em 메트릭으로
4006/// 테두리와 공급된 일반 글자를 그린다. IR과 표시 문자열은 원 코드포인트를 보존한다.
4007#[derive(Clone, Copy, Debug, PartialEq, Eq)]
4008pub(crate) enum EnclosedPua {
4009    /// 사각 안 숫자 0~20 (#6127).
4010    BoxedNumber(u32),
4011    /// 서명·날인 기호 U+F012B — 타원 안 '인' (#8201).
4012    CircledSeal,
4013}
4014
4015pub(crate) fn enclosed_pua(ch: char) -> Option<EnclosedPua> {
4016    if ch == '\u{F012B}' {
4017        return Some(EnclosedPua::CircledSeal);
4018    }
4019    boxed_pua_number(ch).map(EnclosedPua::BoxedNumber)
4020}
4021
4022impl EnclosedPua {
4023    /// 테두리 안에 그리는 일반 글자.
4024    pub(crate) fn inner_text(self) -> String {
4025        match self {
4026            EnclosedPua::BoxedNumber(number) => number.to_string(),
4027            EnclosedPua::CircledSeal => enclosed_pua_geometry::circled_seal_text().to_owned(),
4028        }
4029    }
4030
4031    /// 1em 전진을 정한 근거. 글꼴 결정 진단의 `reason`으로도 노출된다.
4032    pub(crate) fn width_source(self) -> &'static str {
4033        match self {
4034            EnclosedPua::BoxedNumber(_) => "boxedPuaFullwidth",
4035            EnclosedPua::CircledSeal => "circledSealPuaFullwidth",
4036        }
4037    }
4038}
4039
4040/// 실제 `CharOverlap`에 저장된 한컴 사각 안 숫자의 렌더 의미를 반환한다 (#4158).
4041///
4042/// 이 PUA 범위는 문자 자체가 사각형 의미를 포함하므로 raw `border_type=0`이어도 사각형을
4043/// 그린다. 작성된 명시적 테두리는 보존한다. 다중 문자 겹침은 별도의 자리별 PUA 디코더가
4044/// 담당하므로 여기서는 의도적으로 제외한다.
4045pub(crate) fn boxed_pua_char_overlap_semantics(
4046    chars: &[char],
4047    raw_border_type: u8,
4048) -> Option<(u32, u8)> {
4049    let [ch] = chars else {
4050        return None;
4051    };
4052    let number = boxed_pua_number(*ch)?;
4053    let effective_border = if raw_border_type == 0 {
4054        3
4055    } else {
4056        raw_border_type
4057    };
4058    Some((number, effective_border))
4059}
4060
4061// ============================================================
4062// 자동 번호 매기기 (AutoNumber)
4063// ============================================================
4064
4065use crate::model::control::AutoNumberType;
4066
4067/// 자동 번호 카운터
4068///
4069/// 각 번호 종류별로 카운터를 유지하여 순차적인 번호를 생성한다.
4070#[derive(Debug, Clone, Default)]
4071pub struct AutoNumberCounter {
4072    /// 그림 번호
4073    pub picture: u16,
4074    /// 표 번호
4075    pub table: u16,
4076    /// 수식 번호
4077    pub equation: u16,
4078    /// 각주 번호
4079    pub footnote: u16,
4080    /// 미주 번호
4081    pub endnote: u16,
4082    /// 쪽 번호
4083    pub page: u16,
4084}
4085
4086impl AutoNumberCounter {
4087    /// 새 카운터 생성
4088    pub fn new() -> Self {
4089        Self::default()
4090    }
4091
4092    /// 번호 증가 후 현재 값 반환
4093    pub fn increment(&mut self, number_type: AutoNumberType) -> u16 {
4094        match number_type {
4095            AutoNumberType::Picture => {
4096                self.picture += 1;
4097                self.picture
4098            }
4099            AutoNumberType::Table => {
4100                self.table += 1;
4101                self.table
4102            }
4103            AutoNumberType::Equation => {
4104                self.equation += 1;
4105                self.equation
4106            }
4107            AutoNumberType::Footnote => {
4108                self.footnote += 1;
4109                self.footnote
4110            }
4111            AutoNumberType::Endnote => {
4112                self.endnote += 1;
4113                self.endnote
4114            }
4115            AutoNumberType::Page => {
4116                self.page += 1;
4117                self.page
4118            }
4119            // 총 쪽수는 카운터로 증가시키는 값이 아니라 페이지네이션이 끝난 뒤
4120            // 알려지는 문서 전체 쪽수를 그대로 표시하는 필드라 여기서 처리하지 않는다.
4121            AutoNumberType::TotalPage => 0,
4122        }
4123    }
4124
4125    /// 현재 번호 조회 (증가 없이)
4126    pub fn current(&self, number_type: AutoNumberType) -> u16 {
4127        match number_type {
4128            AutoNumberType::Picture => self.picture,
4129            AutoNumberType::Table => self.table,
4130            AutoNumberType::Equation => self.equation,
4131            AutoNumberType::Footnote => self.footnote,
4132            AutoNumberType::Endnote => self.endnote,
4133            AutoNumberType::Page => self.page,
4134            AutoNumberType::TotalPage => 0,
4135        }
4136    }
4137
4138    /// 모든 카운터 초기화
4139    pub fn reset(&mut self) {
4140        *self = Self::default();
4141    }
4142}
4143
4144/// 번호 형식. 문단 번호(표 41)와 각주·미주·쪽 번호·자동 번호(표 134)가 같은 0~16 코드를 쓴다.
4145#[derive(Debug, Clone, Copy, Default, PartialEq)]
4146pub enum NumberFormat {
4147    /// 아라비아 숫자: 1, 2, 3
4148    #[default]
4149    Digit,
4150    /// 원 문자: ①, ②, ③
4151    CircledDigit,
4152    /// 로마 숫자 대문자: I, II, III
4153    RomanUpper,
4154    /// 로마 숫자 소문자: i, ii, iii
4155    RomanLower,
4156    /// 영문 대문자: A, B, C
4157    LatinUpper,
4158    /// 영문 소문자: a, b, c
4159    LatinLower,
4160    /// 원 영문 대문자: Ⓐ, Ⓑ, Ⓒ
4161    CircledLatinUpper,
4162    /// 원 영문 소문자: ⓐ, ⓑ, ⓒ
4163    CircledLatinLower,
4164    /// 한글 가나다: 가, 나, 다
4165    HangulGaNaDa,
4166    /// 원 한글 가나다: ㉮, ㉯, ㉰
4167    CircledHangulGaNaDa,
4168    /// 한글 자모: ㄱ, ㄴ, ㄷ
4169    HangulJamo,
4170    /// 원 한글 자모: ㉠, ㉡, ㉢
4171    CircledHangulJamo,
4172    /// 한글 일이삼: 일, 이, 삼
4173    HangulNumber,
4174    /// 한자 一二三: 一, 二, 三
4175    HanjaNumber,
4176    /// 원 한자: ㊀, ㊁, ㊂
4177    CircledHanjaNumber,
4178    /// 천간 한글: 갑, 을, 병
4179    HangulGapEul,
4180    /// 천간 한자: 甲, 乙, 丙
4181    HanjaGapEul,
4182    /// 4가지 기호(*, †, ‡, §)를 차례로 쓰고, 한 바퀴 돌 때마다 하나씩 더 겹친다.
4183    FourSymbol,
4184}
4185
4186impl NumberFormat {
4187    /// HWP 번호 모양 코드(표 41·표 134)에서 변환한다. 사용자 문자(0x81)는 그 문자를 아는
4188    /// 호출하는 쪽이 따로 다루고 여기서는 숫자로 둔다.
4189    pub fn from_hwp_format(format: u8) -> Self {
4190        match format {
4191            1 => NumberFormat::CircledDigit,
4192            2 => NumberFormat::RomanUpper,
4193            3 => NumberFormat::RomanLower,
4194            4 => NumberFormat::LatinUpper,
4195            5 => NumberFormat::LatinLower,
4196            6 => NumberFormat::CircledLatinUpper,
4197            7 => NumberFormat::CircledLatinLower,
4198            8 => NumberFormat::HangulGaNaDa,
4199            9 => NumberFormat::CircledHangulGaNaDa,
4200            10 => NumberFormat::HangulJamo,
4201            11 => NumberFormat::CircledHangulJamo,
4202            12 => NumberFormat::HangulNumber,
4203            13 => NumberFormat::HanjaNumber,
4204            14 => NumberFormat::CircledHanjaNumber,
4205            15 => NumberFormat::HangulGapEul,
4206            16 => NumberFormat::HanjaGapEul,
4207            0x80 => NumberFormat::FourSymbol,
4208            _ => NumberFormat::Digit,
4209        }
4210    }
4211}
4212
4213/// 번호를 문자열로 변환한다. 글자 차례가 있는 모양은 한/글처럼 차례를 넘으면 처음으로
4214/// 돌아간다(한/글 12.30 Mac: ⑳ 다음 ①, Z 다음 A, ㅎ 다음 ㄱ, 癸 다음 甲).
4215pub fn format_number(number: u16, format: NumberFormat) -> String {
4216    match format {
4217        NumberFormat::Digit => number.to_string(),
4218        NumberFormat::CircledDigit => format_cycle(number, &CIRCLED_DIGITS),
4219        NumberFormat::RomanUpper => format_roman(number, true),
4220        NumberFormat::RomanLower => format_roman(number, false),
4221        NumberFormat::LatinUpper => format_cycle(number, &LATIN_UPPER),
4222        NumberFormat::LatinLower => format_cycle(number, &LATIN_LOWER),
4223        NumberFormat::CircledLatinUpper => format_cycle(number, &CIRCLED_LATIN_UPPER),
4224        NumberFormat::CircledLatinLower => format_cycle(number, &CIRCLED_LATIN_LOWER),
4225        NumberFormat::HangulGaNaDa => format_hangul_ganada(number),
4226        NumberFormat::CircledHangulGaNaDa => format_cycle(number, &CIRCLED_GANADA),
4227        NumberFormat::HangulJamo => format_cycle(number, &JAMO),
4228        NumberFormat::CircledHangulJamo => format_cycle(number, &CIRCLED_JAMO),
4229        NumberFormat::HangulNumber => format_hangul_number(number),
4230        NumberFormat::HanjaNumber => format_hanja_number(number),
4231        NumberFormat::CircledHanjaNumber => format_cycle(number, &CIRCLED_HANJA),
4232        NumberFormat::HangulGapEul => format_cycle(number, &GAPEUL_HANGUL),
4233        NumberFormat::HanjaGapEul => format_cycle(number, &GAPEUL_HANJA),
4234        NumberFormat::FourSymbol => match number.checked_sub(1) {
4235            // 한/글 12.30 Mac: 1 *, 2 †, 3 ‡, 4 §, 5 **, … 18 †††††.
4236            Some(index) => FOUR_SYMBOLS[usize::from(index % 4)]
4237                .to_string()
4238                .repeat(usize::from(index / 4) + 1),
4239            None => number.to_string(),
4240        },
4241    }
4242}
4243
4244const CIRCLED_DIGITS: [char; 20] = [
4245    '①', '②', '③', '④', '⑤', '⑥', '⑦', '⑧', '⑨', '⑩', '⑪', '⑫', '⑬', '⑭', '⑮', '⑯', '⑰', '⑱', '⑲',
4246    '⑳',
4247];
4248const LATIN_UPPER: [char; 26] = [
4249    'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S',
4250    'T', 'U', 'V', 'W', 'X', 'Y', 'Z',
4251];
4252const LATIN_LOWER: [char; 26] = [
4253    'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's',
4254    't', 'u', 'v', 'w', 'x', 'y', 'z',
4255];
4256const JAMO: [char; 14] = [
4257    'ㄱ', 'ㄴ', 'ㄷ', 'ㄹ', 'ㅁ', 'ㅂ', 'ㅅ', 'ㅇ', 'ㅈ', 'ㅊ', 'ㅋ', 'ㅌ', 'ㅍ', 'ㅎ',
4258];
4259const CIRCLED_JAMO: [char; 14] = [
4260    '㉠', '㉡', '㉢', '㉣', '㉤', '㉥', '㉦', '㉧', '㉨', '㉩', '㉪', '㉫', '㉬', '㉭',
4261];
4262const CIRCLED_GANADA: [char; 14] = [
4263    '㉮', '㉯', '㉰', '㉱', '㉲', '㉳', '㉴', '㉵', '㉶', '㉷', '㉸', '㉹', '㉺', '㉻',
4264];
4265const CIRCLED_HANJA: [char; 10] = ['㊀', '㊁', '㊂', '㊃', '㊄', '㊅', '㊆', '㊇', '㊈', '㊉'];
4266const GAPEUL_HANGUL: [char; 10] = ['갑', '을', '병', '정', '무', '기', '경', '신', '임', '계'];
4267const GAPEUL_HANJA: [char; 10] = ['甲', '乙', '丙', '丁', '戊', '己', '庚', '辛', '壬', '癸'];
4268const CIRCLED_LATIN_UPPER: [char; 26] = [
4269    'Ⓐ', 'Ⓑ', 'Ⓒ', 'Ⓓ', 'Ⓔ', 'Ⓕ', 'Ⓖ', 'Ⓗ', 'Ⓘ', 'Ⓙ', 'Ⓚ', 'Ⓛ', 'Ⓜ', 'Ⓝ', 'Ⓞ', 'Ⓟ', 'Ⓠ', 'Ⓡ', 'Ⓢ',
4270    'Ⓣ', 'Ⓤ', 'Ⓥ', 'Ⓦ', 'Ⓧ', 'Ⓨ', 'Ⓩ',
4271];
4272const CIRCLED_LATIN_LOWER: [char; 26] = [
4273    'ⓐ', 'ⓑ', 'ⓒ', 'ⓓ', 'ⓔ', 'ⓕ', 'ⓖ', 'ⓗ', 'ⓘ', 'ⓙ', 'ⓚ', 'ⓛ', 'ⓜ', 'ⓝ', 'ⓞ', 'ⓟ', 'ⓠ', 'ⓡ', 'ⓢ',
4274    'ⓣ', 'ⓤ', 'ⓥ', 'ⓦ', 'ⓧ', 'ⓨ', 'ⓩ',
4275];
4276const FOUR_SYMBOLS: [char; 4] = ['*', '†', '‡', '§'];
4277
4278/// 글자 차례에서 번호 자리의 글자를 고르고, 차례를 넘으면 처음으로 돌아간다. 0은 숫자로 쓴다.
4279fn format_cycle(n: u16, table: &[char]) -> String {
4280    match n.checked_sub(1) {
4281        Some(index) => table[usize::from(index) % table.len()].to_string(),
4282        None => n.to_string(),
4283    }
4284}
4285
4286/// 로마 숫자 변환
4287fn format_roman(n: u16, upper: bool) -> String {
4288    if n == 0 || n > 3999 {
4289        return n.to_string();
4290    }
4291
4292    let values = [1000, 900, 500, 400, 100, 90, 50, 40, 10, 9, 5, 4, 1];
4293    let symbols_upper = [
4294        "M", "CM", "D", "CD", "C", "XC", "L", "XL", "X", "IX", "V", "IV", "I",
4295    ];
4296    let symbols_lower = [
4297        "m", "cm", "d", "cd", "c", "xc", "l", "xl", "x", "ix", "v", "iv", "i",
4298    ];
4299
4300    let symbols = if upper {
4301        &symbols_upper
4302    } else {
4303        &symbols_lower
4304    };
4305    let mut result = String::new();
4306    let mut num = n as i32;
4307
4308    for (i, &val) in values.iter().enumerate() {
4309        while num >= val {
4310            result.push_str(symbols[i]);
4311            num -= val;
4312        }
4313    }
4314    result
4315}
4316
4317/// 한글 가나다 변환. 가~하 14자를 ㅏ·ㅓ·ㅗ·ㅜ·ㅡ·ㅣ 차례로 돌린다(한/글 12.30 Mac:
4318/// 15 거, 29 고, 43 구, 57 그, 71 기, 84 히, 85 가).
4319fn format_hangul_ganada(n: u16) -> String {
4320    // 가나다라마바사아자차카타파하의 초성 순번과 ㅏㅓㅗㅜㅡㅣ의 중성 순번
4321    const CHOSEONG: [u32; 14] = [0, 2, 3, 5, 6, 7, 9, 11, 12, 14, 15, 16, 17, 18];
4322    const JUNGSEONG: [u32; 6] = [0, 4, 8, 13, 18, 20];
4323    let Some(index) = n.checked_sub(1).map(usize::from) else {
4324        return n.to_string();
4325    };
4326    let cho = CHOSEONG[index % 14];
4327    let jung = JUNGSEONG[index / 14 % 6];
4328    char::from_u32(0xAC00 + (cho * 21 + jung) * 28)
4329        .map(String::from)
4330        .unwrap_or_else(|| n.to_string())
4331}
4332
4333/// 한글 숫자 변환 (일, 이, 삼, ...)
4334fn format_hangul_number(n: u16) -> String {
4335    const HANGUL_DIGITS: [&str; 10] = ["", "일", "이", "삼", "사", "오", "육", "칠", "팔", "구"];
4336    const HANGUL_UNITS: [&str; 4] = ["", "십", "백", "천"];
4337    const HANGUL_LARGE: [&str; 4] = ["", "만", "억", "조"];
4338
4339    if n == 0 {
4340        return "영".to_string();
4341    }
4342
4343    let mut result = String::new();
4344    let mut num = n as u32;
4345    let mut large_unit = 0;
4346
4347    while num > 0 {
4348        let group = (num % 10000) as usize;
4349        if group > 0 {
4350            let mut group_str = String::new();
4351            let mut g = group;
4352            let mut unit = 0;
4353
4354            while g > 0 {
4355                let digit = g % 10;
4356                if digit > 0 {
4357                    let digit_str = if digit == 1 && unit > 0 {
4358                        ""
4359                    } else {
4360                        HANGUL_DIGITS[digit]
4361                    };
4362                    group_str.insert_str(0, HANGUL_UNITS[unit]);
4363                    group_str.insert_str(0, digit_str);
4364                }
4365                g /= 10;
4366                unit += 1;
4367            }
4368            group_str.push_str(HANGUL_LARGE[large_unit]);
4369            result.insert_str(0, &group_str);
4370        }
4371        num /= 10000;
4372        large_unit += 1;
4373    }
4374    result
4375}
4376
4377/// 한자 숫자 변환 (一, 二, 三, ...)
4378fn format_hanja_number(n: u16) -> String {
4379    const HANJA_DIGITS: [&str; 10] = ["", "一", "二", "三", "四", "五", "六", "七", "八", "九"];
4380    const HANJA_UNITS: [&str; 4] = ["", "十", "百", "千"];
4381    const HANJA_LARGE: [&str; 4] = ["", "萬", "億", "兆"];
4382
4383    if n == 0 {
4384        return "零".to_string();
4385    }
4386
4387    let mut result = String::new();
4388    let mut num = n as u32;
4389    let mut large_unit = 0;
4390
4391    while num > 0 {
4392        let group = (num % 10000) as usize;
4393        if group > 0 {
4394            let mut group_str = String::new();
4395            let mut g = group;
4396            let mut unit = 0;
4397
4398            while g > 0 {
4399                let digit = g % 10;
4400                if digit > 0 {
4401                    let digit_str = if digit == 1 && unit > 0 {
4402                        ""
4403                    } else {
4404                        HANJA_DIGITS[digit]
4405                    };
4406                    group_str.insert_str(0, HANJA_UNITS[unit]);
4407                    group_str.insert_str(0, digit_str);
4408                }
4409                g /= 10;
4410                unit += 1;
4411            }
4412            group_str.push_str(HANJA_LARGE[large_unit]);
4413            result.insert_str(0, &group_str);
4414        }
4415        num /= 10000;
4416        large_unit += 1;
4417    }
4418    result
4419}
4420
4421/// [#7470] 빈 host 줄이 문단 기준 자리차지 개체의 **띠 안에 흡수**되는가.
4422///
4423/// 한/글은 비TAC · `vert=Para` · TopAndBottom 개체에 줄 폭 전체가 막힌 host 줄을
4424/// `segment_width = 0` 으로 저장하고, 그 줄의 높이·줄간격을 개체 띠와 별도로 전진하지 않는다
4425/// (다음 문단 저장 vpos − 현 vpos = 개체 높이). `sw > 0`(개체 옆에 줄 폭이 남음)인 빈 host 는
4426/// 종전처럼 개체 뒤에 host 한 줄을 더 전진한다(pr-149, Task #683).
4427///
4428/// ```text
4429///   156636617 pi74  그림 h=20409  host lh=1100 ls=772 sw=0      다음 vpos − 현 vpos = 20409
4430///   memo_field pi331 그림 h=20218 host lh=1200 ls=480 sw=0      다음 vpos − 현 vpos = 20218
4431///   pr-149          그림 h=15696  host lh=1000 ls=600 sw=42520  host 한 줄 추가 전진
4432/// ```
4433///
4434/// 조판과 배치가 같은 판별을 쓰도록 한 곳에 둔다. 미주 흐름은 별도 조판 경로라 배치도 본문 단에서만
4435/// 이 판별을 쓴다.
4436pub(crate) fn empty_host_line_absorbed_by_topbottom_float(
4437    para: &crate::model::paragraph::Paragraph,
4438    common: &crate::model::shape::CommonObjAttr,
4439) -> bool {
4440    use crate::model::shape::{TextWrap, VertRelTo};
4441
4442    // 띠가 host 줄 상자 안에서 시작하면 host 줄은 띠 안에 든다. 다음 문단의 저장 vpos 는
4443    // 문단 시작 + max(위 간격, 세로 오프셋) + 개체 높이다(hwpspec 구역 3 첫 쪽: 오프셋 115HU,
4444    // 0 + 115 + 4428 = 4543 · PrEP 3.214: 위 간격 500·오프셋 504HU, 45884 + 504 + 20145 =
4445    // 66533). 오프셋이 줄 상자 아래면 host 줄은 개체 위에 따로 놓인다(#6888).
4446    if common.treat_as_char
4447        || !matches!(common.text_wrap, TextWrap::TopAndBottom)
4448        || !matches!(common.vert_rel_to, VertRelTo::Para)
4449    {
4450        return false;
4451    }
4452    let has_visible_text = para.text.chars().any(|c| c > '\u{001F}' && c != '\u{FFFC}');
4453    if has_visible_text || para.line_segs.len() != 1 {
4454        return false;
4455    }
4456    let seg = &para.line_segs[0];
4457    let offset = crate::renderer::float_placement::signed_hwpunit(common.vertical_offset);
4458    seg.tag & crate::model::paragraph::LineSeg::TAG_IMPLEMENTATION_PROPERTY == 0
4459        && seg.segment_width == 0
4460        && (0..seg.line_height.max(1)).contains(&offset)
4461}
4462
4463/// 글 없는 host 의 줄 상자가 자기 문단 기준 위아래 개체의 띠 **위에** 따로 놓이는가 — 세로
4464/// 오프셋이 저장 줄 높이 이상이라 띠가 줄 상자 아래에서 시작한다(#6133 의 표 판정과 같은 경계).
4465/// 그때 다음 문단은 `max(host 줄 끝, 띠 아래끝)` 에서 시작한다: 1351000-201500141 pi613 줄
4466/// 23224·lh 1000·오프셋 1105 → 다음 저장 vpos 42040 = 23224 + 1105 + 17711(그림 띠 끝). 줄이
4467/// 띠 안에서 시작하면(오프셋 < 줄 높이) 종전대로 줄은 띠 아래로 밀리거나(#409) 띠에
4468/// 흡수된다([`empty_host_line_absorbed_by_topbottom_float`]).
4469/// 저장 줄이 띠 아래끝에 놓였으면(3780000-202000005 pi1042: 앞 줄 끝 2900 근처 + 오프셋 3409
4470/// + 그림 23700 → 줄 vpos 30849) 줄은 띠 아래에 있으므로 이 판정에서 뺀다.
4471pub(crate) fn textless_host_line_above_topbottom_float(
4472    paragraphs: &[crate::model::paragraph::Paragraph],
4473    para_index: usize,
4474    common: &crate::model::shape::CommonObjAttr,
4475) -> bool {
4476    use crate::model::shape::{TextWrap, VertRelTo};
4477
4478    let Some(para) = paragraphs.get(para_index) else {
4479        return false;
4480    };
4481    if common.treat_as_char
4482        || !matches!(common.text_wrap, TextWrap::TopAndBottom)
4483        || !matches!(common.vert_rel_to, VertRelTo::Para)
4484        || para.text.chars().any(|c| c > '\u{001F}' && c != '\u{FFFC}')
4485    {
4486        return false;
4487    }
4488    let [seg] = para.line_segs.as_slice() else {
4489        return false;
4490    };
4491    let offset = crate::renderer::float_placement::signed_hwpunit(common.vertical_offset);
4492    // 저장 줄이 띠보다 앞(문단 시작)에 있을 때만 줄이 띠 위에 따로 있다. 한/글이 줄을
4493    // 띠 아래로 내려 저장했으면(앞 흐름 끝 + 오프셋 + 띠 = 줄 vpos) 종전 경로가 맞다.
4494    let line_before_band = stored_previous_flow_end_hu(paragraphs, para_index)
4495        .is_none_or(|prev_end| seg.vertical_pos < prev_end.saturating_add(offset));
4496    seg.tag & crate::model::paragraph::LineSeg::TAG_IMPLEMENTATION_PROPERTY == 0
4497        && seg.line_height > 0
4498        && offset >= seg.line_height
4499        && line_before_band
4500}
4501
4502/// 띠에 흡수된 빈 host 줄([`empty_host_line_absorbed_by_topbottom_float`])이 흐름에서 돌려받는
4503/// 높이(px). 문단 측정은 `위 간격 + 줄 높이 + 줄간격 + 아래 간격` 을 이미 더했고, 띠는 문단
4504/// 시작에서 `max(위 간격, 세로 오프셋)` 아래에 놓이므로 위 간격을 넘는 오프셋만큼은 돌려주지
4505/// 않는다. 다음 문단은 띠 아래끝에서 시작하므로 host 의 아래 간격도 띠 안에 든다([#8795]
4506/// 1351000-201500141 pi975: 아래 간격 1000HU, 다음 저장 vpos 32185 = 오프셋 307 + 그림 31878.
4507/// 배치 `layout_shape_item` 도 그림 아래끝에서 다음 문단을 잇는다).
4508pub(crate) fn absorbed_host_line_return_px(
4509    para: &crate::model::paragraph::Paragraph,
4510    common: &crate::model::shape::CommonObjAttr,
4511    spacing_before_px: f64,
4512    spacing_after_px: f64,
4513    dpi: f64,
4514) -> f64 {
4515    if !empty_host_line_absorbed_by_topbottom_float(para, common) {
4516        return 0.0;
4517    }
4518    let Some(seg) = para.line_segs.first() else {
4519        return 0.0;
4520    };
4521    let offset = hwpunit_to_px(
4522        crate::renderer::float_placement::signed_hwpunit(common.vertical_offset),
4523        dpi,
4524    );
4525    (hwpunit_to_px(seg.line_height + seg.line_spacing, dpi) + spacing_after_px.max(0.0)
4526        - (offset - spacing_before_px.max(0.0)).max(0.0))
4527    .max(0.0)
4528}
4529
4530/// 앞 문단이 저장 사다리에서 차지한 끝 — 마지막 줄 아래끝과, 앞 문단 자신의 문단 기준
4531/// 위아래(TopAndBottom) 개체가 저장 좌표에서 차지한 띠 아래끝 중 큰 값.
4532///
4533/// [#1079] 의 «그림 para 줄 앞 gap ≥ 그림 높이 → 파일 vpos 가 이 문단의 그림 공간을 이미
4534/// 반영» 판정은 그 gap 이 **이 문단의** 개체 자리일 때만 맞다. 앞 문단의 자리차지 그림이
4535/// 줄 아래로 내려와 만든 gap 을 이 문단 그림의 자리로 읽으면, 조판은 이 그림 높이를 더하지
4536/// 않고 배치는 그림을 줄 위 gap 안에 그려 앞 그림과 겹친다(1351000-201500141 pi613 그림
4537/// 띠 23224 + 1105 + 17711 = 42040 = pi614 줄). 조판(`typeset`)과 배치(`layout`)가 같은 끝을
4538/// 쓰도록 한 곳에 둔다.
4539pub(crate) fn stored_previous_flow_end_hu(
4540    paragraphs: &[crate::model::paragraph::Paragraph],
4541    para_index: usize,
4542) -> Option<i32> {
4543    use crate::model::control::Control;
4544    use crate::model::shape::{TextWrap, VertRelTo};
4545
4546    let prev = paragraphs.get(para_index.checked_sub(1)?)?;
4547    let line_end = prev
4548        .line_segs
4549        .last()
4550        .map(|seg| seg.vertical_pos.saturating_add(seg.line_height))?;
4551    let anchor = prev.line_segs.first()?.vertical_pos;
4552    let band_end = prev
4553        .controls
4554        .iter()
4555        .filter_map(|control| match control {
4556            Control::Picture(pic) => Some(&pic.common),
4557            Control::Shape(shape) => Some(shape.common()),
4558            _ => None,
4559        })
4560        .filter(|common| {
4561            !common.treat_as_char
4562                && matches!(common.text_wrap, TextWrap::TopAndBottom)
4563                && matches!(common.vert_rel_to, VertRelTo::Para)
4564        })
4565        .map(|common| {
4566            anchor
4567                .saturating_add(crate::renderer::float_placement::signed_hwpunit(
4568                    common.vertical_offset,
4569                ))
4570                .saturating_add(common.height as i32)
4571                .saturating_add(common.margin.bottom as i32)
4572        })
4573        .max();
4574    Some(band_end.map_or(line_end, |end| end.max(line_end)))
4575}
4576
4577/// [#6888] **자기 앵커보다 아래로 떨어진 자리차지(TopAndBottom) 개체**인가.
4578///
4579/// `#409` 는 비-TAC · `vert=Para` · TopAndBottom 개체가 뒤따르는 콘텐츠를 개체 높이만큼
4580/// 밀어낸다고 보고 조판·배치 양쪽에서 그 높이를 흐름에 계상한다. 그 전제는 밴드가
4581/// **앵커에서 시작할 때**(`vertOffset == 0`) 참이다. 양수 오프셋이 밴드를 아래로 내려
4582/// 놓으면 그 사이에 들어갈 콘텐츠는 밀릴 이유가 없다.
4583///
4584/// 판별은 문서가 준다 — **다음 문단의 저장 `vpos` 가 이 문단 마지막 줄 바로 뒤**면
4585/// 한글이 개체 자리를 만들어 주지 않았다는 증언이다.
4586///
4587/// ```text
4588///   156730935 1쪽  도형 h=62.7px  vOff=150.3px (TopAndBottom, vert=Para)
4589///   p17 마지막 vpos 61789 + lh 1400 + ls 420 = 63609
4590///   p18 저장 vpos                            63609      ← 틈 0
4591///   종전: 흐름·배치가 각각 +62.7px  → 담당자 표가 본문을 49.3px 넘어 사라진다
4592///   정본: 표 945.2..1013.6(본문 안) · 도형 1018.7(표 아래)
4593/// ```
4594///
4595/// 조판(`typeset`)과 배치(`layout`)가 **같은 답**을 써야 `#409` 가 막으려던 desync 가
4596/// 생기지 않으므로 한 곳에 둔다.
4597pub(crate) fn topbottom_float_displaced_below_following_flow(
4598    para: &crate::model::paragraph::Paragraph,
4599    next_para: Option<&crate::model::paragraph::Paragraph>,
4600    common: &crate::model::shape::CommonObjAttr,
4601    dpi: f64,
4602) -> bool {
4603    use crate::model::shape::{TextWrap, VertRelTo};
4604
4605    if common.treat_as_char
4606        || !matches!(common.text_wrap, TextWrap::TopAndBottom)
4607        || !matches!(common.vert_rel_to, VertRelTo::Para)
4608    {
4609        return false;
4610    }
4611    let v_off = hwpunit_to_px(
4612        crate::renderer::float_placement::signed_hwpunit(common.vertical_offset),
4613        dpi,
4614    );
4615    if v_off <= 0.5 {
4616        return false;
4617    }
4618    // 밴드 상단 = 앵커 문단의 첫 줄 + 세로 오프셋. 저장 사다리와 같은 좌표계다.
4619    let Some(anchor_vpos) = para
4620        .line_segs
4621        .first()
4622        .filter(|seg| seg.tag & crate::model::paragraph::LineSeg::TAG_IMPLEMENTATION_PROPERTY == 0)
4623        .map(|seg| seg.vertical_pos)
4624    else {
4625        return false;
4626    };
4627    let band_top = anchor_vpos.saturating_add(crate::renderer::float_placement::signed_hwpunit(
4628        common.vertical_offset,
4629    ));
4630
4631    next_para
4632        .and_then(|next| next.line_segs.last())
4633        .filter(|seg| seg.tag & crate::model::paragraph::LineSeg::TAG_IMPLEMENTATION_PROPERTY == 0)
4634        .is_some_and(|next_last| {
4635            // 다음 문단이 사다리에서 차지하는 바닥. 밴드가 **그 아래에서** 시작하면
4636            // 사이에 들어갈 콘텐츠가 밀릴 이유가 없다. "틈이 없다"보다 강한 조건이다 —
4637            // 오프셋이 작아 밴드가 다음 콘텐츠와 겹치면 종전대로 밀어낸다.
4638            let next_bottom = next_last
4639                .vertical_pos
4640                .saturating_add(next_last.line_height.max(0));
4641            next_last.vertical_pos > anchor_vpos && band_top >= next_bottom
4642        })
4643}
4644
4645#[cfg(test)]
4646mod tests {
4647    use super::*;
4648    use crate::paint::ResolvedImageKind;
4649    use crate::renderer::image_resolver::{
4650        bmp_bytes_to_png_bytes, grayscale_jpeg_bytes_to_png_bytes, resolve_image_payload,
4651    };
4652    use crate::renderer::render_tree::ImageNode;
4653    use image::{DynamicImage, ImageFormat, Rgb, RgbImage};
4654    use std::io::Cursor;
4655
4656    #[test]
4657    fn positive_distribution_spacing_is_not_part_of_glyph_fit_advance() {
4658        let positive = TextStyle {
4659            extra_char_spacing: 12.0,
4660            ..Default::default()
4661        };
4662        assert_eq!(positive.glyph_fit_advance(20.0), Some(8.0));
4663
4664        let zero = TextStyle::default();
4665        assert_eq!(zero.glyph_fit_advance(8.0), Some(8.0));
4666
4667        let negative = TextStyle {
4668            extra_char_spacing: -3.0,
4669            ..Default::default()
4670        };
4671        assert_eq!(negative.glyph_fit_advance(5.0), Some(5.0));
4672    }
4673
4674    #[test]
4675    fn issue_2809_negative_letter_spacing_does_not_compress_canvas_glyph() {
4676        let style = TextStyle {
4677            fixed_glyph_advances: true,
4678            letter_spacing: -7.5,
4679            ..Default::default()
4680        };
4681        assert_eq!(
4682            canvas_cluster_fit(&style, "a", 7.5, 15.0, None, false),
4683            None
4684        );
4685        assert_eq!(canvas_cluster_fit(&style, "a", 7.5, 15.0, None, true), None);
4686
4687        let mut fonts = native_pua_fonts::NativePuaFonts::default();
4688        fonts
4689            .register_otf_for_source(
4690                "source",
4691                false,
4692                false,
4693                true,
4694                include_bytes!("../../tests/fixtures/fonts/RHWPEquationLatinOnly.ttf"),
4695                0,
4696            )
4697            .unwrap();
4698        let style = TextStyle {
4699            source_font_is_ttf: true,
4700            letter_spacing: -0.4,
4701            native_otf_metrics: fonts.get_otf_for_source("source", false, false, true),
4702            ..Default::default()
4703        };
4704        assert_eq!(
4705            canvas_cluster_fit(&style, "∙", 6.0, 12.0, Some(3.0), false),
4706            Some((1.0, -3.0))
4707        );
4708        assert_eq!(
4709            canvas_cluster_fit(&style, "∘", 6.0, 12.0, Some(3.0), false),
4710            Some((1.0, -3.0))
4711        );
4712        assert_eq!(
4713            canvas_cluster_fit(&style, "∙", 6.0, 12.0, Some(6.4), false),
4714            Some((1.0, -3.0))
4715        );
4716        assert_eq!(
4717            canvas_cluster_fit(&style, "∙", 6.0, 12.0, Some(6.8), false),
4718            Some((1.0, -3.0))
4719        );
4720        assert_eq!(
4721            canvas_cluster_fit(&style, "A", 6.0, 12.0, Some(3.0), false),
4722            None
4723        );
4724        assert_eq!(
4725            canvas_cluster_fit(&style, "∙", 6.0, 12.0, Some(9.0), false),
4726            None
4727        );
4728
4729        let declared = TextStyle {
4730            font_family: "휴먼명조,Haansoft Batang".into(),
4731            glyph_fallback_advance_explicit: true,
4732            source_font_is_ttf: true,
4733            ..Default::default()
4734        };
4735        assert_eq!(
4736            measured_glyph_supplier::family(&declared, "․"),
4737            Some("Haansoft Batang")
4738        );
4739        let other = TextStyle {
4740            font_family: "휴먼명조,Noto Serif".into(),
4741            ..declared
4742        };
4743        assert_eq!(measured_glyph_supplier::family(&other, "․"), None);
4744    }
4745
4746    #[test]
4747    fn canvas_glyph_fit_never_stretches_and_keeps_symbol_ink() {
4748        let style = TextStyle::default();
4749        assert_eq!(
4750            canvas_cluster_fit(&style, "가", 7.5, 15.0, None, false),
4751            Some((0.5, 0.0))
4752        );
4753        assert_eq!(
4754            canvas_cluster_fit(&style, "a", 7.5, 15.0, None, true),
4755            Some((0.5, 0.0))
4756        );
4757        assert_eq!(
4758            canvas_cluster_fit(&style, "가", 15.0, 14.9, None, false),
4759            None
4760        );
4761        // 고정폭 원 글꼴의 `1` 칸(0.5em)에 대체 글꼴의 좁은 `1`(0.25em).
4762        // 종전에는 2배로 늘려 굵은 글자처럼 보였다.
4763        assert_eq!(
4764            canvas_cluster_fit(&style, "1", 8.0, 4.0, Some(2.0), true),
4765            Some((1.0, 2.0))
4766        );
4767        // HFT 자동 쪽번호(`fixed_glyph_advances`)는 원본 폭 점유 계약을 유지한다.
4768        let fixed = TextStyle {
4769            fixed_glyph_advances: true,
4770            ..Default::default()
4771        };
4772        assert_eq!(
4773            canvas_cluster_fit(&fixed, "1", 8.0, 4.0, Some(2.0), true),
4774            Some((2.0, 0.0))
4775        );
4776        // 전각 대체 글꼴의 `•`: 상자 16px, 잉크 4px, 칸 6px.
4777        // 종전에는 상자를 칸에 맞춰 0.375배로 눌렀다. 잉크가 칸에 들어가므로
4778        // 누르지 않고 상자를 칸 가운데에 둔다.
4779        assert_eq!(
4780            canvas_cluster_fit(&style, "•", 6.0, 16.0, Some(4.0), false),
4781            Some((1.0, -5.0))
4782        );
4783        // 잉크가 칸보다 넓으면 잉크만 칸 폭에 맞춘다 (상자 폭 배율보다 덜 누른다).
4784        assert_eq!(
4785            canvas_cluster_fit(&style, "μ", 6.0, 16.0, Some(8.0), false),
4786            Some((0.75, -3.0))
4787        );
4788        // 한글 음절은 상자를 채우는 glyph라 종전대로 상자 폭을 맞춘다.
4789        assert_eq!(
4790            canvas_cluster_fit(&style, "가", 6.0, 16.0, Some(4.0), false),
4791            Some((0.375, 0.0))
4792        );
4793        verified_font_glyph_ink_preserves_natural_width_without_explicit_fit();
4794    }
4795
4796    #[test]
4797    fn distribution_spacing_does_not_resize_ascii_canvas_glyph() {
4798        let positive = TextStyle {
4799            fixed_glyph_advances: true,
4800            extra_char_spacing: 12.0,
4801            ..Default::default()
4802        };
4803        assert_eq!(
4804            canvas_cluster_fit(&positive, "a", 20.0, 8.0, None, true),
4805            Some((1.0, 0.0))
4806        );
4807
4808        let negative = TextStyle {
4809            fixed_glyph_advances: true,
4810            extra_char_spacing: -3.0,
4811            ..Default::default()
4812        };
4813        assert_eq!(
4814            canvas_cluster_fit(&negative, "a", 5.0, 8.0, None, true),
4815            Some((0.625, 0.0))
4816        );
4817        assert_eq!(
4818            canvas_cluster_fit(&negative, "가", 5.0, 8.0, None, false),
4819            Some((0.625, 0.0))
4820        );
4821    }
4822
4823    fn verified_font_glyph_ink_preserves_natural_width_without_explicit_fit() {
4824        for (layout, visual, extra, letter) in [
4825            (7.5, 15.0, 0.0, 0.0),
4826            (20.0, 8.0, 12.0, 0.0),
4827            (5.0, 8.0, -3.0, 0.0),
4828            (7.5, 15.0, 0.0, -7.5),
4829        ] {
4830            let style = TextStyle {
4831                preserve_glyph_ink: true,
4832                extra_char_spacing: extra,
4833                letter_spacing: letter,
4834                ..Default::default()
4835            };
4836            for pin_ascii in [false, true] {
4837                assert_eq!(
4838                    canvas_cluster_fit(&style, "가", layout, visual, None, pin_ascii),
4839                    None
4840                );
4841            }
4842        }
4843    }
4844
4845    #[test]
4846    fn test_script_advance_scale_is_exact_identity_for_non_script() {
4847        // [#2771] 비첨자 배율이 **정확히 1.0** 이어야 기존 golden SVG 의
4848        // textLength 값이 비트 단위로 보존된다 (`x * 1.0` 은 IEEE-754 상
4849        // 반올림이 없는 항등 연산).
4850        let base = TextStyle {
4851            font_size: 20.0,
4852            ..Default::default()
4853        };
4854        assert_eq!(base.script_advance_scale(), 1.0);
4855        for advance in [0.0_f64, 6.2133, 1e-300, 1e300, f64::MIN_POSITIVE] {
4856            assert_eq!(
4857                (advance * base.script_advance_scale()).to_bits(),
4858                advance.to_bits(),
4859                "비첨자 advance 는 비트 단위로 불변이어야 함: {advance}"
4860            );
4861        }
4862
4863        // [#5756] 첨자 run 의 레이아웃 advance 가 그리기 배율(0.7)로 측정되므로
4864        // fit 배율은 첨자에서도 항등(1.0)이다 — 0.7 을 또 곱하면 이중 축소.
4865        let sup = TextStyle {
4866            superscript: true,
4867            ..base.clone()
4868        };
4869        let sub = TextStyle {
4870            subscript: true,
4871            ..base.clone()
4872        };
4873        for style in [&sup, &sub] {
4874            assert_eq!(style.script_advance_scale(), 1.0);
4875            // 그리기 글꼴은 여전히 0.7 배 축소다.
4876            assert_eq!(style.script_draw_metrics(20.0, 0.0).0, 20.0 * 0.7);
4877        }
4878    }
4879
4880    // [#7079] 합성 TAC 줄의 leading 은 호스트 문단의 글자 크기·문단 줄간격에서 나온다.
4881    // 글자모양 0번을 `font_size` px, 문단모양을 Percent `percent` 로 세운 스타일 세트.
4882    fn tac_styles(
4883        font_size: f64,
4884        percent: f64,
4885    ) -> (
4886        crate::renderer::style_resolver::ResolvedStyleSet,
4887        crate::renderer::style_resolver::ResolvedParaStyle,
4888    ) {
4889        let mut styles = crate::renderer::style_resolver::ResolvedStyleSet::default();
4890        let char_style = crate::renderer::style_resolver::ResolvedCharStyle {
4891            font_size,
4892            ..Default::default()
4893        };
4894        styles.char_styles.push(char_style);
4895        let para_style = crate::renderer::style_resolver::ResolvedParaStyle {
4896            line_spacing_type: crate::model::style::LineSpacingType::Percent,
4897            line_spacing: percent,
4898            ..Default::default()
4899        };
4900        (styles, para_style)
4901    }
4902
4903    // [#2287] 저장 LINE_SEG 없는 빈 anchor 문단의 TAC 그림 줄 메트릭 합성.
4904    // [#7079] leading 은 문단의 글자모양에서 나오므로 실제 문서처럼 0번 글자모양을 단다.
4905    fn tac_picture_para(sizes_hu: &[(i32, i32)]) -> crate::model::paragraph::Paragraph {
4906        use crate::model::control::Control;
4907        let mut para = crate::model::paragraph::Paragraph::default();
4908        para.char_shapes
4909            .push(crate::model::paragraph::CharShapeRef {
4910                start_pos: 0,
4911                char_shape_id: 0,
4912            });
4913        for (w, h) in sizes_hu {
4914            let mut pic = crate::model::image::Picture::default();
4915            pic.common.treat_as_char = true;
4916            pic.common.width = *w as u32;
4917            pic.common.height = *h as u32;
4918            para.controls.push(Control::Picture(Box::new(pic)));
4919        }
4920        para
4921    }
4922
4923    #[test]
4924    fn test_tac_object_stack_single_picture_line() {
4925        // 590×387px 그림 1장 (미래부 정서분석 pi854 형상) — 1줄, 그림 높이.
4926        let para = tac_picture_para(&[(44222, 29069)]);
4927        let (styles, para_style) = tac_styles(20.0, 100.0);
4928        let lines =
4929            tac_object_stack_line_metrics(&para, 96.0, Some(661.0), &styles, Some(&para_style))
4930                .unwrap();
4931        assert_eq!(lines.len(), 1);
4932        assert!((lines[0].0 - hwpunit_to_px(29069, 96.0)).abs() < 0.01);
4933        // 100% 는 여분이 없다.
4934        assert_eq!(lines[0].1, 0.0);
4935
4936        // [#7079] leading 은 호스트 문단의 글자·퍼센트에서 나온다.
4937        // 156060125 2쪽: 글자 20.0px · 150% → 10.0px (저장 사다리 752HU).
4938        let para_fsc = tac_picture_para(&[(44852, 29997)]);
4939        let (styles_fsc, ps_fsc) = tac_styles(20.0, 150.0);
4940        let fsc =
4941            tac_object_stack_line_metrics(&para_fsc, 96.0, Some(661.0), &styles_fsc, Some(&ps_fsc))
4942                .unwrap();
4943        assert!((fsc[0].0 - hwpunit_to_px(29997, 96.0)).abs() < 0.01);
4944        assert!((fsc[0].1 - 10.0).abs() < 0.01, "{:?}", fsc[0]);
4945
4946        // 156596828 1쪽: 글자 16.0px · 160% → 9.6px (저장 사다리 720HU). 개체 높이가
4947        // 14배 작아도 같은 값이다 — leading 은 개체가 아니라 글자에서 나온다.
4948        let para_mafra = tac_picture_para(&[(10435, 2023)]);
4949        let (styles_mafra, ps_mafra) = tac_styles(16.0, 160.0);
4950        let mafra = tac_object_stack_line_metrics(
4951            &para_mafra,
4952            96.0,
4953            Some(661.0),
4954            &styles_mafra,
4955            Some(&ps_mafra),
4956        )
4957        .unwrap();
4958        assert!((mafra[0].0 - hwpunit_to_px(2023, 96.0)).abs() < 0.01);
4959        assert!((mafra[0].1 - 9.6).abs() < 0.01, "{:?}", mafra[0]);
4960
4961        // 문단모양을 못 찾으면 종전대로 0 이다.
4962        let no_style =
4963            tac_object_stack_line_metrics(&para_fsc, 96.0, Some(661.0), &styles_fsc, None).unwrap();
4964        assert_eq!(no_style[0].1, 0.0);
4965    }
4966
4967    #[test]
4968    fn test_tac_object_stack_wraps_by_width() {
4969        // 590px 그림 3장, 가용 661px — 줄당 1장씩 3줄 (농촌 S-OJT 스택 형상).
4970        let para = tac_picture_para(&[(44222, 29069); 3]);
4971        let (styles, para_style) = tac_styles(20.0, 150.0);
4972        let lines =
4973            tac_object_stack_line_metrics(&para, 96.0, Some(661.0), &styles, Some(&para_style))
4974                .unwrap();
4975        assert_eq!(lines.len(), 3);
4976        // leading 은 줄마다 같은 몫이다.
4977        assert!(lines.iter().all(|(_, ls)| (ls - 10.0).abs() < 0.01));
4978        // 300px 그림 2장, 가용 661px — 한 줄 수용.
4979        let para2 = tac_picture_para(&[(22000, 10000), (22000, 12000)]);
4980        let lines2 =
4981            tac_object_stack_line_metrics(&para2, 96.0, Some(661.0), &styles, Some(&para_style))
4982                .unwrap();
4983        assert_eq!(lines2.len(), 1);
4984        assert!((lines2[0].0 - hwpunit_to_px(12000, 96.0)).abs() < 0.01);
4985    }
4986
4987    #[test]
4988    fn test_tac_object_stack_rejects_stored_ls_and_non_tac() {
4989        let (styles, para_style) = tac_styles(20.0, 150.0);
4990        // 저장 LINE_SEG 보유 문단 제외 (이중 계상 방지).
4991        let mut para = tac_picture_para(&[(44222, 29069)]);
4992        para.line_segs
4993            .push(crate::model::paragraph::LineSeg::default());
4994        assert!(tac_object_stack_line_metrics(
4995            &para,
4996            96.0,
4997            Some(661.0),
4998            &styles,
4999            Some(&para_style)
5000        )
5001        .is_none());
5002        // 비-TAC 그림 제외 (PageItem::Shape 오버레이 경로 유지).
5003        let mut para2 = tac_picture_para(&[(44222, 29069)]);
5004        if let crate::model::control::Control::Picture(pic) = &mut para2.controls[0] {
5005            pic.common.treat_as_char = false;
5006        }
5007        assert!(tac_object_stack_line_metrics(
5008            &para2,
5009            96.0,
5010            Some(661.0),
5011            &styles,
5012            Some(&para_style)
5013        )
5014        .is_none());
5015        // [#7079] 합성 tag seg 를 가진 문단은 높이 합성은 그대로(#2287) 두되 leading 은
5016        // 0 이다 — 그 seg 의 baseline 이 개체 배치의 근거라 leading 을 얹으면 개체가
5017        // 밀린다 (#6708 tac-img-02: 글자 264px → 158px).
5018        let mut para3 = tac_picture_para(&[(44222, 29069)]);
5019        para3.line_segs.push(crate::model::paragraph::LineSeg {
5020            tag: crate::model::paragraph::LineSeg::TAG_IMPLEMENTATION_PROPERTY,
5021            ..Default::default()
5022        });
5023        assert_eq!(
5024            tac_object_stack_line_leading_px(&para3, &styles, Some(&para_style)),
5025            0.0
5026        );
5027        let synth =
5028            tac_object_stack_line_metrics(&para3, 96.0, Some(661.0), &styles, Some(&para_style))
5029                .expect("합성 tag seg 문단도 높이 합성은 유지한다");
5030        assert!((synth[0].0 - hwpunit_to_px(29069, 96.0)).abs() < 0.01);
5031        assert_eq!(synth[0].1, 0.0);
5032    }
5033
5034    #[test]
5035    fn test_source_line_metrics_reflow_when_text_height_is_implausible() {
5036        let max_fs = hwpunit_to_px(1000, 96.0);
5037        let raw_h = hwpunit_to_px(68800, 96.0);
5038        let (line_height, line_spacing) = corrected_line_metrics_for_source(
5039            raw_h,
5040            raw_h,
5041            0.0,
5042            max_fs,
5043            LineSpacingType::Percent,
5044            160.0,
5045            true,
5046            true,
5047        );
5048
5049        assert!((line_height - max_fs).abs() < 0.01);
5050        assert!((line_spacing - max_fs * 0.6).abs() < 0.01);
5051    }
5052
5053    #[test]
5054    fn test_source_line_metrics_keep_normal_stored_height() {
5055        let max_fs = hwpunit_to_px(1000, 96.0);
5056        let stored_h = hwpunit_to_px(3000, 96.0);
5057        let (line_height, line_spacing) = corrected_line_metrics_for_source(
5058            stored_h,
5059            stored_h,
5060            0.0,
5061            max_fs,
5062            LineSpacingType::Percent,
5063            160.0,
5064            true,
5065            false,
5066        );
5067
5068        assert!((line_height - stored_h).abs() < 0.01);
5069        assert_eq!(line_spacing, 0.0);
5070    }
5071
5072    #[test]
5073    fn test_source_line_metrics_preserve_intentional_tall_section_line() {
5074        let max_fs = hwpunit_to_px(1000, 96.0);
5075        let intentional_tall_line = hwpunit_to_px(55000, 96.0);
5076
5077        assert!(!source_line_metrics_need_reflow(
5078            intentional_tall_line,
5079            intentional_tall_line,
5080            max_fs,
5081            LineSpacingType::Percent,
5082            160.0,
5083            true,
5084        ));
5085    }
5086
5087    #[test]
5088    fn test_source_line_metrics_reflow_replaces_stale_baseline() {
5089        let max_fs = hwpunit_to_px(1000, 96.0);
5090        let stale_baseline = hwpunit_to_px(58480, 96.0);
5091
5092        let baseline = corrected_line_baseline_for_source(stale_baseline, max_fs, true);
5093
5094        assert!((baseline - max_fs * 0.85).abs() < 0.01);
5095        assert!(baseline < stale_baseline / 10.0);
5096    }
5097
5098    #[test]
5099    fn test_structural_controls_mark_section_start() {
5100        assert!(controls_mark_section_start(&[
5101            Control::SectionDef(Box::default()),
5102            Control::ColumnDef(Default::default()),
5103        ]));
5104        assert!(!controls_mark_section_start(&[]));
5105    }
5106
5107    /// [Task #1745] 텍스트 혼합 anchor: 표 geometry 로 wrap 띠 도출
5108    #[test]
5109    fn test_text_anchor_square_table_strip_derives_from_geometry() {
5110        use crate::model::control::Control;
5111        use crate::model::paragraph::{LineSeg, Paragraph};
5112        use crate::model::shape::TextWrap;
5113        use crate::model::table::Table;
5114
5115        let mut table = Table::default();
5116        table.common.treat_as_char = false;
5117        table.common.text_wrap = TextWrap::Square;
5118        table.common.horizontal_offset = 0;
5119        table.common.width = 45002;
5120        table.common.margin.left = 283;
5121        table.common.margin.right = 283;
5122
5123        let mut para = Paragraph::default();
5124        para.text = "■ 약사법 시행령 [별표 2]".to_string();
5125        para.line_segs.push(LineSeg {
5126            column_start: 0,
5127            segment_width: 48188,
5128            ..Default::default()
5129        });
5130        para.controls.push(Control::Table(Box::new(table)));
5131
5132        // samples/task1745: cs=45568(=45002+283×2), sw=2620(=48188−45568)
5133        assert_eq!(text_anchor_square_table_strip(&para), Some((45568, 2620)));
5134    }
5135
5136    /// [Task #1745] 표 단독 anchor(첫 seg 가 이미 wrap 띠) — None (기존 경로 유지)
5137    #[test]
5138    fn test_text_anchor_square_table_strip_none_for_table_only_anchor() {
5139        use crate::model::control::Control;
5140        use crate::model::paragraph::{LineSeg, Paragraph};
5141        use crate::model::shape::TextWrap;
5142        use crate::model::table::Table;
5143
5144        let mut table = Table::default();
5145        table.common.treat_as_char = false;
5146        table.common.text_wrap = TextWrap::Square;
5147        table.common.width = 20000;
5148
5149        // 표 단독 anchor: 첫 LINE_SEG 가 이미 띠 (cs>0)
5150        let mut para = Paragraph::default();
5151        para.text = " ".to_string();
5152        para.line_segs.push(LineSeg {
5153            column_start: 20600,
5154            segment_width: 27000,
5155            ..Default::default()
5156        });
5157        para.controls.push(Control::Table(Box::new(table.clone())));
5158        assert_eq!(text_anchor_square_table_strip(&para), None);
5159
5160        // 텍스트 없는 anchor — None
5161        let mut para2 = Paragraph::default();
5162        para2.text = String::new();
5163        para2.line_segs.push(LineSeg {
5164            column_start: 0,
5165            segment_width: 48188,
5166            ..Default::default()
5167        });
5168        para2.controls.push(Control::Table(Box::new(table.clone())));
5169        assert_eq!(text_anchor_square_table_strip(&para2), None);
5170
5171        // 띠 폭이 남지 않는 표(전폭) — None
5172        let mut wide = table.clone();
5173        wide.common.width = 48188;
5174        let mut para3 = Paragraph::default();
5175        para3.text = "제목".to_string();
5176        para3.line_segs.push(LineSeg {
5177            column_start: 0,
5178            segment_width: 48188,
5179            ..Default::default()
5180        });
5181        para3.controls.push(Control::Table(Box::new(wide)));
5182        assert_eq!(text_anchor_square_table_strip(&para3), None);
5183    }
5184
5185    #[test]
5186    fn test_auto_number_counter() {
5187        let mut counter = AutoNumberCounter::new();
5188        assert_eq!(counter.increment(AutoNumberType::Picture), 1);
5189        assert_eq!(counter.increment(AutoNumberType::Picture), 2);
5190        assert_eq!(counter.increment(AutoNumberType::Table), 1);
5191        assert_eq!(counter.current(AutoNumberType::Picture), 2);
5192        assert_eq!(counter.current(AutoNumberType::Table), 1);
5193        counter.reset();
5194        assert_eq!(counter.current(AutoNumberType::Picture), 0);
5195    }
5196
5197    #[test]
5198    fn test_format_number_digit() {
5199        assert_eq!(format_number(1, NumberFormat::Digit), "1");
5200        assert_eq!(format_number(123, NumberFormat::Digit), "123");
5201    }
5202
5203    #[test]
5204    fn test_format_number_circled() {
5205        assert_eq!(format_number(1, NumberFormat::CircledDigit), "①");
5206        assert_eq!(format_number(10, NumberFormat::CircledDigit), "⑩");
5207        assert_eq!(format_number(20, NumberFormat::CircledDigit), "⑳");
5208        // 한/글 12.30 Mac은 ⑳ 다음을 ①로 돌린다.
5209        assert_eq!(format_number(21, NumberFormat::CircledDigit), "①");
5210    }
5211
5212    #[test]
5213    fn test_format_number_roman() {
5214        assert_eq!(format_number(1, NumberFormat::RomanUpper), "I");
5215        assert_eq!(format_number(4, NumberFormat::RomanUpper), "IV");
5216        assert_eq!(format_number(9, NumberFormat::RomanUpper), "IX");
5217        assert_eq!(format_number(10, NumberFormat::RomanLower), "x");
5218        assert_eq!(format_number(14, NumberFormat::RomanLower), "xiv");
5219    }
5220
5221    #[test]
5222    fn test_format_number_latin() {
5223        assert_eq!(format_number(1, NumberFormat::LatinUpper), "A");
5224        assert_eq!(format_number(26, NumberFormat::LatinUpper), "Z");
5225        // 한/글 12.30 Mac은 Z 다음을 A로 돌린다.
5226        assert_eq!(format_number(27, NumberFormat::LatinUpper), "A");
5227        assert_eq!(format_number(1, NumberFormat::LatinLower), "a");
5228    }
5229
5230    /// [#3314] 굵기 접미사 face 의 base family 추출과 렌더 체인 삽입.
5231    #[test]
5232    fn test_base_family_without_weight_suffix() {
5233        assert_eq!(
5234            base_family_without_weight_suffix("Noto Serif KR Black").as_deref(),
5235            Some("Noto Serif KR")
5236        );
5237        assert_eq!(
5238            base_family_without_weight_suffix("나눔고딕 Bold").as_deref(),
5239            Some("나눔고딕")
5240        );
5241        assert_eq!(
5242            base_family_without_weight_suffix("경기천년제목 Light").as_deref(),
5243            Some("경기천년제목")
5244        );
5245        // 두 토큰 접미사 ("Extra Bold")
5246        assert_eq!(
5247            base_family_without_weight_suffix("Noto Sans KR Extra Bold").as_deref(),
5248            Some("Noto Sans KR")
5249        );
5250        // 접미사 없음 → None (체인 불변)
5251        assert_eq!(base_family_without_weight_suffix("맑은 고딕"), None);
5252        assert_eq!(base_family_without_weight_suffix("HY헤드라인M"), None);
5253        assert_eq!(base_family_without_weight_suffix("휴먼명조"), None);
5254        // 전체가 접미사 토큰뿐이면 벗기지 않는다
5255        assert_eq!(base_family_without_weight_suffix("Light"), None);
5256        // 렌더 체인: 요청 face → base → generic
5257        let chain = render_font_family_chain("Noto Serif KR Black");
5258        assert!(chain.starts_with("'Noto Serif KR Black','Noto Serif KR',"));
5259        let plain = render_font_family_chain("맑은 고딕");
5260        assert!(plain.starts_with("'맑은 고딕','Malgun Gothic'"));
5261        assert!(render_font_family_chain("Tom's Handwriting")
5262            .starts_with("'Tom\\'s Handwriting','Malgun Gothic'"));
5263        assert!(
5264            render_font_family_chain(r"Legacy\Face").starts_with(r"'Legacy\\Face','Malgun Gothic'")
5265        );
5266
5267        // [#6171] `HYGothic` 이 빠지면 `『별표 7』`의 `『`(중고딕 run)이 Windows 에서
5268        // Malgun 으로 떨어진다. `HY중고딕`·`HYGothic-Medium` 은 DirectWrite 가 안 잡고
5269        // 접미사를 뗀 `HYGothic` 만 잡히므로, 두 이름 뒤에 반드시 와야 한다.
5270        assert_eq!(
5271            render_font_family_chain("한양중고딕"),
5272            format!(
5273                "'한양중고딕','HY중고딕','HYGothic','HYGothic-Medium','HCR Dotum','함초롬돋움',{}",
5274                generic_fallback("한양중고딕")
5275            )
5276        );
5277        assert_eq!(
5278            render_font_family_chain("HY중고딕"),
5279            format!(
5280                "'HY중고딕','HYGothic','HYGothic-Medium','HCR Dotum','함초롬돋움','Malgun Gothic',{}",
5281                generic_fallback("HY중고딕")
5282            )
5283        );
5284
5285        // [#6171] 견고딕/견명조도 legacy name 뒤에 설치 face 이름이 와야 한다. 이 arm 이
5286        // 없으면 체인이 곧바로 generic 으로 떨어져 `HY견고딕` 설치본이 있어도 Malgun
5287        // Gothic 이 잡힌다 — 3146683 1쪽 `『별표 7』`의 `별표` 획 굵기 회귀.
5288        assert_eq!(
5289            render_font_family_chain("한양견고딕"),
5290            format!(
5291                "'한양견고딕','HY견고딕','HYGothic-Extra','HCR Dotum','함초롬돋움',{}",
5292                generic_fallback("한양견고딕")
5293            )
5294        );
5295        assert_eq!(
5296            render_font_family_chain("한양견명조"),
5297            format!(
5298                "'한양견명조','HY견명조','HYMyeongJo-Extra','HCR Batang','함초롬바탕',{}",
5299                generic_fallback("한양견명조")
5300            )
5301        );
5302        // 신명조도 같은 짝이다. 이 arm 이 없으면 체인이 `'한양신명조','Batang',…` 로
5303        // 떨어져 `HY신명조`(H2MJSM.TTF) 설치본을 건너뛴다 — 156573118 8쪽 텍스트 런 600개.
5304        // [#6263] 문서가 `HY…` 이름을 직접 쓰는 경우도 접미사를 뗀 이름이 앞에 와야
5305        // 한다. 한국어 이름·`-Medium` 원문은 Windows 에서 둘 다 안 잡힌다(실측 0px).
5306        assert!(render_font_family_chain("HY신명조").starts_with("'HY신명조','HYSinMyeongJo',"));
5307        assert!(render_font_family_chain("HY헤드라인M").starts_with("'HY헤드라인M','HYHeadLine',"));
5308        assert!(render_font_family_chain("HY그래픽M").starts_with("'HY그래픽M','HYGraphic',"));
5309
5310        assert_eq!(
5311            render_font_family_chain("한양신명조"),
5312            format!(
5313                "'한양신명조','HYSinMyeongJo','HY신명조','HYSinMyeongJo-Medium',{}",
5314                generic_fallback("한양신명조")
5315            )
5316        );
5317
5318        assert_eq!(
5319            canvas_font_family_chain("Noto Serif KR Black"),
5320            format!(
5321                "\"Noto Serif KR Black\", \"Noto Serif KR\", {}",
5322                generic_fallback("Noto Serif KR Black")
5323            )
5324        );
5325        // [#6171] studio(canvas) 축도 SVG 와 같은 별칭 표를 쓰므로 `HYGothic` 이 들어간다.
5326        assert_eq!(
5327            canvas_font_family_chain("HY중고딕"),
5328            format!(
5329                "\"HY중고딕\", \"HYGothic\", \"HYGothic-Medium\", \"HCR Dotum\", \"함초롬돋움\", \"Malgun Gothic\", {}",
5330                generic_fallback("HY중고딕")
5331            )
5332        );
5333        assert_eq!(
5334            canvas_font_family_chain("맑은 고딕"),
5335            format!("\"맑은 고딕\", {}", generic_fallback("맑은 고딕"))
5336        );
5337
5338        let government = "정부상징 부처명_16040911,한컴바탕";
5339        assert!(render_font_family_chain(government).starts_with(
5340            "'정부상징 부처명_16040911','ROKG','ROKG R','대한민국정부상징체',\
5341             '대한민국정부상징체 R','ROKGR','한컴바탕',"
5342        ));
5343        assert!(canvas_font_family_chain(government).starts_with(
5344            "\"정부상징 부처명_16040911\", \"ROKG\", \"ROKG R\", \
5345             \"대한민국정부상징체\", \"대한민국정부상징체 R\", \"ROKGR\", \"한컴바탕\", "
5346        ));
5347    }
5348
5349    #[test]
5350    fn test_generic_fallback() {
5351        let serif = "'Haansoft Batang','Batang','바탕','Nanum Myeongjo','AppleMyungjo','Noto Serif KR','Noto Serif CJK KR','HCR Batang','함초롬바탕','HCR Batang Ext','함초롬바탕 확장','HCR Batang ExtB','함초롬바탕 확장B','RHWP Old Hangul','Segoe UI Emoji','Noto Emoji','Noto Color Emoji',serif";
5352        let sans = "'Malgun Gothic','맑은 고딕','Apple SD Gothic Neo','HCR Dotum','함초롬돋움','Noto Sans KR ExtraLight','Noto Sans KR','Noto Sans CJK KR','Pretendard','HCR Batang','함초롬바탕','HCR Batang Ext','함초롬바탕 확장','HCR Batang ExtB','함초롬바탕 확장B','RHWP Old Hangul','Segoe UI Emoji','Noto Emoji','Noto Color Emoji',sans-serif";
5353        // Task #1224: ExtraLight 가 무거운 Noto 직전에 위치하는지 명시 검증
5354        assert!(sans.contains("'Noto Sans KR ExtraLight','Noto Sans KR'"));
5355        // [#4086] 하이픈 표기는 어떤 폰트와도 매칭되지 않는다 — 실제 패밀리명은
5356        // `HCR Batang ExtB` (HANBatangExtB.ttf name table nid1/lid0x409 실측).
5357        for chain in [serif, sans] {
5358            assert!(
5359                !chain.contains("Ext-B"),
5360                "죽은 하이픈 표기가 되살아났다: {chain}"
5361            );
5362            assert!(chain.contains("'HCR Batang ExtB'"));
5363            // PUA 원문자(U+F02B1~F02C4)의 소재는 **일반**이다. 목적이 드러나도록
5364            // 일반을 확장/확장B 앞에 둔다(담당 대역이 겹치지 않아 매칭 결과는 불변).
5365            let plain = chain.find("'HCR Batang','함초롬바탕'").expect("일반 항목");
5366            let ext = chain.find("'HCR Batang Ext'").expect("확장 항목");
5367            let extb = chain.find("'HCR Batang ExtB'").expect("확장B 항목");
5368            assert!(
5369                plain < ext && ext < extb,
5370                "체인 순서가 일반→확장→확장B 가 아니다"
5371            );
5372        }
5373        let mono = "'GulimChe','굴림체','D2Coding','Noto Sans Mono','Segoe UI Emoji','Noto Emoji','Noto Color Emoji',monospace";
5374        // 세리프 계열
5375        assert_eq!(generic_fallback("함초롬바탕"), serif);
5376        assert_eq!(generic_fallback("바탕"), serif);
5377        assert_eq!(generic_fallback("궁서"), serif);
5378        assert_eq!(generic_fallback("HY견명조"), serif);
5379        assert_eq!(generic_fallback("Times New Roman"), serif);
5380        assert_eq!(generic_fallback("Palatino Linotype"), serif);
5381        // KoPub바탕체는 이름에 "바탕체"가 들어가지만 고정폭 BatangChe가 아니라
5382        // 비례폭 본문/제목용 세리프 계열이다.
5383        assert_eq!(generic_fallback("KoPub바탕체 Light"), serif);
5384        assert_eq!(generic_fallback("KoPub바탕체 Medium"), serif);
5385        assert_eq!(generic_fallback("KoPub Batang Medium"), serif);
5386        // 산세리프 계열
5387        assert_eq!(generic_fallback("함초롬돋움"), sans);
5388        assert_eq!(generic_fallback("Arial"), sans);
5389        assert_eq!(generic_fallback("맑은 고딕"), sans);
5390        assert!(generic_fallback("KoPub돋움체 Light")
5391            .starts_with("'Noto Sans KR ExtraLight','Malgun Gothic'"));
5392        assert!(generic_fallback("KoPub Dotum Light")
5393            .starts_with("'Noto Sans KR ExtraLight','Malgun Gothic'"));
5394        // 고정폭 계열
5395        assert_eq!(generic_fallback("굴림체"), mono);
5396        assert_eq!(generic_fallback("바탕체"), serif);
5397        assert_eq!(generic_fallback("BatangChe"), serif);
5398        assert_eq!(generic_fallback("Courier New"), mono);
5399        assert_eq!(generic_fallback("D2Coding ligature"), mono);
5400        assert_eq!(generic_fallback("Noto Sans Mono"), mono);
5401        // 영문 세리프 (issue #616)
5402        assert_eq!(generic_fallback("Noto Serif CJK SC"), serif);
5403        assert_eq!(generic_fallback("Liberation Serif"), serif);
5404        assert_eq!(generic_fallback("Noto Serif KR"), serif);
5405        // "sans" 포함 폰트는 세리프로 분류되지 않음
5406        assert_eq!(generic_fallback("Liberation Sans"), sans);
5407        assert_eq!(generic_fallback("Noto Sans KR"), sans);
5408        // 빈 문자열
5409        assert_eq!(generic_fallback(""), sans);
5410    }
5411
5412    #[test]
5413    fn boxed_pua_number_covers_hancom_square_digits() {
5414        assert_eq!(boxed_pua_number('\u{F02B1}'), Some(1));
5415        assert_eq!(boxed_pua_number('\u{F02BA}'), Some(10));
5416        assert_eq!(boxed_pua_number('\u{F02C4}'), Some(20));
5417        // [#6127] U+F02B0 = 네모 안 0 (2599643 실측 "②⓪⓪").
5418        assert_eq!(boxed_pua_number('\u{F02B0}'), Some(0));
5419        assert_eq!(boxed_pua_number('\u{F02AF}'), None);
5420        assert_eq!(boxed_pua_number('\u{F02C5}'), None);
5421        assert_eq!(boxed_pua_number('1'), None);
5422    }
5423
5424    #[test]
5425    fn boxed_pua_char_overlap_promotes_only_implicit_square_border() {
5426        assert_eq!(
5427            boxed_pua_char_overlap_semantics(&['\u{F02B1}'], 0),
5428            Some((1, 3))
5429        );
5430        assert_eq!(
5431            boxed_pua_char_overlap_semantics(&['\u{F02C4}'], 0),
5432            Some((20, 3))
5433        );
5434        assert_eq!(
5435            boxed_pua_char_overlap_semantics(&['\u{F02B1}'], 1),
5436            Some((1, 1))
5437        );
5438        assert_eq!(
5439            boxed_pua_char_overlap_semantics(&['\u{F02B1}', '\u{F02B2}'], 0),
5440            None
5441        );
5442        assert_eq!(boxed_pua_char_overlap_semantics(&['1'], 0), None);
5443    }
5444
5445    #[test]
5446    fn test_medium_weight_face() {
5447        use crate::renderer::style_resolver::is_medium_weight_face;
5448        assert!(is_medium_weight_face("HY중고딕"));
5449        assert!(is_medium_weight_face("신명 중고딕"));
5450        assert!(is_medium_weight_face("한양중고딕"));
5451        assert!(is_medium_weight_face("HY태고딕"));
5452        assert!(is_medium_weight_face("신명 태고딕"));
5453        assert!(!is_medium_weight_face("HY헤드라인M"));
5454        assert!(!is_medium_weight_face("돋움"));
5455        assert!(!is_medium_weight_face("바탕"));
5456        assert!(!is_medium_weight_face("맑은 고딕"));
5457        assert!(!is_medium_weight_face(""));
5458    }
5459
5460    #[test]
5461    fn test_explicit_face_weight_hints() {
5462        let light = TextStyle {
5463            font_family: "KoPub돋움체 Light".to_string(),
5464            ..Default::default()
5465        };
5466        assert_eq!(light.css_font_weight(), Some("300"));
5467
5468        let bold = TextStyle {
5469            font_family: "KoPub바탕체 Bold".to_string(),
5470            ..Default::default()
5471        };
5472        assert_eq!(bold.css_font_weight(), Some("bold"));
5473        assert!(bold.is_visually_bold());
5474    }
5475
5476    #[test]
5477    fn test_format_number_hangul() {
5478        for (number, expected) in [(1, "ㄱ"), (2, "ㄴ"), (4, "ㄹ"), (14, "ㅎ")] {
5479            assert_eq!(format_number(number, NumberFormat::HangulJamo), expected);
5480        }
5481        assert_eq!(format_number(1, NumberFormat::HangulGaNaDa), "가");
5482        assert_eq!(format_number(2, NumberFormat::HangulGaNaDa), "나");
5483        assert_eq!(format_number(1, NumberFormat::HangulNumber), "일");
5484        assert_eq!(format_number(12, NumberFormat::HangulNumber), "십이");
5485    }
5486
5487    fn jpeg_from_pixels(width: u32, height: u32, pixels: impl Fn(u32, u32) -> [u8; 3]) -> Vec<u8> {
5488        let mut img = RgbImage::new(width, height);
5489        for y in 0..height {
5490            for x in 0..width {
5491                img.put_pixel(x, y, Rgb(pixels(x, y)));
5492            }
5493        }
5494
5495        let mut out = Vec::new();
5496        DynamicImage::ImageRgb8(img)
5497            .write_to(&mut Cursor::new(&mut out), ImageFormat::Jpeg)
5498            .expect("encode jpeg");
5499        out
5500    }
5501
5502    /// 메모가 다른 그림의 결과를 흘리지 않는다.
5503    #[test]
5504    fn different_images_keep_their_own_results() {
5505        let gray = jpeg_from_pixels(2, 2, |x, y| {
5506            let g = 120 + (x + y) as u8;
5507            [g, g, g]
5508        });
5509        let color = jpeg_from_pixels(2, 2, |x, y| {
5510            if (x + y) % 2 == 0 {
5511                [210, 48, 48]
5512            } else {
5513                [48, 110, 210]
5514            }
5515        });
5516
5517        assert!(grayscale_jpeg_bytes_to_png_bytes(&gray).is_some());
5518        assert!(grayscale_jpeg_bytes_to_png_bytes(&color).is_none());
5519        // 순서를 바꿔도 각자의 결과가 나온다 (둘 다 메모에 들어간 뒤).
5520        assert!(grayscale_jpeg_bytes_to_png_bytes(&color).is_none());
5521        assert!(grayscale_jpeg_bytes_to_png_bytes(&gray).is_some());
5522    }
5523
5524    #[test]
5525    fn grayscale_jpeg_is_normalized_to_png() {
5526        let jpeg = jpeg_from_pixels(2, 2, |x, y| {
5527            let g = 180 + (x + y) as u8;
5528            [g, g, g]
5529        });
5530
5531        let png = grayscale_jpeg_bytes_to_png_bytes(&jpeg).expect("gray jpeg should normalize");
5532        assert!(png.starts_with(b"\x89PNG\r\n\x1a\n"));
5533    }
5534
5535    #[test]
5536    fn color_jpeg_keeps_jpeg_path() {
5537        let jpeg = jpeg_from_pixels(2, 2, |x, y| {
5538            if (x + y) % 2 == 0 {
5539                [220, 64, 64]
5540            } else {
5541                [64, 120, 220]
5542            }
5543        });
5544
5545        assert!(grayscale_jpeg_bytes_to_png_bytes(&jpeg).is_none());
5546    }
5547
5548    #[test]
5549    fn tiff_image_payload_is_normalized_to_png() {
5550        let mut img = RgbImage::new(2, 2);
5551        for y in 0..2 {
5552            for x in 0..2 {
5553                img.put_pixel(x, y, Rgb([32 + x as u8, 96 + y as u8, 160]));
5554            }
5555        }
5556        let mut tiff = Vec::new();
5557        DynamicImage::ImageRgb8(img)
5558            .write_to(&mut Cursor::new(&mut tiff), ImageFormat::Tiff)
5559            .expect("encode tiff");
5560
5561        let image = ImageNode::new(1, Some(tiff));
5562        let resolved = resolve_image_payload(&image).expect("tiff should resolve");
5563
5564        assert_eq!(resolved.mime, "image/png");
5565        assert_eq!(resolved.kind, ResolvedImageKind::FormatConverted);
5566        assert!(resolved.data.starts_with(b"\x89PNG\r\n\x1a\n"));
5567        assert!(!resolved.suppress_effects);
5568    }
5569
5570    #[test]
5571    fn oversized_compact_bmp_is_rejected_before_layer_conversion() {
5572        let mut bmp = vec![0u8; 58];
5573        bmp[..2].copy_from_slice(b"BM");
5574        bmp[2..6].copy_from_slice(&58u32.to_le_bytes());
5575        bmp[10..14].copy_from_slice(&54u32.to_le_bytes());
5576        bmp[14..18].copy_from_slice(&40u32.to_le_bytes());
5577        bmp[18..22].copy_from_slice(&8193i32.to_le_bytes());
5578        bmp[22..26].copy_from_slice(&8193i32.to_le_bytes());
5579        bmp[26..28].copy_from_slice(&1u16.to_le_bytes());
5580        bmp[28..30].copy_from_slice(&8u16.to_le_bytes());
5581        bmp[30..34].copy_from_slice(&1u32.to_le_bytes());
5582        bmp[54..58].copy_from_slice(&[0, 1, 0, 1]);
5583
5584        assert!(bmp_bytes_to_png_bytes(&bmp).is_none());
5585        assert!(resolve_image_payload(&ImageNode::new(1, Some(bmp))).is_none());
5586    }
5587}
5588
5589crate::storage::clone_fields!(PatternFillInfo, {pattern_type, tile_size, pattern_color, background_color});
5590crate::storage::clone_fields!(GradientFillInfo, {gradient_type, angle, center_x, center_y, colors, positions});