arc-ui 0.4.0

Physics-first native Rust desktop UI component library & charts for GPUI (120+ interactive components ported from Arc).
Documentation
//! 真实字形轮廓:`stroke_text` 与 `fold_text` 共用同一套字体解析与轮廓构建。
//!
//! 坐标沿用字体坐标(y 向上为负),调用方按需翻转;这里只负责把 ttf 的线段/贝塞尔
//! 拆成折线,让上层可以按弧长(描边)或按顶点(透视投影)自由处理。

use std::sync::{Mutex, OnceLock};

use arc_motion::{PathPoint, PolylinePath};

/// 二次/三次贝塞尔的细分数:128px 下肉眼已看不出折角,继续加只增内存。
const QUAD_STEPS: usize = 16;
const CUBIC_STEPS: usize = 24;

#[derive(Default)]
pub(crate) struct Outline {
    pub contours: Vec<PolylinePath>,
    current: Vec<PathPoint>,
    cursor: (f32, f32),
}

impl Outline {
    fn finish(&mut self) {
        if self.current.len() > 1 {
            self.contours
                .push(PolylinePath::new(std::mem::take(&mut self.current)));
        } else {
            self.current.clear();
        }
    }

    fn add(&mut self, x: f32, y: f32) {
        // 字体坐标 y 向上,这里统一翻成屏幕方向(y 向下为正)。
        self.current.push(PathPoint::new(x, -y));
        self.cursor = (x, y);
    }

    /// 取一个字形(含内轮廓/字怀)的折线集合。
    pub fn glyph(face: &ttf_parser::Face<'_>, id: ttf_parser::GlyphId) -> Self {
        let mut outline = Self::default();
        face.outline_glyph(id, &mut outline);
        outline.finish();
        outline
    }
}

impl ttf_parser::OutlineBuilder for Outline {
    fn move_to(&mut self, x: f32, y: f32) {
        self.finish();
        self.add(x, y);
    }

    fn line_to(&mut self, x: f32, y: f32) {
        self.add(x, y);
    }

    fn quad_to(&mut self, x1: f32, y1: f32, x: f32, y: f32) {
        let (x0, y0) = self.cursor;
        for step in 1..=QUAD_STEPS {
            let t = step as f32 / QUAD_STEPS as f32;
            let u = 1.0 - t;
            self.add(
                u * u * x0 + 2.0 * u * t * x1 + t * t * x,
                u * u * y0 + 2.0 * u * t * y1 + t * t * y,
            );
        }
    }

    fn curve_to(&mut self, x1: f32, y1: f32, x2: f32, y2: f32, x: f32, y: f32) {
        let (x0, y0) = self.cursor;
        for step in 1..=CUBIC_STEPS {
            let t = step as f32 / CUBIC_STEPS as f32;
            let u = 1.0 - t;
            self.add(
                u.powi(3) * x0 + 3.0 * u * u * t * x1 + 3.0 * u * t * t * x2 + t.powi(3) * x,
                u.powi(3) * y0 + 3.0 * u * u * t * y1 + 3.0 * u * t * t * y2 + t.powi(3) * y,
            );
        }
    }

    fn close(&mut self) {
        if let Some(first) = self.current.first().copied() {
            self.current.push(first);
        }
        self.finish();
    }
}

static FONTS: OnceLock<Mutex<fontdb::Database>> = OnceLock::new();

/// 加载系统字体库(只做一次;首次约几十毫秒,调用方应放到后台线程)。
pub(crate) fn install_fonts() {
    FONTS.get_or_init(|| {
        let mut db = fontdb::Database::new();
        db.load_system_fonts();
        Mutex::new(db)
    });
}

/// SVG 文字塑形复用同一份系统字体库;不为每个模糊档位重新发现字体。
#[cfg(test)]
pub(crate) fn svg_font_database() -> Result<std::sync::Arc<fontdb::Database>, String> {
    static SHARED: OnceLock<std::sync::Arc<fontdb::Database>> = OnceLock::new();
    if let Some(db) = SHARED.get() {
        return Ok(db.clone());
    }
    install_fonts();
    let db = FONTS
        .get()
        .ok_or("字体数据库不可用")?
        .lock()
        .map_err(|_| "字体数据库不可用".to_string())?;
    Ok(SHARED
        .get_or_init(|| std::sync::Arc::new(db.clone()))
        .clone())
}

/// 按族名 + 字重挑一个可用字面,交给回调读取轮廓数据。
pub(crate) fn with_face<R>(
    family: &str,
    weight: u16,
    body: impl FnOnce(&mut ttf_parser::Face<'_>) -> Result<R, String>,
) -> Result<R, String> {
    install_fonts();
    let db = FONTS.get().ok_or("字体数据库不可用")?;
    let db = db.lock().map_err(|_| "字体数据库不可用".to_string())?;
    let families = [
        fontdb::Family::Name(family),
        fontdb::Family::Name("Segoe UI"),
        fontdb::Family::Name("Arial"),
        fontdb::Family::Name("DejaVu Sans"),
        fontdb::Family::SansSerif,
    ];
    let id = db
        .query(&fontdb::Query {
            families: &families,
            weight: fontdb::Weight(weight.clamp(100, 900)),
            ..Default::default()
        })
        .ok_or("没有可用的轮廓字体")?;
    db.with_face_data(id, |bytes, index| {
        let mut face =
            ttf_parser::Face::parse(bytes, index).map_err(|e| format!("无法解析字体:{e:?}"))?;
        face.set_variation(ttf_parser::Tag::from_bytes(b"wght"), weight as f32);
        body(&mut face)
    })
    .ok_or_else(|| "无法读取字体数据".to_string())?
}