use super::{hwpunit_to_px, GradientFillInfo, PatternFillInfo, TabStop};
use crate::model::document::{DocInfo, Document};
use crate::model::image::ImageEffect;
use crate::model::style::{
Alignment, BorderFill, BorderLine, Bullet, CenterLine, CharShape, DiagonalLine, FillType,
HeadType, ImageFillMode, LineSpacingType, Numbering, ParaShape, TabDef, UnderlineType,
};
use crate::model::ColorRef;
use crate::renderer::font_rule_layout_name_projection::{
find_font_rule_layout_name, GeneratedFontRuleProjection,
};
pub const LANG_COUNT: usize = 7;
mod ascii_punctuation;
mod document_font_chain;
mod missing_fonts;
pub(crate) use missing_fonts::{missing_char_table, missing_latin_default};
mod page_number;
mod resolved;
pub(crate) use crate::storage;
pub use resolved::{
ResolvedBorderStyle, ResolvedCharStyle, ResolvedImageFill, ResolvedParaStyle, ResolvedStyleSet,
};
pub fn resolve_styles(doc_info: &DocInfo, dpi: f64) -> ResolvedStyleSet {
resolve_styles_with_variant(doc_info, dpi, false)
}
pub(crate) fn resolve_styles_for_document(document: &Document, dpi: f64) -> ResolvedStyleSet {
match try_resolve_styles_for_document(document, dpi, &storage::Unbounded) {
Ok(styles) => styles,
Err(never) => match never {},
}
}
pub(crate) fn try_resolve_styles_for_document<S: storage::Storage>(
document: &Document,
dpi: f64,
storage: &S,
) -> Result<ResolvedStyleSet, S::Error> {
let profile = document.layout_profile();
let lookup = missing_fonts::try_lookup_context(document, storage)?;
let mut styles = try_resolve_styles_with_variant(&lookup, dpi, profile.hwp3_layout(), storage)?;
styles.source_hwp3_native = profile.hwp3_native_layout();
if document.provenance.format == crate::model::provenance::SourceFormat::Hwp5
&& !document.provenance.hwpx_lineage
{
for style in &mut styles.char_styles {
style.font_families_source_ttf.fill(false);
}
}
if missing_fonts::missing_char_table(document) {
styles.page_number_char_style_id = Some(0);
styles.page_number_font_is_hft = false;
}
if document.provenance.format == crate::model::provenance::SourceFormat::Hwp5 {
styles.char_overlap_size_bounds = Some((-8, 2));
}
super::legacy_font_advances::select_native_programs(document, &mut styles);
styles.hft_ascii_halfwidth |= document.provenance.hft_ascii_halfwidth_witnessed;
if profile.hwpx_stored_layout() {
let mut body_space_styles = std::collections::HashSet::new();
let mut table_space_styles = std::collections::HashSet::new();
for section in &document.sections {
for para in §ion.paragraphs {
if !para
.controls
.iter()
.any(|control| matches!(control, crate::model::control::Control::Table(_)))
{
collect_paragraph_space_styles(para, &mut body_space_styles);
}
for control in ¶.controls {
if let crate::model::control::Control::Table(table) = control {
collect_table_space_styles(table, &mut table_space_styles);
}
}
}
}
for (id, style) in styles.char_styles.iter_mut().enumerate() {
if body_space_styles.contains(&(id as u32))
&& !table_space_styles.contains(&(id as u32))
&& style.font_size >= 56.0 / 3.0 - 0.01
&& style.font_family.split(',').next() == Some("한양신명조")
&& style.font_space_em.is_none()
{
style.font_space_em = Some(0.5);
}
}
}
Ok(styles)
}
fn collect_paragraph_space_styles(
para: &crate::model::paragraph::Paragraph,
ids: &mut std::collections::HashSet<u32>,
) {
for (index, ch) in para.text.chars().enumerate() {
if ch == ' ' {
if let Some(id) = para.char_shape_id_at(index) {
ids.insert(id);
}
}
}
}
fn collect_table_space_styles(
table: &crate::model::table::Table,
ids: &mut std::collections::HashSet<u32>,
) {
for cell in &table.cells {
for para in &cell.paragraphs {
collect_paragraph_space_styles(para, ids);
for control in ¶.controls {
if let crate::model::control::Control::Table(nested) = control {
collect_table_space_styles(nested, ids);
}
}
}
}
}
pub(crate) fn resolve_styles_with_environment(
document: &Document,
dpi: f64,
environment: Option<&super::font_environment::FontEnvironment>,
profile: crate::model::provenance::LayoutCompatibilityProfile,
) -> ResolvedStyleSet {
let mut styles = resolve_styles_for_document(document, dpi);
styles.script_metrics = super::script_metrics::ScriptMetricsContract::for_profile(profile);
styles.isolated_jamo_font = (!profile.hangul2024_layout()
&& document.provenance.format != crate::model::provenance::SourceFormat::Pdf)
.then_some(crate::renderer::IsolatedJamoFont::HcrDotum);
if !missing_fonts::missing_char_table(document) {
(
styles.page_number_char_style_id,
styles.page_number_font_is_hft,
) = page_number::resolve(&document.doc_info, profile.hangul2024_layout());
}
if environment.is_some() {
let lookup = missing_fonts::lookup_context(document);
let font_requests = super::font_environment::FontEnvironment::document_requests_with_slots(
&document.doc_info,
);
let display_only_fonts: std::collections::HashSet<_> = environment
.map(|env| {
font_requests
.iter()
.filter_map(|(lang, id, request)| {
if !env.preserves_source_metrics_for(&request.source) {
return None;
}
let target = env.replacement_for(&request.source, *lang, *id)?;
let original = request
.primary
.iter()
.any(|name| name.trim().eq_ignore_ascii_case(target.trim()));
(!original && !env.selects_true_type(target)).then_some((*lang, *id))
})
.collect()
})
.unwrap_or_default();
let selected_source_programs: std::collections::HashSet<_> = environment
.map(|env| {
font_requests
.iter()
.filter_map(|(lang, id, request)| {
let query = env.selected_program_query_for(&request.source, *lang, *id)?;
request
.primary
.iter()
.chain(request.substitute.iter())
.any(|name| name == query)
.then_some((*lang, *id))
})
.collect()
})
.unwrap_or_default();
let mut display_only_slots = std::collections::HashSet::new();
for (style_id, (style, shape)) in styles
.char_styles
.iter_mut()
.zip(&document.doc_info.char_shapes)
.enumerate()
{
let mut latin_program_changed = false;
for lang in 0..LANG_COUNT {
if style.source_ttf_for_lang(lang)
&& display_only_fonts.contains(&(lang, shape.font_ids[lang]))
{
display_only_slots.insert((style_id as u32, lang));
}
let decision = lookup_font_name_in_environment(
&lookup,
lang,
shape.font_ids[lang],
environment,
);
if decision.environment_profile_id.is_some() {
let source_metric_face = style.font_families_metric_face[lang]
.as_deref()
.unwrap_or_else(|| primary_font_name(&style.font_families[lang]))
.to_owned();
style.font_families[lang] = decision.css_family_chain.join(",");
style.font_families_glyph_fallback_advance_explicit[lang] = decision.embedded
!= Some(true)
&& environment.is_some_and(|env| {
decision
.normalized_face
.as_deref()
.and_then(|face| {
decision.requested_face.as_deref().and_then(|source| {
env.glyph_fallbacks_for_slot(
source,
face,
lang,
shape.font_ids[lang],
)
})
})
.is_some()
});
if display_only_fonts.contains(&(lang, shape.font_ids[lang]))
&& !selected_source_programs.contains(&(lang, shape.font_ids[lang]))
{
style.font_families_metric_face[lang] = Some(source_metric_face);
continue;
}
let target = decision
.normalized_face
.as_deref()
.unwrap_or_else(|| primary_font_name(&style.font_families[lang]));
let original = lookup_font_name_decision(&lookup, lang, shape.font_ids[lang]);
let preserve_source_metrics = environment.is_some_and(|env| {
original.requested_face.as_deref().map_or_else(
|| env.preserves_source_metrics(),
|source| env.preserves_source_metrics_for(source),
)
});
let source_font = document
.doc_info
.font_faces
.get(lang)
.and_then(|faces| faces.get(shape.font_ids[lang] as usize));
let primary_true_type_program = environment
.is_some_and(|env| env.selects_true_type(target))
&& original.substitution_boundary.is_none()
&& original.normalized_face.as_deref() == Some(target)
&& source_font.is_some_and(|face| face.native_program.is_none())
&& (metric_widths_verified_face(target)
|| matches!(target, "휴먼명조" | "HumanMyeongJo"));
let keep_source_metrics = !primary_true_type_program
&& preserve_source_metrics
&& (original.alt_type == Some(2)
|| style.font_families_source_hft[lang])
&& original.embedded != Some(true)
&& original.requested_face.as_deref().is_some_and(|face| {
crate::renderer::font_metrics_data::legacy_hft_metric_face(face).is_some()
|| has_own_metric_table(&face, style.bold, style.italic)
|| crate::renderer::font_metrics_data::has_declared_original_glyph_metrics(face)
});
if keep_source_metrics
&& source_font.is_none_or(|face| face.native_program.is_none())
{
style.font_families_metric_face[lang] = original
.requested_face
.as_deref()
.and_then(|face| {
crate::renderer::font_metrics_data::legacy_hft_metric_face(face)
.or_else(|| {
has_own_metric_table(&face, style.bold, style.italic)
.then_some(face)
})
})
.map(str::to_owned);
}
let explicit_true_type = !keep_source_metrics
&& environment.is_some_and(|env| env.selects_true_type(target));
let explicit_replacement = environment.is_some_and(|env| {
decision
.requested_face
.as_deref()
.is_some_and(|face| env.replacement(face).is_some())
});
style.font_families_preserve_glyph_ink[lang] = (explicit_true_type
|| explicit_replacement)
&& !preserve_source_metrics
&& environment.is_some_and(|env| {
original
.requested_face
.as_deref()
.is_some_and(|source| env.selects_natural_program_for(source))
});
if style.font_families_preserve_glyph_ink[lang] {
style.font_families_hft_print_frame[lang] = false;
}
if !keep_source_metrics && (explicit_true_type || explicit_replacement) {
latin_program_changed |= lang == 1;
style.font_families_metric_trusted[lang] = explicit_true_type
&& (metric_widths_verified_face(target)
|| matches!(target, "휴먼명조" | "HumanMyeongJo"));
}
if explicit_true_type {
style.font_families_hft_hangul[lang] = false;
style.font_families_hft_fullwidth_dot[lang] = false;
style.font_families_metric_face[lang] = None;
if !primary_true_type_program || !preserve_source_metrics {
style.font_families_hft_print_frame[lang] = false;
}
style.font_families_original_glyph_metric_face[lang] = None;
} else if explicit_replacement {
if let Some(metric) =
super::font_metrics_data::legacy_hft_metric_face(target)
{
style.font_families_metric_face[lang] = Some(metric.to_owned());
style.font_families_hft_fullwidth_dot[lang] = true;
}
}
}
}
style.font_family = style.font_families[0].clone();
if latin_program_changed {
style.font_space_em = resolved_space_advance_em(
shape.use_font_space,
&style.font_families,
&style.font_families_original_glyph_metric_face,
style.bold,
style.italic,
);
}
}
styles.display_only_otf_slots = std::sync::Arc::new(display_only_slots);
}
match refresh_source_program_projection_slots_with_storage(
&document.doc_info,
&mut styles,
&storage::Unbounded,
) {
Ok(()) => (),
Err(never) => match never {},
}
if let Some(style) = styles
.page_number_char_style_id
.and_then(|id| styles.char_styles.get(id))
{
styles.page_number_font_is_hft |= style
.metric_face_for_lang(1)
.is_some_and(super::font_metrics_data::is_legacy_hft_metric_face);
}
styles
}
pub fn resolve_styles_with_variant(
doc_info: &DocInfo,
dpi: f64,
is_hwp3_variant: bool,
) -> ResolvedStyleSet {
match try_resolve_styles_with_variant(doc_info, dpi, is_hwp3_variant, &storage::Unbounded) {
Ok(styles) => styles,
Err(never) => match never {},
}
}
fn try_resolve_styles_with_variant<S: storage::Storage>(
doc_info: &DocInfo,
dpi: f64,
is_hwp3_variant: bool,
storage: &S,
) -> Result<ResolvedStyleSet, S::Error> {
let mut char_styles = storage.vec(doc_info.char_shapes.len())?;
for shape in &doc_info.char_shapes {
char_styles.push(try_resolve_single_char_style(
shape, doc_info, dpi, storage,
)?);
}
let mut para_styles = storage.vec(doc_info.para_shapes.len())?;
let char_unit_hu = para_margin_char_unit_hu(doc_info);
for shape in &doc_info.para_shapes {
para_styles.push(try_resolve_single_para_style(
shape,
&doc_info.tab_defs,
dpi,
is_hwp3_variant,
char_unit_hu,
storage,
)?);
}
let mut border_styles = storage.vec(doc_info.border_fills.len())?;
for fill in &doc_info.border_fills {
border_styles.push(try_resolve_single_border_style(fill, dpi, storage)?);
}
let numberings = storage.clone_record(&doc_info.numberings)?;
let bullets = storage.clone_record(&doc_info.bullets)?;
storage.bytes(
2 * std::mem::size_of::<usize>()
+ std::mem::size_of::<super::native_pua_fonts::NativePuaFonts>(),
)?;
let (page_number_char_style_id, page_number_font_is_hft) =
page_number::resolve(doc_info, false);
let mut styles = ResolvedStyleSet {
source_hwp3_native: false,
source_program_projection_slots: Default::default(),
script_metrics: Default::default(),
native_pua_fonts: Default::default(),
display_only_otf_slots: Default::default(),
char_overlap_size_bounds: None,
source_char_shapes: {
storage.bytes(
2 * std::mem::size_of::<usize>()
+ std::mem::size_of_val(doc_info.char_shapes.as_slice()),
)?;
storage
.try_collect(doc_info.char_shapes.iter().map(|source| {
if let Some(raw) = &source.raw_data {
storage.bytes(raw.len())?;
}
let mut shape = storage.clone_record(source)?;
shape.raw_data = None;
Ok(shape)
}))?
.into()
},
section_tab_width_bits: {
storage.bytes(2 * std::mem::size_of::<usize>() + std::mem::size_of::<u64>())?;
Default::default()
},
resolved_dpi: Some(dpi),
isolated_jamo_font: None,
page_number_char_style_id,
page_number_font_is_hft,
style_char_shapes: storage.try_collect(
doc_info
.styles
.iter()
.map(|style| Ok(u32::from(style.char_shape_id))),
)?,
char_styles,
para_styles,
border_styles,
numberings,
bullets,
hwp3_variant: is_hwp3_variant,
hft_ascii_halfwidth: is_hwp3_variant,
kerning_measurement_context: None,
horizontal_shaping_context: None,
supplemental_metrics: None,
};
refresh_source_program_projection_slots_with_storage(doc_info, &mut styles, storage)?;
Ok(styles)
}
fn refresh_source_program_projection_slots_with_storage<S: storage::Storage>(
doc_info: &DocInfo,
styles: &mut ResolvedStyleSet,
storage: &S,
) -> Result<(), S::Error> {
styles.source_program_projection_slots = Default::default();
let dpi = styles.resolved_dpi.unwrap_or(96.0);
let mut fallback_char_styles = None;
let mut build_fallback = || -> Result<Vec<ResolvedCharStyle>, S::Error> {
let mut fallback_info = storage.clone_doc_info(doc_info)?;
for fonts in &mut fallback_info.font_faces {
for font in fonts {
if let Some(substitute) = font.subst_font.take() {
if substitute.font_type == 1 && !substitute.face.trim().is_empty() {
font.name = substitute.face;
}
}
}
}
storage.try_collect(
fallback_info
.char_shapes
.iter()
.map(|cs| try_resolve_single_char_style(cs, &fallback_info, dpi, storage)),
)
};
for (shape_id, shape) in doc_info.char_shapes.iter().enumerate() {
let Some(style) = styles.char_styles.get(shape_id) else {
continue;
};
for language in 0..LANG_COUNT {
let Some(font) = doc_info
.font_faces
.get(language)
.and_then(|fonts| fonts.get(shape.font_ids[language] as usize))
else {
continue;
};
let primary = primary_font_name(style.font_family_for_lang(language));
if font.alt_type != 1
|| font.is_embedded
|| font.native_program.is_some()
|| (primary != font.name.trim()
&& !super::installed_font_program_aliases(font.name.trim()).contains(&primary))
|| !font.subst_font.as_ref().is_some_and(|substitute| {
substitute.font_type == 1
&& !substitute.face.trim().is_empty()
&& substitute.face.trim() != primary
})
|| style.metric_face_for_lang(language).is_some()
|| style
.original_glyph_metric_face_for_lang(language)
.is_some()
{
continue;
}
if style.font_metric_trusted_for_lang(language)
|| super::layout::verified_source_projection_face(primary, style.bold, style.italic)
{
if fallback_char_styles.is_none() {
fallback_char_styles = Some(build_fallback()?);
}
if let Some(fallback) = fallback_char_styles
.as_ref()
.and_then(|values| values.get(shape_id))
{
let copied = crate::storage::try_clone(fallback, storage)?;
storage.insert_map(
std::sync::Arc::make_mut(&mut styles.source_program_projection_slots),
(shape_id as u32, language),
copied,
)?;
}
}
}
}
Ok(())
}
fn hft_program_metric_face(face: &&str) -> bool {
*face == "HCI Poppy"
}
fn has_own_metric_table(face: &&str, bold: bool, italic: bool) -> bool {
if *face == "HCI Tulip" {
return true;
}
crate::renderer::font_metrics_data::find_metric_decision(face, bold, italic).is_some_and(
|decision| {
decision.alias_rule_id.is_none()
&& decision.metric.bold == bold
&& decision.metric.italic == italic
},
)
}
fn verified_ttf_substitute(font: &crate::model::style::Font) -> Option<&str> {
if font.alt_type != 1 {
return None;
}
let substitute = match (&font.subst_font, &font.alt_name) {
(Some(subst), _) => (subst.font_type != 2 && !subst.is_embedded).then(|| subst.face.trim()),
(None, Some(alt_name)) => Some(alt_name.trim()),
(None, None) => None,
}?;
(!substitute.is_empty()
&& substitute != font.name.trim()
&& metric_widths_verified_face(substitute))
.then_some(substitute)
}
pub(crate) fn declared_space_advance_em(
css_family_chain: &str,
bold: bool,
italic: bool,
) -> Option<f64> {
let primary = css_family_chain
.split(',')
.next()?
.trim()
.trim_matches('\'')
.trim_matches('"');
if let Some(em) = crate::renderer::layout::kopub_declared_space_em(primary) {
return Some(em);
}
let decision = crate::renderer::font_metrics_data::find_metric_decision(primary, bold, italic)?;
let em = decision.metric.em_size;
if em == 0 {
return None;
}
let width = decision.metric.get_width(' ')?;
if width == 0 {
return None;
}
Some(f64::from(width) / f64::from(em))
}
fn resolved_space_advance_em(
use_font_space: bool,
families: &[String],
original_glyph_faces: &[Option<String>],
bold: bool,
italic: bool,
) -> Option<f64> {
use_font_space
.then(|| {
original_glyph_faces
.get(1)
.and_then(Option::as_deref)
.and_then(|face| {
crate::renderer::font_metrics_data::declared_original_glyph_advance_em(
face, bold, italic, ' ',
)
})
.or_else(|| {
families
.get(1)
.and_then(|chain| declared_space_advance_em(chain, bold, italic))
})
})
.flatten()
}
fn resolve_char_styles(doc_info: &DocInfo, dpi: f64) -> Vec<ResolvedCharStyle> {
doc_info
.char_shapes
.iter()
.map(|cs| resolve_single_char_style(cs, doc_info, dpi))
.collect()
}
fn resolve_single_char_style(cs: &CharShape, doc_info: &DocInfo, dpi: f64) -> ResolvedCharStyle {
match try_resolve_single_char_style(cs, doc_info, dpi, &storage::Unbounded) {
Ok(style) => style,
Err(never) => match never {},
}
}
pub(crate) fn try_resolve_single_char_style<A: storage::Storage>(
cs: &CharShape,
doc_info: &DocInfo,
dpi: f64,
storage: &A,
) -> Result<ResolvedCharStyle, A::Error> {
let font_size = hwpunit_to_px(cs.base_size, dpi);
let mut font_families = storage.vec(LANG_COUNT)?;
let mut font_families_metric_trusted = storage.vec(LANG_COUNT)?;
let mut font_families_glyph_fallback_advance_explicit = storage.vec(LANG_COUNT)?;
let mut font_families_hft_hangul = storage.vec(LANG_COUNT)?;
let mut font_families_source_hft = storage.vec(LANG_COUNT)?;
let mut font_families_source_ttf = storage.vec(LANG_COUNT)?;
let mut font_families_verified_hft_bold_tracking = storage.vec(LANG_COUNT)?;
let mut font_families_hft_print_frame = storage.vec(LANG_COUNT)?;
let mut font_families_hft_fullwidth_dot = storage.vec(LANG_COUNT)?;
let mut font_families_metric_face: Vec<Option<String>> = storage.vec(LANG_COUNT)?;
let mut font_families_original_glyph_metric_face = storage.vec(LANG_COUNT)?;
let mut letter_spacings = storage.vec(LANG_COUNT)?;
let mut ratios = storage.vec(LANG_COUNT)?;
let mut font_sizes = storage.vec(LANG_COUNT)?;
let mut latin_slot_legacy = false;
let mut latin_declared_hft = false;
let latin_slot_explicit = false;
for lang in 0..LANG_COUNT {
let font_id = cs.font_ids[lang];
let source_font = doc_info
.font_faces
.get(lang)
.and_then(|faces| faces.get(font_id as usize));
font_families_source_hft.push(source_font.is_some_and(|face| face.alt_type == 2));
font_families_source_ttf.push(source_font.is_some_and(|face| face.alt_type == 1));
font_families_verified_hft_bold_tracking.push(source_font.is_some_and(
crate::renderer::legacy_font_advances::has_verified_hft_bold_tracking_source,
));
let decision = try_lookup_font_name_decision(doc_info, lang, font_id, storage)?;
let substituted = decision.substitution_boundary.is_some()
&& decision.normalized_face != decision.requested_face;
let document_true_type_substitute = source_font.is_some_and(|face| {
face.alt_type == 1
&& face.subst_font.as_ref().is_some_and(|substitute| {
let name = substitute.face.trim();
substitute.font_type == 1
&& !name.is_empty()
&& decision.normalized_face.as_deref()
== Some(
resolve_font_substitution_decision(
name,
substitute.font_type,
lang,
)
.map(|(resolved, _, _)| resolved)
.unwrap_or(name),
)
})
});
if lang == 1 {
latin_declared_hft = decision.alt_type == Some(2) && !substituted;
}
let substitute_ttf = doc_info
.font_faces
.get(lang)
.and_then(|faces| faces.get(font_id as usize))
.and_then(verified_ttf_substitute);
font_families_metric_trusted.push(
substitute_ttf.is_some()
|| (decision.alt_type == Some(1)
&& !substituted
&& decision
.requested_face
.as_deref()
.is_some_and(metric_widths_verified_face)),
);
font_families_glyph_fallback_advance_explicit.push(false);
font_families_hft_hangul
.push(decision.substitution_boundary == Some(FontSubstitutionBoundary::Hft));
font_families_hft_fullwidth_dot.push(decision.alt_type == Some(2) && !substituted);
font_families_hft_print_frame
.push(decision.alt_type == Some(2) && !substituted && decision.embedded != Some(true));
font_families_metric_face.push(if let Some(face) = substitute_ttf {
Some(storage.string(face)?)
} else if decision.alt_type == Some(2)
&& decision.requested_face.as_deref().is_some_and(|face| {
crate::renderer::font_metrics_data::legacy_hft_metric_face(face).is_some()
})
{
decision
.requested_face
.as_deref()
.and_then(crate::renderer::font_metrics_data::legacy_hft_metric_face)
.map(|face| storage.string(face))
.transpose()?
} else {
(decision.substitution_boundary == Some(FontSubstitutionBoundary::LegacyLatin))
.then(|| {
decision
.requested_face
.as_deref()
.filter(|face| has_own_metric_table(face, cs.bold, cs.italic))
.filter(|face| {
decision.alt_type == Some(2) || !hft_program_metric_face(face)
})
})
.flatten()
.map(|face| storage.string(face))
.transpose()?
});
font_families_original_glyph_metric_face.push(
(!document_true_type_substitute
&& decision.embedded != Some(true)
&& (decision.substitution_boundary == Some(FontSubstitutionBoundary::LegacyLatin)
|| decision.alt_type == Some(2)))
.then(|| {
decision
.requested_face
.as_deref()
.filter(|face| {
crate::renderer::font_metrics_data::has_declared_original_glyph_metrics(
face,
)
})
.map(|face| storage.string(face))
})
.flatten()
.transpose()?,
);
font_families.push(storage.join(&decision.css_family_chain, ",")?);
let spacing_percent = cs.spacings[lang] as f64;
ratios.push(cs.ratios[lang] as f64 / 100.0);
let relative_size = f64::from(cs.relative_sizes[lang]) / 100.0;
let lang_font_size = font_size * relative_size;
letter_spacings.push(lang_font_size * spacing_percent / 100.0);
font_sizes.push(lang_font_size);
}
let font_space_em = resolved_space_advance_em(
cs.use_font_space,
&font_families,
&font_families_original_glyph_metric_face,
cs.bold,
cs.italic,
);
let ascii_punct_latin_slot = ascii_punctuation::uses_latin_slot(
&font_families,
font_families_metric_face[1].as_deref(),
latin_slot_legacy,
font_families_hft_hangul[0],
latin_declared_hft,
cs.bold,
cs.italic,
);
let primary = |chain: &String| {
storage.string(
chain
.split(',')
.next()
.unwrap_or("")
.trim()
.trim_matches(|c| c == '\'' || c == '"'),
)
};
let explicit_latin_slot = latin_slot_explicit
&& latin_slot_legacy
&& primary(&font_families[0])? != primary(&font_families[1])?;
let ascii_punct_latin_slot = ascii_punct_latin_slot || explicit_latin_slot;
let latin_primary = primary(&font_families[1])?;
let ascii_punct_latin_slot = ascii_punct_latin_slot
|| (primary(&font_families[0])? != latin_primary
&& (latin_slot_explicit
|| crate::renderer::font_metrics_data::find_metric(
&latin_primary,
cs.bold,
cs.italic,
)
.is_some_and(|found| found.metric.hangul.is_none())));
let font_family = storage.string(&font_families[0])?;
let letter_spacing = letter_spacings[0];
let ratio = ratios[0];
Ok(ResolvedCharStyle {
font_family,
font_families,
font_families_metric_trusted,
font_families_glyph_fallback_advance_explicit,
font_families_hft_hangul,
font_families_source_hft,
font_families_source_ttf,
font_families_verified_hft_bold_tracking,
font_families_hft_print_frame,
font_families_preserve_glyph_ink: vec![false; LANG_COUNT],
font_families_hft_fullwidth_dot,
ascii_punct_latin_slot,
explicit_latin_slot,
font_families_metric_face,
font_families_original_glyph_metric_face,
font_space_em,
font_size,
font_sizes,
font_positions: storage.copy_slice(&cs.char_offsets)?,
bold: cs.bold,
italic: cs.italic,
text_color: cs.text_color,
underline: cs.underline_type,
underline_color: cs.underline_color,
strike_color: cs.strike_color,
strikethrough: cs.strikethrough,
letter_spacing,
letter_spacings,
ratio,
ratios,
border_fill_id: cs.border_fill_id,
text_paint: cs.text_paint.map(|paint| paint.at_dpi(dpi)),
outline_type: cs.outline_type,
shadow_type: cs.shadow_type,
shadow_color: cs.shadow_color,
shadow_offset_x: cs.shadow_offset_x,
shadow_offset_y: cs.shadow_offset_y,
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,
kerning: cs.kerning,
shade_color: cs.shade_color,
})
}
impl ResolvedCharStyle {
pub(crate) fn with_base_size(&self, cs: &CharShape, font_size: f64) -> Self {
let mut style = self.clone();
style.font_size = font_size;
style.font_sizes = (0..LANG_COUNT)
.map(|lang| font_size * (f64::from(cs.relative_sizes[lang]) / 100.0))
.collect();
style.letter_spacings = (0..LANG_COUNT)
.map(|lang| style.font_sizes[lang] * cs.spacings[lang] as f64 / 100.0)
.collect();
style.letter_spacing = style.letter_spacings[0];
style
}
}
pub(crate) fn is_latin_slot_symbol(ch: char) -> bool {
matches!(ch, '\u{00A1}'..='\u{00AC}' | '\u{00AE}'..='\u{00BF}')
|| matches!(
ch,
'\u{2018}'
| '\u{2019}'
| '\u{201A}'
| '\u{201B}'
| '\u{201C}'
| '\u{201D}'
| '\u{201E}'
| '\u{201F}'
)
}
fn is_symbol_slot_char(cp: u32) -> bool {
matches!(
cp,
0x0391..=0x03A1 | 0x03A3..=0x03A9 | 0x03B1..=0x03C9 | 0x0401 | 0x0410..=0x044F | 0x0451 |
0x2013..=0x2014 | 0x2017 | 0x2020..=0x2022 | 0x2025..=0x2026 | 0x2030 | 0x2032..=0x2033 |
0x2039..=0x203C | 0x203E | 0x2044 | 0x2047 | 0x204E..=0x204F | 0x2053..=0x205E |
0x2074 | 0x207F | 0x2081..=0x2084 | 0x2090..=0x2094 |
0x20A3..=0x20A4 | 0x20A7 | 0x20A9 | 0x20AC |
0x2103 | 0x2105 | 0x2109 | 0x2113 | 0x2116 | 0x2121..=0x2122 | 0x2126 | 0x212B | 0x212E |
0x213B..=0x214E |
0x2153..=0x2154 | 0x215B..=0x215E |
0x3200..=0x321C | 0x3260..=0x327B | 0x327F | 0x3380..=0x3384 | 0x3388..=0x33CA |
0x33CF..=0x33D0 | 0x33D3 | 0x33D6 | 0x33D8 | 0x33DB..=0x33DD
)
}
pub fn detect_lang_category(ch: char) -> usize {
let cp = ch as u32;
match cp {
0x318D => 6,
0x2018 | 0x2019 | 0x201C | 0x201D => 1,
0x2024 | 0x2027 => 5,
0xFF01..=0xFF60 | 0xFFE0..=0xFFE6 => 5,
0x2160..=0x2188 => 5,
0x1100..=0x11FF | 0x3130..=0x318F | 0xAC00..=0xD7AF |
0xA960..=0xA97F | 0xD7B0..=0xD7FF => 0,
0x0041..=0x005A | 0x0061..=0x007A | 0x0030..=0x0039 |
0x00C0..=0x024F |
0x1E00..=0x1EFF => 1,
_ if is_latin_slot_symbol(ch) => 1,
0x4E00..=0x9FFF | 0x3400..=0x4DBF |
0xF900..=0xFAFF |
0x20000..=0x2A6DF => 2,
0x3040..=0x309F | 0x30A0..=0x30FF |
0x31F0..=0x31FF => 3,
0x2015 | 0x2190..=0x21FF | 0x2200..=0x22FF | 0x2300..=0x23FF |
0x2500..=0x257F | 0x2580..=0x259F | 0x25A0..=0x25FF |
0x2600..=0x26FF | 0x2700..=0x27BF |
0x2460..=0x24FF |
0x3000..=0x303F => 5,
0x27C0..=0x27FF | 0x2900..=0x2BFF => 5,
_ if is_symbol_slot_char(cp) => 5,
_ => 0,
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub(crate) enum FontSubstitutionBoundary {
LegacyLatin,
Hft,
Ttf,
MissingProgram,
}
impl FontSubstitutionBoundary {
pub(crate) const fn source_boundary_id(self) -> &'static str {
match self {
Self::LegacyLatin => "rust-style-resolution.legacy-latin",
Self::Hft => "rust-style-resolution.hft",
Self::Ttf => "rust-style-resolution.ttf",
Self::MissingProgram => "rust-style-resolution.missing-program",
}
}
pub(crate) fn language_condition(self, source_face: &str) -> &'static str {
match self {
Self::LegacyLatin => "1",
Self::Ttf | Self::MissingProgram => "all",
Self::Hft
if find_font_rule_layout_name(self.source_boundary_id(), source_face, 0)
.is_some() =>
{
"all"
}
Self::Hft => "1",
}
}
}
#[derive(Debug, Clone)]
pub(crate) struct FontNameDecision {
pub(crate) environment_profile_id: Option<String>,
pub(crate) language_slot: usize,
pub(crate) font_id: u16,
pub(crate) requested_face: Option<String>,
pub(crate) alt_type: Option<u8>,
pub(crate) embedded: Option<bool>,
pub(crate) normalized_face: Option<String>,
pub(crate) requested_subst_font: Option<String>,
pub(crate) subst_font: Option<String>,
pub(crate) document_substitute_rule_id: Option<&'static str>,
pub(crate) css_family_chain: Vec<String>,
pub(crate) substitution_boundary: Option<FontSubstitutionBoundary>,
pub(crate) substitution_rule_id: Option<&'static str>,
}
fn metric_widths_verified_face(face: &str) -> bool {
matches!(
face.trim(),
"HY신명조"
| "HYSinMyeongJo-Medium"
| "HY중고딕"
| "HYGothic-Medium"
| "HY헤드라인M"
| "HYHeadLine-Medium"
| "HY울릉도M"
| "HYwulM"
| "HY견고딕"
| "HYGothic-Extra"
| "HY그래픽"
| "HYGraphic-Medium"
| "휴먼명조"
| "HumanMyeongJo"
| "Times New Roman"
| "휴먼고딕"
)
}
pub(crate) fn lookup_font_name_decision(
doc_info: &DocInfo,
lang_index: usize,
font_id: u16,
) -> FontNameDecision {
match try_lookup_font_name_decision(doc_info, lang_index, font_id, &storage::Unbounded) {
Ok(decision) => decision,
Err(never) => match never {},
}
}
fn try_lookup_font_name_decision<A: storage::Storage>(
doc_info: &DocInfo,
lang_index: usize,
font_id: u16,
storage: &A,
) -> Result<FontNameDecision, A::Error> {
let mut decision = FontNameDecision {
environment_profile_id: None,
language_slot: lang_index,
font_id,
requested_face: None,
alt_type: None,
embedded: None,
normalized_face: None,
requested_subst_font: None,
subst_font: None,
document_substitute_rule_id: None,
css_family_chain: Vec::new(),
substitution_boundary: None,
substitution_rule_id: None,
};
if lang_index < doc_info.font_faces.len() {
let lang_fonts = &doc_info.font_faces[lang_index];
if (font_id as usize) < lang_fonts.len() {
let font = &lang_fonts[font_id as usize];
let name = &font.name;
decision.requested_face = Some(storage.string(name)?);
decision.alt_type = Some(font.alt_type);
decision.embedded = Some(font.is_embedded);
let substitution = resolve_font_substitution_decision(name, font.alt_type, lang_index);
let resolved = storage.string(substitution.map(|(face, _, _)| face).unwrap_or(name))?;
decision.normalized_face = Some(storage.string(&resolved)?);
decision.substitution_boundary = substitution.map(|(_, boundary, _)| boundary);
decision.substitution_rule_id = substitution.map(|(_, _, rule_id)| rule_id);
storage.push(&mut decision.css_family_chain, storage.string(&resolved)?)?;
if let Some(substitute) = font
.subst_font
.as_ref()
.filter(|substitute| !substitute.is_embedded)
.filter(|substitute| !substitute.face.trim().is_empty())
.filter(|substitute| substitute.face.trim() != resolved)
{
let requested = substitute.face.trim();
decision.requested_subst_font = Some(storage.string(requested)?);
let rule = (!font.is_embedded && font.alt_type == 1 && substitute.font_type == 1)
.then(|| {
find_font_rule_layout_name(
"rust-style-resolution.document-substitute",
requested,
lang_index,
)
})
.flatten()
.filter(|rule| {
rule.conditions.alt_type == Some("1")
&& rule.conditions.availability
== Some("nonembedded-ttf-document-substitute")
});
let face =
storage.string(rule.map_or(requested, |rule| rule.target_face_or_policy))?;
decision.document_substitute_rule_id = rule.map(|rule| rule.rule_id);
decision.subst_font = Some(storage.string(&face)?);
if face != resolved {
storage.push(&mut decision.css_family_chain, face)?;
}
}
document_font_chain::prefer_declared_single_face(font, &mut decision, storage)?;
}
}
Ok(decision)
}
pub(crate) fn lookup_font_name_in_environment(
doc_info: &DocInfo,
lang_index: usize,
font_id: u16,
environment: Option<&super::font_environment::FontEnvironment>,
) -> FontNameDecision {
let mut decision = lookup_font_name_decision(doc_info, lang_index, font_id);
if decision.embedded != Some(true) {
if let Some((environment, target)) = environment.and_then(|env| {
decision
.requested_face
.as_deref()
.and_then(|face| env.replacement_for(face, lang_index, font_id))
.map(|target| (env, target))
}) {
let same_primary_family = decision.normalized_face.as_deref() == Some(target);
if !same_primary_family {
decision.normalized_face = Some(target.to_string());
decision.css_family_chain = vec![target.to_string()];
}
if let Some(query) = decision.requested_face.as_deref().and_then(|source| {
environment.selected_program_query_for(source, lang_index, font_id)
}) {
let preserves_hft_alias = decision.alt_type == Some(2)
&& decision.requested_face.as_deref() == Some(query)
&& environment.preserves_source_metrics_for(query);
if query != target && !preserves_hft_alias {
decision.css_family_chain.retain(|face| face != query);
decision.css_family_chain.insert(0, query.to_string());
}
}
let canonical_rule = decision.requested_face.as_deref().and_then(|source| {
environment.canonical_selection_rule_for(source, lang_index, font_id)
});
decision.substitution_boundary =
canonical_rule.map(|_| FontSubstitutionBoundary::MissingProgram);
decision.substitution_rule_id = canonical_rule;
decision.environment_profile_id = Some(environment.id().to_string());
}
}
if decision.embedded != Some(true)
&& environment.is_some_and(|env| {
decision
.normalized_face
.as_deref()
.is_some_and(|face| env.selects_true_type(face))
})
{
decision.environment_profile_id = environment.map(|env| env.id().to_string());
}
if decision.embedded != Some(true) {
if let Some((environment, fallbacks)) = environment.and_then(|env| {
decision
.normalized_face
.as_deref()
.and_then(|face| {
decision.requested_face.as_deref().and_then(|source| {
env.glyph_fallbacks_for_slot(source, face, lang_index, font_id)
})
})
.map(|fallbacks| (env, fallbacks))
}) {
let source_fallbacks = decision.css_family_chain.split_off(1);
for face in fallbacks.iter().chain(&source_fallbacks) {
if !decision.css_family_chain.contains(face) {
decision.css_family_chain.push(face.clone());
}
}
decision.environment_profile_id = Some(environment.id().to_string());
} else if let Some(primary) = decision.normalized_face.as_deref() {
for face in super::font_metrics_data::verified_program_glyph_fallback_families(primary)
{
if !decision
.css_family_chain
.iter()
.any(|existing| existing == face)
{
decision.css_family_chain.push((*face).to_string());
}
}
}
}
decision
}
fn lookup_font_name(doc_info: &DocInfo, lang_index: usize, font_id: u16) -> String {
lookup_font_name_decision(doc_info, lang_index, font_id)
.css_family_chain
.join(",")
}
pub fn primary_font_name(font_family: &str) -> &str {
font_family.split(',').next().unwrap_or(font_family).trim()
}
pub(crate) fn resolve_font_substitution(
name: &str,
alt_type: u8,
lang_index: usize,
) -> Option<&'static str> {
resolve_font_substitution_decision(name, alt_type, lang_index).map(|(face, _, _)| face)
}
pub(crate) fn resolve_font_substitution_decision(
name: &str,
alt_type: u8,
lang_index: usize,
) -> Option<(&'static str, FontSubstitutionBoundary, &'static str)> {
if let Some(rule) =
resolve_projected_font_rule(FontSubstitutionBoundary::LegacyLatin, name, lang_index)
{
return Some((
rule.target_face_or_policy,
FontSubstitutionBoundary::LegacyLatin,
rule.rule_id,
));
}
if alt_type == 2 {
if let Some(rule) =
resolve_projected_font_rule(FontSubstitutionBoundary::Hft, name, lang_index)
{
return Some((
rule.target_face_or_policy,
FontSubstitutionBoundary::Hft,
rule.rule_id,
));
}
}
resolve_projected_font_rule(FontSubstitutionBoundary::Ttf, name, lang_index).map(|rule| {
(
rule.target_face_or_policy,
FontSubstitutionBoundary::Ttf,
rule.rule_id,
)
})
}
fn resolve_projected_font_rule(
boundary: FontSubstitutionBoundary,
name: &str,
lang_index: usize,
) -> Option<&'static GeneratedFontRuleProjection> {
find_font_rule_layout_name(boundary.source_boundary_id(), name, lang_index)
}
pub(crate) fn is_heavy_display_face(font_family: &str) -> bool {
let primary = font_family
.split(',')
.next()
.unwrap_or(font_family)
.trim()
.trim_matches('\'')
.trim_matches('"');
matches!(
primary,
"HY헤드라인M"
| "HYHeadLine M"
| "HYHeadLine Medium"
| "HY견고딕"
| "한양견고딕"
| "HYGothic-Extra"
| "HY견명조B"
| "HY그래픽"
| "HY그래픽M"
| "휴먼엑스포"
)
}
fn primary_font_face(font_family: &str) -> &str {
font_family
.split(',')
.next()
.unwrap_or(font_family)
.trim()
.trim_matches('\'')
.trim_matches('"')
}
pub(crate) fn is_bold_weight_face(font_family: &str) -> bool {
let primary = primary_font_face(font_family);
let lower = primary.to_lowercase();
lower.contains("bold") || lower.contains("볼드")
}
pub(crate) fn is_light_weight_face(font_family: &str) -> bool {
let primary = primary_font_face(font_family);
let lower = primary.to_lowercase();
!is_bold_weight_face(font_family)
&& (lower.contains("light")
|| lower.contains("extralight")
|| lower.contains("thin")
|| lower.contains("ultralight"))
}
pub(crate) fn is_medium_weight_face(font_family: &str) -> bool {
let primary = primary_font_face(font_family);
let lower = primary.to_lowercase();
lower.contains("중고딕")
|| lower.contains("태고딕")
|| lower.contains("mediumgothic")
|| lower.contains("hymedium")
}
fn resolve_para_styles(doc_info: &DocInfo, dpi: f64) -> Vec<ResolvedParaStyle> {
resolve_para_styles_with_variant(doc_info, dpi, false)
}
fn resolve_para_styles_with_variant(
doc_info: &DocInfo,
dpi: f64,
is_hwp3_variant: bool,
) -> Vec<ResolvedParaStyle> {
let char_unit_hu = para_margin_char_unit_hu(doc_info);
doc_info
.para_shapes
.iter()
.map(|ps| {
resolve_single_para_style(ps, &doc_info.tab_defs, dpi, is_hwp3_variant, char_unit_hu)
})
.collect()
}
fn para_margin_char_unit_hu(doc_info: &DocInfo) -> f64 {
let base_size = doc_info
.styles
.first()
.and_then(|style| doc_info.char_shapes.get(style.char_shape_id as usize))
.map(|shape| shape.base_size)
.filter(|&size| size > 0)
.unwrap_or(1000);
base_size as f64 / 200.0
}
fn para_margin_hwpunit(stored: i32, char_unit_hu: f64) -> f64 {
if stored % 2 != 0 {
((stored - 1) / 2) as f64 * char_unit_hu
} else {
(stored / 2) as f64
}
}
pub(crate) fn paragraph_margin_hwpunit(raw: i32, doc_info: &DocInfo) -> f64 {
para_margin_hwpunit(raw, para_margin_char_unit_hu(doc_info))
}
fn resolve_single_para_style(
ps: &ParaShape,
tab_defs: &[TabDef],
dpi: f64,
is_hwp3_variant: bool,
char_unit_hu: f64,
) -> ResolvedParaStyle {
match try_resolve_single_para_style(
ps,
tab_defs,
dpi,
is_hwp3_variant,
char_unit_hu,
&storage::Unbounded,
) {
Ok(style) => style,
Err(never) => match never {},
}
}
#[cfg(feature = "pdf-import")]
pub(crate) fn try_resolve_paragraph_style<A: storage::Storage>(
ps: &ParaShape,
doc_info: &DocInfo,
dpi: f64,
storage: &A,
) -> Result<ResolvedParaStyle, A::Error> {
try_resolve_single_para_style(
ps,
&doc_info.tab_defs,
dpi,
false,
para_margin_char_unit_hu(doc_info),
storage,
)
}
fn try_resolve_single_para_style<A: storage::Storage>(
ps: &ParaShape,
tab_defs: &[TabDef],
dpi: f64,
is_hwp3_variant: bool,
char_unit_hu: f64,
storage: &A,
) -> Result<ResolvedParaStyle, A::Error> {
let line_spacing = match ps.line_spacing_type {
LineSpacingType::Percent => ps.line_spacing as f64,
_ => hwpunit_to_px(ps.line_spacing, dpi) / 2.0,
};
let default_tab_width = hwpunit_to_px(4000, dpi);
let tab_def = tab_defs.get(ps.tab_def_id as usize);
let mut tab_stops = storage.vec(tab_def.map_or(0, |definition| definition.tabs.len()))?;
if let Some(definition) = tab_def {
for tab in &definition.tabs {
tab_stops.push(TabStop {
position: hwpunit_to_px(tab.position as i32, dpi) / 2.0,
tab_type: tab.tab_type,
fill_type: tab.fill_type,
});
}
}
let auto_tab_right = tab_def.map(|td| td.auto_tab_right).unwrap_or(false);
let _ = is_hwp3_variant;
let margin_px = |stored: i32| {
para_margin_hwpunit(stored, char_unit_hu) * dpi / crate::renderer::HWPUNIT_PER_INCH
};
Ok(ResolvedParaStyle {
alignment: ps.alignment,
vertical_alignment: ((ps.attr1 >> 20) & 0x03) as u8,
line_spacing,
line_spacing_type: ps.line_spacing_type,
margin_left: margin_px(ps.margin_left),
margin_right: margin_px(ps.margin_right),
indent: margin_px(ps.indent),
spacing_before: margin_px(ps.spacing_before),
spacing_after: margin_px(ps.spacing_after),
head_type: ps.head_type,
para_level: ps.para_level,
numbering_id: ps.numbering_id,
border_fill_id: ps.border_fill_id,
border_spacing: [
hwpunit_to_px(ps.border_spacing[0] as i32, dpi),
hwpunit_to_px(ps.border_spacing[1] as i32, dpi),
hwpunit_to_px(ps.border_spacing[2] as i32, dpi),
hwpunit_to_px(ps.border_spacing[3] as i32, dpi),
],
border_connect: ps.attr1 & (1 << 28) != 0,
border_ignore_margin: ps.attr1 & (1 << 29) != 0,
default_tab_width,
tab_stops,
auto_tab_left: tab_def.is_some_and(|td| td.auto_tab_left),
auto_tab_right,
condense_min_space: ((ps.attr1 >> 9) & 0x7f).min(75) as u8,
english_break_unit: ((ps.attr1 >> 5) & 0x03) as u8,
korean_break_unit: ((ps.attr1 >> 7) & 0x01) as u8,
widow_orphan: (ps.attr1 >> 16) & 1 != 0,
keep_with_next: (ps.attr1 >> 17) & 1 != 0,
keep_lines: (ps.attr1 >> 18) & 1 != 0,
page_break_before: (ps.attr1 >> 19) & 1 != 0,
})
}
fn resolve_border_styles(doc_info: &DocInfo, dpi: f64) -> Vec<ResolvedBorderStyle> {
doc_info
.border_fills
.iter()
.map(|bf| resolve_single_border_style(bf, dpi))
.collect()
}
fn resolve_single_border_style(bf: &BorderFill, dpi: f64) -> ResolvedBorderStyle {
match try_resolve_single_border_style(bf, dpi, &storage::Unbounded) {
Ok(style) => style,
Err(never) => match never {},
}
}
fn try_resolve_single_border_style<S: storage::Storage>(
bf: &BorderFill,
dpi: f64,
storage: &S,
) -> Result<ResolvedBorderStyle, S::Error> {
let fill_color = match bf.fill.fill_type {
FillType::Solid => bf.fill.solid.as_ref().and_then(|s| {
if s.pattern_type > 0 || (s.background_color >> 24) != 0 {
None
} else {
Some(s.background_color)
}
}),
_ => None,
};
let pattern = match bf.fill.fill_type {
FillType::Solid => bf.fill.solid.as_ref().and_then(|s| {
if s.pattern_type > 0 {
Some(PatternFillInfo {
pattern_type: s.pattern_type,
tile_size: hwpunit_to_px(576, dpi),
pattern_color: s.pattern_color,
background_color: s.background_color,
})
} else {
None
}
}),
_ => None,
};
let gradient = match bf.fill.fill_type {
FillType::Gradient => {
if let Some(g) = bf.fill.gradient.as_ref() {
if g.colors.len() < 2
|| g.colors.len() > 64
|| g.center_x.abs() > 200
|| g.center_y.abs() > 200
{
None
} else {
let positions: Vec<f64> = if g.positions.is_empty() {
let n = g.colors.len();
storage.collect((0..n).map(|i| i as f64 / (n.max(2) - 1).max(1) as f64))?
} else {
storage.collect(g.positions.iter().map(|&p| p as f64 / 100.0))?
};
let (colors, positions) = super::try_expand_gradient_steps(
&g.colors,
&positions,
g.blur,
g.step_center,
storage,
)?;
storage.bytes(std::mem::size_of::<GradientFillInfo>())?;
Some(Box::new(GradientFillInfo {
gradient_type: g.gradient_type,
angle: g.angle,
center_x: g.center_x,
center_y: g.center_y,
colors,
positions,
}))
}
} else {
None
}
}
_ => None,
};
let image_fill = match bf.fill.fill_type {
FillType::Image => bf.fill.image.as_ref().map(|img| ResolvedImageFill {
bin_data_id: img.bin_data_id,
fill_mode: img.fill_mode,
brightness: img.brightness,
contrast: img.contrast,
effect: image_fill_effect(img.effect),
}),
_ => None,
};
Ok(ResolvedBorderStyle {
borders: bf.borders,
fill_color,
pattern,
gradient,
image_fill,
diagonal_attr: bf.attr,
diagonal: bf.diagonal,
center_line: if bf.center_line != CenterLine::None {
bf.center_line
} else {
CenterLine::from_hwp_attr(bf.attr)
},
})
}
fn image_fill_effect(effect: u8) -> ImageEffect {
match effect {
1 => ImageEffect::GrayScale,
2 => ImageEffect::BlackWhite,
3 => ImageEffect::Pattern8x8,
_ => ImageEffect::RealPic,
}
}
#[cfg(test)]
mod tests;