use std::cell::RefCell;
use std::collections::hash_map::DefaultHasher;
use std::collections::HashMap;
use std::hash::{Hash, Hasher};
use mgui_core::{
BoxConstraints, Color, ElementId, LayoutContext, PaintCommand, PaintList, Point, Rect, RenderObject, Size,
};
const ATLAS_SIZE: u32 = 1024;
const ATLAS_PADDING: u32 = 1;
const FALLBACK_ADVANCE_X: f32 = 8.0;
const MAX_ATLAS_SIZE: u32 = 8192;
pub const DEFAULT_FONT_STACK: &str =
"system-ui, 'Segoe UI', Tahoma, 'Arial', 'Segoe UI Symbol', 'Microsoft YaHei UI', 'Segoe UI Emoji', sans-serif";
#[derive(Clone, Copy, Debug)]
#[allow(dead_code)]
pub struct AtlasEntry {
pub uv: [f32; 4],
pub width: u32,
pub height: u32,
}
pub struct Atlas {
width: u32,
height: u32,
next_x: u32,
next_y: u32,
row_height: u32,
pixels: Vec<u8>,
entries: HashMap<GlyphKey, AtlasEntry>,
dirty: bool,
dirty_rows: Option<(u32, u32)>,
generation: u64,
}
#[derive(Clone, Copy, Debug, Eq, PartialEq, Hash)]
pub struct GlyphKey(pub u64);
impl GlyphKey {
pub fn new(
font_blob_id: usize,
glyph_id: u16,
size_px_bits: u32,
x_bin: i32,
y_bin: i32,
subpixel_bits: u8,
) -> Self {
let mut h = DefaultHasher::new();
font_blob_id.hash(&mut h);
glyph_id.hash(&mut h);
size_px_bits.hash(&mut h);
x_bin.hash(&mut h);
y_bin.hash(&mut h);
subpixel_bits.hash(&mut h);
GlyphKey(h.finish())
}
}
fn raster_font_id(font_blob_id: usize, coords: &[swash::NormalizedCoord]) -> usize {
if coords.is_empty() {
return font_blob_id;
}
let mut h = DefaultHasher::new();
font_blob_id.hash(&mut h);
for c in coords {
c.hash(&mut h);
}
h.finish() as usize
}
impl Atlas {
pub fn new(width: u32, height: u32) -> Self {
Self {
width,
height,
next_x: 0,
next_y: 0,
row_height: 0,
pixels: vec![0; (width * height) as usize],
entries: HashMap::new(),
dirty: false,
dirty_rows: None,
generation: 1,
}
}
fn expand_2x(&mut self) {
let new_w = (self.width * 2).min(MAX_ATLAS_SIZE);
let new_h = (self.height * 2).min(MAX_ATLAS_SIZE);
if new_w == self.width && new_h == self.height {
return; }
let old_w = self.width;
let old_h = self.height;
let new_size = (new_w * new_h) as usize;
let mut new_pixels = vec![0u8; new_size];
for row in 0..old_h as usize {
let src_start = row * old_w as usize;
let dst_start = row * new_w as usize;
new_pixels[dst_start..dst_start + old_w as usize]
.copy_from_slice(&self.pixels[src_start..src_start + old_w as usize]);
}
self.pixels = new_pixels;
let scale_u = old_w as f32 / new_w as f32; let scale_v = old_h as f32 / new_h as f32;
for entry in self.entries.values_mut() {
entry.uv[0] *= scale_u;
entry.uv[1] *= scale_v;
entry.uv[2] *= scale_u;
entry.uv[3] *= scale_v;
}
self.width = new_w;
self.height = new_h;
self.dirty = true;
self.dirty_rows = Some((0, new_h));
self.generation += 1;
mgui_core::element::request_full_repaint();
}
fn clear_atlas(&mut self) {
self.entries.clear();
self.pixels.fill(0);
self.next_x = 0;
self.next_y = 0;
self.row_height = 0;
self.dirty = true;
self.dirty_rows = Some((0, self.height));
self.generation += 1;
mgui_core::element::request_full_repaint();
}
pub fn get_or_insert(&mut self, key: GlyphKey, bitmap: &[u8], w: u32, h: u32) -> AtlasEntry {
if let Some(&e) = self.entries.get(&key) {
return e;
}
let alloc_w = w + ATLAS_PADDING * 2;
let alloc_h = h + ATLAS_PADDING * 2;
if self.next_x + alloc_w > self.width {
self.next_x = 0;
self.next_y += self.row_height;
self.row_height = 0;
}
if self.next_y + alloc_h > self.height {
if self.width >= MAX_ATLAS_SIZE && self.height >= MAX_ATLAS_SIZE {
self.clear_atlas();
} else {
self.expand_2x();
}
return self.get_or_insert(key, bitmap, w, h);
}
let dst_x = self.next_x + ATLAS_PADDING;
let dst_y = self.next_y + ATLAS_PADDING;
for row in 0..h {
let src_start = (row * w) as usize;
let src_end = src_start + w as usize;
let dst_row = (dst_y + row) as usize * self.width as usize + dst_x as usize;
self.pixels[dst_row..dst_row + w as usize].copy_from_slice(&bitmap[src_start..src_end]);
}
let u0 = dst_x as f32 / self.width as f32;
let v0 = dst_y as f32 / self.height as f32;
let u1 = (dst_x + w) as f32 / self.width as f32;
let v1 = (dst_y + h) as f32 / self.height as f32;
let entry = AtlasEntry { uv: [u0, v0, u1, v1], width: w, height: h };
self.entries.insert(key, entry);
self.next_x += alloc_w;
if alloc_h > self.row_height {
self.row_height = alloc_h;
}
self.mark_rows_written(dst_y, h);
self.generation += 1;
entry
}
fn mark_rows_written(&mut self, y: u32, h: u32) {
self.dirty = true;
let end = (y + h).min(self.height);
self.dirty_rows = Some(match self.dirty_rows {
Some((top, bottom)) => (top.min(y), bottom.max(end)),
None => (y, end),
});
}
pub fn pixels(&self) -> &[u8] {
&self.pixels
}
#[allow(dead_code)]
pub fn glyph_count(&self) -> usize {
self.entries.len()
}
pub fn is_dirty(&self) -> bool {
self.dirty
}
pub fn clear_dirty(&mut self) {
self.dirty = false;
self.dirty_rows = None;
}
}
#[derive(Clone)]
struct RasterGlyph {
data: Vec<u8>,
width: u32,
height: u32,
left: i32,
top: i32,
last_used: u64,
}
type LineCacheKey = (TextKey, u32, Option<u32>, u64);
struct LineCacheEntry {
line: std::rc::Rc<ShapedLine>,
last_used: u64,
}
pub struct FontState {
pub font_cx: parley::FontContext,
pub layout_cx: parley::LayoutContext<()>,
pub scale_cx: swash::scale::ScaleContext,
pub atlas: Atlas,
raster_cache: HashMap<GlyphKey, RasterGlyph>,
raster_cache_bytes: usize,
line_cache: HashMap<LineCacheKey, LineCacheEntry>,
rich_cache: HashMap<RichCacheKey, RichCacheEntry>,
rich_clock: u64,
line_clock: u64,
glyph_clock: u64,
pub shape_calls: usize,
}
impl FontState {
fn new() -> Self {
Self {
font_cx: parley::FontContext::new(),
layout_cx: parley::LayoutContext::<()>::new(),
scale_cx: swash::scale::ScaleContext::new(),
atlas: Atlas::new(ATLAS_SIZE, ATLAS_SIZE),
raster_cache: HashMap::new(),
raster_cache_bytes: 0,
line_cache: HashMap::new(),
rich_cache: HashMap::new(),
rich_clock: 0,
line_clock: 0,
glyph_clock: 0,
shape_calls: 0,
}
}
}
thread_local! {
static FONT_STATE: RefCell<Option<FontState>> = const { RefCell::new(None) }; static TEXT_DPR: std::cell::Cell<f32> = const { std::cell::Cell::new(1.0) };
}
pub fn set_text_dpr(dpr: f32) {
TEXT_DPR.with(|c| c.set(if dpr > 0.0 { dpr } else { 1.0 }));
}
fn text_dpr() -> f32 {
TEXT_DPR.with(|c| c.get())
}
pub fn with_font<F, R>(f: F) -> R
where
F: FnOnce(&mut FontState) -> R,
{
FONT_STATE.with(|cell| {
let mut opt = cell.borrow_mut();
if opt.is_none() {
*opt = Some(FontState::new());
}
f(opt.as_mut().unwrap())
})
}
const LINE_CACHE_LIMIT: usize = 4096;
const LINE_CACHE_TARGET: usize = LINE_CACHE_LIMIT - LINE_CACHE_LIMIT / 4;
fn evict_line_cache_lru(fs: &mut FontState) {
if fs.line_cache.len() <= LINE_CACHE_TARGET {
return;
}
let mut by_age: Vec<(u64, LineCacheKey)> = fs.line_cache.iter().map(|(k, v)| (v.last_used, k.clone())).collect();
by_age.sort_unstable_by_key(|&(last_used, _)| last_used);
let remove = fs.line_cache.len().saturating_sub(LINE_CACHE_TARGET);
for (_, key) in by_age.into_iter().take(remove) {
fs.line_cache.remove(&key);
}
}
const RASTER_CACHE_BUDGET_BYTES: usize = 32 * 1024 * 1024;
const RASTER_CACHE_TARGET_BYTES: usize = RASTER_CACHE_BUDGET_BYTES * 3 / 4;
fn insert_raster_glyph(fs: &mut FontState, key: GlyphKey, mut glyph: RasterGlyph) {
fs.glyph_clock += 1;
glyph.last_used = fs.glyph_clock;
let bytes = glyph.data.len();
if let Some(old) = fs.raster_cache.insert(key, glyph) {
fs.raster_cache_bytes = fs.raster_cache_bytes.saturating_sub(old.data.len());
}
fs.raster_cache_bytes += bytes;
trim_raster_cache(fs);
}
fn trim_raster_cache(fs: &mut FontState) {
if fs.raster_cache_bytes <= RASTER_CACHE_BUDGET_BYTES {
return;
}
let mut candidates: Vec<(u64, GlyphKey, usize)> =
fs.raster_cache.iter().map(|(&key, g)| (g.last_used, key, g.data.len())).collect();
candidates.sort_unstable_by_key(|&(last_used, _, _)| last_used);
for (_, key, bytes) in candidates {
if fs.raster_cache_bytes <= RASTER_CACHE_TARGET_BYTES {
break;
}
fs.raster_cache.remove(&key);
fs.raster_cache_bytes = fs.raster_cache_bytes.saturating_sub(bytes);
}
}
#[derive(Clone, PartialEq, Eq, Hash)]
enum TextKey {
Owned(String),
Shared(std::rc::Rc<str>, Option<(usize, usize)>),
}
impl TextKey {
fn owned(text: &str) -> Self {
TextKey::Owned(text.to_string())
}
}
struct ShapedGlyph {
raster_key: GlyphKey,
glyph_id: u16,
x: f32,
w: f32,
#[allow(dead_code)]
y: f32,
ascent: f32,
descent: f32,
cluster: u32,
}
struct ShapedRun {
glyphs: Vec<ShapedGlyph>,
baseline_y: f32,
font: parley::Font,
norm_coords: std::rc::Rc<[swash::NormalizedCoord]>,
raster_size: f32,
}
struct ShapedLine {
runs: Vec<ShapedRun>,
max_x: f32,
#[allow(dead_code)]
max_y: f32,
visual_lines: Vec<(usize, usize)>,
}
fn shape_text(
fs: &mut FontState,
text: &str,
raster_px: f32,
max_width_px: Option<f32>,
font_stack: &str,
) -> std::rc::Rc<ShapedLine> {
shape_text_keyed(fs, text, TextKey::owned(text), raster_px, max_width_px, font_stack)
}
fn shape_text_keyed(
fs: &mut FontState,
text: &str,
text_key: TextKey,
raster_px: f32,
max_width_px: Option<f32>,
font_stack: &str,
) -> std::rc::Rc<ShapedLine> {
let font_stack_hash = {
let mut h = DefaultHasher::new();
font_stack.hash(&mut h);
h.finish()
};
let key = (text_key, raster_px.to_bits(), max_width_px.map(|w| w.to_bits()), font_stack_hash);
if let Some(entry) = fs.line_cache.get_mut(&key) {
fs.line_clock += 1;
entry.last_used = fs.line_clock;
return std::rc::Rc::clone(&entry.line);
}
fs.shape_calls += 1;
let dpr = text_dpr();
let scale = 1.0f32;
let font_size_px = raster_px / dpr;
let wrap_opt = max_width_px.filter(|&w| w > 0.0);
let mut builder = fs.layout_cx.ranged_builder(&mut fs.font_cx, text, scale, true);
builder.push_default(parley::StyleProperty::FontSize(font_size_px));
builder.push_default(parley::StyleProperty::LineHeight(1.2));
builder.push_default(parley::StyleProperty::FontStack(parley::FontStack::Source(std::borrow::Cow::Borrowed(
font_stack,
))));
builder.push_default(parley::StyleProperty::WordBreak(parley::swash::text::WordBreakStrength::KeepAll));
builder.push_default(parley::StyleProperty::OverflowWrap(parley::OverflowWrap::Anywhere));
let mut layout: parley::Layout<()> = builder.build(text);
layout.break_all_lines(wrap_opt);
layout.align(wrap_opt, parley::Alignment::Start, parley::AlignmentOptions::default());
let mut runs = Vec::new();
let mut max_x = 0.0f32;
let mut max_y = 0.0f32;
let mut visual_lines = Vec::new();
for line in layout.lines() {
let mut line_start = usize::MAX;
let mut line_end = 0usize;
for run in line.runs() {
let range = run.text_range();
line_start = line_start.min(range.start);
line_end = line_end.max(range.end);
}
visual_lines.push(if line_start == usize::MAX { (0, 0) } else { (line_start, line_end) });
let line_m = line.metrics();
let baseline_y = line_m.baseline * dpr;
for item in line.items() {
let parley::PositionedLayoutItem::GlyphRun(gr) = item else {
continue;
};
let run_metrics = gr.run().metrics();
let ascent = run_metrics.ascent * dpr;
let descent = run_metrics.descent * dpr;
let font_size_logical = gr.run().font_size(); let font_size_phys = font_size_logical * dpr; let font_blob_id = gr.run().font().data.id() as usize;
let mut run_glyphs: Vec<ShapedGlyph> = Vec::new();
let norm_coords: std::rc::Rc<[swash::NormalizedCoord]> = gr.run().normalized_coords().to_vec().into();
let run_font = gr.run().font().clone();
let mut pen_x = gr.offset();
let run_baseline = gr.baseline();
for cluster in gr.run().visual_clusters() {
let cluster_byte = cluster.text_range().start as u32;
for g in cluster.glyphs() {
let glyph_id = g.id; let size_bits = font_size_phys.to_bits(); let x_bin = 0; let y_bin = 0;
let raster_key =
GlyphKey::new(raster_font_id(font_blob_id, &norm_coords), glyph_id, size_bits, x_bin, y_bin, 0);
if !fs.raster_cache.contains_key(&raster_key) {
if let Some(rg) =
rasterize_one_glyph(&run_font, font_size_phys, glyph_id, &norm_coords, &mut fs.scale_cx)
{
insert_raster_glyph(fs, raster_key, rg);
}
}
let gx = pen_x + g.x;
run_glyphs.push(ShapedGlyph {
raster_key,
glyph_id,
x: gx * dpr, w: g.advance * dpr, y: (run_baseline + g.y) * dpr, ascent,
descent,
cluster: cluster_byte,
});
max_x = max_x.max((gx + g.advance) * dpr);
max_y = max_y.max(baseline_y + descent);
pen_x += g.advance;
}
}
if !run_glyphs.is_empty() {
runs.push(ShapedRun {
glyphs: run_glyphs,
baseline_y,
font: run_font,
norm_coords,
raster_size: font_size_phys,
});
}
}
}
if max_y == 0.0 {
max_y = raster_px * 1.2;
}
let line = std::rc::Rc::new(ShapedLine { runs, max_x, max_y, visual_lines });
if fs.line_cache.len() >= LINE_CACHE_LIMIT {
evict_line_cache_lru(fs);
}
fs.line_clock += 1;
let entry = LineCacheEntry { line: std::rc::Rc::clone(&line), last_used: fs.line_clock };
fs.line_cache.insert(key, entry);
line
}
#[derive(Clone)]
pub struct AtlasSnapshot {
pub width: u32,
pub height: u32,
pub dirty: bool,
pub dirty_y: (u32, u32),
pub pixels: Option<Vec<u8>>,
}
pub fn atlas_snapshot() -> AtlasSnapshot {
with_font(|fs| {
let dirty = fs.atlas.is_dirty();
let (y0, y1) = if dirty {
let (a, b) = fs.atlas.dirty_rows.unwrap_or((0, fs.atlas.height));
(a.min(fs.atlas.height), b.min(fs.atlas.height))
} else {
(0, 0)
};
let pixels = if dirty {
let w = fs.atlas.width as usize;
Some(fs.atlas.pixels()[(y0 as usize * w)..(y1 as usize * w)].to_vec())
} else {
None
};
AtlasSnapshot { width: fs.atlas.width, height: fs.atlas.height, dirty, dirty_y: (y0, y1), pixels }
})
}
pub fn atlas_clear_dirty() {
with_font(|fs| {
fs.atlas.clear_dirty();
})
}
pub fn atlas_generation() -> u64 {
with_font(|fs| fs.atlas.generation)
}
#[derive(Clone, Copy, Debug, Default)]
pub struct AtlasStats {
pub width: u32,
pub height: u32,
pub glyph_count: usize,
pub used_height: u32,
pub dirty: bool,
}
pub fn atlas_stats() -> AtlasStats {
with_font(|fs| {
let atlas = &fs.atlas;
AtlasStats {
width: atlas.width,
height: atlas.height,
glyph_count: atlas.entries.len(),
used_height: (atlas.next_y + atlas.row_height).min(atlas.height),
dirty: atlas.dirty,
}
})
}
pub fn with_atlas<R>(f: impl FnOnce(u32, u32, &[u8]) -> R) -> R {
with_font(|fs| {
let atlas = &fs.atlas;
f(atlas.width, atlas.height, &atlas.pixels)
})
}
pub struct TextRenderObject {
text: String,
size_px: f32,
color: Color,
max_width: Option<f32>,
max_width_explicit: bool,
size: Size,
element_id: Option<ElementId>,
}
impl TextRenderObject {
pub fn new(text: String, size_px: f32, color: Color) -> Self {
Self { text, size_px, color, max_width: None, max_width_explicit: false, size: Size::ZERO, element_id: None }
}
pub fn with_max_width(mut self, max_width: f32) -> Self {
self.max_width = Some(max_width);
self.max_width_explicit = true;
self
}
pub fn set_max_width(&mut self, max_width: Option<f32>) {
self.max_width = max_width;
self.max_width_explicit = max_width.is_some();
}
fn measure(&self) -> Size {
let dpr = text_dpr();
let raster_px = self.size_px * dpr;
let width = with_font(|fs| {
let line = shape_text(fs, &self.text, raster_px, self.max_width, DEFAULT_FONT_STACK);
let max_x = line.max_x / dpr;
if max_x == 0.0 && !self.text.is_empty() {
self.text.chars().count() as f32 * FALLBACK_ADVANCE_X
} else {
max_x
}
});
let height = text_visual_height(&self.text, self.size_px, self.max_width);
Size::new(width, height)
}
}
pub fn measure_text_width(text: &str, size_px: f32) -> f32 {
measure_text_width_styled(text, size_px, DEFAULT_FONT_STACK)
}
pub fn measure_text_width_styled(text: &str, size_px: f32, font_stack: &str) -> f32 {
if text.is_empty() {
return 0.0;
}
with_font(|fs| {
let dpr = text_dpr();
let raster_px = size_px * dpr;
let line = shape_text(fs, text, raster_px, None, font_stack);
let w = line.max_x / dpr;
if w == 0.0 {
text.chars().count() as f32 * FALLBACK_ADVANCE_X
} else {
w
}
})
}
pub fn text_visual_height(text: &str, size_px: f32, max_width_px: Option<f32>) -> f32 {
text_visual_height_styled(text, size_px, max_width_px, DEFAULT_FONT_STACK)
}
pub fn text_visual_height_styled(text: &str, size_px: f32, max_width_px: Option<f32>, font_stack: &str) -> f32 {
if text.is_empty() {
return size_px;
}
with_font(|fs| {
let dpr = text_dpr();
let raster_px = size_px * dpr;
let line = shape_text(fs, text, raster_px, max_width_px, font_stack);
if line.runs.is_empty() {
return size_px;
}
let first_run = &line.runs[0];
let first_ascent = first_run.glyphs.first().map(|g| g.ascent).unwrap_or(raster_px);
let first_baseline = first_run.baseline_y;
let visual_top = first_baseline - first_ascent;
let mut visual_bottom = 0.0f32;
for run in &line.runs {
for sg in &run.glyphs {
let bottom = run.baseline_y + sg.descent;
visual_bottom = visual_bottom.max(bottom);
}
}
if visual_bottom > visual_top {
(visual_bottom - visual_top) / dpr
} else {
size_px
}
})
}
pub fn paint_text_line(
text: &str,
size_px: f32,
color: Color,
offset: Point,
list: &mut PaintList,
max_width_px: Option<f32>,
) -> f32 {
paint_text_line_impl(text, TextKey::owned(text), size_px, color, offset, list, max_width_px, DEFAULT_FONT_STACK)
}
#[allow(clippy::too_many_arguments)]
pub fn paint_text_line_styled(
text: &str,
size_px: f32,
color: Color,
offset: Point,
list: &mut PaintList,
max_width_px: Option<f32>,
font_stack: &str,
) -> f32 {
paint_text_line_impl(text, TextKey::owned(text), size_px, color, offset, list, max_width_px, font_stack)
}
#[allow(clippy::too_many_arguments)]
pub fn paint_text_span(
text: &std::rc::Rc<str>,
range: Option<(usize, usize)>,
size_px: f32,
color: Color,
offset: Point,
list: &mut PaintList,
max_width_px: Option<f32>,
) -> f32 {
let (start, end) = match range {
Some(r) => clamp_char_range(text, r),
None => (0, text.len()),
};
paint_text_line_impl(
&text[start..end],
TextKey::Shared(std::rc::Rc::clone(text), range),
size_px,
color,
offset,
list,
max_width_px,
DEFAULT_FONT_STACK,
)
}
pub fn text_ascent(text: &str, size_px: f32) -> f32 {
if text.is_empty() {
return size_px;
}
with_font(|fs| {
let dpr = text_dpr();
let shaped = shape_text(fs, text, size_px * dpr, None, DEFAULT_FONT_STACK);
first_glyph_ascent(&shaped).map(|a| a / dpr).unwrap_or(size_px)
})
}
pub fn text_span_ascent(text: &std::rc::Rc<str>, range: Option<(usize, usize)>, size_px: f32) -> f32 {
let (start, end) = match range {
Some(r) => clamp_char_range(text, r),
None => (0, text.len()),
};
if start >= end {
return size_px;
}
with_font(|fs| {
let dpr = text_dpr();
let shaped = shape_text_keyed(
fs,
&text[start..end],
TextKey::Shared(std::rc::Rc::clone(text), range),
size_px * dpr,
None,
DEFAULT_FONT_STACK,
);
first_glyph_ascent(&shaped).map(|a| a / dpr).unwrap_or(size_px)
})
}
fn first_glyph_ascent(shaped: &ShapedLine) -> Option<f32> {
shaped.runs.first().and_then(|r| r.glyphs.first()).map(|g| g.ascent)
}
fn clamp_char_range(text: &str, range: (usize, usize)) -> (usize, usize) {
let mut start = range.0.min(text.len());
let mut end = range.1.min(text.len());
while !text.is_char_boundary(start) {
start += 1;
}
while !text.is_char_boundary(end) {
end -= 1;
}
if end < start {
end = start;
}
(start, end)
}
#[allow(clippy::too_many_arguments)]
fn paint_text_line_impl(
text: &str,
text_key: TextKey,
size_px: f32,
color: Color,
offset: Point,
list: &mut PaintList,
max_width_px: Option<f32>,
font_stack: &str,
) -> f32 {
if text.is_empty() {
return 0.0;
}
let width = with_font(|fs| {
let dpr = text_dpr();
let raster_px = size_px * dpr;
let shaped = shape_text_keyed(fs, text, text_key, raster_px, max_width_px, font_stack);
let first_run = match shaped.runs.first() {
Some(r) => r,
None => return 0.0,
};
let first_ascent = first_run.glyphs.first().map(|g| g.ascent).unwrap_or(raster_px);
let first_baseline = first_run.baseline_y;
let anchor = first_baseline - first_ascent;
let mut max_x = 0.0f32;
for run in &shaped.runs {
for sg in &run.glyphs {
if !fs.raster_cache.contains_key(&sg.raster_key) {
if let Some(rg) =
rasterize_one_glyph(&run.font, run.raster_size, sg.glyph_id, &run.norm_coords, &mut fs.scale_cx)
{
insert_raster_glyph(fs, sg.raster_key, rg);
}
}
let Some(r) = fs.raster_cache.get_mut(&sg.raster_key) else {
continue;
};
if r.width == 0 || r.height == 0 {
continue;
}
fs.glyph_clock += 1;
r.last_used = fs.glyph_clock;
let entry = fs.atlas.get_or_insert(sg.raster_key, &r.data, r.width, r.height);
let x = offset.x + (sg.x + r.left as f32) / dpr;
let glyph_visual_top = run.baseline_y - r.top as f32;
let y = offset.y + (glyph_visual_top - anchor) / dpr;
let rect = Rect::new(x, y, r.width as f32 / dpr, r.height as f32 / dpr);
list.push(PaintCommand::TexturedRect {
rect,
color,
uv: entry.uv,
texture_id: 0,
mode: mgui_core::paint::TextureMode::Mask,
});
max_x = max_x.max((sg.x + sg.w) / dpr);
}
}
if max_x == 0.0 {
max_x = text.chars().count() as f32 * FALLBACK_ADVANCE_X;
}
max_x
});
width
}
pub fn wrapped_line_ranges(text: &str, size_px: f32, max_width: f32) -> Vec<(usize, usize)> {
if text.is_empty() {
return vec![(0, 0)];
}
if max_width <= 0.0 {
return vec![(0, text.len())];
}
with_font(|fs| {
let dpr = text_dpr();
let raster_px = size_px * dpr;
let shaped = shape_text(fs, text, raster_px, Some(max_width), DEFAULT_FONT_STACK);
shaped.visual_lines.clone()
})
}
pub fn measure_char_prefix_widths(text: &str, size_px: f32, font_stack: &str) -> Vec<f32> {
if text.is_empty() {
return vec![0.0];
}
with_font(|fs| {
let dpr = text_dpr();
let raster_px = size_px * dpr;
let shaped = shape_text(fs, text, raster_px, None, font_stack);
let char_count = text.chars().count();
let mut widths = vec![0.0f32; char_count + 1];
let mut byte_x: Vec<(u32, f32)> = Vec::new();
for run in &shaped.runs {
for sg in &run.glyphs {
match byte_x.last_mut() {
Some((b, _)) if *b == sg.cluster => {}
_ => byte_x.push((sg.cluster, sg.x)),
}
}
}
let mut prev = 0.0f32;
let mut bi = 0usize;
for (ci, (byte_pos, _)) in text.char_indices().enumerate() {
while bi < byte_x.len() && byte_x[bi].0 <= byte_pos as u32 {
prev = byte_x[bi].1 / dpr;
bi += 1;
}
widths[ci] = prev;
}
widths[char_count] = shaped.max_x / dpr;
widths
})
}
fn rasterize_one_glyph(
font: &parley::Font,
font_size: f32,
glyph_id: u16,
norm_coords: &[swash::NormalizedCoord],
scale_cx: &mut swash::scale::ScaleContext,
) -> Option<RasterGlyph> {
let bytes = font.data.data();
if bytes.is_empty() {
return None;
}
let font_ref = swash::FontRef::from_index(bytes, font.index as usize)?;
let mut scaler =
scale_cx.builder(font_ref).size(font_size).normalized_coords(norm_coords.iter()).hint(true).build();
let image = swash::scale::Render::new(&[
swash::scale::Source::ColorOutline(0),
swash::scale::Source::ColorBitmap(swash::scale::StrikeWith::BestFit),
swash::scale::Source::Outline,
])
.render(&mut scaler, glyph_id)?;
if image.placement.width == 0 || image.placement.height == 0 {
return Some(RasterGlyph { data: Vec::new(), width: 0, height: 0, left: 0, top: 0, last_used: 0 });
}
Some(RasterGlyph {
data: image.data.to_vec(),
width: image.placement.width,
height: image.placement.height,
left: image.placement.left,
top: image.placement.top,
last_used: 0,
})
}
impl RenderObject for TextRenderObject {
fn layout(&mut self, _bc: BoxConstraints, _ctx: &mut LayoutContext) -> Size {
let s = self.measure();
self.size = s;
s
}
fn content_size(&self) -> Size {
self.size
}
fn paint(&self, offset: Point, list: &mut PaintList) {
paint_text_line(&self.text, self.size_px, self.color, offset, list, self.max_width);
}
fn set_element_id(&mut self, id: ElementId) {
self.element_id = Some(id);
}
fn hit_test(&self, position: Point, offset: Point) -> Option<ElementId> {
let r = Rect::new(offset.x, offset.y, self.size.width, self.size.height);
if r.contains(position) {
self.element_id
} else {
None
}
}
}
#[cfg(test)]
mod tests {
use super::*;
fn mk_key(id: u32) -> GlyphKey {
GlyphKey(id as u64)
}
#[test]
fn atlas_get_or_insert_dedupes() {
let mut a = Atlas::new(64, 64);
let k = mk_key(1);
let e1 = a.get_or_insert(k, &[255; 8], 2, 4);
let e2 = a.get_or_insert(k, &[0; 8], 2, 4);
assert_eq!(e1.uv, e2.uv, "重复 key 必须返回同一 entry");
assert_eq!(a.glyph_count(), 1);
}
#[test]
fn atlas_wraps_to_next_row() {
let mut a = Atlas::new(20, 20);
let k1 = mk_key(1);
a.get_or_insert(k1, &[1; 64], 16, 4);
let k2 = mk_key(2);
let e2 = a.get_or_insert(k2, &[2; 64], 16, 4);
assert!(e2.uv[1] > 0.0, "第二个 glyph 应该换行,uv.v0 > 0");
}
#[test]
fn atlas_dirty_flag_lifecycle() {
let mut a = Atlas::new(64, 64);
assert!(!a.is_dirty());
a.get_or_insert(mk_key(1), &[255; 8], 2, 4);
assert!(a.is_dirty(), "get_or_insert 后应该 dirty");
a.clear_dirty();
assert!(!a.is_dirty());
a.get_or_insert(mk_key(1), &[0; 8], 2, 4);
assert!(!a.is_dirty(), "重复 key 不应触发 dirty");
a.get_or_insert(mk_key(2), &[0; 8], 2, 4);
assert!(a.is_dirty());
}
#[test]
fn atlas_snapshot_uploads_only_dirty_rows() {
let width = with_font(|fs| {
fs.atlas = Atlas::new(ATLAS_SIZE, ATLAS_SIZE);
fs.atlas.width
});
with_font(|fs| {
fs.atlas.get_or_insert(GlyphKey::new(7, 7, 0, 0, 0, 0), &[9u8; 16], 4, 4);
fs.atlas.get_or_insert(GlyphKey::new(7, 8, 0, 0, 0, 0), &[9u8; 16], 4, 4);
assert_eq!(fs.atlas.dirty_rows, Some((1, 5)), "同一行的写入应合并为单行带");
});
let snap = atlas_snapshot();
assert!(snap.dirty);
assert_eq!(snap.dirty_y, (1, 5));
assert_eq!(snap.pixels.as_ref().map(Vec::len), Some(width as usize * 4), "快照只拷贝 dirty 行");
atlas_clear_dirty();
let clean = atlas_snapshot();
assert!(!clean.dirty);
assert_eq!(clean.dirty_y, (0, 0));
assert!(clean.pixels.is_none());
}
#[test]
fn atlas_auto_expands_when_full() {
let mut a = Atlas::new(32, 32);
let e_before = a.get_or_insert(mk_key(1), &[100; 9], 3, 3);
let uv_scalar_before = e_before.uv[0];
let big: Vec<u8> = vec![200; 400]; for i in 2..10 {
a.get_or_insert(mk_key(i), &big, 20, 20);
}
assert!(a.width >= 32, "atlas 应保持原尺寸或扩容");
assert!(a.glyph_count() >= 8, "扩容后应能放下 8+ glyphs,实际 {}", a.glyph_count());
if a.width > 32 {
let e_after = a.get_or_insert(mk_key(1), &[0; 9], 3, 3);
let expected = uv_scalar_before / 2.0;
assert!((e_after.uv[0] - expected).abs() < 0.01, "扩容后 uv.u0 应为 {expected}, 实际 {}", e_after.uv[0]);
}
}
#[test]
fn atlas_accepts_new_glyphs_after_expansion() {
let mut a = Atlas::new(16, 16);
a.get_or_insert(mk_key(1), &[50; 144], 12, 12);
let e2 = a.get_or_insert(mk_key(2), &[100; 144], 12, 12);
assert!(a.width > 16 || a.height > 16, "应该扩容了");
let e1 = a.get_or_insert(mk_key(1), &[0; 144], 12, 12);
assert!(e2.uv[1] >= e1.uv[1], "第二个 glyph 应在第一个下方");
}
#[test]
fn text_measure_produces_nonzero_size() {
let t = TextRenderObject::new("Hello".into(), 24.0, Color::WHITE);
let s = t.measure();
assert!(s.width > 0.0, "width should be > 0 for 'Hello'");
assert!(s.height > 0.0, "height should be > 0");
}
#[test]
fn text_paint_emits_textured_rects() {
let t = TextRenderObject::new("Hi".into(), 24.0, Color::WHITE);
let mut list = PaintList::new();
t.paint(Point::new(0.0, 0.0), &mut list);
assert!(!list.is_empty(), "paint should emit at least 1 textured rect");
for cmd in &list.commands {
match cmd {
PaintCommand::TexturedRect { texture_id, uv, .. } => {
assert_eq!(*texture_id, 0);
assert!(uv[0] < uv[2]);
assert!(uv[1] < uv[3]);
}
_ => panic!("expected TexturedRect, got Rect"),
}
}
}
#[test]
fn text_paint_with_offset_shifts_rects() {
let t = TextRenderObject::new("X".into(), 24.0, Color::WHITE);
let mut list = PaintList::new();
t.paint(Point::new(100.0, 50.0), &mut list);
for cmd in &list.commands {
if let PaintCommand::TexturedRect { rect, .. } = cmd {
assert!(rect.x >= 100.0 - 1.0, "x={}", rect.x);
assert!(rect.y >= 50.0 - 1.0, "y={}", rect.y);
}
}
}
#[test]
fn shape_line_cache_hits_second_paint() {
let mut list1 = PaintList::new();
paint_text_line("cache-hit-test", 20.0, Color::WHITE, Point::ZERO, &mut list1, None);
let calls_1 = with_font(|fs| fs.shape_calls);
let mut list2 = PaintList::new();
paint_text_line("cache-hit-test", 20.0, Color::WHITE, Point::new(5.0, 5.0), &mut list2, None);
let calls_2 = with_font(|fs| fs.shape_calls);
assert_eq!(calls_1, calls_2, "第二次 paint 应命中缓存,不再 shape");
assert_eq!(list1.commands.len(), list2.commands.len(), "缓存命中的绘制输出数量应一致");
}
#[test]
fn shape_line_cache_evicts_lru_at_limit() {
let fake_line =
|| std::rc::Rc::new(ShapedLine { runs: Vec::new(), max_x: 0.0, max_y: 0.0, visual_lines: Vec::new() });
let hot_key = (TextKey::Owned("hot-entry".to_string()), 0, None, 0);
let oldest_key = (TextKey::Owned("fake-entry-0".to_string()), 0, None, 0);
with_font(|fs| {
fs.line_cache.clear();
fs.line_clock = 0;
fs.line_clock += 1;
fs.line_cache.insert(hot_key.clone(), LineCacheEntry { line: fake_line(), last_used: fs.line_clock });
for i in 0..LINE_CACHE_LIMIT - 1 {
fs.line_clock += 1;
fs.line_cache.insert(
(TextKey::Owned(format!("fake-entry-{i}")), 0, None, 0),
LineCacheEntry { line: fake_line(), last_used: fs.line_clock },
);
}
fs.line_clock += 1;
fs.line_cache.get_mut(&hot_key).expect("hot entry").last_used = fs.line_clock;
});
let mut list = PaintList::new();
paint_text_line("trigger-evict", 14.0, Color::WHITE, Point::ZERO, &mut list, None);
with_font(|fs| {
assert!(fs.line_cache.len() <= LINE_CACHE_LIMIT, "超限后应回收到上限内");
assert!(fs.line_cache.len() >= LINE_CACHE_TARGET, "LRU 只应淘汰最旧 1/4");
assert!(fs.line_cache.contains_key(&hot_key), "刚访问过的热条目不应被淘汰");
assert!(!fs.line_cache.contains_key(&oldest_key), "最久未访问的条目应被淘汰");
fs.line_cache.clear();
});
}
#[test]
fn paint_rebuilds_evicted_raster_glyphs() {
let mut first = PaintList::new();
paint_text_line("raster-rebuild-test", 18.0, Color::WHITE, Point::ZERO, &mut first, None);
assert!(!first.commands.is_empty());
with_font(|fs| {
fs.raster_cache.clear();
fs.raster_cache_bytes = 0;
});
let mut second = PaintList::new();
paint_text_line("raster-rebuild-test", 18.0, Color::WHITE, Point::ZERO, &mut second, None);
assert_eq!(first.commands.len(), second.commands.len(), "位图淘汰后应重建 glyph,而不是丢字");
assert!(!second.commands.is_empty());
}
#[test]
fn zero_size_glyphs_are_cached_not_rerasterized() {
with_font(|fs| {
fs.raster_cache.clear();
fs.raster_cache_bytes = 0;
let _ = shape_text(fs, "a b c", 13.0, None, DEFAULT_FONT_STACK);
let cached = fs.raster_cache.len();
assert!(
fs.raster_cache.values().any(|g| g.width == 0 && g.height == 0),
"空格等零尺寸 glyph 必须缓存占位,不能每次重栅格化"
);
let _ = shape_text(fs, "a b c d", 13.0, None, DEFAULT_FONT_STACK);
assert_eq!(fs.raster_cache.len(), cached + 1, "除新字符外不得新增栅格化条目");
fs.raster_cache.clear();
fs.raster_cache_bytes = 0;
});
}
#[test]
fn raster_cache_trims_to_budget() {
with_font(|fs| {
fs.raster_cache.clear();
fs.raster_cache_bytes = 0;
let chunk = vec![0u8; 8 * 1024 * 1024];
for i in 0..5u16 {
insert_raster_glyph(
fs,
GlyphKey::new(0, i, 0, 0, 0, 0),
RasterGlyph { data: chunk.clone(), width: 2048, height: 1024, left: 0, top: 0, last_used: 0 },
);
}
assert!(fs.raster_cache_bytes <= RASTER_CACHE_TARGET_BYTES, "应回收到目标水位");
assert_eq!(fs.raster_cache.len(), 3, "LRU 应保留最近的条目");
assert!(!fs.raster_cache.contains_key(&GlyphKey::new(0, 0, 0, 0, 0, 0)), "最旧条目应被淘汰");
assert!(fs.raster_cache.contains_key(&GlyphKey::new(0, 4, 0, 0, 0, 0)), "最新条目应保留");
fs.raster_cache.clear();
fs.raster_cache_bytes = 0;
});
}
#[test]
fn paint_text_line_dpr_rasterizes_at_physical_resolution() {
fn paint_once(dpr: f32) -> (f32, f32, f32) {
set_text_dpr(dpr);
let mut list = PaintList::new();
let width = paint_text_line("H", 24.0, Color::WHITE, Point::ZERO, &mut list, None);
let (rect_w, uv_span) = match &list.commands[0] {
PaintCommand::TexturedRect { rect, uv, .. } => (rect.width, (uv[2] - uv[0]) * ATLAS_SIZE as f32),
_ => panic!("expected TexturedRect"),
};
set_text_dpr(1.0); (rect_w, uv_span, width)
}
let (w1, span1, ret1) = paint_once(1.0);
let (w2, span2, ret2) = paint_once(2.0);
assert!((w1 - w2).abs() <= 2.0, "rect 逻辑尺寸应 dpr 无关(允许取整 ≤2px): dpr1={w1} vs dpr2={w2}");
assert!((ret1 - ret2).abs() < 0.5 && ret1 > 0.0, "返回宽度(逻辑)应 dpr 无关: {ret1} vs {ret2}");
assert!(span2 > span1 * 1.5, "atlas 位图分辨率应随 dpr 变大: dpr1={span1}px vs dpr2={span2}px");
let mw = measure_text_width("H", 24.0);
assert!((ret1 - mw).abs() < 0.5, "paint 宽度应与 measure 一致(TextField 光标定位依赖): {ret1} vs {mw}");
}
}
pub fn is_rtl_text(text: &str) -> bool {
for ch in text.chars() {
let code = ch as u32;
let rtl = matches!(
code,
0x0590..=0x05FF | 0x0600..=0x06FF | 0x0700..=0x074F | 0x0750..=0x077F | 0x0780..=0x07BF | 0x0860..=0x086F | 0x08A0..=0x08FF | 0xFB1D..=0xFB4F | 0xFB50..=0xFDFF | 0xFE70..=0xFEFF );
if rtl {
return true;
}
if ch.is_alphabetic() {
return false;
}
}
false
}
pub fn mirror_carets_for_rtl(widths: &[f32]) -> Vec<f32> {
let chars = widths.len().saturating_sub(1);
if chars == 0 {
return widths.to_vec();
}
let mut carets = vec![0.0f32; chars + 1];
carets[0] = widths[chars];
carets[1..=chars].copy_from_slice(&widths[..chars]);
carets
}
pub fn measure_caret_positions(text: &str, size_px: f32, font_stack: &str) -> Vec<f32> {
let widths = measure_char_prefix_widths(text, size_px, font_stack);
if is_rtl_text(text) {
mirror_carets_for_rtl(&widths)
} else {
widths
}
}
pub fn nearest_caret_index(carets: &[f32], x: f32) -> usize {
carets
.iter()
.enumerate()
.min_by(|(ia, a), (ib, b)| (**a - x).abs().total_cmp(&(**b - x).abs()).then_with(|| ia.cmp(ib)))
.map(|(index, _)| index)
.unwrap_or(0)
}
#[cfg(test)]
mod rtl_tests {
use super::*;
#[test]
fn detects_base_direction() {
assert!(is_rtl_text("مرحبا بالعالم"));
assert!(is_rtl_text("שלום"));
assert!(!is_rtl_text("hello مرحبا")); assert!(!is_rtl_text("123 !?"));
assert!(is_rtl_text("123 مرحبا")); }
#[test]
fn rtl_caret_mirroring_and_nearest_index() {
let widths = [0.0, 10.0, 25.0, 40.0];
let carets = mirror_carets_for_rtl(&widths);
assert_eq!(carets, vec![40.0, 0.0, 10.0, 25.0]);
assert_eq!(nearest_caret_index(&carets, 38.0), 0, "靠近右缘 → 文本起点");
assert_eq!(nearest_caret_index(&carets, 2.0), 1);
assert_eq!(nearest_caret_index(&carets, 24.0), 3, "靠近左缘 → 文本末尾");
assert_eq!(mirror_carets_for_rtl(&[0.0]), vec![0.0]);
assert_eq!(nearest_caret_index(&widths, 12.0), 1);
}
}
#[derive(Clone, Debug, PartialEq)]
pub struct RichTextSpan {
pub text: String,
pub size_px: f32,
pub color: Option<Color>,
pub font_stack: Option<String>,
pub weight: Option<u16>,
pub italic: bool,
}
impl RichTextSpan {
pub fn new(text: impl Into<String>) -> Self {
Self { text: text.into(), size_px: 15.0, color: None, font_stack: None, weight: None, italic: false }
}
pub fn with_size(mut self, size_px: f32) -> Self {
self.size_px = size_px;
self
}
pub fn with_color(mut self, color: Color) -> Self {
self.color = Some(color);
self
}
pub fn with_font_stack(mut self, stack: impl Into<String>) -> Self {
self.font_stack = Some(stack.into());
self
}
pub fn with_weight(mut self, weight: u16) -> Self {
self.weight = Some(weight.clamp(1, 1000));
self
}
pub fn bold(self) -> Self {
self.with_weight(700)
}
pub fn with_italic(mut self, italic: bool) -> Self {
self.italic = italic;
self
}
pub fn italic(self) -> Self {
self.with_italic(true)
}
}
pub type InlinePainter = std::rc::Rc<dyn Fn(&mut PaintList, Rect)>;
#[derive(Clone)]
pub struct InlineItem {
pub width: f32,
pub height: f32,
pub painter: InlinePainter,
}
impl InlineItem {
pub fn new(width: f32, height: f32, painter: impl Fn(&mut PaintList, Rect) + 'static) -> Self {
Self { width, height, painter: std::rc::Rc::new(painter) }
}
}
impl std::fmt::Debug for InlineItem {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
f.debug_struct("InlineItem").field("width", &self.width).field("height", &self.height).finish()
}
}
impl PartialEq for InlineItem {
fn eq(&self, other: &Self) -> bool {
self.width == other.width && self.height == other.height && std::rc::Rc::ptr_eq(&self.painter, &other.painter)
}
}
#[derive(Clone, Debug, PartialEq)]
pub enum RichItem {
Text(RichTextSpan),
Inline(InlineItem),
}
#[derive(Clone, Debug, PartialEq)]
pub struct RichText {
text: std::rc::Rc<str>,
spans: Vec<RichTextSpan>,
ranges: Vec<(usize, usize)>,
inlines: Vec<(usize, InlineItem)>,
}
impl RichText {
pub fn new(spans: Vec<RichTextSpan>) -> Self {
Self::from_items(spans.into_iter().map(RichItem::Text).collect())
}
pub fn from_items(items: Vec<RichItem>) -> Self {
let mut text = String::new();
let mut spans = Vec::new();
let mut ranges = Vec::new();
let mut inlines = Vec::new();
for item in items {
match item {
RichItem::Text(span) => {
let start = text.len();
text.push_str(&span.text);
spans.push(span);
ranges.push((start, text.len()));
}
RichItem::Inline(inline) => inlines.push((text.len(), inline)),
}
}
Self { text: text.into(), spans, ranges, inlines }
}
pub fn plain_text(&self) -> &str {
&self.text
}
pub fn spans(&self) -> &[RichTextSpan] {
&self.spans
}
pub fn is_empty(&self) -> bool {
self.text.is_empty() && self.inlines.is_empty()
}
}
struct RichShapedGlyph {
raster_key: GlyphKey,
glyph_id: u16,
x: f32,
span: u16,
}
struct RichShapedRun {
glyphs: Vec<RichShapedGlyph>,
baseline_y: f32,
ascent: f32,
font: parley::Font,
norm_coords: std::rc::Rc<[swash::NormalizedCoord]>,
raster_size: f32,
}
struct RichInlineBox {
id: u16,
x: f32,
y: f32,
width: f32,
height: f32,
line_baseline: f32,
}
struct RichShapedLine {
runs: Vec<RichShapedRun>,
inline_boxes: Vec<RichInlineBox>,
max_x: f32,
max_y: f32,
}
#[derive(Clone, PartialEq, Eq, Hash)]
struct RichCacheKey {
text: std::rc::Rc<str>,
styles: Vec<(usize, usize, u32, u64)>,
inlines: Vec<(usize, u32, u32)>,
width_bits: Option<u32>,
dpr_bits: u32,
}
struct RichCacheEntry {
line: std::rc::Rc<RichShapedLine>,
last_used: u64,
}
fn rich_style_signature(rich: &RichText) -> Vec<(usize, usize, u32, u64)> {
rich.ranges
.iter()
.zip(&rich.spans)
.map(|((start, end), span)| {
let stack = span.font_stack.as_deref().unwrap_or(DEFAULT_FONT_STACK);
let mut h = DefaultHasher::new();
stack.hash(&mut h);
span.weight.unwrap_or(400).hash(&mut h);
span.italic.hash(&mut h);
(*start, *end, span.size_px.max(1.0).to_bits(), h.finish())
})
.collect()
}
fn span_index_at(ranges: &[(usize, usize)], byte: usize) -> u16 {
ranges.iter().position(|(start, end)| byte >= *start && byte < *end).unwrap_or(0) as u16
}
fn shape_rich(fs: &mut FontState, rich: &RichText, max_width_px: Option<f32>) -> std::rc::Rc<RichShapedLine> {
let dpr = text_dpr();
let key = RichCacheKey {
text: std::rc::Rc::clone(&rich.text),
styles: rich_style_signature(rich),
inlines: rich
.inlines
.iter()
.map(|(index, inline)| (*index, inline.width.to_bits(), inline.height.to_bits()))
.collect(),
width_bits: max_width_px.map(|w| w.to_bits()),
dpr_bits: dpr.to_bits(),
};
if let Some(entry) = fs.rich_cache.get_mut(&key) {
fs.rich_clock += 1;
entry.last_used = fs.rich_clock;
return std::rc::Rc::clone(&entry.line);
}
let text: &str = &rich.text;
let mut builder = fs.layout_cx.ranged_builder(&mut fs.font_cx, text, 1.0, true);
builder.push_default(parley::StyleProperty::FontSize(15.0));
builder.push_default(parley::StyleProperty::LineHeight(1.2));
builder.push_default(parley::StyleProperty::FontStack(parley::FontStack::Source(std::borrow::Cow::Borrowed(
DEFAULT_FONT_STACK,
))));
builder.push_default(parley::StyleProperty::WordBreak(parley::swash::text::WordBreakStrength::KeepAll));
builder.push_default(parley::StyleProperty::OverflowWrap(parley::OverflowWrap::Anywhere));
for ((start, end), span) in rich.ranges.iter().zip(&rich.spans) {
if span.size_px > 0.0 {
builder.push(parley::StyleProperty::FontSize(span.size_px), *start..*end);
}
if let Some(stack) = &span.font_stack {
builder.push(
parley::StyleProperty::FontStack(parley::FontStack::Source(std::borrow::Cow::Borrowed(stack))),
*start..*end,
);
}
if let Some(weight) = span.weight {
builder.push(parley::StyleProperty::FontWeight(parley::FontWeight::new(weight as f32)), *start..*end);
}
if span.italic {
builder.push(parley::StyleProperty::FontStyle(parley::FontStyle::Italic), *start..*end);
}
}
for (id, (index, inline)) in rich.inlines.iter().enumerate() {
builder.push_inline_box(parley::InlineBox {
id: id as u64,
index: *index,
width: inline.width,
height: inline.height,
});
}
let mut layout: parley::Layout<()> = builder.build(text);
let wrap_opt = max_width_px.filter(|w| *w > 0.0);
layout.break_all_lines(wrap_opt);
layout.align(wrap_opt, parley::Alignment::Start, parley::AlignmentOptions::default());
let mut runs = Vec::new();
let mut inline_boxes = Vec::new();
let mut max_x = 0.0f32;
let mut max_y = 0.0f32;
for line in layout.lines() {
let line_m = line.metrics();
let baseline_y = line_m.baseline * dpr;
for item in line.items() {
let parley::PositionedLayoutItem::GlyphRun(gr) = item else {
if let parley::PositionedLayoutItem::InlineBox(b) = item {
inline_boxes.push(RichInlineBox {
id: b.id as u16,
x: b.x,
y: b.y,
width: b.width,
height: b.height,
line_baseline: baseline_y,
});
max_x = max_x.max((b.x + b.width) * dpr);
max_y = max_y.max((b.y + b.height) * dpr);
}
continue;
};
let run_metrics = gr.run().metrics();
let ascent = run_metrics.ascent * dpr;
let descent = run_metrics.descent * dpr;
let font_size_phys = gr.run().font_size() * dpr;
let font_blob_id = gr.run().font().data.id() as usize;
let norm_coords: std::rc::Rc<[swash::NormalizedCoord]> = gr.run().normalized_coords().to_vec().into();
let run_font = gr.run().font().clone();
let mut pen_x = gr.offset();
let mut run_glyphs = Vec::new();
for cluster in gr.run().visual_clusters() {
let cluster_byte = cluster.text_range().start;
let span = span_index_at(&rich.ranges, cluster_byte);
for g in cluster.glyphs() {
let raster_key = GlyphKey::new(
raster_font_id(font_blob_id, &norm_coords),
g.id,
font_size_phys.to_bits(),
0,
0,
0,
);
if !fs.raster_cache.contains_key(&raster_key) {
if let Some(rg) =
rasterize_one_glyph(&run_font, font_size_phys, g.id, &norm_coords, &mut fs.scale_cx)
{
insert_raster_glyph(fs, raster_key, rg);
}
}
let gx = pen_x + g.x;
run_glyphs.push(RichShapedGlyph { raster_key, glyph_id: g.id, x: gx * dpr, span });
max_x = max_x.max((gx + g.advance) * dpr);
max_y = max_y.max(baseline_y + descent);
pen_x += g.advance;
}
}
if !run_glyphs.is_empty() {
runs.push(RichShapedRun {
glyphs: run_glyphs,
baseline_y,
ascent,
font: run_font,
norm_coords,
raster_size: font_size_phys,
});
}
}
}
if max_y == 0.0 {
max_y = rich.spans.iter().map(|s| s.size_px).fold(15.0, f32::max) * 1.2 * dpr;
}
let line = std::rc::Rc::new(RichShapedLine { runs, inline_boxes, max_x, max_y });
if fs.rich_cache.len() >= LINE_CACHE_LIMIT {
fs.rich_cache.clear();
}
fs.rich_clock += 1;
fs.rich_cache.insert(key, RichCacheEntry { line: std::rc::Rc::clone(&line), last_used: fs.rich_clock });
line
}
pub fn rich_text_size(rich: &RichText, max_width: Option<f32>) -> Size {
if rich.is_empty() {
return Size::ZERO;
}
with_font(|fs| {
let dpr = text_dpr();
let shaped = shape_rich(fs, rich, max_width);
let first_baseline = shaped.runs.first().map(|r| r.baseline_y);
let (anchor, fallback_h) = match first_baseline {
Some(baseline) => {
let first_ascent =
shaped.runs.iter().filter(|r| r.baseline_y == baseline).map(|r| r.ascent).fold(0.0f32, f32::max);
let inline_top = shaped
.inline_boxes
.iter()
.filter(|b| b.line_baseline == baseline)
.map(|b| b.y * dpr)
.fold(f32::INFINITY, f32::min);
((baseline - first_ascent).min(inline_top), 0.0)
}
None => (0.0, shaped.max_y),
};
let height = if shaped.max_y > anchor { (shaped.max_y - anchor) / dpr } else { fallback_h / dpr };
Size::new(shaped.max_x / dpr, height)
})
}
#[derive(Clone, Debug, PartialEq)]
pub struct RichTextLayout {
pub size: Size,
pub inline_rects: Vec<Rect>,
}
pub fn rich_text_layout(rich: &RichText, max_width: Option<f32>) -> RichTextLayout {
if rich.is_empty() {
return RichTextLayout { size: Size::ZERO, inline_rects: Vec::new() };
}
with_font(|fs| {
let dpr = text_dpr();
let shaped = shape_rich(fs, rich, max_width);
let first_baseline = shaped.runs.first().map(|r| r.baseline_y);
let anchor = match first_baseline {
Some(baseline) => {
let first_ascent =
shaped.runs.iter().filter(|r| r.baseline_y == baseline).map(|r| r.ascent).fold(0.0f32, f32::max);
let inline_top = shaped
.inline_boxes
.iter()
.filter(|b| b.line_baseline == baseline)
.map(|b| b.y * dpr)
.fold(f32::INFINITY, f32::min);
(baseline - first_ascent).min(inline_top)
}
None => 0.0,
};
let height = if shaped.max_y > anchor { (shaped.max_y - anchor) / dpr } else { 0.0 };
let mut inline_rects = vec![Rect::new(0.0, 0.0, 0.0, 0.0); rich.inlines.len()];
for b in &shaped.inline_boxes {
if let Some(slot) = inline_rects.get_mut(b.id as usize) {
*slot = Rect::new(b.x, (b.y * dpr - anchor) / dpr, b.width, b.height);
}
}
RichTextLayout { size: Size::new(shaped.max_x / dpr, height), inline_rects }
})
}
pub fn paint_rich_text(rich: &RichText, offset: Point, list: &mut PaintList, max_width: Option<f32>) -> f32 {
paint_rich_text_with_default(rich, Color::WHITE, offset, list, max_width)
}
pub fn paint_rich_text_with_default(
rich: &RichText,
default_color: Color,
offset: Point,
list: &mut PaintList,
max_width: Option<f32>,
) -> f32 {
if rich.is_empty() {
return 0.0;
}
with_font(|fs| {
let dpr = text_dpr();
let shaped = shape_rich(fs, rich, max_width);
let Some(first_run) = shaped.runs.first() else {
return 0.0;
};
let first_baseline = first_run.baseline_y;
let first_ascent =
shaped.runs.iter().filter(|r| r.baseline_y == first_baseline).map(|r| r.ascent).fold(0.0f32, f32::max);
let inline_top = shaped
.inline_boxes
.iter()
.filter(|b| b.line_baseline == first_baseline)
.map(|b| b.y * dpr)
.fold(f32::INFINITY, f32::min);
let anchor = (first_baseline - first_ascent).min(inline_top);
for run in &shaped.runs {
for sg in &run.glyphs {
if !fs.raster_cache.contains_key(&sg.raster_key) {
if let Some(rg) =
rasterize_one_glyph(&run.font, run.raster_size, sg.glyph_id, &run.norm_coords, &mut fs.scale_cx)
{
insert_raster_glyph(fs, sg.raster_key, rg);
}
}
let Some(r) = fs.raster_cache.get_mut(&sg.raster_key) else {
continue;
};
if r.width == 0 || r.height == 0 {
continue;
}
fs.glyph_clock += 1;
r.last_used = fs.glyph_clock;
let entry = fs.atlas.get_or_insert(sg.raster_key, &r.data, r.width, r.height);
let x = offset.x + (sg.x + r.left as f32) / dpr;
let glyph_visual_top = run.baseline_y - r.top as f32;
let y = offset.y + (glyph_visual_top - anchor) / dpr;
let rect = Rect::new(x, y, r.width as f32 / dpr, r.height as f32 / dpr);
let color = rich.spans.get(sg.span as usize).and_then(|s| s.color).unwrap_or(default_color);
list.push(PaintCommand::TexturedRect {
rect,
color,
uv: entry.uv,
texture_id: 0,
mode: mgui_core::paint::TextureMode::Mask,
});
}
}
for b in &shaped.inline_boxes {
if let Some((_, inline)) = rich.inlines.get(b.id as usize) {
let rect = Rect::new(offset.x + b.x, offset.y + b.y - anchor / dpr, b.width, b.height);
(inline.painter)(list, rect);
}
}
shaped.max_x / dpr
})
}
#[cfg(test)]
mod rich_text_tests {
use super::*;
#[test]
fn mixed_styles_measure_and_paint_with_span_colors() {
set_text_dpr(1.0);
let red = Color::from_rgb8(255, 0, 0);
let rich = RichText::new(vec![
RichTextSpan::new("Hello ").with_size(18.0).with_color(Color::WHITE),
RichTextSpan::new("World").with_size(30.0).with_color(red),
]);
let size = rich_text_size(&rich, None);
assert!(size.width > 0.0, "宽度必须 > 0");
assert!(size.height >= 30.0, "高度应容纳 30px 字号: {size:?}");
let mut list = PaintList::new();
let width = paint_rich_text(&rich, Point::ZERO, &mut list, None);
assert!((width - size.width).abs() < 0.5, "绘制宽度应与测量一致: {width} vs {}", size.width);
let colors: Vec<Color> = list
.commands
.iter()
.filter_map(|c| match c {
PaintCommand::TexturedRect { color, .. } => Some(*color),
_ => None,
})
.collect();
assert!(colors.contains(&Color::WHITE), "应包含第一段白色字形");
assert!(colors.contains(&red), "应包含第二段红色字形");
}
#[test]
fn inline_item_measures_paints_and_sits_on_baseline() {
use std::cell::RefCell;
set_text_dpr(1.0);
let captured: std::rc::Rc<RefCell<Option<Rect>>> = std::rc::Rc::new(RefCell::new(None));
let cap = captured.clone();
let rich = RichText::from_items(vec![
RichItem::Text(RichTextSpan::new("A").with_size(16.0)),
RichItem::Inline(InlineItem::new(30.0, 24.0, move |_list, rect| *cap.borrow_mut() = Some(rect))),
RichItem::Text(RichTextSpan::new("B").with_size(16.0)),
]);
let size = rich_text_size(&rich, None);
assert!(size.width >= 30.0, "宽度应包含内联项: {size:?}");
assert!(size.height >= 20.0, "高度应容纳内联项: {size:?}");
let mut list = PaintList::new();
let width = paint_rich_text(&rich, Point::new(10.0, 5.0), &mut list, None);
assert!(width >= 30.0);
let rect = captured.borrow().expect("内联项绘制回调应被调用");
assert!((rect.width - 30.0).abs() < 0.01 && (rect.height - 24.0).abs() < 0.01, "{rect:?}");
assert!(rect.x >= 10.0 && rect.y >= 5.0, "内联项应带 offset: {rect:?}");
}
#[test]
fn inline_items_wrap_when_narrow() {
set_text_dpr(1.0);
let rich = RichText::from_items(vec![
RichItem::Inline(InlineItem::new(40.0, 20.0, |_, _| {})),
RichItem::Inline(InlineItem::new(40.0, 20.0, |_, _| {})),
]);
let one_line = rich_text_size(&rich, None);
let wrapped = rich_text_size(&rich, Some(50.0));
assert!(one_line.width > wrapped.width, "窄宽度应减少行宽: {one_line:?} vs {wrapped:?}");
assert!(
wrapped.height > one_line.height * 1.5,
"两个 40 宽内联项在 50 宽内应换行: {one_line:?} vs {wrapped:?}"
);
}
#[test]
fn soft_wrap_uses_max_width() {
set_text_dpr(1.0);
let rich = RichText::new(vec![RichTextSpan::new("word ".repeat(40)).with_size(16.0)]);
let single = rich_text_size(&rich, None);
let wrapped = rich_text_size(&rich, Some(120.0));
assert!(single.height > 0.0 && wrapped.height > 0.0);
assert!(wrapped.height > single.height * 2.0, "换行后高度应显著增加: {single:?} vs {wrapped:?}");
assert!(wrapped.width <= 130.0, "换行后宽度应受 max_width 约束: {wrapped:?}");
}
#[test]
fn span_builders_set_weight_and_italic() {
assert_eq!(RichTextSpan::new("x").weight, None, "默认不指定字重(跟随 400)");
assert!(!RichTextSpan::new("x").italic);
assert_eq!(RichTextSpan::new("x").bold().weight, Some(700));
assert_eq!(RichTextSpan::new("x").with_weight(500).weight, Some(500));
assert_eq!(RichTextSpan::new("x").with_weight(0).weight, Some(1), "非法值夹紧到 ≥1");
assert!(RichTextSpan::new("x").italic().italic);
assert!(!RichTextSpan::new("x").with_italic(true).with_italic(false).italic);
}
#[test]
fn bold_span_is_wider_and_cache_keeps_weights_apart() {
set_text_dpr(1.0);
let text = "Handgloves 字重";
let regular = RichText::new(vec![RichTextSpan::new(text).with_size(20.0)]);
let bold = RichText::new(vec![RichTextSpan::new(text).with_size(20.0).bold()]);
let w_regular = rich_text_size(®ular, None).width;
let w_bold = rich_text_size(&bold, None).width;
assert!(w_bold > w_regular + 0.5, "粗体字面应比常规更宽: regular={w_regular} bold={w_bold}");
assert!((rich_text_size(®ular, None).width - w_regular).abs() < 0.01, "缓存不能把粗体轮廓复用给常规 span");
let mut list = PaintList::new();
let painted = paint_rich_text(&bold, Point::ZERO, &mut list, None);
assert!((painted - w_bold).abs() < 0.5, "绘制宽度应与测量一致: {painted} vs {w_bold}");
let glyphs = list.commands.iter().filter(|c| matches!(c, PaintCommand::TexturedRect { .. })).count();
assert!(glyphs > 4, "粗体也应画出成片字形,实际 {glyphs}");
}
#[test]
fn italic_span_paints_without_changing_line_box() {
set_text_dpr(1.0);
let text = "Italic style";
let regular = RichText::new(vec![RichTextSpan::new(text).with_size(18.0)]);
let italic = RichText::new(vec![RichTextSpan::new(text).with_size(18.0).italic()]);
let mut list = PaintList::new();
let painted = paint_rich_text(&italic, Point::ZERO, &mut list, None);
let glyphs = list.commands.iter().filter(|c| matches!(c, PaintCommand::TexturedRect { .. })).count();
assert!(glyphs > 4, "斜体应照常成片绘制,实际 {glyphs}");
let w_italic = rich_text_size(&italic, None).width;
assert!(w_italic > 0.0, "斜体宽度有效: {w_italic}");
assert!((painted - w_italic).abs() < 0.5, "斜体绘制宽度应与测量一致: {painted} vs {w_italic}");
assert!(
w_italic.abs() < rich_text_size(®ular, None).width * 2.0,
"斜体宽度应与常规同量级: italic={w_italic}"
);
}
#[test]
fn raster_font_id_folds_variation_coords() {
assert_eq!(raster_font_id(42, &[]), 42);
let a: [swash::NormalizedCoord; 1] = [1];
let b: [swash::NormalizedCoord; 1] = [2];
let coords_a: &[swash::NormalizedCoord] = &a;
let coords_b: &[swash::NormalizedCoord] = &b;
assert_ne!(raster_font_id(42, coords_a), raster_font_id(42, coords_b), "不同可变轴坐标必须是不同栅格身份");
assert_eq!(raster_font_id(42, coords_a), raster_font_id(42, coords_a), "同坐标必须稳定(缓存命中)");
assert_ne!(raster_font_id(42, coords_a), raster_font_id(43, coords_a), "不同 blob 也必须区分");
}
}
#[cfg(test)]
mod multiline_regression {
use super::*;
#[test]
fn multiline_text_lines_have_distinct_y() {
let mut list = PaintList::new();
paint_text_line("第一行AAA\n第二行BBB", 20.0, Color::WHITE, Point::new(50.0, 100.0), &mut list, None);
let ys: Vec<f32> = list
.commands
.iter()
.filter_map(|c| match c {
PaintCommand::TexturedRect { rect, .. } => Some((rect.y * 10.0).round() / 10.0),
_ => None,
})
.collect();
assert!(!ys.is_empty(), "应画出 glyph");
let y0 = ys[0];
assert!(ys.iter().any(|&y| (y - y0).abs() > 20.0), "多行文本各行 y 必须拉开,实际全部≈{}: {:?}", y0, ys);
}
#[test]
fn wrapped_text_lines_have_distinct_y() {
let mut list = PaintList::new();
paint_text_line(
"第一行文本内容比较长需要折行",
20.0,
Color::WHITE,
Point::new(0.0, 0.0),
&mut list,
Some(60.0),
);
let ys: Vec<f32> = list
.commands
.iter()
.filter_map(|c| match c {
PaintCommand::TexturedRect { rect, .. } => Some((rect.y * 10.0).round() / 10.0),
_ => None,
})
.collect();
let y0 = ys[0];
assert!(ys.iter().any(|&y| (y - y0).abs() > 20.0), "soft-wrap 多行 y 必须拉开,实际全部≈{}: {:?}", y0, ys);
}
}