1use 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;
118pub(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#[derive(Debug, Clone, Copy, PartialEq)]
158pub enum RenderBackend {
159 Canvas,
161 Svg,
163 Html,
165}
166
167impl RenderBackend {
168 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#[derive(Debug, Clone, PartialEq, Serialize)]
181pub struct TabStop {
182 pub position: f64,
184 pub tab_type: u8,
186 pub fill_type: u8,
188}
189crate::storage::clone_fields!(TabStop, {position, tab_type, fill_type});
190
191#[derive(Debug, Clone, PartialEq, Serialize)]
193pub struct TabLeaderInfo {
194 pub start_x: f64,
196 pub end_x: f64,
198 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
225pub(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 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 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
286pub(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
329pub(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#[derive(Debug, Clone, PartialEq, Serialize)]
354pub struct TextStyle {
355 #[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 #[serde(skip_serializing_if = "std::ops::Not::not")]
362 pub literal_figure_space: bool,
363 #[serde(skip_serializing_if = "Option::is_none")]
365 pub literal_figure_space_em: Option<f64>,
366 #[serde(skip)]
368 pub script_metrics: script_metrics::ScriptMetricsContract,
369 #[serde(skip)]
371 pub shadow_offset_percent: Option<[i8; 2]>,
372 #[serde(skip)]
374 pub continuous_shadow: Option<crate::paint::text_shadow::ContinuousTextShadow>,
375 #[serde(skip)]
377 pub native_pua_metrics: Option<std::sync::Arc<native_pua_fonts::NativePuaMetrics>>,
378 #[serde(skip)]
380 pub native_otf_metrics: Option<std::sync::Arc<native_pua_fonts::NativeOtfMetrics>>,
381 #[serde(skip_serializing_if = "Option::is_none")]
383 pub bidi_layout: Option<BidiLayout>,
384 pub emphasis_skip_first_cluster: bool,
386 #[serde(skip_serializing_if = "Option::is_none")]
388 pub top_underline_font_size: Option<f64>,
389 #[serde(skip_serializing_if = "Option::is_none")]
391 pub top_underline_phase: Option<f64>,
392 #[serde(skip)]
394 pub supplemental_metrics:
395 Option<std::sync::Arc<supplemental_metrics::SupplementalMetricSnapshot>>,
396 #[serde(skip)]
398 pub isolated_jamo_font: Option<IsolatedJamoFont>,
399 #[serde(skip)]
401 pub space_compression: Option<space_compression::SpaceCompression>,
402 pub font_family: String,
404 pub font_size: f64,
406 #[serde(skip_serializing)]
410 pub fixed_glyph_advances: bool,
411 #[serde(skip_serializing)]
413 pub source_font_is_hft: bool,
414 #[serde(skip_serializing)]
416 pub source_font_is_ttf: bool,
417 #[serde(skip)]
419 pub selected_primary_font_program: Option<font_environment::FontProgramIdentity>,
420 #[serde(skip_serializing)]
422 pub source_verified_hft_bold_tracking: bool,
423 #[serde(skip_serializing)]
425 pub source_hwp3_hft_bold: bool,
426 #[serde(skip_serializing)]
428 pub resolved_font_size: bool,
429 #[serde(skip)]
431 pub print_ink_font_size: Option<f64>,
432 #[serde(skip_serializing_if = "Option::is_none")]
434 pub font_position: Option<i8>,
435 #[serde(skip_serializing)]
437 pub hft_print_frame: bool,
438 #[serde(skip_serializing)]
441 pub print_text_device_frame: bool,
442 #[serde(skip_serializing)]
444 pub preserve_glyph_ink: bool,
445 #[serde(skip)]
447 pub natural_program_metrics: bool,
448 pub color: ColorRef,
450 pub bold: bool,
452 pub italic: bool,
454 pub underline: UnderlineType,
456 pub strikethrough: bool,
458 #[serde(skip_serializing_if = "std::ops::Not::not")]
464 pub kerning: bool,
465 pub letter_spacing: f64,
467 pub ratio: f64,
469 pub default_tab_width: f64,
471 pub tab_stops: Vec<TabStop>,
473 pub auto_tab_right: bool,
475 #[serde(default, skip_serializing_if = "Option::is_none")]
477 pub auto_left_tab_position: Option<f64>,
478 pub available_width: f64,
480 pub line_x_offset: f64,
482 pub text_start_offset: f64,
489 pub right_tab_block_width_override: Option<f64>,
495 pub tab_leaders: Vec<TabLeaderInfo>,
497 pub inline_tabs: Vec<[u16; 7]>,
499 pub extra_word_spacing: f64,
501 #[serde(skip_serializing_if = "has_no_unjustified_leading_spaces")]
504 pub unjustified_leading_spaces: usize,
505 pub extra_char_spacing: f64,
507 pub extra_dash_advance: f64,
511 pub outline_type: u8,
513 pub shadow_type: u8,
515 pub shadow_color: ColorRef,
517 pub shadow_offset_x: f64,
519 pub shadow_offset_y: f64,
521 pub emboss: bool,
523 pub engrave: bool,
525 pub superscript: bool,
527 pub subscript: bool,
529 pub emphasis_dot: u8,
531 pub underline_shape: u8,
533 pub strike_shape: u8,
535 pub underline_color: ColorRef,
537 pub strike_color: ColorRef,
539 pub shade_color: ColorRef,
541 #[serde(skip_serializing)]
546 pub font_metric_trusted: bool,
547 #[serde(skip_serializing)]
549 pub glyph_fallback_advance_explicit: bool,
550 #[serde(skip_serializing)]
559 pub metric_font_family: Option<String>,
560 #[serde(skip_serializing)]
563 pub original_glyph_metric_family: Option<std::sync::Arc<String>>,
564 #[serde(skip_serializing)]
593 pub font_space_em: Option<f64>,
594 #[serde(skip_serializing)]
596 pub inherited_half_space_em: bool,
597 #[serde(skip_serializing)]
599 pub layout_half_space: bool,
600 #[serde(skip_serializing)]
603 pub layout_half_space_em: Option<f64>,
604 #[serde(skip_serializing)]
606 pub regenerated_font_metrics: bool,
607 #[serde(skip_serializing)]
614 pub hft_hangul_face: bool,
615 #[serde(skip_serializing)]
619 pub hft_font_face: bool,
620 #[serde(skip_serializing)]
622 pub hft_fullwidth_dot: bool,
623 #[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#[derive(Debug, Clone, PartialEq)]
636pub struct LatinSlotMetrics {
637 pub font_family: String,
638 pub native_otf_metrics: Option<std::sync::Arc<native_pua_fonts::NativeOtfMetrics>>,
640 pub metric_font_family: Option<String>,
641 pub original_glyph_metric_family: Option<std::sync::Arc<String>>,
644 pub font_metric_trusted: bool,
645 pub source_font_is_hft: bool,
647 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
658pub const SCRIPT_FONT_SCALE: f64 = 0.7;
660pub const SUPERSCRIPT_RISE_EM: f64 = 0.3;
662pub const SUBSCRIPT_DROP_EM: f64 = 0.15;
664
665pub(crate) const HANCOM_FAUX_BOLD_STROKE_EM: f64 = 0.02;
667
668pub(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 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 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 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 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 pub fn script_advance_scale(&self) -> f64 {
752 1.0
753 }
754
755 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 pub fn ratio_draw_params(&self, font_size: f64) -> (f64, f64) {
779 condensed_ratio_draw_params(font_size, self.ratio)
780 }
781
782 pub fn has_horizontal_ratio(&self) -> bool {
785 self.ratio_draw_params(1.0).1 != 1.0
786 }
787
788 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 pub fn is_medium_weight(&self) -> bool {
802 !self.bold && crate::renderer::style_resolver::is_medium_weight_face(&self.font_family)
803 }
804
805 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
819pub 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#[derive(Debug, Clone, Copy, Serialize)]
921pub struct PatternFillInfo {
922 pub pattern_type: i32,
924 pub tile_size: f64,
926 pub pattern_color: ColorRef,
928 pub background_color: ColorRef,
930}
931
932#[derive(Debug, Clone, Serialize)]
934pub struct ShapeStyle {
935 pub fill_color: Option<ColorRef>,
937 pub pattern: Option<PatternFillInfo>,
939 pub stroke_color: Option<ColorRef>,
941 pub stroke_width: f64,
943 pub stroke_dash: StrokeDash,
945 pub opacity: f64,
947 pub shadow: Option<ShadowStyle>,
949}
950
951#[derive(Debug, Clone, Serialize)]
953pub struct ShadowStyle {
954 pub shadow_type: u32,
956 pub color: ColorRef,
958 pub offset_x: f64,
960 pub offset_y: f64,
962 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#[derive(Debug, Clone, Serialize)]
982pub struct GradientFillInfo {
983 pub gradient_type: i16,
985 pub angle: i16,
987 pub center_x: i16,
989 pub center_y: i16,
991 pub colors: Vec<ColorRef>,
996 pub positions: Vec<f64>,
998}
999
1000fn 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 let v = (a + ((b - a) * t).trunc()).clamp(0.0, 255.0) as u32;
1011 out |= v << shift;
1012 }
1013 out
1014}
1015
1016fn 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
1046pub 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 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
1116pub 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
1155pub(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 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
1210pub 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
1221pub 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
1237pub 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#[derive(Debug, Clone, Default, Serialize)]
1260pub struct LineStyle {
1261 pub color: ColorRef,
1263 pub width: f64,
1265 pub dash: StrokeDash,
1267 #[serde(skip_serializing_if = "Option::is_none")]
1270 pub dash_pattern: Option<Vec<f64>>,
1271 pub line_type: LineRenderType,
1273 #[serde(skip_serializing_if = "std::ops::Not::not")]
1276 pub compound_component: bool,
1277 #[serde(skip_serializing_if = "std::ops::Not::not")]
1280 pub preserve_fractional_position: bool,
1281 pub start_arrow: ArrowStyle,
1283 pub end_arrow: ArrowStyle,
1285 pub start_arrow_size: u8,
1287 pub end_arrow_size: u8,
1289 pub shadow: Option<ShadowStyle>,
1291}
1292
1293#[derive(Debug, Clone, Copy, Default, PartialEq, Serialize)]
1295pub enum StrokeDash {
1296 #[default]
1297 Solid,
1298 Dash,
1299 Dot,
1300 DashDot,
1301 DashDotDot,
1302 HwpDash,
1304 HwpDot,
1305 HwpDashDot,
1306 HwpDashDotDot,
1307 HwpLongDash,
1308 HwpCircle,
1309 Explicit([f64; 6]),
1311}
1312
1313#[derive(Debug, Clone, Copy, Default, PartialEq, Serialize)]
1315pub enum LineRenderType {
1316 #[default]
1317 Single,
1318 Double,
1320 ThinThickDouble,
1322 ThickThinDouble,
1324 ThinThickThinTriple,
1326}
1327
1328#[derive(Debug, Clone, Copy, Default, PartialEq, Serialize)]
1330pub enum ArrowStyle {
1331 #[default]
1332 None,
1333 Arrow,
1335 ConcaveArrow,
1337 OpenDiamond,
1339 OpenCircle,
1341 OpenSquare,
1343 Diamond,
1345 Circle,
1347 Square,
1349 OpenArrow,
1351}
1352
1353#[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 ArcTo(f64, f64, f64, bool, bool, f64, f64),
1361 ClosePath,
1362}
1363
1364pub 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 if (x1 - x2).abs() < 1e-6 && (y1 - y2).abs() < 1e-6 {
1386 return result;
1387 }
1388 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 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 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 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 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 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 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 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 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 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 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
1487pub(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 "⚫" => (
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
1516pub trait Renderer {
1518 fn begin_page(&mut self, width: f64, height: f64);
1520 fn end_page(&mut self);
1522
1523 fn draw_text(&mut self, text: &str, x: f64, y: f64, style: &TextStyle);
1525 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 fn draw_rect(&mut self, x: f64, y: f64, w: f64, h: f64, corner_radius: f64, style: &ShapeStyle);
1542 fn draw_line(&mut self, x1: f64, y1: f64, x2: f64, y2: f64, style: &LineStyle);
1544 fn draw_ellipse(&mut self, cx: f64, cy: f64, rx: f64, ry: f64, style: &ShapeStyle);
1546 fn draw_image(&mut self, data: &[u8], x: f64, y: f64, w: f64, h: f64);
1548 fn draw_path(&mut self, commands: &[PathCommand], style: &ShapeStyle);
1550}
1551
1552pub const DEFAULT_DPI: f64 = 96.0;
1554pub const HWPUNIT_PER_INCH: f64 = 7200.0;
1555
1556#[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#[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 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#[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
1636pub(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 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
1683pub(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
1730pub(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
1746pub(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
1751pub(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#[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#[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#[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#[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
1849pub(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(¶.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
1893pub(crate) use stored_line_ladder::stored_line_ladder_is_uniform_filler;
1909
1910#[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#[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#[inline]
1972pub(crate) fn hwp3_variant_flow_spacing_before(base: f64, _is_hwp3_variant: bool) -> f64 {
1973 base
1974}
1975
1976pub(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
2002pub(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
2022pub(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#[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
2045pub(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
2055pub(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
2065pub(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
2084pub(crate) struct TacHostControlOnlyTail<'a> {
2086 pub lines: &'a [crate::model::paragraph::LineSeg],
2088 pub same_frame: bool,
2090}
2091
2092pub(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 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
2142pub(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
2180pub(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
2195pub(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 Control::SectionDef(_)
2212 | Control::ColumnDef(_)
2213 | Control::Header(_)
2214 | Control::Footer(_) => true,
2215 _ => false,
2216 })
2217}
2218
2219pub(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
2242pub(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
2284pub(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 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
2385fn 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
2403pub(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#[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 seg.tag & crate::model::paragraph::LineSeg::TAG_IMPLEMENTATION_PROPERTY == 0
2434 && (cell_para_index == 0 || seg.vertical_pos > 0)
2435 })
2436}
2437
2438#[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#[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
2465pub(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
2491pub(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
2546pub(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#[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 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
2636pub(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
2658pub(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
2711pub(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
2790pub(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
2829pub(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
2866pub(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 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#[inline]
2922pub fn hwpunit_to_px(hwpunit: i32, dpi: f64) -> f64 {
2923 hwpunit as f64 * dpi / HWPUNIT_PER_INCH
2924}
2925
2926pub(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
2939pub(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 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
2980pub(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
2998pub(crate) fn multicol_band_break_pad_px(dpi: f64) -> f64 {
3000 hwpunit_to_px(1500, dpi)
3001}
3002
3003pub(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
3031pub(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
3070pub(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
3101pub(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
3146pub(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
3200pub(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
3207pub(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#[inline]
3223pub fn px_to_hwpunit(px: f64, dpi: f64) -> i32 {
3224 physical_units::px_to_hwpunit(px, dpi)
3225}
3226
3227#[inline]
3235pub fn tac_table_effective_height(seg_lh: f64, mt_h: f64) -> f64 {
3236 seg_lh.max(mt_h)
3237}
3238
3239pub(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
3282pub(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
3323pub(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
3395pub(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 ¶.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
3448pub(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
3462pub(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
3483pub(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 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
3564pub fn base_family_without_weight_suffix(font_family: &str) -> Option<String> {
3573 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
3609fn installed_font_program_aliases(name: &str) -> &'static [&'static str] {
3620 match name {
3621 "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 "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 "한양중고딕" => &["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 "돋움" => &["Dotum"],
3694 "Dotum" => &["돋움"],
3695 "돋움체" => &["DotumChe"],
3699 "DotumChe" => &["돋움체"],
3700 "나눔고딕" => &["NanumGothic"],
3701 "NanumGothic" => &["나눔고딕"],
3702 "한컴바탕" => &["Haansoft Batang"],
3703 "HCRBatang" => &["HCR Batang"],
3705 "HCRDotum" => &["HCR Dotum"],
3706 "굴림" => &["Gulim"],
3708 "굴림체" => &["GulimChe"],
3709 "바탕" => &["Batang"],
3710 "바탕체" => &["BatangChe"],
3711 "한양중고딕" => &[
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 "한양견고딕" => &["HY견고딕", "HYGothic-Extra", "HCR Dotum", "함초롬돋움"],
3745 "한양견명조" => &["HY견명조", "HYMyeongJo-Extra", "HCR Batang", "함초롬바탕"],
3746 "한양신명조" => &["HYSinMyeongJo", "HY신명조", "HYSinMyeongJo-Medium"],
3757 "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 "한컴 윤고딕 250" => &["Haan YGodic 250"],
3792 "정부상징 부처명_16040911" | "Government_16040911" => &[
3795 "ROKG",
3796 "ROKG R",
3797 "대한민국정부상징체",
3798 "대한민국정부상징체 R",
3799 "ROKGR",
3800 ],
3801 _ => &[],
3802 }
3803}
3804
3805pub(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
3842fn css_single_quoted_font_family(font_family: &str) -> String {
3847 let escaped = font_family.replace('\\', "\\\\").replace('\'', "\\'");
3848 format!("'{escaped}'")
3849}
3850
3851pub(crate) const NOTO_SANS_KR_EXTRALIGHT: &str = "Noto Sans KR ExtraLight";
3853
3854pub(crate) fn drop_noto_sans_kr_extralight(chain: &str) -> String {
3860 let quoted = [
3861 format!("'{NOTO_SANS_KR_EXTRALIGHT}',"),
3862 format!("'{NOTO_SANS_KR_EXTRALIGHT}',"),
3863 format!("\"{NOTO_SANS_KR_EXTRALIGHT}\","),
3864 format!("'{NOTO_SANS_KR_EXTRALIGHT}'"),
3865 format!("'{NOTO_SANS_KR_EXTRALIGHT}'"),
3866 format!("\"{NOTO_SANS_KR_EXTRALIGHT}\""),
3867 ];
3868 let mut out = chain.to_string();
3869 for token in "ed {
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
3879pub fn render_font_family_chain(font_family: &str) -> String {
3882 render_font_family_chain_for_weight(font_family, false)
3883}
3884
3885pub 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
3900pub(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
3934pub fn canvas_font_family_chain(font_family: &str) -> String {
3940 canvas_font_family_chain_for_selection(font_family, false)
3941}
3942
3943pub(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
3991pub(crate) fn boxed_pua_number(ch: char) -> Option<u32> {
3996 let code_point = ch as u32;
3997 (0xF02B0..=0xF02C4)
3999 .contains(&code_point)
4000 .then(|| code_point - 0xF02B0)
4001}
4002
4003#[derive(Clone, Copy, Debug, PartialEq, Eq)]
4008pub(crate) enum EnclosedPua {
4009 BoxedNumber(u32),
4011 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 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 pub(crate) fn width_source(self) -> &'static str {
4033 match self {
4034 EnclosedPua::BoxedNumber(_) => "boxedPuaFullwidth",
4035 EnclosedPua::CircledSeal => "circledSealPuaFullwidth",
4036 }
4037 }
4038}
4039
4040pub(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
4061use crate::model::control::AutoNumberType;
4066
4067#[derive(Debug, Clone, Default)]
4071pub struct AutoNumberCounter {
4072 pub picture: u16,
4074 pub table: u16,
4076 pub equation: u16,
4078 pub footnote: u16,
4080 pub endnote: u16,
4082 pub page: u16,
4084}
4085
4086impl AutoNumberCounter {
4087 pub fn new() -> Self {
4089 Self::default()
4090 }
4091
4092 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 AutoNumberType::TotalPage => 0,
4122 }
4123 }
4124
4125 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 pub fn reset(&mut self) {
4140 *self = Self::default();
4141 }
4142}
4143
4144#[derive(Debug, Clone, Copy, Default, PartialEq)]
4146pub enum NumberFormat {
4147 #[default]
4149 Digit,
4150 CircledDigit,
4152 RomanUpper,
4154 RomanLower,
4156 LatinUpper,
4158 LatinLower,
4160 CircledLatinUpper,
4162 CircledLatinLower,
4164 HangulGaNaDa,
4166 CircledHangulGaNaDa,
4168 HangulJamo,
4170 CircledHangulJamo,
4172 HangulNumber,
4174 HanjaNumber,
4176 CircledHanjaNumber,
4178 HangulGapEul,
4180 HanjaGapEul,
4182 FourSymbol,
4184}
4185
4186impl NumberFormat {
4187 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
4213pub 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 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
4278fn 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
4286fn 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
4317fn format_hangul_ganada(n: u16) -> String {
4320 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
4333fn 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
4377fn 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
4421pub(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 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 = ¶.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
4463pub(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 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
4502pub(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
4530pub(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
4577pub(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 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 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 assert_eq!(
4764 canvas_cluster_fit(&style, "1", 8.0, 4.0, Some(2.0), true),
4765 Some((1.0, 2.0))
4766 );
4767 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 assert_eq!(
4780 canvas_cluster_fit(&style, "•", 6.0, 16.0, Some(4.0), false),
4781 Some((1.0, -5.0))
4782 );
4783 assert_eq!(
4785 canvas_cluster_fit(&style, "μ", 6.0, 16.0, Some(8.0), false),
4786 Some((0.75, -3.0))
4787 );
4788 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 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 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 assert_eq!(style.script_draw_metrics(20.0, 0.0).0, 20.0 * 0.7);
4877 }
4878 }
4879
4880 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 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 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(¶, 96.0, Some(661.0), &styles, Some(¶_style))
4930 .unwrap();
4931 assert_eq!(lines.len(), 1);
4932 assert!((lines[0].0 - hwpunit_to_px(29069, 96.0)).abs() < 0.01);
4933 assert_eq!(lines[0].1, 0.0);
4935
4936 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(¶_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 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 ¶_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 let no_style =
4963 tac_object_stack_line_metrics(¶_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 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(¶, 96.0, Some(661.0), &styles, Some(¶_style))
4974 .unwrap();
4975 assert_eq!(lines.len(), 3);
4976 assert!(lines.iter().all(|(_, ls)| (ls - 10.0).abs() < 0.01));
4978 let para2 = tac_picture_para(&[(22000, 10000), (22000, 12000)]);
4980 let lines2 =
4981 tac_object_stack_line_metrics(¶2, 96.0, Some(661.0), &styles, Some(¶_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 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 ¶,
4996 96.0,
4997 Some(661.0),
4998 &styles,
4999 Some(¶_style)
5000 )
5001 .is_none());
5002 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 ¶2,
5009 96.0,
5010 Some(661.0),
5011 &styles,
5012 Some(¶_style)
5013 )
5014 .is_none());
5015 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(¶3, &styles, Some(¶_style)),
5025 0.0
5026 );
5027 let synth =
5028 tac_object_stack_line_metrics(¶3, 96.0, Some(661.0), &styles, Some(¶_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 #[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 assert_eq!(text_anchor_square_table_strip(¶), Some((45568, 2620)));
5134 }
5135
5136 #[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 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(¶), None);
5159
5160 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(¶2), None);
5170
5171 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(¶3), 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 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 assert_eq!(format_number(27, NumberFormat::LatinUpper), "A");
5227 assert_eq!(format_number(1, NumberFormat::LatinLower), "a");
5228 }
5229
5230 #[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 assert_eq!(
5247 base_family_without_weight_suffix("Noto Sans KR Extra Bold").as_deref(),
5248 Some("Noto Sans KR")
5249 );
5250 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 assert_eq!(base_family_without_weight_suffix("Light"), None);
5256 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 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 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 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 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 assert!(sans.contains("'Noto Sans KR ExtraLight','Noto Sans KR'"));
5355 for chain in [serif, sans] {
5358 assert!(
5359 !chain.contains("Ext-B"),
5360 "죽은 하이픈 표기가 되살아났다: {chain}"
5361 );
5362 assert!(chain.contains("'HCR Batang ExtB'"));
5363 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 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 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 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 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 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 assert_eq!(generic_fallback("Liberation Sans"), sans);
5407 assert_eq!(generic_fallback("Noto Sans KR"), sans);
5408 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 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 #[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 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});