use super::super::font_metrics_data;
use super::super::kerning::{ExactFontSourceHandle, KerningRunMeasurement, KerningSourceSession};
use super::super::style_resolver::{ResolvedCharStyle, ResolvedStyleSet};
use super::super::{TabLeaderInfo, TabStop, TextStyle};
mod inline_right_tab;
mod kopub_cjk_coverage;
mod kopub_symbol_advances;
pub trait TextMeasurer {
fn estimate_text_width(&self, text: &str, style: &TextStyle) -> f64;
fn compute_char_positions(&self, text: &str, style: &TextStyle) -> Vec<f64>;
}
pub(super) use super::super::conjoining_jamo::cluster_lengths as build_cluster_len;
use super::super::conjoining_jamo::{is_hangul_choseong, is_hangul_jongseong, is_hangul_jungseong};
pub(crate) fn build_cluster_len_with_storage<S: crate::storage::Storage>(
chars: &[char],
storage: &S,
) -> Result<Vec<u8>, S::Error> {
storage.bytes(chars.len())?;
Ok(build_cluster_len(chars))
}
#[inline]
fn glyph_letter_spacing(letter_spacing_px: f64, glyph_base_px: f64, font_size: f64) -> f64 {
if font_size <= 0.0 {
return letter_spacing_px;
}
letter_spacing_px * (glyph_base_px / font_size)
}
const HANCOM_DEVICE_UNIT_HU: f64 = 4.0;
fn hancom_device_advance_px(
em_fraction: f64,
font_size: f64,
ratio: f64,
spacing_fraction: f64,
is_space: bool,
) -> f64 {
const EPS: f64 = 1e-6;
if font_size <= 0.0 || em_fraction <= 0.0 {
return 0.0;
}
let ppem = (font_size * 75.0 / HANCOM_DEVICE_UNIT_HU + EPS).floor();
let advance_units = if is_space {
let base_units = (em_fraction * ppem + EPS).floor();
if (ratio - 1.0).abs() <= EPS {
base_units
} else {
(base_units * ratio + 0.5 + EPS).floor()
}
} else if (ratio - 1.0).abs() <= EPS {
(em_fraction * ppem + 0.5 + EPS).floor()
} else {
(em_fraction * ppem * ratio + EPS).floor()
};
let spacing = spacing_fraction * advance_units;
let spacing_units = spacing.signum() * (spacing.abs() + 0.5 + EPS).floor();
(advance_units + spacing_units) * HANCOM_DEVICE_UNIT_HU / 75.0
}
fn style_params(style: &TextStyle) -> (f64, f64, f64) {
let base_font_size = style.effective_font_size();
let font_size = style.script_font_size(base_font_size);
let ratio = if style.ratio > 0.0 { style.ratio } else { 1.0 };
let tab_w = if style.default_tab_width > 0.0 {
style.default_tab_width
} else {
base_font_size * 4.0
};
(font_size, ratio, tab_w)
}
fn reflow_space_font_size(style: &TextStyle) -> f64 {
let size = style.effective_font_size();
if style.font_space_em.is_none() {
if let Some(em) = style.layout_half_space_em {
return size * 2.0 * em;
}
}
size
}
#[inline]
pub(super) fn inline_tab_type(ext: &[u16; 7]) -> u8 {
((ext[2] >> 8) & 0xFF) as u8
}
pub(crate) fn find_next_tab_stop(
abs_x: f64,
tab_stops: &[TabStop],
default_tab_width: f64,
auto_tab_right: bool,
available_width: f64,
text_start_offset: f64,
) -> (f64, u8, u8) {
let right_edge = text_start_offset + available_width;
for ts in tab_stops {
let pos = if ts.tab_type == 1 && available_width > 0.0 && ts.position > right_edge {
right_edge
} else if ts.tab_type != 1 && ts.position > available_width && available_width > 0.0 {
available_width
} else {
ts.position
};
if pos > abs_x + 0.5 {
return (pos, ts.tab_type, ts.fill_type);
}
}
if auto_tab_right && available_width > 0.0 && right_edge > abs_x + 0.5 {
return (right_edge, 1, 0); }
let tab_w = if default_tab_width > 0.0 {
default_tab_width
} else {
48.0
};
let next = ((abs_x / tab_w).floor() + 1.0) * tab_w;
(next, 0, 0) }
fn measure_segment_from(
chars: &[char],
cluster_len: &[u8],
start: usize,
char_width: &dyn Fn(usize) -> f64,
) -> f64 {
let mut w = 0.0;
for i in start..chars.len() {
if chars[i] == '\t' {
break;
}
if cluster_len[i] == 0 {
continue;
}
w += char_width(i);
}
w
}
fn tab_suffix_is_ascii_page_number(chars: &[char], start: usize) -> bool {
let mut seen_digit = false;
for ch in chars.iter().skip(start) {
if *ch == '\t' {
return false;
}
if ch.is_whitespace() {
continue;
}
if ch.is_ascii_digit() {
seen_digit = true;
continue;
}
return false;
}
seen_digit
}
fn right_leader_tab_target_rel(style: &TextStyle) -> Option<f64> {
super::leader_tab::right_aligned_target(style, !style.inline_tabs.is_empty())
.map(|target| target - style.line_x_offset)
}
fn right_leader_tab_fill(style: &TextStyle) -> Option<u8> {
style
.tab_stops
.iter()
.rev()
.find(|tab| tab.tab_type == 1 && tab.fill_type != 0)
.map(|tab| tab.fill_type)
}
pub fn extract_tab_leaders(text: &str, positions: &[f64], style: &TextStyle) -> Vec<TabLeaderInfo> {
extract_tab_leaders_with_extended(text, positions, style, &[])
}
pub const TAB_LEADER_HEAD_GAP_EM: f64 = 0.25;
pub fn extract_tab_leaders_with_extended(
text: &str,
positions: &[f64],
style: &TextStyle,
tab_extended: &[[u16; 7]],
) -> Vec<TabLeaderInfo> {
let chars: Vec<char> = text.chars().collect();
let tab_w = if style.default_tab_width > 0.0 {
style.default_tab_width
} else {
48.0
};
let mut leaders = Vec::new();
let mut tab_idx = 0usize; for (i, c) in text.chars().enumerate() {
if c == '\t' && i + 1 < positions.len() {
let before_x = positions[i];
let after_x = positions[i + 1];
let has_more_tabs_after = chars.iter().skip(i + 1).any(|ch| *ch == '\t');
let tabdef_page_number_fill = if tab_extended.is_empty()
&& !has_more_tabs_after
&& tab_suffix_is_ascii_page_number(&chars, i + 1)
{
right_leader_tab_fill(style)
} else {
None
};
let ext_fill = if tab_idx < tab_extended.len() {
(tab_extended[tab_idx][2] & 0x00FF) as u8
} else {
0
};
let tabdef_fill = if let Some(fill) = tabdef_page_number_fill {
fill
} else if !style.tab_stops.is_empty() || style.auto_tab_right {
let abs_before = style.line_x_offset + before_x;
let (_, _, ft) = find_next_tab_stop(
abs_before,
&style.tab_stops,
tab_w,
style.auto_tab_right,
style.available_width,
style.text_start_offset,
);
ft
} else {
0
};
let fill_type = if ext_fill > 0 { ext_fill } else { tabdef_fill };
if fill_type > 0 && after_x > before_x + 1.0 {
let head_gap = style.font_size * TAB_LEADER_HEAD_GAP_EM;
let space_gap = style.font_size * 0.25;
let content_x = text.chars().enumerate().skip(i + 1).find_map(|(j, ch)| {
if ch != '\t' && !ch.is_whitespace() && j < positions.len() {
Some(positions[j])
} else {
None
}
});
let end_x = content_x
.map(|x| x - space_gap)
.unwrap_or(after_x - space_gap)
.min(after_x - space_gap);
let start_x = (before_x + head_gap).min(after_x);
leaders.push(TabLeaderInfo {
start_x,
end_x: end_x.max(start_x),
fill_type,
});
}
tab_idx += 1;
}
}
if leaders.len() > 1 {
let mut min_following_end = f64::INFINITY;
for leader in leaders.iter_mut().rev() {
if min_following_end.is_finite() && leader.end_x > min_following_end {
leader.end_x = min_following_end.max(leader.start_x);
}
min_following_end = min_following_end.min(leader.end_x);
}
}
leaders
}
fn compute_char_positions_walk(
text: &str,
style: &TextStyle,
include_hft_bold_tracking: bool,
inline_tab_x: &dyn Fn(usize, f64, &[u16; 7], &[char], &[u8], &dyn Fn(usize) -> f64) -> f64,
) -> Vec<f64> {
let (_, _, tab_w) = style_params(style);
let chars: Vec<char> = text.chars().collect();
let char_count = chars.len();
let mut positions = Vec::with_capacity(char_count + 1);
let mut x = 0.0;
positions.push(x);
let cluster_len = build_cluster_len(&chars);
let has_custom_tabs = !style.tab_stops.is_empty() || style.auto_tab_right;
let supplemental = super::super::supplemental_metrics::standalone_scalar_mask(text, style);
let contextual = super::super::arabic_context::advances(&chars, style);
let char_width = |i: usize| -> f64 {
char_width_decision_with_hft_tracking(
&chars,
&cluster_len,
i,
style,
supplemental.as_ref().is_some_and(|mask| mask[i]),
include_hft_bold_tracking,
contextual.as_ref().and_then(|widths| widths[i]),
)
.final_width_px
};
let mut tab_char_idx = 0usize; for i in 0..char_count {
let c = chars[i];
if cluster_len[i] == 0 {
positions.push(x);
continue;
}
if c == '\t' {
if let Some(position) = style
.auto_left_tab_position
.filter(|position| *position > style.line_x_offset + x)
{
x = position - style.line_x_offset;
tab_char_idx += 1;
positions.push(x);
continue;
}
let stored_ext = style
.inline_tabs
.get(tab_char_idx)
.filter(|ext| !crate::model::paragraph::tab_ext_is_placeholder(ext));
if let Some(ext) = stored_ext {
x = inline_tab_x(i, x, ext, &chars, &cluster_len, &char_width);
tab_char_idx += 1;
} else if has_custom_tabs {
let has_more_tabs_after = chars[i + 1..].contains(&'\t');
let abs_x = style.line_x_offset + x;
let (tab_pos, tab_type, fill_type) = find_next_tab_stop(
abs_x,
&style.tab_stops,
tab_w,
style.auto_tab_right,
style.available_width,
style.text_start_offset,
);
let rel_tab = tab_pos - style.line_x_offset;
match tab_type {
1 => {
let seg_start = if fill_type != 0 {
i + 1
} else {
let mut s = i + 1;
while s < chars.len() && chars[s] == ' ' && cluster_len[s] != 0 {
s += 1;
}
s
};
let seg_w = if !has_more_tabs_after {
style.right_tab_block_width_override.unwrap_or_else(|| {
measure_segment_from(&chars, &cluster_len, seg_start, &char_width)
})
} else {
measure_segment_from(&chars, &cluster_len, seg_start, &char_width)
};
x = (rel_tab - seg_w).max(x);
}
2 => {
let seg_w = measure_segment_from(&chars, &cluster_len, i + 1, &char_width);
x = (rel_tab - seg_w / 2.0).max(x);
}
_ => {
x = rel_tab.max(x);
}
}
tab_char_idx += 1;
} else {
let abs_x = style.line_x_offset + x;
if tab_w > 0.0 {
let next_abs = ((abs_x / tab_w).floor() + 1.0) * tab_w;
x = (next_abs - style.line_x_offset).max(x);
}
tab_char_idx += 1;
}
positions.push(x);
continue;
}
x += char_width(i);
positions.push(x);
}
positions
}
pub struct EmbeddedTextMeasurer;
impl EmbeddedTextMeasurer {
fn estimate_text_width_exact(&self, text: &str, style: &TextStyle) -> f64 {
match self.estimate_text_width_exact_with_storage(text, style, &crate::storage::Unbounded) {
Ok(value) => value,
Err(never) => match never {},
}
}
pub(crate) fn estimate_text_width_exact_with_storage<S: crate::storage::Storage>(
&self,
text: &str,
style: &TextStyle,
storage: &S,
) -> Result<f64, S::Error> {
Ok({
let (font_size, _, tab_w) = style_params(style);
let chars: Vec<char> = storage.collect(text.chars())?;
let cluster_len = build_cluster_len_with_storage(&chars, storage)?;
let char_count = chars.len();
let has_custom_tabs = !style.tab_stops.is_empty() || style.auto_tab_right;
let supplemental =
super::super::supplemental_metrics::standalone_scalar_mask_with_storage(
text, style, storage,
)?;
let contextual =
super::super::arabic_context::advances_with_storage(&chars, style, storage)?;
let char_width = |i: usize| -> f64 {
char_width_decision_with_hft_tracking(
&chars,
&cluster_len,
i,
style,
supplemental.as_ref().is_some_and(|mask| mask[i]),
true,
contextual.as_ref().and_then(|widths| widths[i]),
)
.final_width_px
};
let mut total = 0.0;
let mut tab_char_idx = 0usize;
for i in 0..char_count {
let c = chars[i];
if cluster_len[i] == 0 {
continue;
}
if c == '\t' {
if let Some(position) = style
.auto_left_tab_position
.filter(|position| *position > style.line_x_offset + total)
{
total = position - style.line_x_offset;
tab_char_idx += 1;
continue;
}
let stored_ext = style
.inline_tabs
.get(tab_char_idx)
.filter(|ext| !crate::model::paragraph::tab_ext_is_placeholder(ext));
if let Some(ext) = stored_ext {
let tab_width_px = ext[0] as f64 * 96.0 / 7200.0;
let tab_type = ext[2];
let tab_target = total + tab_width_px;
let has_more_tabs_after = chars[i + 1..].contains(&'\t');
let inline_type_hi = ((tab_type >> 8) & 0xFF) as u8;
let inline_is_explicit_left = inline_type_hi == 1 || inline_type_hi == 4;
let override_to_right = style.auto_tab_right
&& !has_more_tabs_after
&& style.available_width > 0.0
&& !inline_is_explicit_left;
if override_to_right {
let seg_w = style.right_tab_block_width_override.unwrap_or_else(|| {
measure_segment_from(&chars, &cluster_len, i + 1, &char_width)
});
total =
inline_right_tab::text_start(style, total, tab_target, seg_w, ext);
} else if inline_type_hi == 0
&& !has_more_tabs_after
&& (tab_suffix_is_ascii_page_number(&chars, i + 1)
|| style.right_tab_block_width_override.is_some())
{
if let Some(target_rel) = right_leader_tab_target_rel(style) {
let seg_w =
measure_segment_from(&chars, &cluster_len, i + 1, &char_width);
total = (target_rel - seg_w).max(total);
} else {
total = tab_target.max(total);
}
} else {
match tab_type {
_ if inline_type_hi == 2
&& (tab_type & 0xff) != 0
&& chars[i + 1..].iter().any(|ch| !ch.is_whitespace()) =>
{
let seg_w = measure_segment_from(
&chars,
&cluster_len,
i + 1,
&char_width,
);
total = inline_right_tab::text_start(
style, total, tab_target, seg_w, ext,
);
}
1 => {
let seg_w = measure_segment_from(
&chars,
&cluster_len,
i + 1,
&char_width,
);
total = (tab_target - seg_w).max(total);
}
2 => {
let seg_w = measure_segment_from(
&chars,
&cluster_len,
i + 1,
&char_width,
);
total = (tab_target - seg_w / 2.0).max(total);
}
_ => {
total = tab_target.max(total);
}
}
}
tab_char_idx += 1;
} else if has_custom_tabs {
let has_more_tabs_after = chars[i + 1..].contains(&'\t');
let abs_x = style.line_x_offset + total;
let (tab_pos, tab_type, _) = find_next_tab_stop(
abs_x,
&style.tab_stops,
tab_w,
style.auto_tab_right,
style.available_width,
style.text_start_offset,
);
let rel_tab = tab_pos - style.line_x_offset;
match tab_type {
1 => {
let seg_w = if !has_more_tabs_after {
style.right_tab_block_width_override.unwrap_or_else(|| {
measure_segment_from(
&chars,
&cluster_len,
i + 1,
&char_width,
)
})
} else {
measure_segment_from(&chars, &cluster_len, i + 1, &char_width)
};
total = (rel_tab - seg_w).max(total);
}
2 => {
let seg_w =
measure_segment_from(&chars, &cluster_len, i + 1, &char_width);
total = (rel_tab - seg_w / 2.0).max(total);
}
_ => {
total = rel_tab.max(total);
}
}
tab_char_idx += 1;
} else {
let abs_x = style.line_x_offset + total;
if tab_w > 0.0 {
let next_abs = ((abs_x / tab_w).floor() + 1.0) * tab_w;
total = (next_abs - style.line_x_offset).max(total);
}
tab_char_idx += 1;
}
continue;
}
if cluster_len[i] == 0 {
continue;
}
total += char_width(i);
}
total
})
}
}
impl TextMeasurer for EmbeddedTextMeasurer {
fn estimate_text_width(&self, text: &str, style: &TextStyle) -> f64 {
self.estimate_text_width_exact(text, style).round()
}
fn compute_char_positions(&self, text: &str, style: &TextStyle) -> Vec<f64> {
self.compute_char_positions_with_hft_tracking(text, style, true)
}
}
impl EmbeddedTextMeasurer {
fn compute_char_positions_with_hft_tracking(
&self,
text: &str,
style: &TextStyle,
include_hft_bold_tracking: bool,
) -> Vec<f64> {
let inline_tab_x = |i: usize,
x_in: f64,
ext: &[u16; 7],
chars: &[char],
cluster_len: &[u8],
char_width: &dyn Fn(usize) -> f64|
-> f64 {
let mut x = x_in;
let tab_width_px = ext[0] as f64 * 96.0 / 7200.0;
let tab_type_raw = ext[2];
let tab_target = x + tab_width_px;
let has_more_tabs_after = chars[i + 1..].contains(&'\t');
let inline_type_hi = ((tab_type_raw >> 8) & 0xFF) as u8;
let inline_is_explicit_left = inline_type_hi == 1 || inline_type_hi == 4;
let override_to_right = style.auto_tab_right
&& !has_more_tabs_after
&& style.available_width > 0.0
&& !inline_is_explicit_left;
let body_right_legacy = if style.available_width > 0.0 {
style.available_width - style.line_x_offset
} else {
f64::INFINITY
};
if override_to_right {
let seg_w = if let Some(w) = style.right_tab_block_width_override {
w
} else {
let seg_start = {
let mut s = i + 1;
while s < chars.len() && chars[s] == ' ' && cluster_len[s] != 0 {
s += 1;
}
s
};
measure_segment_from(&chars, &cluster_len, seg_start, &char_width)
};
x = inline_right_tab::text_start(style, x, tab_target, seg_w, ext);
} else if inline_type_hi == 0
&& !has_more_tabs_after
&& (tab_suffix_is_ascii_page_number(&chars, i + 1)
|| style.right_tab_block_width_override.is_some())
{
if let Some(target_rel) = right_leader_tab_target_rel(style) {
let seg_w = style.right_tab_block_width_override.unwrap_or_else(|| {
measure_segment_from(&chars, &cluster_len, i + 1, &char_width)
});
x = (target_rel - seg_w).max(x);
} else {
x = tab_target.max(x);
}
} else {
let high_byte = (tab_type_raw >> 8) & 0xFF;
let fill_low = tab_type_raw & 0xFF;
match (high_byte, tab_type_raw) {
(_, 1) => {
let seg_start = {
let mut s = i + 1;
while s < chars.len() && chars[s] == ' ' && cluster_len[s] != 0 {
s += 1;
}
s
};
let seg_w =
measure_segment_from(&chars, &cluster_len, seg_start, &char_width);
x = (tab_target - seg_w).max(x);
}
(_, 2) => {
let seg_w = measure_segment_from(&chars, &cluster_len, i + 1, &char_width);
x = (tab_target - seg_w / 2.0).max(x);
}
(2, _) if fill_low != 0 => {
let seg_start_skipped = {
let mut s = i + 1;
while s < chars.len() && chars[s] == ' ' && cluster_len[s] != 0 {
s += 1;
}
s
};
let has_content_after = seg_start_skipped < chars.len();
if has_content_after {
let seg_w_full =
measure_segment_from(&chars, &cluster_len, i + 1, &char_width);
x = inline_right_tab::text_start(style, x, tab_target, seg_w_full, ext);
} else {
let seg_w = measure_segment_from(
&chars,
&cluster_len,
seg_start_skipped,
&char_width,
);
x = (body_right_legacy - seg_w).max(x);
}
}
(2, _) if has_more_tabs_after => {
x = tab_target.max(x);
}
(2, _) => {
let seg_start = {
let mut s = i + 1;
while s < chars.len() && chars[s] == ' ' && cluster_len[s] != 0 {
s += 1;
}
s
};
let seg_w =
measure_segment_from(&chars, &cluster_len, seg_start, &char_width);
x = (body_right_legacy - seg_w).max(x);
}
_ => {
x = tab_target.max(x);
}
}
}
x
};
compute_char_positions_walk(text, style, include_hft_bold_tracking, &inline_tab_x)
}
}
fn default_measurer() -> EmbeddedTextMeasurer {
EmbeddedTextMeasurer
}
pub(crate) fn resolved_to_text_style(styles: &ResolvedStyleSet, id: u32, lang: usize) -> TextStyle {
match try_resolved_to_text_style(
styles,
id,
lang,
&crate::renderer::style_resolver::storage::Unbounded,
) {
Ok(style) => style,
Err(never) => match never {},
}
}
fn try_original_metric_family<S: crate::renderer::style_resolver::storage::Storage>(
face: Option<&str>,
storage: &S,
) -> Result<Option<std::sync::Arc<String>>, S::Error> {
face.map(|face| {
storage.bytes(2 * std::mem::size_of::<usize>() + std::mem::size_of::<String>())?;
Ok(std::sync::Arc::new(storage.string(face)?))
})
.transpose()
}
pub(crate) fn try_resolved_to_text_style<S: crate::renderer::style_resolver::storage::Storage>(
styles: &ResolvedStyleSet,
char_style_id: u32,
lang_index: usize,
storage: &S,
) -> Result<TextStyle, S::Error> {
try_char_style_to_text_style(
styles,
styles.char_styles.get(char_style_id as usize),
char_style_id,
lang_index,
storage,
)
}
pub(crate) fn char_style_to_text_style(
styles: &ResolvedStyleSet,
char_style: &ResolvedCharStyle,
char_style_id: u32,
lang_index: usize,
) -> TextStyle {
match try_char_style_to_text_style(
styles,
Some(char_style),
char_style_id,
lang_index,
&crate::renderer::style_resolver::storage::Unbounded,
) {
Ok(style) => style,
Err(never) => match never {},
}
}
fn try_char_style_to_text_style<S: crate::renderer::style_resolver::storage::Storage>(
styles: &ResolvedStyleSet,
char_style: Option<&ResolvedCharStyle>,
char_style_id: u32,
lang_index: usize,
storage: &S,
) -> Result<TextStyle, S::Error> {
if let Some(cs) = char_style {
Ok(TextStyle {
print_ink_font_size: None,
script_metrics: styles.script_metrics,
native_pua_metrics: (!styles.has_exact_font_source(char_style_id, lang_index))
.then(|| {
styles.native_pua_fonts.get_for_source(
cs.font_family_for_lang(lang_index),
cs.bold,
cs.italic,
cs.source_ttf_for_lang(lang_index),
)
})
.flatten(),
native_otf_metrics: (!styles.has_exact_font_source(char_style_id, lang_index)
&& styles.allows_native_otf_metrics(char_style_id, lang_index))
.then(|| {
styles.native_pua_fonts.get_otf_for_source(
cs.font_family_for_lang(lang_index),
cs.bold,
cs.italic,
styles.native_otf_metrics_source_ttf(char_style_id, lang_index),
)
})
.flatten(),
bidi_layout: None,
emphasis_skip_first_cluster: false,
top_underline_font_size: None,
top_underline_phase: None,
fixed_glyph_advances: false,
source_font_is_hft: cs.source_hft_for_lang(lang_index),
source_font_is_ttf: cs.source_ttf_for_lang(lang_index),
selected_primary_font_program: cs
.font_families_primary_program
.get(lang_index)
.copied()
.flatten(),
source_verified_hft_bold_tracking: cs.verified_hft_bold_tracking_for_lang(lang_index),
source_hwp3_hft_bold: (styles.hwp3_variant || styles.source_hwp3_native)
&& cs.source_hft_for_lang(lang_index),
hft_print_frame: cs.hft_print_frame_for_lang(lang_index),
print_text_device_frame: cs.print_text_device_frame_for_lang(lang_index),
preserve_glyph_ink: cs
.font_families_preserve_glyph_ink
.get(lang_index)
.copied()
.unwrap_or(false),
natural_program_metrics: cs
.font_families_natural_program_metrics
.get(lang_index)
.copied()
.unwrap_or(false),
isolated_jamo_font: styles.isolated_jamo_font.or_else(|| {
matches!(
cs.font_family_for_lang(lang_index)
.split(',')
.next()
.map(str::trim),
Some("HCR Dotum" | "HCRDotum" | "함초롬돋움")
)
.then_some(crate::renderer::IsolatedJamoFont::HcrDotum)
}),
font_family: storage.string(cs.font_family_for_lang(lang_index))?,
supplemental_metrics: styles.supplemental_metrics.clone(),
space_compression: None,
font_metric_trusted: cs.font_metric_trusted_for_lang(lang_index),
glyph_fallback_advance_explicit: cs
.glyph_fallback_advance_explicit_for_lang(lang_index),
metric_font_family: cs
.metric_face_for_lang(lang_index)
.map(|face| storage.string(face))
.transpose()?,
original_glyph_metric_family: try_original_metric_family(
cs.original_glyph_metric_face_for_lang(lang_index),
storage,
)?,
font_space_em: cs.font_space_em,
inherited_half_space_em: false,
layout_half_space: false,
layout_half_space_em: {
let effective_ratio = |ratio: f64| if ratio > 0.0 { ratio } else { 1.0 };
let current_em = cs.font_size_for_lang(lang_index)
* effective_ratio(cs.ratio_for_lang(lang_index));
let source_em = cs.font_size_for_lang(0) * effective_ratio(cs.ratio_for_lang(0));
(current_em > 0.0 && source_em.is_finite() && source_em >= 0.0)
.then(|| 0.5 * source_em / current_em)
},
regenerated_font_metrics: false,
literal_figure_space: false,
literal_soft_hyphen: false,
literal_figure_space_em: None,
hft_hangul_face: styles.hft_ascii_halfwidth && cs.hft_hangul_face_for_lang(lang_index),
hft_font_face: cs.hft_hangul_face_for_lang(lang_index),
hft_fullwidth_dot: cs.hft_fullwidth_dot_for_lang(lang_index),
font_size: cs.font_size_for_lang(lang_index),
resolved_font_size: true,
font_position: (cs.font_position_for_lang(lang_index) != 0)
.then(|| cs.font_position_for_lang(lang_index)),
color: cs.text_color,
bold: cs.bold,
italic: cs.italic,
underline: cs.underline,
strikethrough: cs.strikethrough,
kerning: cs.kerning,
letter_spacing: cs.letter_spacing_for_lang(lang_index),
ratio: cs.ratio_for_lang(lang_index),
default_tab_width: 0.0,
tab_stops: Vec::new(),
auto_tab_right: false,
auto_left_tab_position: None,
available_width: 0.0,
line_x_offset: 0.0,
text_start_offset: 0.0,
right_tab_block_width_override: None,
tab_leaders: Vec::new(),
inline_tabs: Vec::new(),
extra_word_spacing: 0.0,
unjustified_leading_spaces: 0,
extra_char_spacing: 0.0,
extra_dash_advance: 0.0,
text_paint: cs.text_paint,
outline_type: cs.outline_type,
shadow_type: cs.shadow_type,
shadow_offset_percent: Some([cs.shadow_offset_x, cs.shadow_offset_y]),
continuous_shadow: None,
shadow_color: cs.shadow_color,
shadow_offset_x: cs.font_size * cs.shadow_offset_x as f64 / 100.0,
shadow_offset_y: cs.font_size * cs.shadow_offset_y as f64 / 100.0,
emboss: cs.emboss,
engrave: cs.engrave,
superscript: cs.superscript,
subscript: cs.subscript,
emphasis_dot: cs.emphasis_dot,
underline_shape: cs.underline_shape,
strike_shape: cs.strike_shape,
underline_color: cs.underline_color,
strike_color: cs.strike_color,
shade_color: cs.shade_color,
ascii_punct_latin: (lang_index != 1 && cs.ascii_punct_latin_slot)
.then(|| {
storage.bytes(std::mem::size_of::<crate::renderer::LatinSlotMetrics>())?;
Ok(Box::new(crate::renderer::LatinSlotMetrics {
font_family: storage.string(cs.font_family_for_lang(1))?,
native_otf_metrics: (!styles.has_exact_font_source(char_style_id, 1)
&& styles.allows_native_otf_metrics(char_style_id, 1))
.then(|| {
styles.native_pua_fonts.get_otf_for_source(
cs.font_family_for_lang(1),
cs.bold,
cs.italic,
styles.native_otf_metrics_source_ttf(char_style_id, 1),
)
})
.flatten(),
metric_font_family: cs
.metric_face_for_lang(1)
.map(|face| storage.string(face))
.transpose()?,
original_glyph_metric_family: try_original_metric_family(
cs.original_glyph_metric_face_for_lang(1),
storage,
)?,
font_metric_trusted: cs.font_metric_trusted_for_lang(1),
source_font_is_hft: cs.source_hft_for_lang(1),
source_font_is_ttf: cs.source_ttf_for_lang(1),
selected_primary_font_program: cs
.font_families_primary_program
.get(1)
.copied()
.flatten(),
source_verified_hft_bold_tracking: cs
.verified_hft_bold_tracking_for_lang(1),
letter_spacing: cs.letter_spacing_for_lang(1),
ratio: cs.ratio_for_lang(1),
}))
})
.transpose()?,
})
} else {
Ok(TextStyle::default())
}
}
pub(crate) fn resolved_letter_spacing(
styles: &ResolvedStyleSet,
char_style_id: u32,
lang_index: usize,
) -> f64 {
styles
.char_styles
.get(char_style_id as usize)
.map(|cs| cs.letter_spacing_for_lang(lang_index))
.unwrap_or_else(|| TextStyle::default().letter_spacing)
}
fn is_monospace_metric(metric: &font_metrics_data::FontMetric) -> bool {
let mut common: Option<u16> = None;
let mut count = 0u32;
for range in metric.latin_ranges {
if range.start > 0x007E || range.end < 0x0021 {
continue;
}
for (i, &w) in range.widths.iter().enumerate() {
let code = range.start + i as u32;
if !(0x0021..=0x007E).contains(&code) || w == 0 {
continue;
}
count += 1;
match common {
None => common = Some(w),
Some(cw) if cw != w => return false,
_ => {}
}
}
}
count >= 16
}
fn latin1_table_is_uninformative(metric: &font_metrics_data::FontMetric) -> bool {
let mut seen = 0u32;
for range in metric.latin_ranges {
if range.start > 0x00FF || range.end < 0x00A0 {
continue;
}
for (i, &w) in range.widths.iter().enumerate() {
let code = range.start + i as u32;
if !(0x00A0..=0x00FF).contains(&code) {
continue;
}
seen += 1;
if w != 0 && w != metric.em_size {
return false;
}
}
}
seen > 0
}
pub(crate) fn font_family_has_metrics(font_family: &str, bold: bool, italic: bool) -> bool {
let primary_name = font_family.split(',').next().unwrap_or(font_family).trim();
font_metrics_data::find_metric(primary_name, bold, italic).is_some()
}
fn quantize_hwp_px(px: f64) -> f64 {
let hwp = (px * 75.0) as i32;
hwp as f64 / 75.0
}
static KOPUB_DOTUM_LATIN_0: [u16; 95] = [
290, 300, 320, 590, 590, 874, 706, 180, 310, 310, 446, 590, 300, 570, 300, 446, 563, 563, 563,
563, 563, 563, 563, 563, 563, 563, 316, 316, 425, 590, 425, 486, 882, 662, 664, 664, 713, 609,
555, 712, 718, 283, 500, 609, 555, 872, 718, 758, 609, 758, 664, 601, 555, 718, 621, 990, 609,
609, 555, 310, 446, 310, 434, 490, 291, 506, 562, 506, 562, 562, 341, 562, 562, 232, 232, 506,
232, 891, 562, 549, 562, 562, 341, 506, 341, 562, 504, 802, 506, 504, 451, 310, 386, 310, 527,
];
pub(crate) fn verified_source_projection_face(face: &str, bold: bool, italic: bool) -> bool {
let face = face.trim();
!bold
&& !italic
&& (matches!(face, "KoPub돋움체 Light" | "KoPubDotum Light" | "KoPub Dotum Light")
|| super::super::installed_font_program_aliases("KoPub돋움체 Light").contains(&face))
}
pub(crate) fn verified_source_projection_text(
face: &str,
bold: bool,
italic: bool,
text: &str,
) -> bool {
verified_source_projection_face(face, bold, italic)
&& text.chars().all(|ch| {
(' '..='~').contains(&ch)
|| ('가'..='힣').contains(&ch)
|| super::kopub_symbol_metrics::advance_em(true, false, ch).is_some()
})
}
pub(crate) fn verified_source_projection_text_with_fallback(style: &TextStyle, text: &str) -> bool {
let primary = css_primary_face(&style.font_family);
if style.source_font_is_hft
|| !verified_source_projection_face(primary, style.bold, style.italic)
{
return false;
}
text.chars().all(|ch| {
if (' '..='~').contains(&ch)
|| ('가'..='힣').contains(&ch)
|| super::kopub_symbol_metrics::advance_em(true, false, ch).is_some()
{
return true;
}
if font_metrics_data::verified_named_program_has_glyph(
primary,
style.bold,
style.italic,
ch,
) != Some(false)
{
return false;
}
let decision = char_width_decision(&[ch], &[1], 0, style, false);
if decision.width_source != "declaredGlyphFallbackMetric"
|| decision.character_match != "hit"
{
return false;
}
let Some(supplier) = decision.metric else {
return false;
};
style
.font_family
.split(',')
.map(str::trim)
.filter(|family| !family.is_empty())
.skip(1)
.any(|family| {
font_metrics_data::find_metric(family, style.bold, style.italic)
.is_some_and(|found| found.metric.name == supplier.metric.name)
})
})
}
static KOPUB_BATANG_LATIN_0: [u16; 95] = [
312, 312, 312, 573, 573, 745, 789, 312, 312, 312, 419, 648, 312, 503, 312, 468, 573, 573, 573,
573, 573, 573, 573, 573, 573, 573, 312, 312, 484, 556, 484, 468, 834, 668, 640, 708, 770, 590,
554, 768, 770, 352, 358, 746, 552, 874, 778, 812, 612, 816, 672, 532, 652, 740, 686, 954, 708,
706, 638, 312, 468, 312, 477, 540, 312, 558, 606, 536, 592, 548, 360, 548, 624, 324, 282, 564,
288, 900, 612, 612, 632, 596, 416, 432, 350, 604, 506, 772, 588, 516, 476, 312, 468, 312, 648,
];
#[derive(Clone, Copy, PartialEq, Eq)]
enum KoPubFamily {
Dotum,
Batang,
WorldDotum,
WorldBatang,
}
impl KoPubFamily {
fn from_primary(primary_name: &str) -> Option<Self> {
const RECENT: usize = 8;
thread_local! {
static RECENT_NAMES: std::cell::RefCell<Vec<(Box<str>, Option<KoPubFamily>)>> =
const { std::cell::RefCell::new(Vec::new()) };
}
RECENT_NAMES.with(|recent| {
let mut recent = recent.borrow_mut();
if let Some((_, family)) = recent.iter().find(|(name, _)| **name == *primary_name) {
return *family;
}
let family = Self::classify(primary_name);
if recent.len() >= RECENT {
recent.remove(0);
}
recent.push((primary_name.into(), family));
family
})
}
fn classify(primary_name: &str) -> Option<Self> {
let lower = primary_name.to_lowercase().replace(' ', "");
if primary_name.contains("KoPubWorld바탕체")
|| lower.contains("kopubworld batang")
|| lower.contains("kopubworldbatang")
{
Some(Self::WorldBatang)
} else if primary_name.contains("KoPubWorld돋움체")
|| lower.contains("kopubworld dotum")
|| lower.contains("kopubworlddotum")
{
Some(Self::WorldDotum)
} else if primary_name.contains("KoPub돋움체") || lower.contains("kopubdotum") {
Some(Self::Dotum)
} else if primary_name.contains("KoPub바탕체")
|| primary_name.contains("KoPubWorld바탕체")
|| lower.contains("kopubbatang")
|| lower.contains("kopubworldbatang")
{
Some(Self::Batang)
} else {
None
}
}
fn latin_table(self) -> &'static [u16; 95] {
match self {
Self::Dotum | Self::WorldDotum => &KOPUB_DOTUM_LATIN_0,
Self::Batang | Self::WorldBatang => &KOPUB_BATANG_LATIN_0,
}
}
}
pub(crate) fn kopub_declared_space_em(primary_name: &str) -> Option<f64> {
KoPubFamily::from_primary(primary_name)
.map(|family| f64::from(family.latin_table()[0]) / 1000.0)
}
fn kopub_char_advance_em(primary_name: &str, bold: bool, c: char) -> Option<f64> {
let family = KoPubFamily::from_primary(primary_name)?;
if is_unicode_halfwidth_form(c) {
return None;
}
if c == ' ' {
return Some(0.5);
}
if let Some(index) = (c as u32)
.checked_sub(0x20)
.filter(|_| ('\u{20}'..='\u{7E}').contains(&c))
{
let units = family.latin_table()[index as usize];
if units > 0 {
return Some(f64::from(units) / 1000.0);
}
}
if matches!(family, KoPubFamily::Dotum | KoPubFamily::Batang) {
let effective_bold = bold || primary_name.to_ascii_lowercase().contains("bold");
if let Some(em) =
super::kopub_symbol_metrics::advance_em(family == KoPubFamily::Dotum, effective_bold, c)
{
return Some(em);
}
}
if let Some(units) = kopub_cjk_symbol_units(family, c) {
return Some(f64::from(units) / 1000.0);
}
if is_fullwidth_symbol(c)
|| matches!(c, '\u{3164}'..='\u{318E}' | '\u{3400}'..='\u{4DBF}'
| '\u{4E00}'..='\u{9FFF}' | '\u{F900}'..='\u{FAFF}'
| '\u{FF01}'..='\u{FF5E}' | '\u{FFE0}'..='\u{FFE6}')
{
return None;
}
if matches!(family, KoPubFamily::WorldDotum | KoPubFamily::WorldBatang) {
if !('\u{AC00}'..='\u{D7A3}').contains(&c) {
return None;
}
let effective_bold = bold || primary_name.to_ascii_lowercase().contains("bold");
let units = match family {
KoPubFamily::WorldBatang => 936.0,
KoPubFamily::WorldDotum if effective_bold && matches!(c, '\u{C88B}' | '\u{CC27}') => {
1000.0
}
_ => 872.0,
};
return Some(units / 1000.0);
}
if is_narrow_punctuation(c) {
return Some(0.3);
}
if is_cjk_char(c) || is_fullwidth_symbol(c) {
let factor = if family == KoPubFamily::Dotum {
0.872
} else {
0.936
};
return Some(factor);
}
None
}
fn kopub_cjk_symbol_units(family: KoPubFamily, c: char) -> Option<u16> {
let batang = matches!(family, KoPubFamily::Batang | KoPubFamily::WorldBatang);
if matches!(family, KoPubFamily::Dotum | KoPubFamily::Batang) {
if let Ok(cp) = u16::try_from(u32::from(c)) {
if let Ok(index) = kopub_symbol_advances::KOPUB_SYMBOL_ADVANCES
.binary_search_by_key(&cp, |&(code, _, _)| code)
{
let (_, dotum, batang_units) = kopub_symbol_advances::KOPUB_SYMBOL_ADVANCES[index];
return Some(if batang { batang_units } else { dotum });
}
}
}
match c {
'\u{3001}' | '\u{3002}' | '\u{3008}'..='\u{3011}' | '\u{3014}' | '\u{3015}' => Some(450),
'\u{223C}' => Some(900),
'\u{25E6}' => Some(600),
'\u{20A9}' => Some(894),
'\u{00A3}' => Some(if batang { 555 } else { 533 }),
'\u{00A5}' => Some(if batang { 706 } else { 520 }),
'\u{3000}' | '\u{3003}' | '\u{3013}' | '\u{203B}' => Some(900),
'\u{3164}'..='\u{318E}'
| '\u{4E00}'..='\u{9FFF}'
| '\u{3400}'..='\u{4DBF}'
| '\u{F900}'..='\u{FAFF}'
| '\u{FF01}'..='\u{FF5E}'
| '\u{FFE0}'..='\u{FFE6}'
if kopub_cjk_coverage::contains(
matches!(family, KoPubFamily::WorldDotum | KoPubFamily::WorldBatang),
c,
) =>
{
Some(900)
}
_ if kopub_shared_fullwidth_symbol(c) => Some(900),
_ => None,
}
}
fn kopub_shared_fullwidth_symbol(c: char) -> bool {
matches!(c,
'\u{20AC}'
| '\u{2103}'
| '\u{2113}'
| '\u{2160}'..='\u{2169}'
| '\u{2170}'..='\u{2179}'
| '\u{2190}'..='\u{2199}'
| '\u{21D2}'
| '\u{21D4}'
| '\u{2460}'..='\u{2487}'
| '\u{249C}'..='\u{24F4}'
| '\u{24FF}'
| '\u{25A0}'..='\u{25A1}'
| '\u{25A3}'..='\u{25A9}'
| '\u{25B2}'..='\u{25B3}'
| '\u{25B6}'..='\u{25B7}'
| '\u{25BC}'..='\u{25BD}'
| '\u{25C0}'..='\u{25C1}'
| '\u{25C6}'..='\u{25C8}'
| '\u{25CB}'
| '\u{25CE}'..='\u{25D1}'
| '\u{2605}'..='\u{2606}'
| '\u{260E}'..='\u{260F}'
| '\u{261C}'
| '\u{261E}'
| '\u{2640}'
| '\u{2642}'
| '\u{2660}'..='\u{2661}'
| '\u{2663}'..='\u{2665}'
| '\u{2667}'..='\u{266A}'
| '\u{266C}'..='\u{266D}'
| '\u{274C}'
| '\u{2776}'..='\u{2793}'
| '\u{3200}'..='\u{321C}'
| '\u{3251}'..='\u{327B}'
| '\u{327E}'..='\u{327F}'
| '\u{32B1}'..='\u{32BF}'
| '\u{3380}'..='\u{3384}'
| '\u{3388}'..='\u{33CA}'
| '\u{33CF}'..='\u{33D0}'
| '\u{33D3}'
| '\u{33D6}'
| '\u{33D8}'
| '\u{33DB}'..='\u{33DD}'
)
}
pub(crate) fn kopub_space_advance_em(style: &TextStyle) -> Option<f64> {
kopub_declared_space_em(style.font_family.split(',').next()?.trim())
}
const HANYANG_JUNGGOTHIC_PDF_SPACE_UNITS: u16 = 512;
fn hanyang_junggothic_pdf_space_width(primary_name: &str) -> Option<u16> {
(primary_name == "한양중고딕").then_some(HANYANG_JUNGGOTHIC_PDF_SPACE_UNITS)
}
fn hancom_pdf_space_width(primary_name: &str) -> Option<u16> {
hanyang_junggothic_pdf_space_width(primary_name)
}
pub(crate) fn area_dot_fallback_width(font_family: &str, font_size: f64) -> Option<f64> {
let fam = font_family.split(',').next().unwrap_or("").trim();
if fam.contains("함초롬")
|| fam.contains("HCR")
|| fam.contains("한컴")
|| fam.contains("Haansoft")
{
return None;
}
Some(font_size)
}
#[derive(Debug, Clone, Copy)]
pub(crate) struct CharWidthDecision<'a> {
pub(crate) width_source: &'static str,
pub(crate) measurement_character: Option<char>,
pub(crate) base_width_px: f64,
pub(crate) final_width_px: f64,
pub(crate) bold_tracking_px: f64,
pub(crate) applied_letter_spacing_px: f64,
pub(crate) metric: Option<font_metrics_data::MetricLookupDecision<'a>>,
pub(crate) character_match: &'static str,
pub(crate) dash_leader: bool,
pub(crate) negative_spacing_clamped: bool,
}
const HALFWIDTH_PUNCTUATION_WIDTH_SOURCE: &str = "metricHalfwidthPunctuationOverlay";
#[derive(Debug, Clone, Copy)]
struct EmbeddedWidthDecision<'a> {
width_px: Option<f64>,
em_fraction: Option<f64>,
width_source: &'static str,
metric: Option<font_metrics_data::MetricLookupDecision<'a>>,
character_match: &'static str,
}
fn measure_char_width_embedded_decision<'a>(
font_family: &'a str,
bold: bool,
italic: bool,
c: char,
font_size: f64,
) -> EmbeddedWidthDecision<'a> {
measure_char_width_embedded_decision_for_font(
font_family,
bold,
italic,
c,
font_size,
false,
false,
false,
)
}
fn css_primary_face(font_family: &str) -> &str {
let plain = !font_family.contains([',', '\'', '"'])
&& !font_family.starts_with(char::is_whitespace)
&& !font_family.ends_with(char::is_whitespace);
if plain {
return font_family;
}
font_family
.split(',')
.next()
.unwrap_or(font_family)
.trim()
.trim_matches('\'')
.trim_matches('"')
}
#[allow(clippy::too_many_arguments)]
fn measure_char_width_embedded_decision_for_font<'a>(
font_family: &'a str,
bold: bool,
italic: bool,
c: char,
font_size: f64,
font_metric_trusted: bool,
hft_hangul_face: bool,
regular_bold_advance: bool,
) -> EmbeddedWidthDecision<'a> {
let primary_name = css_primary_face(font_family);
if let Some(em) = font_metrics_data::original_glyph_advance_em(primary_name, bold, italic, c) {
return EmbeddedWidthDecision {
width_px: Some(quantize_hwp_px(font_size * em)),
em_fraction: Some(em),
width_source: "measuredOriginalGlyph",
metric: None,
character_match: "hit",
};
}
if let Some(em) = kopub_char_advance_em(primary_name, bold, c) {
return EmbeddedWidthDecision {
width_px: Some(quantize_hwp_px(font_size * em)),
em_fraction: Some(em),
width_source: "kopubTable",
metric: None,
character_match: "hit",
};
}
let Some(mm) =
font_metrics_data::find_metric_decision_for_character(primary_name, bold, italic, c)
else {
return EmbeddedWidthDecision {
width_px: None,
em_fraction: None,
width_source: "metricMiss",
metric: None,
character_match: "notApplicable",
};
};
let c = if c == '\u{00A0}' { ' ' } else { c };
let (w, width_source) = if c == ' ' {
if let Some(width) = hancom_pdf_space_width(primary_name) {
(width, "metricSpaceOverlay")
} else {
(mm.metric.em_size / 2, "metricHalfSpace")
}
} else {
let Some(glyph_w) = mm.metric.get_width(c) else {
return EmbeddedWidthDecision {
width_px: None,
em_fraction: None,
width_source: "metricCharacterMiss",
metric: Some(mm),
character_match: "miss",
};
};
let glyph_w = regular_bold_advance
.then(|| font_metrics_data::regular_advance_metric(mm.metric))
.flatten()
.and_then(|regular| regular.get_width(c))
.unwrap_or(glyph_w);
let verified_true_type_width = font_metric_trusted
.then(|| font_metrics_data::verified_program_punctuation_width(mm.metric, c))
.flatten();
let hft_hangul_halfwidth_ascii = hft_hangul_face && c.is_ascii_graphic();
let is_halfwidth_punct = matches!(c, '\u{2018}'..='\u{2027}')
&& !matches!(
c,
'\u{2020}' | '\u{2021}' | '\u{2022}' | '\u{2025}' | '\u{2026}'
);
let quote_width_is_authentic = (matches!(c, '\u{2018}' | '\u{2019}')
&& is_monospace_metric(mm.metric))
|| (matches!(c, '\u{2018}' | '\u{2019}' | '\u{201C}' | '\u{201D}')
&& font_metric_trusted);
let is_narrow_unicode_punct =
matches!(c, '\u{2018}' | '\u{2019}' | '\u{2027}') && !quote_width_is_authentic;
let is_b7_notdef_artifact = c == '\u{00B7}'
&& glyph_w >= mm.metric.em_size
&& !is_monospace_metric(mm.metric)
&& (!font_metric_trusted || latin1_table_is_uninformative(mm.metric));
if let Some(width) = verified_true_type_width {
(width, "metricTrueTypeGlyph")
} else if hft_hangul_halfwidth_ascii {
(mm.metric.em_size / 2, "metricHftHangulHalfwidthAscii")
} else if (is_narrow_unicode_punct && glyph_w >= mm.metric.em_size) || is_b7_notdef_artifact
{
(
(mm.metric.em_size as f64 * 0.3) as u16,
"metricNarrowPunctuationOverlay",
)
} else if is_halfwidth_punct && !quote_width_is_authentic && glyph_w >= mm.metric.em_size {
(mm.metric.em_size / 2, HALFWIDTH_PUNCTUATION_WIDTH_SOURCE)
} else {
(glyph_w, "embeddedMetric")
}
};
EmbeddedWidthDecision {
width_px: Some(quantize_hwp_px(
w as f64 * font_size / mm.metric.em_size as f64,
)),
em_fraction: Some(w as f64 / mm.metric.em_size as f64),
width_source,
metric: Some(mm),
character_match: "hit",
}
}
pub(crate) fn char_width_decision<'a>(
chars: &[char],
cluster_len: &[u8],
i: usize,
style: &'a TextStyle,
allow_supplemental: bool,
) -> CharWidthDecision<'a> {
let contextual = super::super::arabic_context::advances(chars, style);
char_width_decision_with_hft_tracking(
chars,
cluster_len,
i,
style,
allow_supplemental,
true,
contextual.as_ref().and_then(|widths| widths[i]),
)
}
fn char_width_decision_with_hft_tracking<'a>(
chars: &[char],
cluster_len: &[u8],
i: usize,
style: &'a TextStyle,
allow_supplemental: bool,
include_hft_bold_tracking: bool,
contextual_advance: Option<f64>,
) -> CharWidthDecision<'a> {
let (font_size, ratio, _) = style_params(style);
let c = if style
.native_pua_metrics
.as_ref()
.is_some_and(|program| program.advance_em(chars[i]).is_some())
{
super::super::composer::hancom_symbol_display_key(chars[i])
} else {
super::super::composer::single_scalar_display_char(chars[i])
};
let font_size = if style.layout_half_space && matches!(c, ' ' | '\u{00A0}') {
reflow_space_font_size(style)
} else {
font_size
};
let latin = c
.is_ascii_punctuation()
.then_some(style.ascii_punct_latin.as_deref())
.flatten();
let ratio = latin.map_or(ratio, |l| if l.ratio > 0.0 { l.ratio } else { 1.0 });
let letter_spacing = latin.map_or(style.letter_spacing, |l| l.letter_spacing);
if cluster_len[i] == 0 {
return CharWidthDecision {
width_source: "clusterContinuation",
measurement_character: None,
base_width_px: 0.0,
final_width_px: 0.0,
bold_tracking_px: 0.0,
applied_letter_spacing_px: 0.0,
metric: None,
character_match: "notApplicable",
dash_leader: false,
negative_spacing_clamped: false,
};
}
if cluster_len[i] == 1
&& super::super::conjoining_jamo::is_mark(c)
&& style.isolated_jamo_font == Some(crate::renderer::IsolatedJamoFont::HcrDotum)
{
return CharWidthDecision {
width_source: "isolatedConjoiningJamo",
measurement_character: None,
base_width_px: 0.0,
final_width_px: 0.0,
bold_tracking_px: 0.0,
applied_letter_spacing_px: 0.0,
metric: None,
character_match: "notApplicable",
dash_leader: false,
negative_spacing_clamped: false,
};
}
if c == '\u{FFFC}' {
return CharWidthDecision {
width_source: "inlineObjectPlaceholder",
measurement_character: None,
base_width_px: 0.0,
final_width_px: 0.0,
bold_tracking_px: 0.0,
applied_letter_spacing_px: 0.0,
metric: None,
character_match: "notApplicable",
dash_leader: false,
negative_spacing_clamped: false,
};
}
if c == '\u{2007}' {
let base_width_px = if style.literal_figure_space {
style
.literal_figure_space_em
.map(|em| font_size * em)
.unwrap_or_else(|| {
char_width_decision_with_hft_tracking(
&['0'],
&[1],
0,
style,
false,
false,
None,
)
.base_width_px
})
} else {
font_size * 0.25
};
let applied_letter_spacing_px =
glyph_letter_spacing(style.letter_spacing, base_width_px * ratio, font_size);
let final_width_px =
base_width_px * ratio + applied_letter_spacing_px + style.extra_char_spacing;
return CharWidthDecision {
width_source: if style.literal_figure_space {
"literalFigureSpace"
} else {
"figureSpace"
},
measurement_character: None,
base_width_px,
final_width_px,
bold_tracking_px: 0.0,
applied_letter_spacing_px,
metric: None,
character_match: "notApplicable",
dash_leader: false,
negative_spacing_clamped: false,
};
}
let font_space_width = (c == ' ' || (c == '\u{00a0}' && style.inherited_half_space_em))
.then_some(style.font_space_em)
.flatten()
.map(|em| quantize_hwp_px(font_size * em));
let mut em_exact: Option<f64> = None;
let mut source_hft_metric = false;
let mut measurement_character = None;
let (base_width_raw, width_source, metric, character_match) = if let Some(w) = font_space_width
{
(w, "useFontSpace", None, "notApplicable")
} else if let Some(em) = style
.native_pua_metrics
.as_ref()
.and_then(|program| program.advance_em(c))
{
em_exact = Some(em);
(font_size * em, "verifiedSourcePua", None, "exact")
} else if let Some(enclosed) = crate::renderer::enclosed_pua(c) {
(font_size, enclosed.width_source(), None, "notApplicable")
} else {
let metric_family = match latin {
Some(l) => l.metric_font_family.as_deref().unwrap_or(&l.font_family),
None => style
.metric_font_family
.as_deref()
.unwrap_or(&style.font_family),
};
let display_family = latin.map_or(&style.font_family, |l| &l.font_family);
let measured_family =
crate::renderer::legacy_font_advances::measurement_face(metric_family);
source_hft_metric = font_metrics_data::is_legacy_hft_metric_face(measured_family);
let measured_bold = crate::renderer::legacy_font_advances::measurement_bold(
metric_family,
style.bold,
style.regenerated_font_metrics,
);
let metric_character = if cluster_len[i] > 1 {
crate::renderer::pua_glyph::modern_syllable(
&chars[i..i + usize::from(cluster_len[i])]
.iter()
.collect::<String>(),
)
.unwrap_or(c)
} else {
c
};
let original_glyph_face = latin
.map_or(style.original_glyph_metric_family.as_deref(), |slot| {
slot.original_glyph_metric_family.as_deref()
});
let source_hft = latin.map_or(style.source_font_is_hft, |slot| slot.source_font_is_hft);
let source_ttf = latin.map_or(style.source_font_is_ttf, |slot| slot.source_font_is_ttf);
let regular_bold_advance = !source_hft && (source_ttf || original_glyph_face.is_none());
let implicit_symbol_em = font_metrics_data::implicit_symbol_advance_em(chars[i]);
let original_glyph_em = implicit_symbol_em.or_else(|| {
original_glyph_face.and_then(|face| {
font_metrics_data::declared_original_glyph_advance_em(
face,
style.bold,
style.italic,
chars[i],
)
.or_else(|| {
font_metrics_data::declared_original_glyph_advance_em(
face,
style.bold,
style.italic,
c,
)
})
})
});
let mut embedded = if let Some(em) = original_glyph_em {
EmbeddedWidthDecision {
width_px: Some(quantize_hwp_px(font_size * em)),
em_fraction: Some(em),
width_source: if implicit_symbol_em.is_some() {
"implicitSymbolProgram"
} else {
"measuredOriginalGlyph"
},
metric: None,
character_match: "hit",
}
} else {
measure_char_width_embedded_decision_for_font(
measured_family,
measured_bold,
style.italic,
metric_character,
font_size,
latin.map_or(style.font_metric_trusted, |l| l.font_metric_trusted),
latin.is_none() && style.hft_hangul_face,
regular_bold_advance,
)
};
if original_glyph_em.is_none() && metric_character != c && embedded.width_px.is_some() {
embedded.width_source = "canonicalHangulMetric";
measurement_character = Some(metric_character);
}
if let Some(em) = contextual_advance {
embedded.width_px = Some(quantize_hwp_px(font_size * em));
embedded.em_fraction = Some(em);
embedded.width_source = "sourceContextualMetric";
}
if embedded.width_px.is_none()
&& latin.is_none()
&& !style.hft_hangul_face
&& !style.hft_fullwidth_dot
&& !style.source_font_is_hft
{
if let Some(metric) = embedded.metric.and_then(|primary| {
font_metrics_data::verified_missing_glyph_supplier(primary.metric, c)
.and_then(|face| font_metrics_data::find_metric_decision(face, false, false))
}) {
if let Some(width) = metric.metric.get_width(c) {
embedded = EmbeddedWidthDecision {
width_px: Some(quantize_hwp_px(
font_size * f64::from(width) / f64::from(metric.metric.em_size),
)),
em_fraction: Some(f64::from(width) / f64::from(metric.metric.em_size)),
width_source: "metricGlyphFallback",
metric: Some(metric),
character_match: "hit",
};
}
}
}
if (c.is_ascii_graphic() || source_hft_metric)
&& embedded.width_source == "metricCharacterMiss"
&& measured_family != display_family
{
let display_metric = measure_char_width_embedded_decision_for_font(
display_family,
style.bold,
style.italic,
c,
font_size,
false,
false,
regular_bold_advance,
);
if display_metric.width_px.is_some() {
embedded = display_metric;
embedded.width_source = "unmeasuredSourceDisplayMetric";
}
}
let display_family = latin.map_or(&style.font_family, |l| &l.font_family);
if embedded.width_px.is_none() && metric_family != display_family {
let fallback = measure_char_width_embedded_decision_for_font(
display_family,
style.bold,
style.italic,
c,
font_size,
latin.map_or(style.font_metric_trusted, |l| l.font_metric_trusted),
latin.is_none() && style.hft_hangul_face,
regular_bold_advance,
);
if fallback.width_px.is_some() {
embedded = fallback;
}
}
let verified_primary_missing = metric_family == display_family
&& embedded.metric.is_some_and(|found| {
(found.metric.bold == style.bold || found.bold_fallback)
&& found.metric.italic == style.italic
&& font_metrics_data::verified_metric_has_glyph(found.metric, c) == Some(false)
});
let verified_named_primary_missing = !style.source_font_is_hft
&& measured_family == display_family
&& font_metrics_data::verified_named_program_has_glyph(
measured_family,
style.bold,
style.italic,
c,
) == Some(false);
let verified_primary_missing = verified_primary_missing
|| verified_named_primary_missing
|| (latin.is_none()
&& style.source_font_is_ttf
&& style.glyph_fallback_advance_explicit
&& !is_narrow_punctuation(c)
&& style
.native_otf_metrics
.as_ref()
.is_some_and(|font| !font.has_glyph(c)))
|| (!style.source_font_is_hft
&& measured_family == display_family
&& KoPubFamily::from_primary(measured_family).is_some_and(|family| {
c as u32 <= 0xFFFF
&& is_fullwidth_symbol(c)
&& kopub_cjk_symbol_units(family, c).is_none()
}));
if verified_primary_missing
&& !c.is_whitespace()
&& !style.hft_hangul_face
&& !style.hft_fullwidth_dot
&& (c != '\u{2024}'
|| verified_named_primary_missing
|| style.glyph_fallback_advance_explicit
|| latin.is_some()
|| latin.map_or(style.font_metric_trusted, |l| l.font_metric_trusted))
{
let paint_family = crate::renderer::render_font_family_chain_for_weight(
display_family,
style.is_visually_bold(),
);
for family in paint_family.split(',').skip(1).map(str::trim) {
let fallback = measure_char_width_embedded_decision_for_font(
family,
style.bold,
style.italic,
c,
font_size,
false,
false,
regular_bold_advance,
);
if fallback.width_px.is_some()
&& fallback.metric.is_some_and(|found| {
(found.metric.bold == style.bold || found.bold_fallback)
&& found.metric.italic == style.italic
&& font_metrics_data::verified_metric_has_glyph(found.metric, c)
== Some(true)
})
{
let program = fallback.metric.expect("확인한 대체 프로그램").metric.name;
embedded = measure_char_width_embedded_decision_for_font(
program,
style.bold,
style.italic,
c,
font_size,
false,
false,
regular_bold_advance,
);
embedded.width_source = "declaredGlyphFallbackMetric";
break;
}
}
}
if style.layout_half_space
&& matches!(c, ' ' | '\u{00A0}')
&& embedded.width_source != "metricHalfSpace"
{
embedded.width_px = Some(font_size * 0.5);
embedded.em_fraction = Some(0.5);
embedded.width_source = if embedded.metric.is_some() {
"metricHalfSpace"
} else {
"heuristicHalfwidth"
};
embedded.character_match = if embedded.metric.is_some() {
"hit"
} else {
"notApplicable"
};
}
if style.hft_fullwidth_dot
&& style.bold
&& latin.is_none()
&& (('\u{AC00}'..='\u{D7A3}').contains(&c) || matches!(c, '\u{2022}' | '【' | '】'))
&& !matches!(
style.metric_font_family.as_deref(),
Some(
crate::renderer::legacy_font_advances::HUMAN_HFT_METRIC_FACE
| crate::renderer::legacy_font_advances::HANYANG_HFT_METRIC_FACE
)
)
&& embedded.metric.is_some_and(|metric| {
metric.bold_fallback
&& match metric.metric.name {
"HanyangSinMyeongJo" => true,
"HumanMyeongJo" => ('\u{AC00}'..='\u{D7A3}').contains(&c),
_ => false,
}
})
{
if let Some(width) = embedded.width_px {
embedded.width_px = Some(quantize_hwp_px(width * 1.05));
embedded.em_fraction = embedded.em_fraction.map(|em| em * 1.05);
embedded.width_source = "metricHftBoldAdvance";
}
}
if let Some(w) = embedded.width_px {
em_exact = embedded.em_fraction;
(
w,
embedded.width_source,
embedded.metric,
embedded.character_match,
)
} else if let Some(w) = (c == '\u{318D}')
.then(|| area_dot_fallback_width(&style.font_family, font_size))
.flatten()
{
(w, "areaDotFallback", None, "notApplicable")
} else if cluster_len[i] <= 1 && is_unicode_halfwidth_form(c) {
(
font_size * 0.5,
"heuristicHalfwidthForm",
embedded.metric,
embedded.character_match,
)
} else if cluster_len[i] > 1
|| c == '\u{3000}'
|| (('\u{3001}'..='\u{303F}').contains(&c)
&& unicode_width::UnicodeWidthChar::width(c) == Some(2))
|| is_cjk_char(c)
|| is_fullwidth_symbol(c)
|| (style.source_font_is_hft && matches!(c, '\u{223C}' | '\u{203B}'))
|| (latin.is_none() && embedded.metric.is_some() && c == '\u{2024}')
{
(
font_size,
"heuristicFullwidth",
embedded.metric,
embedded.character_match,
)
} else if is_narrow_punctuation(c)
|| is_narrow_paren_for_font(latin.map_or(&style.font_family, |l| &l.font_family), c)
{
(
font_size * 0.3,
"heuristicNarrow",
embedded.metric,
embedded.character_match,
)
} else {
(
font_size * 0.5,
"heuristicHalfwidth",
embedded.metric,
embedded.character_match,
)
}
};
let dash_leader = is_dash_leader_run(chars, i);
let source_ttf = latin.map_or(style.source_font_is_ttf, |slot| slot.source_font_is_ttf);
let inferred_hft_fullwidth = !style.natural_program_metrics
&& !source_ttf
&& latin.map_or(style.source_font_is_hft, |slot| slot.source_font_is_hft)
&& latin.map_or(!style.font_family.trim().is_empty(), |slot| {
!slot.font_family.trim().is_empty()
})
&& width_source == "heuristicFullwidth";
let clamp_dash_leader = dash_leader
&& !(style.natural_program_metrics
&& character_match == "hit"
&& width_source == "embeddedMetric");
let verified_source_advance = matches!(
width_source,
"measuredOriginalGlyph" | "implicitSymbolProgram" | "verifiedSourcePua"
) || (style.source_font_is_hft
&& character_match == "hit"
&& width_source == "embeddedMetric"
&& metric.is_some_and(|found| {
font_metrics_data::is_verified_original_hft_advance(found.metric)
}));
let otf_metrics = latin.map_or(style.native_otf_metrics.as_ref(), |slot| {
slot.native_otf_metrics.as_ref()
});
let otf_advance = if !source_ttf
&& cluster_len[i] <= 1
&& !dash_leader
&& !c.is_whitespace()
&& !c.is_control()
&& !verified_source_advance
&& !(style.source_font_is_hft && c != chars[i])
{
otf_metrics.and_then(|font| font.advance_em(c))
} else {
None
};
let ttf_advance = if (source_ttf
|| otf_metrics.is_some_and(|font| font.uses_original_truetype()))
&& cluster_len[i] <= 1
&& !dash_leader
&& !c.is_whitespace()
&& !c.is_control()
&& matches!(
width_source,
"heuristicHalfwidth" | "heuristicNarrow" | "heuristicFullwidth"
) {
otf_metrics.and_then(|font| font.source_ttf_advance_em(c))
} else {
None
};
let (base_width_raw, width_source) = if let Some(em) = otf_advance {
em_exact = Some(em);
(font_size * em, "nativeOtf")
} else if let Some(em) = ttf_advance {
em_exact = Some(em);
(font_size * em, "nativeTrueType")
} else {
(base_width_raw, width_source)
};
let supplement = (allow_supplemental
&& super::super::supplemental_metrics::accepts_prepared_glyph_advance(width_source)
&& !(style.source_font_is_hft && c != chars[i])
&& !dash_leader
&& !c.is_whitespace()
&& !c.is_control()
&& crate::renderer::enclosed_pua(c).is_none())
.then(|| {
let snapshot = style.supplemental_metrics.as_ref()?;
snapshot.lookup(snapshot.context(), style, c)
})
.flatten();
let supplemented = supplement.is_some();
let (base_width_raw, width_source) = supplement
.map(|entry| (entry.natural_advance_px(), entry.width_source()))
.unwrap_or((base_width_raw, width_source));
let base_width_px = if clamp_dash_leader {
base_width_raw.min(font_size * 0.3)
} else {
base_width_raw
};
let include_hft_bold_tracking =
include_hft_bold_tracking && width_source != "implicitSymbolProgram";
let font_tracking =
if include_hft_bold_tracking && style.bold && !c.is_whitespace() && !c.is_control() {
if otf_advance.is_some() {
if otf_metrics.is_some_and(|font| font.needs_faux_bold(c)) {
let verified_source = latin
.map_or(style.source_verified_hft_bold_tracking, |slot| {
slot.source_verified_hft_bold_tracking
});
let verified_program = verified_source
&& otf_metrics.is_some_and(|font| font.has_verified_hft_bold_tracking(c));
if style.source_hwp3_hft_bold
|| source_hft_metric
|| verified_program
|| (inferred_hft_fullwidth
&& !latin
.map_or(style.selected_primary_font_program, |slot| {
slot.selected_primary_font_program
})
.is_some_and(|digest| {
otf_metrics
.is_some_and(|font| font.glyph_program_matches(c, &digest))
}))
{
font_size * 0.05
} else {
let original_face = latin
.map_or(style.original_glyph_metric_family.as_deref(), |slot| {
slot.original_glyph_metric_family.as_deref()
});
crate::renderer::legacy_font_advances::bold_advance(
style,
c,
base_width_raw,
font_size,
original_face.map(String::as_str),
)
}
} else {
0.0
}
} else if source_hft_metric
|| (style.source_font_is_hft && width_source == "heuristicFullwidth")
{
font_size * 0.05
} else {
0.0
}
} else {
0.0
};
let extra_char_spacing = if i < style.unjustified_leading_spaces {
0.0
} else {
style.extra_char_spacing
};
let glyph_advance_px = if supplemented {
let advanced = (base_width_px + font_tracking) * ratio;
advanced + glyph_letter_spacing(letter_spacing, advanced, font_size)
} else {
let em_fraction = match em_exact {
Some(em) if !clamp_dash_leader => em,
_ if font_size > 0.0 => base_width_px / font_size,
_ => 0.0,
};
let spacing_fraction = if font_size > 0.0 {
letter_spacing / font_size
} else {
0.0
};
let tracking_em = if font_size > 0.0 {
font_tracking / font_size
} else {
0.0
};
hancom_device_advance_px(
em_fraction + tracking_em,
font_size,
ratio,
spacing_fraction,
matches!(c, ' ' | '\u{00A0}'),
)
};
let mut final_width_px = glyph_advance_px + extra_char_spacing;
let mut applied_letter_spacing_px = glyph_advance_px - base_width_px * ratio;
let original_glyph_face = latin.map_or(style.original_glyph_metric_family.as_deref(), |slot| {
slot.original_glyph_metric_family.as_deref()
});
let bold_tracking_px = crate::renderer::legacy_font_advances::bold_advance(
style,
c,
base_width_px * ratio + applied_letter_spacing_px,
font_size * ratio,
original_glyph_face.map(String::as_str),
);
let bold_tracking_px =
if include_hft_bold_tracking && font_tracking == 0.0 && otf_advance.is_none() {
bold_tracking_px
} else {
0.0
};
final_width_px += bold_tracking_px;
if c == ' ' && i >= style.unjustified_leading_spaces {
final_width_px += style.extra_word_spacing;
}
if dash_leader {
final_width_px += style.extra_dash_advance;
}
let mut without_bold_tracking_px = final_width_px - bold_tracking_px;
let mut negative_spacing_clamped = false;
if letter_spacing + extra_char_spacing < 0.0 {
let min_width = base_width_px * ratio * 0.5;
without_bold_tracking_px = without_bold_tracking_px.max(min_width);
if final_width_px < min_width {
applied_letter_spacing_px += min_width - final_width_px;
final_width_px = min_width;
negative_spacing_clamped = true;
}
}
if c == ' ' {
if let Some(compression) = &style.space_compression {
let reduction = compression.reduction_at(i);
final_width_px -= reduction;
without_bold_tracking_px -= reduction;
debug_assert!(final_width_px >= 0.0);
}
}
CharWidthDecision {
width_source,
measurement_character: if width_source == "canonicalHangulMetric" {
measurement_character
} else {
None
},
base_width_px,
final_width_px,
bold_tracking_px: final_width_px - without_bold_tracking_px,
applied_letter_spacing_px,
metric,
character_match,
dash_leader: clamp_dash_leader,
negative_spacing_clamped,
}
}
fn measure_char_width_embedded(
font_family: &str,
bold: bool,
italic: bool,
c: char,
font_size: f64,
) -> Option<f64> {
measure_char_width_embedded_decision(font_family, bold, italic, c, font_size).width_px
}
pub(crate) fn estimate_text_width(text: &str, style: &TextStyle) -> f64 {
default_measurer().estimate_text_width(text, style)
}
pub(crate) fn estimate_text_width_exact(text: &str, style: &TextStyle) -> f64 {
default_measurer().estimate_text_width_exact(text, style)
}
pub(crate) fn estimate_text_width_unrounded(text: &str, style: &TextStyle) -> f64 {
match estimate_text_width_unrounded_with_storage(text, style, &crate::storage::Unbounded) {
Ok(value) => value,
Err(never) => match never {},
}
}
pub(crate) fn estimate_text_width_unrounded_with_storage<S: crate::storage::Storage>(
text: &str,
style: &TextStyle,
storage: &S,
) -> Result<f64, S::Error> {
let (_, _, tab_w) = style_params(style);
let chars: Vec<char> = storage.collect(text.chars())?;
let cluster_len = build_cluster_len_with_storage(&chars, storage)?;
let char_count = chars.len();
let supplemental = super::super::supplemental_metrics::standalone_scalar_mask_with_storage(
text, style, storage,
)?;
let contextual = super::super::arabic_context::advances_with_storage(&chars, style, storage)?;
let char_width = |i: usize| -> f64 {
char_width_decision_with_hft_tracking(
&chars,
&cluster_len,
i,
style,
supplemental.as_ref().is_some_and(|mask| mask[i]),
true,
contextual.as_ref().and_then(|widths| widths[i]),
)
.final_width_px
};
let mut total = 0.0;
for i in 0..char_count {
if cluster_len[i] == 0 {
continue;
}
let c = chars[i];
if c == '\t' {
let abs_x = style.line_x_offset + total;
if tab_w > 0.0 {
let next_abs = ((abs_x / tab_w).floor() + 1.0) * tab_w;
total = (next_abs - style.line_x_offset).max(total);
}
continue;
}
total += char_width(i);
}
Ok(total) }
pub(crate) fn hancom_regenerated_space_width(style: &TextStyle) -> Option<f64> {
let (_, ratio, _) = style_params(style);
let font_size = reflow_space_font_size(style);
let base_w = font_size * style.font_space_em.unwrap_or(0.5);
let mut width = base_w * ratio
+ glyph_letter_spacing(style.letter_spacing, base_w * ratio, font_size)
+ style.extra_char_spacing
+ style.extra_word_spacing;
if style.letter_spacing + style.extra_char_spacing < 0.0 {
width = width.max(base_w * ratio * 0.5);
}
let stored_width = estimate_text_width_unrounded(" ", style);
(width > stored_width + f64::EPSILON).then_some(width)
}
pub(crate) fn compute_char_positions(text: &str, style: &TextStyle) -> Vec<f64> {
default_measurer().compute_char_positions(text, style)
}
pub(crate) fn has_hft_bold_tracking(style: &TextStyle) -> bool {
let own_metric =
|face: Option<&str>| face.is_some_and(font_metrics_data::is_legacy_hft_metric_face);
style.bold
&& (own_metric(style.metric_font_family.as_deref())
|| style
.ascii_punct_latin
.as_ref()
.is_some_and(|latin| own_metric(latin.metric_font_family.as_deref())))
}
pub(crate) fn compute_glyph_fit_positions(text: &str, style: &TextStyle) -> Vec<f64> {
default_measurer().compute_char_positions_with_hft_tracking(text, style, false)
}
pub(crate) fn compute_kerning_run_measurement(
text: &str,
style: &TextStyle,
source_handle: Option<&ExactFontSourceHandle>,
session: &mut KerningSourceSession<'_>,
) -> KerningRunMeasurement {
let (effective_font_size_px, width_ratio, _) = style_params(style);
let base_positions = compute_char_positions(text, style);
super::super::kerning::compute_kerning_run_measurement(
text,
style.kerning,
base_positions,
effective_font_size_px,
width_ratio,
source_handle,
session,
)
}
pub(crate) fn trace_char_width_decisions<'a>(
text: &str,
style: &'a TextStyle,
) -> Vec<CharWidthDecision<'a>> {
let chars: Vec<char> = text.chars().collect();
let cluster_len = build_cluster_len(&chars);
let positions = compute_char_positions(text, style);
let supplemental = super::super::supplemental_metrics::standalone_scalar_mask(text, style);
chars
.iter()
.enumerate()
.map(|(i, &ch)| {
let mut decision = char_width_decision(
&chars,
&cluster_len,
i,
style,
supplemental.as_ref().is_some_and(|mask| mask[i]),
);
if ch == '\t' {
let advance = positions
.get(i + 1)
.zip(positions.get(i))
.map(|(after, before)| after - before)
.unwrap_or(0.0);
decision.width_source = "tabAdvance";
decision.base_width_px = advance;
decision.final_width_px = advance;
decision.bold_tracking_px = 0.0;
decision.applied_letter_spacing_px = 0.0;
decision.metric = None;
decision.character_match = "notApplicable";
decision.dash_leader = false;
decision.negative_spacing_clamped = false;
}
decision
})
.collect()
}
pub(crate) fn is_cjk_char(c: char) -> bool {
c == '\u{3007}' || ('\u{1100}'..='\u{11FF}').contains(&c) || ('\u{3130}'..='\u{318F}').contains(&c) || ('\u{AC00}'..='\u{D7AF}').contains(&c) || ('\u{A960}'..='\u{A97F}').contains(&c) || ('\u{D7B0}'..='\u{D7FF}').contains(&c) || ('\u{4E00}'..='\u{9FFF}').contains(&c) || ('\u{3400}'..='\u{4DBF}').contains(&c) || ('\u{F900}'..='\u{FAFF}').contains(&c) || ('\u{3040}'..='\u{30FF}').contains(&c) || ('\u{FF00}'..='\u{FFEF}').contains(&c) }
fn is_narrow_punctuation(c: char) -> bool {
matches!(
c,
',' | '.' | ':' | ';' | '\'' | '"' | '`' |
'\u{00B7}' | '\u{2018}' | '\u{2019}' | '\u{2027}' | '\u{302E}' | '\u{302F}' )
}
fn is_narrow_paren_for_font(font_family: &str, c: char) -> bool {
if !matches!(c, '(' | ')') {
return false;
}
let primary = font_family.split(',').next().unwrap_or(font_family).trim();
primary.contains("휴먼명조") || primary.contains("한양중고딕") || primary.contains("HY중고딕")
}
fn is_unicode_halfwidth_form(c: char) -> bool {
('\u{FF61}'..='\u{FFDC}').contains(&c) || ('\u{FFE8}'..='\u{FFEE}').contains(&c)
}
pub(crate) fn is_halfwidth_cjk_quote(c: char) -> bool {
matches!(c, '\u{300C}' | '\u{300D}')
}
pub fn forces_halfwidth_cjk_quote(
font_family: &str,
bold: bool,
italic: bool,
c: char,
font_size: f64,
) -> bool {
if !is_halfwidth_cjk_quote(c) {
return false;
}
measure_char_width_embedded_decision(font_family, bold, italic, c, font_size).width_source
== HALFWIDTH_PUNCTUATION_WIDTH_SOURCE
}
pub fn forces_halfwidth_punct_paint(style: &TextStyle, c: char) -> bool {
if !matches!(c, '\u{2018}'..='\u{2027}') {
return false;
}
let metric_family = style
.metric_font_family
.as_deref()
.unwrap_or(&style.font_family);
let decision = measure_char_width_embedded_decision_for_font(
metric_family,
style.bold,
style.italic,
c,
style.font_size,
style.font_metric_trusted,
style.hft_hangul_face,
!style.source_font_is_hft,
);
matches!(
decision.width_source,
HALFWIDTH_PUNCTUATION_WIDTH_SOURCE | "metricNarrowPunctuationOverlay"
)
}
fn is_dash_leader_run(chars: &[char], i: usize) -> bool {
if chars[i] != '-' {
return false;
}
let mut count = 1usize;
let mut j = i;
while j > 0 && chars[j - 1] == '-' {
count += 1;
j -= 1;
if count >= 3 {
return true;
}
}
let mut j = i;
while j + 1 < chars.len() && chars[j + 1] == '-' {
count += 1;
j += 1;
if count >= 3 {
return true;
}
}
false
}
fn is_fullwidth_symbol(c: char) -> bool {
matches!(c,
'\u{2103}' | '\u{2113}' | '\u{20A9}' | '\u{20AC}' | '\u{00A3}' | '\u{00A5}' | '\u{F00E1}' )
|| ('\u{2190}'..='\u{21FF}').contains(&c) || ('\u{2460}'..='\u{24FF}').contains(&c) || ('\u{25A0}'..='\u{25FF}').contains(&c) || ('\u{2600}'..='\u{26FF}').contains(&c) || ('\u{2700}'..='\u{27BF}').contains(&c) || ('\u{3200}'..='\u{32FF}').contains(&c) || ('\u{3300}'..='\u{33FF}').contains(&c) || ('\u{2160}'..='\u{217F}').contains(&c) }
pub fn split_into_clusters(text: &str) -> Vec<(usize, String)> {
let chars: Vec<char> = text.chars().collect();
let mut clusters: Vec<(usize, String)> = Vec::new();
let mut i = 0;
while i < chars.len() {
if is_hangul_choseong(chars[i]) {
let start = i;
let mut cluster = String::new();
cluster.push(chars[i]);
i += 1;
if i < chars.len() && is_hangul_jungseong(chars[i]) {
cluster.push(chars[i]);
i += 1;
if i < chars.len() && is_hangul_jongseong(chars[i]) {
cluster.push(chars[i]);
i += 1;
}
}
clusters.push((start, cluster));
} else {
clusters.push((i, chars[i].to_string()));
i += 1;
}
}
clusters
}
pub(crate) fn is_vertical_rotate_char(c: char) -> bool {
matches!(
c,
'(' | ')' | '[' | ']' | '{' | '}' | '<' | '>'
| '.' | ',' | '_' | '-' | '~'
| '\u{2026}' | '\u{2015}' | '\u{2500}' | '\u{2014}' | '\u{2013}' | '\u{3008}' | '\u{3009}' | '\u{300A}' | '\u{300B}' | '\u{300C}' | '\u{300D}' | '\u{300E}' | '\u{300F}' | '\u{3010}' | '\u{3011}' | '\u{FF08}' | '\u{FF09}' | '\u{FF3B}' | '\u{FF3D}' | '\u{FF5B}' | '\u{FF5D}' )
}
pub(crate) fn vertical_substitute_char(c: char) -> Option<char> {
match c {
'(' | '\u{FF08}' => Some('\u{FE35}'), ')' | '\u{FF09}' => Some('\u{FE36}'), '{' | '\u{FF5B}' => Some('\u{FE37}'), '}' | '\u{FF5D}' => Some('\u{FE38}'), '[' | '\u{FF3B}' => Some('\u{FE39}'), ']' | '\u{FF3D}' => Some('\u{FE3A}'), '\u{3010}' => Some('\u{FE3B}'), '\u{3011}' => Some('\u{FE3C}'), '\u{3008}' => Some('\u{FE3F}'), '\u{3009}' => Some('\u{FE40}'), '\u{300A}' => Some('\u{FE3D}'), '\u{300B}' => Some('\u{FE3E}'), '\u{300C}' => Some('\u{FE41}'), '\u{300D}' => Some('\u{FE42}'), '\u{300E}' => Some('\u{FE43}'), '\u{300F}' => Some('\u{FE44}'), '\u{2014}' => Some('\u{FE31}'), '\u{2013}' => Some('\u{FE32}'), '\u{2015}' => Some('\u{FE31}'), '\u{2500}' => Some('\u{2502}'), '\u{2026}' => Some('\u{FE19}'), '~' => Some('\u{FE34}'), '_' => Some('\u{FE33}'), _ => None,
}
}
pub(crate) fn estimate_text_width_with_storage<S: crate::storage::Storage>(
text: &str,
style: &TextStyle,
storage: &S,
) -> Result<f64, S::Error> {
Ok(default_measurer()
.estimate_text_width_exact_with_storage(text, style, storage)?
.round())
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn issue_4442_noto_sans_kr_regular_ascii_shared_width_uses_tracked_advances() {
let style = TextStyle {
font_family: "Noto Sans KR".to_string(),
font_size: 1000.0,
..Default::default()
};
let mut expected = vec![0.0];
for units in [11400.0, 10781.0, 11400.0, 11231.0, 11400.0, 11906.0] {
expected.push(expected.last().unwrap() + units * 4.0 / 75.0);
}
assert_eq!(
estimate_text_width_unrounded("AVATAR", &style),
*expected.last().unwrap()
);
assert_eq!(compute_char_positions("AVATAR", &style), expected);
}
#[test]
fn latin_metric_coverage_report() {
let fonts = [
"바탕",
"돋움",
"굴림",
"궁서",
"맑은 고딕",
"함초롬바탕",
"함초롬돋움",
"한컴바탕",
"한컴돋움",
"HY견고딕",
"HY견명조",
"HY중고딕",
"HY신명조",
"휴먼명조",
"한양신명조",
"중고딕",
"Noto Sans KR",
"Noto Serif KR",
"Batang",
"Dotum",
"Gulim",
"Arial",
"Times New Roman",
"Calibri",
"KoPub바탕체",
"KoPub돋움체",
"나눔고딕",
"나눔명조",
"굴림체",
"돋움체",
];
let mut have = 0;
for f in fonts {
let ok = font_family_has_metrics(f, false, false);
let dedicated = f.contains("함초롬")
|| f.contains("HCR")
|| f.contains("KoPub")
|| measure_char_width_embedded(f, false, false, 'E', 100.0).is_some();
let tag = if ok {
"metric 있음"
} else if dedicated {
"전용 표(정확)"
} else {
"→ 0.5em 폴백"
};
println!(" {f:<22} {tag}");
have += (ok || dedicated) as u32;
}
println!(
"
{}/{} 정확, 나머지는 라틴 0.5em 폴백",
have,
fonts.len()
);
assert!(have >= 29, "라틴 metric 커버리지 회귀: {have}/30");
}
pub struct MockTextMeasurer {
pub char_width: f64,
}
impl TextMeasurer for MockTextMeasurer {
fn estimate_text_width(&self, text: &str, style: &TextStyle) -> f64 {
let (font_size, ratio, tab_w) = style_params(style);
let chars: Vec<char> = text.chars().collect();
let cluster_len = build_cluster_len(&chars);
let mut total = 0.0;
for i in 0..chars.len() {
if cluster_len[i] == 0 {
continue;
}
if chars[i] == '\t' {
total = ((total / tab_w).floor() + 1.0) * tab_w;
continue;
}
total += self.char_width * ratio + style.letter_spacing;
if i >= style.unjustified_leading_spaces {
total += style.extra_char_spacing;
}
if chars[i] == ' ' && i >= style.unjustified_leading_spaces {
total += style.extra_word_spacing;
}
}
total
}
fn compute_char_positions(&self, text: &str, style: &TextStyle) -> Vec<f64> {
let (font_size, ratio, tab_w) = style_params(style);
let chars: Vec<char> = text.chars().collect();
let cluster_len = build_cluster_len(&chars);
let mut positions = Vec::with_capacity(chars.len() + 1);
let mut x = 0.0;
positions.push(x);
for i in 0..chars.len() {
if cluster_len[i] == 0 {
positions.push(x);
continue;
}
if chars[i] == '\t' {
x = ((x / tab_w).floor() + 1.0) * tab_w;
positions.push(x);
continue;
}
x += self.char_width * ratio + style.letter_spacing;
if i >= style.unjustified_leading_spaces {
x += style.extra_char_spacing;
}
if chars[i] == ' ' && i >= style.unjustified_leading_spaces {
x += style.extra_word_spacing;
}
positions.push(x);
}
positions
}
}
#[test]
fn issue_4701_hcr_batang_latin_uses_font_hmtx() {
let fs = 40.0 / 3.0; let w = |c: char| {
measure_char_width_embedded("함초롬바탕", false, false, c, fs)
.unwrap_or_else(|| panic!("측정 실패: {c:?}"))
};
let hcr_batang = |c: char| {
measure_char_width_embedded("HCR Batang", false, false, c, fs)
.unwrap_or_else(|| panic!("HCR Batang 측정 실패: {c:?}"))
};
for (c, em) in [
('(', 0.3200),
(',', 0.3200),
('.', 0.3200),
('·', 0.3200),
('0', 0.5500),
('9', 0.5500),
('A', 0.7060),
] {
assert!(
(w(c) - fs * em).abs() < 0.05,
"{c:?} {} ≠ {em}em (hmtx)",
w(c)
);
}
for pair in [('0', '9'), ('(', ')'), ('.', ',')] {
assert_eq!(w(pair.0), w(pair.1), "{pair:?} 는 hmtx 가 동일하다");
}
assert_eq!(w('('), hcr_batang('('), "별칭도 같은 경로를 타야 함");
assert!(
(w('가') - fs * 0.9700).abs() < 0.05,
"한글 {} ≠ 0.97em",
w('가')
);
}
#[test]
fn issue_2279_hancom_dotum_batang_use_haansoft_metrics() {
let fs = 20.0; let w = |fam: &str, c: char| {
measure_char_width_embedded(fam, false, false, c, fs)
.unwrap_or_else(|| panic!("측정 실패: {fam} {c:?}"))
};
assert!(
(w("한컴돋움", '*') - fs * 0.583).abs() < 0.05,
"'*' {}",
w("한컴돋움", '*')
);
assert!(
(w("한컴돋움", '0') - fs * 0.583).abs() < 0.05,
"'0' {}",
w("한컴돋움", '0')
);
assert!(
(w("한컴돋움", '가') - fs * 1.0).abs() < 0.05,
"'가' {}",
w("한컴돋움", '가')
);
assert!(
(w("한컴바탕", '가') - fs * 1.0).abs() < 0.05,
"'가' {}",
w("한컴바탕", '가')
);
assert!(
(w("한컴바탕", '*') - fs * 0.5).abs() < 0.05,
"'*' {}",
w("한컴바탕", '*')
);
assert!(
(w("함초롬돋움", '가') - fs * 0.97).abs() < 0.05,
"HCR '가' {}",
w("함초롬돋움", '가')
);
assert!(area_dot_fallback_width("한컴돋움", fs).is_none());
assert!(area_dot_fallback_width("한컴바탕", fs).is_none());
assert_eq!(area_dot_fallback_width("명조", fs), Some(fs));
assert_eq!(area_dot_fallback_width("맑은 고딕", fs), Some(fs));
assert_eq!(area_dot_fallback_width("한양신명조", fs), Some(fs));
}
#[test]
fn issue_2430_hft_faces_ascii_embedded_coverage() {
let fs = 40.0 / 3.0; for fam in [
"한양신명조",
"한양중고딕",
"한양견명조",
"한양견고딕",
"휴먼명조",
] {
for code in 0x20..=0x7Eu32 {
let c = char::from_u32(code).unwrap();
let w =
measure_char_width_embedded(fam, false, false, c, fs).unwrap_or_else(|| {
panic!("{fam} {c:?}: embedded 메트릭 미해소 — Canvas 폴백 회귀")
});
assert!(w > 0.0, "{fam} {c:?}: 비정상 폭 {w}");
}
}
let w = |fam: &str, c: char| measure_char_width_embedded(fam, false, false, c, fs).unwrap();
assert!(
(w("한양신명조", '0') - fs * 0.497).abs() < 0.05,
"신명조 '0' {}",
w("한양신명조", '0')
);
assert!(
(w("휴먼명조", '0') - fs * 0.497).abs() < 0.05,
"휴먼명조 '0' {}",
w("휴먼명조", '0')
);
assert!(
(w("한양견명조", '0') - fs * 0.565).abs() < 0.05,
"견명조 '0' {}",
w("한양견명조", '0')
);
assert!(
(w("한양견고딕", '0') - fs * 0.565).abs() < 0.05,
"견고딕 '0' {}",
w("한양견고딕", '0')
);
}
#[test]
fn issue_3820_hanyang_junggothic_space_uses_pdf_advance_only() {
let fs = 40.0 / 3.0; let hanyang = measure_char_width_embedded("한양중고딕", false, false, ' ', fs)
.expect("한양중고딕 space metric");
let hy = measure_char_width_embedded("HY중고딕", false, false, ' ', fs)
.expect("HY중고딕 space metric");
let other = measure_char_width_embedded("한양견고딕", false, false, ' ', fs)
.expect("한양견고딕 space metric");
assert!(
(hanyang - quantize_hwp_px(fs * 0.5)).abs() < f64::EPSILON,
"한양중고딕 PDF space advance={hanyang:.3}"
);
for digit in '0'..='9' {
let width = measure_char_width_embedded("한양중고딕", false, false, digit, fs)
.expect("한양중고딕 숫자 메트릭");
assert!(
(width - quantize_hwp_px(fs * 0.5)).abs() < f64::EPSILON,
"한양중고딕 숫자 {digit}는 PDF의 반각 전진폭을 보존해야 함: {width}"
);
}
assert!(
(hy - quantize_hwp_px(fs * 0.5)).abs() < f64::EPSILON,
"HY중고딕 일반 반각 space={hy:.3}"
);
assert!(
(other - quantize_hwp_px(fs * 0.5)).abs() < f64::EPSILON,
"다른 한양 face 일반 반각 space={other:.3}"
);
}
#[test]
fn issue_7418_hanyang_shinmyeongjo_space_is_half_em_at_every_size() {
let standard_body_fs = 16.0; let p81_fs = 56.0 / 3.0; let receipt_fs = 40.0 / 3.0; for (label, fs) in [
("12pt", standard_body_fs),
("14pt", p81_fs),
("10pt", receipt_fs),
] {
let space = measure_char_width_embedded("한양신명조", false, false, ' ', fs)
.expect("한양신명조 space metric");
assert!(
(space - quantize_hwp_px(fs * 0.5)).abs() < f64::EPSILON,
"한양신명조 {label} 반각 space={space:.3}"
);
}
let stale_split_style = TextStyle {
font_family: "한양신명조".to_string(),
font_size: standard_body_fs,
..Default::default()
};
assert_eq!(
hancom_regenerated_space_width(&stale_split_style),
None,
"#4138 split stale-cell 12pt space는 이미 반각이다"
);
}
#[test]
fn test_mock_measurer_fixed_width() {
let m = MockTextMeasurer { char_width: 10.0 };
let style = TextStyle {
font_size: 16.0,
..Default::default()
};
let w = m.estimate_text_width("ABC", &style);
assert!((w - 30.0).abs() < 0.01, "expected 30.0, got {}", w);
}
#[test]
fn test_mock_measurer_positions() {
let m = MockTextMeasurer { char_width: 10.0 };
let style = TextStyle {
font_size: 16.0,
..Default::default()
};
let pos = m.compute_char_positions("AB", &style);
assert_eq!(pos.len(), 3);
assert!((pos[0]).abs() < 0.01);
assert!((pos[1] - 10.0).abs() < 0.01);
assert!((pos[2] - 20.0).abs() < 0.01);
}
#[test]
fn test_mock_measurer_ratio() {
let m = MockTextMeasurer { char_width: 10.0 };
let style = TextStyle {
font_size: 16.0,
ratio: 0.5,
..Default::default()
};
let w = m.estimate_text_width("AB", &style);
assert!(
(w - 10.0).abs() < 0.01,
"expected 10.0 (2*10*0.5), got {}",
w
);
}
#[test]
fn test_mock_measurer_letter_spacing() {
let m = MockTextMeasurer { char_width: 10.0 };
let style = TextStyle {
font_size: 16.0,
letter_spacing: 2.0,
..Default::default()
};
let w = m.estimate_text_width("AB", &style);
assert!(
(w - 24.0).abs() < 0.01,
"expected 24.0 (2*(10+2)), got {}",
w
);
}
#[test]
fn test_mock_measurer_extra_word_spacing() {
let m = MockTextMeasurer { char_width: 10.0 };
let style = TextStyle {
font_size: 16.0,
extra_word_spacing: 5.0,
..Default::default()
};
let w = m.estimate_text_width("A B", &style);
assert!((w - 35.0).abs() < 0.01, "expected 35.0, got {}", w);
}
#[test]
fn test_unicode_arrow_uses_symbol_advance() {
let style = TextStyle {
font_family: "KoPub돋움체 Light".to_string(),
font_size: 10.0,
..Default::default()
};
let arrow = estimate_text_width("⇒", &style);
let ascii = estimate_text_width("A", &style);
assert!(
arrow > ascii,
"arrow should use symbol advance, arrow={arrow}, ascii={ascii}"
);
}
#[test]
fn test_mock_measurer_tab() {
let m = MockTextMeasurer { char_width: 10.0 };
let style = TextStyle {
font_size: 16.0,
..Default::default()
};
let pos = m.compute_char_positions("\tA", &style);
assert_eq!(pos.len(), 3);
assert!(
(pos[1] - 64.0).abs() < 0.01,
"tab should snap to 64, got {}",
pos[1]
);
assert!(
(pos[2] - 74.0).abs() < 0.01,
"A should be at 74, got {}",
pos[2]
);
}
#[test]
fn test_embedded_measurer_latin_heuristic() {
let m = EmbeddedTextMeasurer;
let style = TextStyle {
font_size: 16.0,
..Default::default()
};
let w = m.estimate_text_width("AB", &style);
assert!(
(w - 16.0).abs() < 0.01,
"expected 16.0 (2*8.0 heuristic), got {}",
w
);
}
#[test]
fn test_embedded_measurer_cjk_heuristic() {
let m = EmbeddedTextMeasurer;
let style = TextStyle {
font_size: 16.0,
..Default::default()
};
let w = m.estimate_text_width("가나", &style);
assert!(
(w - 32.0).abs() < 0.01,
"expected 32.0 (2*16.0 heuristic), got {}",
w
);
}
#[test]
fn test_kopub_dotum_hangul_872_advance() {
let m = EmbeddedTextMeasurer;
let style = TextStyle {
font_family: "KoPub돋움체 Light".to_string(),
font_size: 14.0,
..Default::default()
};
let w = m.estimate_text_width("가나", &style);
assert_eq!(w, 24.0);
}
#[test]
fn test_embedded_measurer_known_font() {
let m = EmbeddedTextMeasurer;
let style = TextStyle {
font_family: "함초롬돋움".to_string(),
font_size: 16.0,
..Default::default()
};
let w = m.estimate_text_width("A", &style);
assert!(
w > 0.0 && w < 16.0,
"Latin 'A' should be narrower than CJK, got {}",
w
);
}
#[test]
fn test_embedded_matches_free_fn() {
let style = TextStyle {
font_size: 16.0,
..Default::default()
};
let free_fn_result = estimate_text_width("ABC가나다", &style);
let trait_result = EmbeddedTextMeasurer.estimate_text_width("ABC가나다", &style);
assert!(
(free_fn_result - trait_result).abs() < 0.01,
"free fn ({}) != trait ({})",
free_fn_result,
trait_result,
);
}
#[test]
fn test_embedded_positions_match_free_fn() {
let style = TextStyle {
font_size: 16.0,
..Default::default()
};
let free_fn_result = compute_char_positions("ABC", &style);
let trait_result = EmbeddedTextMeasurer.compute_char_positions("ABC", &style);
assert_eq!(free_fn_result.len(), trait_result.len());
for (a, b) in free_fn_result.iter().zip(trait_result.iter()) {
assert!((a - b).abs() < 0.01, "position mismatch: {} != {}", a, b);
}
}
#[test]
fn test_inline_object_placeholder_has_zero_advance() {
let style = TextStyle {
font_family: "Haansoft Dotum".to_string(),
font_size: 12.0,
..Default::default()
};
assert_eq!(estimate_text_width("\u{FFFC}", &style), 0.0);
assert_eq!(
estimate_text_width("\u{FFFC}\u{FFFC}A", &style),
estimate_text_width("A", &style),
"U+FFFC placeholder 는 실제 TAC 노드가 따로 폭을 차지하므로 텍스트 폭에 더하면 안 됨"
);
let positions = compute_char_positions("\u{FFFC}A", &style);
assert_eq!(positions[0], positions[1]);
assert!(positions[2] > positions[1]);
}
#[test]
fn test_overflow_compression_positions_monotonic_comma() {
let m = EmbeddedTextMeasurer;
let style = TextStyle {
font_family: "맑은 고딕".to_string(),
font_size: 12.0,
ratio: 1.0,
extra_char_spacing: -2.88,
..Default::default()
};
let positions = m.compute_char_positions("65,063,026,600", &style);
for win in positions.windows(2) {
assert!(
win[1] >= win[0] - 1e-6,
"positions must be non-decreasing: {:?}",
positions
);
}
}
#[test]
fn test_charshape_negative_letter_spacing_no_reverse() {
let m = EmbeddedTextMeasurer;
let style = TextStyle {
font_family: "맑은 고딕".to_string(),
font_size: 12.0,
ratio: 1.0,
letter_spacing: -2.88,
extra_char_spacing: 0.0,
..Default::default()
};
let positions = m.compute_char_positions("65,063,026,600", &style);
for win in positions.windows(2) {
assert!(
win[1] >= win[0] - 1e-6,
"positions must be non-decreasing: {:?}",
positions
);
}
}
#[test]
fn test_overflow_compression_positions_monotonic_period() {
let m = EmbeddedTextMeasurer;
let style = TextStyle {
font_family: "맑은 고딕".to_string(),
font_size: 12.0,
ratio: 1.0,
extra_char_spacing: -2.88,
..Default::default()
};
let positions = m.compute_char_positions("526.278", &style);
for win in positions.windows(2) {
assert!(
win[1] >= win[0] - 1e-6,
"positions must be non-decreasing: {:?}",
positions
);
}
}
#[test]
fn test_non_compression_width_unchanged_by_fix() {
let m = EmbeddedTextMeasurer;
let style_a = TextStyle {
font_family: "맑은 고딕".to_string(),
font_size: 12.0,
ratio: 1.0,
..Default::default()
};
let w = m.estimate_text_width("65,063,026,600", &style_a);
assert!(
w > 50.0 && w < 200.0,
"sanity: non-compression width reasonable, got {}",
w
);
}
#[test]
fn test_build_cluster_len_basic() {
let chars: Vec<char> = "ABC".chars().collect();
let cl = build_cluster_len(&chars);
assert_eq!(cl, vec![1, 1, 1]);
}
#[test]
fn test_build_cluster_len_hangul_jamo() {
let chars: Vec<char> = "\u{1100}\u{1161}\u{11AB}".chars().collect();
let cl = build_cluster_len(&chars);
assert_eq!(cl, vec![3, 0, 0]);
}
#[test]
fn test_build_cluster_len_mixed() {
let chars: Vec<char> = "A\u{1100}\u{1161}B".chars().collect();
let cl = build_cluster_len(&chars);
assert_eq!(cl, vec![1, 2, 0, 1]);
}
const UNREGISTERED_FONT: &str = "__rhwp_test_unregistered_font__";
#[test]
fn test_narrow_glyph_comma_base_width() {
let m = EmbeddedTextMeasurer;
let style = TextStyle {
font_family: UNREGISTERED_FONT.to_string(),
font_size: 13.333,
ratio: 1.0,
..Default::default()
};
let positions = m.compute_char_positions("A,B", &style);
let comma_advance = positions[2] - positions[1];
assert!(
comma_advance <= style.font_size * 0.35,
"narrow comma advance should be ≤ font_size * 0.35 ({:.2}), got {:.2}",
style.font_size * 0.35,
comma_advance
);
}
#[test]
fn test_narrow_glyph_middle_dot_base_width() {
let m = EmbeddedTextMeasurer;
let style = TextStyle {
font_family: UNREGISTERED_FONT.to_string(),
font_size: 16.667,
ratio: 1.0,
..Default::default()
};
let positions = m.compute_char_positions("가\u{00B7}나", &style);
let dot_advance = positions[2] - positions[1];
assert!(
dot_advance <= style.font_size * 0.35,
"narrow middle-dot advance should be ≤ font_size * 0.35 ({:.2}), got {:.2}",
style.font_size * 0.35,
dot_advance
);
}
#[test]
fn test_paren_narrow_is_font_conditioned() {
let m = EmbeddedTextMeasurer;
let style = TextStyle {
font_family: UNREGISTERED_FONT.to_string(),
font_size: 13.333,
ratio: 1.0,
..Default::default()
};
let positions = m.compute_char_positions("A(B", &style);
let advance = positions[2] - positions[1];
assert!(
(advance - style.font_size * 0.5).abs() < 0.5,
"미실측 폰트 '(' 는 0.5em 폴백이어야 함, got {:.2}",
advance
);
let style_hy = TextStyle {
font_family: "한양중고딕".to_string(),
font_size: 13.333,
ratio: 1.0,
..Default::default()
};
let positions_hy = m.compute_char_positions("A(B", &style_hy);
let advance_hy = positions_hy[2] - positions_hy[1];
assert!(
advance_hy <= style_hy.font_size * 0.45,
"한양중고딕 '(' 는 narrow(≤0.45em)여야 함, got {:.2}",
advance_hy
);
}
#[test]
fn test_narrow_glyph_tone_marks() {
let m = EmbeddedTextMeasurer;
let style = TextStyle {
font_family: UNREGISTERED_FONT.to_string(),
font_size: 16.667,
ratio: 1.0,
..Default::default()
};
for text in &["가\u{302E}나", "가\u{302F}나"] {
let positions = m.compute_char_positions(text, &style);
let advance = positions[2] - positions[1];
assert!(
advance <= style.font_size * 0.35,
"tone mark advance should be ≤ font_size * 0.35 ({:.2}), got {:.2} for {:?}",
style.font_size * 0.35,
advance,
text
);
}
}
#[test]
fn test_narrow_glyph_period_and_colon() {
let m = EmbeddedTextMeasurer;
let style = TextStyle {
font_family: UNREGISTERED_FONT.to_string(),
font_size: 13.333,
ratio: 1.0,
..Default::default()
};
for (ch, text) in &[('.', "A.B"), (':', "A:B")] {
let positions = m.compute_char_positions(text, &style);
let advance = positions[2] - positions[1];
assert!(
advance <= style.font_size * 0.35,
"narrow '{}' advance should be ≤ font_size * 0.35 ({:.2}), got {:.2}",
ch,
style.font_size * 0.35,
advance
);
}
}
#[test]
fn test_non_narrow_char_unchanged() {
let m = EmbeddedTextMeasurer;
let style = TextStyle {
font_family: UNREGISTERED_FONT.to_string(),
font_size: 13.333,
ratio: 1.0,
..Default::default()
};
let pos_a = m.compute_char_positions("AA", &style);
let a_advance = pos_a[1] - pos_a[0];
assert!(
(a_advance - style.font_size * 0.5).abs() < 0.1,
"Latin 'A' advance should remain font_size * 0.5 ({:.2}), got {:.2}",
style.font_size * 0.5,
a_advance
);
let pos_k = m.compute_char_positions("가가", &style);
let k_advance = pos_k[1] - pos_k[0];
assert!(
(k_advance - style.font_size).abs() < 0.1,
"CJK '가' advance should remain font_size ({:.2}), got {:.2}",
style.font_size,
k_advance
);
}
#[test]
fn test_630_middle_dot_full_width_in_registered_font() {
let m = EmbeddedTextMeasurer;
let style = TextStyle {
font_family: "돋움체".to_string(),
font_size: 17.333,
ratio: 1.0,
..Default::default()
};
let positions = m.compute_char_positions("가\u{00B7}나", &style);
assert!(positions.len() >= 3, "positions should have ≥ 3 entries");
let dot_advance = positions[2] - positions[1];
let expected = style.font_size;
assert!(
(dot_advance - expected).abs() < 1.5,
"DotumChe 의 `·` (U+00B7) advance 가 전각 (={:.2}) 으로 측정되어야 함, got {:.2}\n\
정정 전: 반각 (≈{:.2}). is_halfwidth_punct 가 U+00B7 강제 반각 처리 (Issue #630).",
expected,
dot_advance,
expected / 2.0
);
}
#[test]
fn test_6478_corner_quote_is_fullwidth_in_registered_font() {
let m = EmbeddedTextMeasurer;
let style = TextStyle {
font_family: "돋움체".to_string(),
font_size: 13.333,
ratio: 1.0,
..Default::default()
};
let positions = m.compute_char_positions("「여", &style);
let quote_advance = positions[1] - positions[0];
let hangul_advance = positions[2] - positions[1];
assert!(
quote_advance >= style.font_size * 0.9,
"`「` 는 등록 폰트에서 전각 advance 로 측정되어야 함. got {:.2}",
quote_advance
);
assert!(
hangul_advance >= style.font_size * 0.9,
"뒤따르는 한글은 전각 advance 를 유지해야 함. got {:.2}",
hangul_advance
);
for face in ["바탕체", "굴림체", "궁서체"] {
let style = TextStyle {
font_family: face.to_string(),
font_size: 18.667,
ratio: 1.0,
..Default::default()
};
let positions = m.compute_char_positions("「여", &style);
let adv = positions[1] - positions[0];
assert!(
adv >= style.font_size * 0.9,
"{face} 의 `「` 도 전각이어야 함. got {adv:.2}"
);
}
}
#[test]
fn test_b7_advance_follows_the_font_table_only_when_trusted() {
let m = EmbeddedTextMeasurer;
let advance = |family: &str, trusted: bool| {
let style = TextStyle {
font_family: family.to_string(),
font_size: 20.0,
ratio: 1.0,
font_metric_trusted: trusted,
..Default::default()
};
let positions = m.compute_char_positions("가\u{00B7}나", &style);
assert!(positions.len() >= 3, "세 글자의 원점이 모두 있어야 한다");
(positions[2] - positions[1]) / style.font_size
};
for (family, trusted, expected_em) in [
("HY신명조", true, 1.0),
("HY신명조", false, 0.3),
("휴먼명조", true, 1.0),
("휴먼명조", false, 0.3),
("휴먼고딕", true, 1.0),
("휴먼고딕", false, 0.3),
("HYGothic-Medium", true, 1.0),
("HYGothic-Medium", false, 0.3),
("한양신명조", true, 0.384),
] {
let em = advance(family, trusted);
assert!(
(em - expected_em).abs() < 0.05,
"{family}(신뢰={trusted}) 가운뎃점 전진폭은 {expected_em}em 이어야 한다 — got {em:.3}em"
);
}
for (trusted, expected_em) in [(true, 1.0), (false, 0.3)] {
let style = TextStyle {
font_family: "HYGothic-Medium".into(),
font_size: 20.0,
ratio: 1.0,
font_metric_trusted: trusted,
..Default::default()
};
for quote in ['‘', '’'] {
let text = format!("가{quote}나");
let positions = m.compute_char_positions(&text, &style);
assert_eq!(
positions.len(),
text.chars().count() + 1,
"원문과 종료 경계 보존"
);
let em = (positions[2] - positions[1]) / style.font_size;
assert!(
(em - expected_em).abs() < 0.05,
"검증된 HYGothic-Medium 작은따옴표 {quote}(신뢰={trusted})는 {expected_em}em — got {em:.3}em"
);
}
}
}
}