Skip to content

The native runtime for three.js: three.js, down to the metal. 45× smaller than Electron, on a Sony PS3, and path-traced at 60 fps on ray-tracing GPUs.

7.3 KB
Raw Blame
//! Blocks of text for a native UI text provider: measure a line, find soft breaks, paint lines.
//!
//! The same font resolution, per-character fallback and colour-emoji advances as `fillText`
//! (`text::layout`), so a UI drawn through this matches the canvas and Chrome's text metrics.

use std::rc::Rc;

use objc2_core_foundation::{CFAttributedString, CFDictionary, CFIndex, CFString, CFType, CGAffineTransform};
use objc2_core_text::{kCTFontAttributeName, CTTypesetter};

use crate::canvas::{Canvas, Paint, Use2};
use crate::fonts::{self, Font, ParsedFont};
use crate::text;

/// A face request: CSS families, weight (100–900), italic, size in px.
#[derive(Clone, Debug, PartialEq)]
pub struct TextFont {
    pub families: Vec<String>,
    pub weight: u16,
    pub italic: bool,
    pub size: f64,
}

/// A resolved face for text blocks.
pub struct BlockFont {
    parsed: Rc<ParsedFont>,
    font: Rc<Font>,
}

impl BlockFont {
    pub fn new(spec: &TextFont) -> BlockFont {
        let parsed = Rc::new(ParsedFont {
            families: spec.families.clone(),
            weight: spec.weight,
            italic: spec.italic,
            size: spec.size,
            line_height: None,
            small_caps: false,
            stretch: None,
            oblique: false,
        });
        let font = fonts::resolve_parsed(&parsed);
        BlockFont { parsed, font }
    }
    /// CSS `line-height: normal` for this face, in px.
    pub fn normal_line_height(&self) -> f64 {
        self.font.line_metrics().line_spacing()
    }
    /// The advance width of one line (no `'\n'`), in px.
    pub fn measure(&self, line: &str) -> f64 {
        self.measure_spaced(line, 0.0)
    }
    /// The advance width of one line with `tracking` px after each character (CSS letter-spacing).
    pub fn measure_spaced(&self, line: &str, tracking: f64) -> f64 {
        let utf16: Vec<u16> = line.encode_utf16().collect();
        text::layout(&self.font, &utf16, tracking, 0.0, true).width
    }
    /// Soft-break positions (UTF-16 offsets, ascending) that keep each row of `line` within
    /// `max_width` px: Unicode line breaking as CoreText applies it, trailing spaces hanging.
    /// A row too narrow for one grapheme still takes one.
    pub fn wrap(&self, line: &str, max_width: f64) -> Vec<u32> {
        let utf16: Vec<u16> = line.encode_utf16().collect();
        let mut breaks = Vec::new();
        if utf16.is_empty() || !(max_width > 0.0) || self.measure(line) <= max_width {
            return breaks;
        }
        let string = CFString::from_str(line);
        let key: &CFString = unsafe { kCTFontAttributeName };
        let value: &CFType = self.font.ct.as_ref();
        let attributes = CFDictionary::from_slices(&[key], &[value]);
        let Some(attributed) = (unsafe { CFAttributedString::new(None, Some(&string), Some(attributes.as_opaque())) }) else {
            return breaks;
        };
        let typesetter = unsafe { CTTypesetter::with_attributed_string(&attributed) };
        let mut start = 0usize;
        while start < utf16.len() {
            let mut count = unsafe { typesetter.suggest_line_break(start as CFIndex, max_width) } as usize;
            if count == 0 {
                count = fonts::grapheme_end(&utf16, start) - start;
            }
            // CoreText measures with its own advances; keep the row within our measure.
            while count > 1 {
                let row = String::from_utf16_lossy(&utf16[start..start + count]);
                if self.measure(row.trim_end()) <= max_width + 0.5 {
                    break;
                }
                let shorter = unsafe { typesetter.suggest_line_break(start as CFIndex, max_width - 1.0) } as usize;
                count = if shorter > 0 && shorter < count { shorter } else { count - 1 };
            }
            let end = start + count.max(1);
            if end >= utf16.len() {
                break;
            }
            breaks.push(end as u32);
            start = end;
        }
        breaks
    }
}

/// Pixels of a painted block.
pub struct PaintedBlock {
    pub width: u32,
    pub height: u32,
    /// straight-alpha RGBA8, sRGB
    pub rgba: Vec<u8>,
    /// logical offset of pixel (0, 0) from the block's origin
    pub offset: [f32; 2],
}

/// Paint `text` (lines separated by `'\n'`) in `color` (straight RGBA): each line in a row of
/// `line_height` px with CSS half-leading, aligned within `box_width` (0 left, 1 center,
/// 2 right), `tracking` px after each character, at `scale` device px per px.
#[allow(clippy::too_many_arguments)]
pub fn paint(font: &BlockFont, text: &str, color: [u8; 4], align: u8, box_width: f32, line_height: f32, tracking: f32, scale: f32) -> Option<PaintedBlock> {
    let lines: Vec<&str> = text.split('\n').collect();
    let widths: Vec<f64> = lines.iter().map(|line| font.measure_spaced(line, tracking as f64)).collect();
    if widths.iter().all(|w| *w <= 0.0) {
        return None;
    }
    let metrics = font.font.line_metrics();
    let line_h = line_height as f64;
    // ink may leave the line box: emoji and descenders below, accents above, italics sideways
    let pad_x = (font.parsed.size * 0.25).ceil() + 1.0;
    let overflow = ((metrics.ascent + metrics.descent - line_h) / 2.0).max(0.0);
    let pad_y = (overflow + font.parsed.size * 0.15).ceil() + 1.0;
    let content_w = widths.iter().cloned().fold(box_width as f64, f64::max);
    let logical_w = content_w + 2.0 * pad_x;
    let logical_h = line_h * lines.len() as f64 + 2.0 * pad_y;
    let scale = scale as f64;
    let width = (logical_w * scale).ceil() as u32;
    let height = (logical_h * scale).ceil() as u32;
    if width == 0 || height == 0 || width > 16384 || height > 16384 {
        return None;
    }
    let mut pixels = vec![0u8; width as usize * height as usize * 4];
    {
        let mut canvas = Canvas::new(pixels.as_mut_ptr(), width, height);
        canvas.state.ctm = CGAffineTransform { a: scale, b: 0.0, c: 0.0, d: scale, tx: 0.0, ty: 0.0 };
        canvas.state.font = font.parsed.clone();
        canvas.state.resolved = Some(font.font.clone());
        canvas.state.fill = Paint::color(color[0] as f64 / 255.0, color[1] as f64 / 255.0, color[2] as f64 / 255.0, color[3] as f64 / 255.0);
        canvas.state.align = 2; // left: x is the line's start
        canvas.state.letter_spacing = tracking as f64;
        canvas.state.baseline = 0; // alphabetic
        for (row, (line, line_w)) in lines.iter().zip(&widths).enumerate() {
            if line.is_empty() {
                continue;
            }
            let dx = match align {
                1 => (box_width as f64 - line_w) / 2.0,
                2 => box_width as f64 - line_w,
                _ => 0.0,
            };
            // CSS: the glyphs' ascent+descent centred in the line box (half-leading)
            let top = row as f64 * line_h + (line_h - (metrics.ascent + metrics.descent)) / 2.0;
            let utf16: Vec<u16> = line.encode_utf16().collect();
            canvas.draw_text(&utf16, pad_x + dx, pad_y + top + metrics.ascent, None, Use2::Fill);
        }
    }
    // premultiplied → straight alpha
    for px in pixels.chunks_exact_mut(4) {
        let a = px[3] as u32;
        if a != 0 && a != 255 {
            for c in &mut px[..3] {
                *c = ((*c as u32 * 255 + a / 2) / a).min(255) as u8;
            }
        }
    }
    Some(PaintedBlock { width, height, rgba: pixels, offset: [-pad_x as f32, -pad_y as f32] })
}