rhwp 0.9.0

HWP/HWPX document engine for Rust applications, WebAssembly, and CLI automation
Documentation
//! Shared font setup for horizontal positioned Canvas2D text and its provider.
//! This does not select an exact fallback face or authorize another backend.

use super::{canvas_font_family_chain, TextStyle};

#[derive(Debug, Clone)]
pub struct CanvasTextFont {
    descriptor: String,
    old_hangul_descriptor: String,
    draw_size: f64,
    baseline: f64,
    horizontal_scale: f64,
    layout_ratio: f64,
}

impl CanvasTextFont {
    /// 측정과 paint가 같은 크기·장평·CSS 반올림과 face 사다리를 사용한다.
    /// 자체 굵기용 face가 공급되지 않았으면 원래 bold fallback으로 이어진다.
    /// Registration must reject invalid styles; painting keeps its old fallback.
    pub fn for_positioned_text(style: &TextStyle, baseline: f64) -> Self {
        let base_size = style.effective_font_size();
        let (size, baseline) = style.script_draw_metrics(base_size, baseline);
        let (draw_size, horizontal_scale) = style.ratio_draw_params(size);
        let family = family_chain(style);
        let prefix = format!(
            "{}{}{:.3}px ",
            super::text_italic::css_prefix(style.italic),
            if style.is_visually_bold() && super::faux_bold_stroke_width(style, draw_size).is_none()
            {
                "bold "
            } else {
                ""
            },
            draw_size,
        );
        Self {
            descriptor: format!("{prefix}{family}"),
            old_hangul_descriptor: format!("{prefix}'RHWP Old Hangul', {family}"),
            draw_size,
            baseline,
            horizontal_scale,
            layout_ratio: if style.ratio > 0.0 { style.ratio } else { 1.0 },
        }
    }

    pub fn descriptor(&self) -> &str {
        &self.descriptor
    }

    pub fn old_hangul_descriptor(&self) -> &str {
        &self.old_hangul_descriptor
    }

    pub fn draw_size(&self) -> f64 {
        self.draw_size
    }

    pub fn baseline(&self) -> f64 {
        self.baseline
    }

    pub fn horizontal_scale(&self) -> f64 {
        self.horizontal_scale
    }

    /// Convert measureText at the *actual CSS size* to the pre-ratio advance
    /// consumed by layout. Then layout_advance = measured * paint_scale exactly.
    /// Do not scale by nominal_size / rounded_CSS_size: that would undo CSS
    /// rounding (or optical-size-dependent metrics) which the painter retains.
    pub fn natural_advance(&self, measured_advance: f64) -> Option<f64> {
        if !measured_advance.is_finite()
            || measured_advance < 0.0
            || !self.draw_size.is_finite()
            || self.draw_size < 0.0005 // CSS {:.3} would become 0.000px
            || !self.layout_ratio.is_finite()
            || !self.horizontal_scale.is_finite()
        {
            return None;
        }
        let advance = measured_advance * (self.horizontal_scale / self.layout_ratio);
        (advance.is_finite() && advance >= 0.0).then_some(advance)
    }
}

/// 원 face의 자체 굵기와 fallback 보완 굵기를 CSS face 선택 단계에서 구분한다.
/// 예약 별칭은 실제 프로그램의 family가 확인된 정상 face에만 공급한다.
/// 원 face에 없는 글리프는 뒤의 원래 사다리에서 bold fallback을 사용한다.
/// 명시적 bold는 별칭을 사용하지 않아 추가 굵기 요청을 보존한다.
pub(crate) fn family_chain(style: &TextStyle) -> String {
    let mut fallback = canvas_font_family_chain(&style.font_family);
    let primary = super::internal_font_family_members(&style.font_family);
    let Some(primary) = primary.first() else {
        return fallback;
    };
    if style.source_font_is_ttf {
        // 호스트가 원본 TTF용 별칭을 준비하지 못한 경우에도 원래 CSS 사다리로 폴백한다.
        fallback = format!(
            "'__rhwp_ttf__{}', {}",
            primary.replace('\\', "\\\\").replace('\'', "\\'"),
            fallback
        );
    }
    if style.bold || !super::style_resolver::is_heavy_display_face(&style.font_family) {
        return fallback;
    }
    format!(
        "'__rhwp_intrinsic__{}', {}",
        primary.replace('\\', "\\\\").replace('\'', "\\'"),
        fallback
    )
}