mirror of
https://github.com/storytold/egui.git
synced 2026-11-25 03:53:35 +01:00
Render any glyph and colored emoji on web (#8490)
* Closes https://github.com/emilk/egui/pull/7852 * Web-only support for https://github.com/emilk/egui/issues/2551 * Related to https://github.com/emilk/egui/issues/7325 This adds support for rendering _any glyph_ on web, including colored emojis! Test string: ✨ We support ไทย, 한국어, and 🦀 🚀 🤖/🦾/📷/🎞️ <img width="435" height="115" alt="Screenshot 2026-09-03 at 20 29 43" src="https://github.com/user-attachments/assets/86133103-8474-48b8-8792-e48ac3a4286c" /> <img width="465" height="111" alt="Screenshot 2026-09-03 at 20 29 36" src="https://github.com/user-attachments/assets/7f7fb2a6-a6c6-42b1-85df-6c5745523ea4" /> --------- Co-authored-by: Claude Fable 5.1 <noreply@anthropic.com>
This commit is contained in:
1 parent
e63fa0b314
commit
f7b4e41cf1
15 files changed
+1261
-108
No files matched your search
@@ -1624,6 +1624,7 @@ dependencies = [
|
||||
"skrifa",
|
||||
"smallvec",
|
||||
"unicode-general-category",
|
||||
"unicode-properties",
|
||||
"unicode-segmentation",
|
||||
"vello_cpu",
|
||||
]
|
||||
|
||||
@@ -145,6 +145,7 @@ toml = { version = "1.1", default-features = false }
|
||||
type-map = "0.5.1"
|
||||
unicode_names2 = { version = "3.1", default-features = false }
|
||||
unicode-general-category = "1.1"
|
||||
unicode-properties = { version = "0.1.4", default-features = false, features = ["emoji"] }
|
||||
unicode-segmentation = "1.13"
|
||||
vello_cpu = { version = "0.2.0", default-features = false, features = [
|
||||
"std",
|
||||
|
||||
@@ -223,6 +223,7 @@ web-sys = { workspace = true, features = [
|
||||
"Clipboard",
|
||||
"ClipboardEvent",
|
||||
"ClipboardItem",
|
||||
"CanvasRenderingContext2d",
|
||||
"CompositionEvent",
|
||||
"console",
|
||||
"CssStyleDeclaration",
|
||||
@@ -245,6 +246,7 @@ web-sys = { workspace = true, features = [
|
||||
"HtmlElement",
|
||||
"HtmlInputElement",
|
||||
"InputEvent",
|
||||
"ImageData",
|
||||
"KeyboardEvent",
|
||||
"Location",
|
||||
"MediaQueryList",
|
||||
@@ -261,6 +263,7 @@ web-sys = { workspace = true, features = [
|
||||
"ResizeObserverSize",
|
||||
"ShadowRoot",
|
||||
"Storage",
|
||||
"TextMetrics",
|
||||
"Touch",
|
||||
"TouchEvent",
|
||||
"PointerEvent",
|
||||
|
||||
@@ -47,6 +47,7 @@ impl AppRunner {
|
||||
text_agent: TextAgent,
|
||||
) -> Result<Self, String> {
|
||||
let egui_ctx = egui::Context::default();
|
||||
egui_ctx.set_glyph_rasterizer(Some(super::canvas_glyphs::glyph_rasterizer()));
|
||||
|
||||
#[allow(clippy::allow_attributes, unused_assignments)]
|
||||
#[cfg(feature = "glow")]
|
||||
|
||||
@@ -0,0 +1,262 @@
|
||||
//! Browser glyph rasterization for egui's unsupported-glyph fallback.
|
||||
//!
|
||||
//! This draws unsupported grapheme clusters with Canvas 2D, then puts the resulting pixels in
|
||||
//! egui's font atlas. Clusters the browser cannot render either (tofu) are rejected,
|
||||
//! so egui draws its own replacement glyph.
|
||||
|
||||
use core::cell::RefCell;
|
||||
use std::collections::HashMap;
|
||||
|
||||
use egui::{
|
||||
ColorImage, GlyphRasterizer, GlyphRasterizerRequest, MAX_GLYPH_SIZE, RasterizedGlyph,
|
||||
has_emoji_presentation, vec2,
|
||||
};
|
||||
use wasm_bindgen::JsCast as _;
|
||||
use web_sys::{CanvasRenderingContext2d, HtmlCanvasElement};
|
||||
|
||||
/// Room for anti-aliased pixels at the glyph bounds, in physical pixels.
|
||||
const PADDING: f64 = 2.0;
|
||||
|
||||
/// Result of drawing some text on the canvas.
|
||||
struct Drawn {
|
||||
/// Straight (unpremultiplied) RGBA.
|
||||
rgba: Vec<u8>,
|
||||
width: u32,
|
||||
height: u32,
|
||||
|
||||
/// Distance from the pen to the left edge of the ink.
|
||||
left: f64,
|
||||
|
||||
/// Distance from the baseline to the top of the ink.
|
||||
ascent: f64,
|
||||
|
||||
/// Horizontal advance.
|
||||
advance: f64,
|
||||
}
|
||||
|
||||
struct CanvasGlyphs {
|
||||
canvas: HtmlCanvasElement,
|
||||
context: CanvasRenderingContext2d,
|
||||
|
||||
/// What the browser draws for a missing glyph, per `(font, subpixel offset)`.
|
||||
///
|
||||
/// `None` if the browser draws nothing.
|
||||
tofu_cache: HashMap<(String, u32), Option<Drawn>>,
|
||||
}
|
||||
|
||||
impl CanvasGlyphs {
|
||||
fn new() -> Option<Self> {
|
||||
let document = web_sys::window()?.document()?;
|
||||
let canvas = document
|
||||
.create_element("canvas")
|
||||
.ok()?
|
||||
.dyn_into::<HtmlCanvasElement>()
|
||||
.ok()?;
|
||||
let context = canvas
|
||||
.get_context("2d")
|
||||
.ok()??
|
||||
.dyn_into::<CanvasRenderingContext2d>()
|
||||
.ok()?;
|
||||
Some(Self {
|
||||
canvas,
|
||||
context,
|
||||
tofu_cache: Default::default(),
|
||||
})
|
||||
}
|
||||
|
||||
fn rasterize(&mut self, request: &GlyphRasterizerRequest<'_>) -> Option<RasterizedGlyph> {
|
||||
let GlyphRasterizerRequest {
|
||||
cluster,
|
||||
family,
|
||||
font_size_px,
|
||||
subpixel_offset_px,
|
||||
} = request;
|
||||
|
||||
if cluster.trim().is_empty() || !font_size_px.is_finite() || *font_size_px <= 0.0 {
|
||||
return None;
|
||||
}
|
||||
|
||||
let family = match family {
|
||||
egui::FontFamily::Monospace => "monospace",
|
||||
_ => {
|
||||
"system-ui, sans-serif, \"Apple Color Emoji\", \"Segoe UI Emoji\", \"Noto Color Emoji\""
|
||||
}
|
||||
};
|
||||
let font = format!("{font_size_px}px {family}");
|
||||
|
||||
// White, like egui's own glyph rasterizer: the atlas stores coverage,
|
||||
// and the tessellator multiplies it with the text color.
|
||||
let white = self.draw(cluster, &font, "white", *subpixel_offset_px)?;
|
||||
|
||||
if self.is_tofu(&white, &font, *subpixel_offset_px) {
|
||||
return None; // Let egui draw its own replacement glyph instead.
|
||||
}
|
||||
|
||||
// Is this a monochrome glyph (to be tinted by the text color) or a color emoji (not)?
|
||||
// Monochrome glyphs take the fill color, color glyphs ignore it,
|
||||
// so we draw twice and see if the fill color made a difference.
|
||||
let black = self.draw(cluster, &font, "black", *subpixel_offset_px)?;
|
||||
let is_color = is_color(cluster, &white, &black);
|
||||
|
||||
let Drawn {
|
||||
rgba,
|
||||
width,
|
||||
height,
|
||||
left,
|
||||
ascent,
|
||||
advance,
|
||||
} = white;
|
||||
|
||||
Some(RasterizedGlyph {
|
||||
image: ColorImage::from_rgba_unmultiplied([width as _, height as _], &rgba),
|
||||
// The pen sits at `(PADDING + left, PADDING + ascent)` in the image,
|
||||
// so the image's top-left is this far from the pen:
|
||||
offset_px: vec2(-(left + PADDING) as f32, -(ascent + PADDING) as f32),
|
||||
advance_px: advance as f32,
|
||||
is_color,
|
||||
})
|
||||
}
|
||||
|
||||
/// Did the browser draw its "missing glyph" box (tofu)?
|
||||
///
|
||||
/// Browsers draw a box for glyphs they lack, and `measureText` reports
|
||||
/// a width for it, so the only way to tell is to compare pixels.
|
||||
fn is_tofu(&mut self, drawn: &Drawn, font: &str, subpixel_offset_px: f32) -> bool {
|
||||
/// An unassigned code point, so no font has a glyph for it.
|
||||
const MISSING_GLYPH: &str = "\u{0378}";
|
||||
|
||||
let key = (font.to_owned(), subpixel_offset_px.to_bits());
|
||||
if !self.tofu_cache.contains_key(&key) {
|
||||
let tofu = self.draw(MISSING_GLYPH, font, "white", subpixel_offset_px);
|
||||
self.tofu_cache.insert(key.clone(), tofu);
|
||||
}
|
||||
|
||||
self.tofu_cache
|
||||
.get(&key)
|
||||
.and_then(Option::as_ref)
|
||||
.is_some_and(|tofu| {
|
||||
tofu.width == drawn.width && tofu.height == drawn.height && tofu.rgba == drawn.rgba
|
||||
})
|
||||
}
|
||||
|
||||
/// Draw `text` with the given CSS `font` and `fill_style` and read back the pixels.
|
||||
fn draw(
|
||||
&self,
|
||||
text: &str,
|
||||
font: &str,
|
||||
fill_style: &str,
|
||||
subpixel_offset_px: f32,
|
||||
) -> Option<Drawn> {
|
||||
self.context.set_font(font);
|
||||
self.context.set_text_baseline("alphabetic");
|
||||
let metrics = self.context.measure_text(text).ok()?;
|
||||
let left = metrics.actual_bounding_box_left();
|
||||
let ascent = metrics.actual_bounding_box_ascent();
|
||||
let right = metrics.actual_bounding_box_right();
|
||||
let descent = metrics.actual_bounding_box_descent();
|
||||
|
||||
let width = (left + right + 2.0 * PADDING).ceil().max(1.0) as u32;
|
||||
let height = (ascent + descent + 2.0 * PADDING).ceil().max(1.0) as u32;
|
||||
if MAX_GLYPH_SIZE < width as usize || MAX_GLYPH_SIZE < height as usize {
|
||||
return None;
|
||||
}
|
||||
|
||||
// Only grow: resizing reallocates the backing store and resets all canvas state.
|
||||
if self.canvas.width() < width {
|
||||
self.canvas.set_width(width);
|
||||
}
|
||||
if self.canvas.height() < height {
|
||||
self.canvas.set_height(height);
|
||||
}
|
||||
self.context
|
||||
.clear_rect(0.0, 0.0, width as f64, height as f64);
|
||||
self.context.set_font(font);
|
||||
self.context.set_text_baseline("alphabetic");
|
||||
self.context.set_fill_style_str(fill_style);
|
||||
// Canvas positions text by its baseline, while the image starts at its top-left.
|
||||
self.context
|
||||
.fill_text(
|
||||
text,
|
||||
PADDING + left + subpixel_offset_px as f64,
|
||||
PADDING + ascent,
|
||||
)
|
||||
.ok()?;
|
||||
let rgba = self
|
||||
.context
|
||||
.get_image_data(0.0, 0.0, width as f64, height as f64)
|
||||
.ok()?
|
||||
.data()
|
||||
.0;
|
||||
|
||||
Some(Drawn {
|
||||
rgba,
|
||||
width,
|
||||
height,
|
||||
left,
|
||||
ascent,
|
||||
advance: metrics.width(),
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
/// Did the fill color affect the pixels?
|
||||
///
|
||||
/// Compares a `white` and a `black` draw of the same cluster, pixel by pixel.
|
||||
/// A monochrome glyph takes the fill color, so its pixels differ between the two.
|
||||
/// A color glyph (emoji) ignores it, so its pixels stay the same.
|
||||
///
|
||||
/// This is a majority vote rather than an exact comparison:
|
||||
/// some browsers (e.g. Firefox for Android) are not pixel-exact between two draws,
|
||||
/// and some color glyphs have layers that take the fill color.
|
||||
/// Unicode emoji presentation breaks ties, e.g. for glyphs with no opaque pixels.
|
||||
///
|
||||
/// Looking at the pixels of a single draw does not work:
|
||||
/// a black-and-white emoji (⚫, 🖤) looks monochrome but must not be tinted,
|
||||
/// and some platforms draw e.g. Thai and Korean with colored (subpixel-antialiased) fringes.
|
||||
fn is_color(cluster: &str, white: &Drawn, black: &Drawn) -> bool {
|
||||
let mut monochrome_votes = 0_usize;
|
||||
let mut color_votes = 0_usize;
|
||||
|
||||
for (&[white_r, white_g, white_b, white_a], &[black_r, black_g, black_b, black_a]) in
|
||||
core::iter::zip(white.rgba.as_chunks::<4>().0, black.rgba.as_chunks::<4>().0)
|
||||
{
|
||||
if white_a < 255 || black_a < 255 {
|
||||
continue; // let's only count opaque pixels
|
||||
}
|
||||
let diff_r = white_r.abs_diff(black_r);
|
||||
let diff_g = white_g.abs_diff(black_g);
|
||||
let diff_b = white_b.abs_diff(black_b);
|
||||
let max_diff = diff_r.max(diff_g).max(diff_b);
|
||||
let similar = max_diff < 128;
|
||||
|
||||
if similar {
|
||||
color_votes += 1;
|
||||
} else {
|
||||
monochrome_votes += 1;
|
||||
}
|
||||
}
|
||||
|
||||
if monochrome_votes == color_votes {
|
||||
has_emoji_presentation(cluster)
|
||||
} else {
|
||||
monochrome_votes < color_votes
|
||||
}
|
||||
}
|
||||
|
||||
thread_local! {
|
||||
// `Context` and `GlyphRasterizer` are `Send + Sync`, but browser Canvas handles are not.
|
||||
// Keeping the handles here lets the callback stay capture-free and usable from `egui::Context`.
|
||||
static CANVAS_GLYPHS: RefCell<Option<CanvasGlyphs>> = const { RefCell::new(None) };
|
||||
}
|
||||
|
||||
pub(super) fn glyph_rasterizer() -> GlyphRasterizer {
|
||||
GlyphRasterizer::new(|request| {
|
||||
CANVAS_GLYPHS.with(|glyphs| {
|
||||
let mut glyphs = glyphs.borrow_mut();
|
||||
if glyphs.is_none() {
|
||||
*glyphs = CanvasGlyphs::new();
|
||||
}
|
||||
glyphs.as_mut()?.rasterize(request)
|
||||
})
|
||||
})
|
||||
}
|
||||
@@ -5,6 +5,7 @@
|
||||
|
||||
mod app_runner;
|
||||
mod backend;
|
||||
mod canvas_glyphs;
|
||||
mod dropped_file;
|
||||
mod events;
|
||||
mod input;
|
||||
|
||||
@@ -16,12 +16,13 @@ use epaint::{
|
||||
};
|
||||
|
||||
use crate::{
|
||||
Align2, CursorIcon, DeferredViewportUiCallback, FontDefinitions, Grid, Id, ImmediateViewport,
|
||||
ImmediateViewportRendererCallback, Key, KeyboardShortcut, Label, LayerId, Memory,
|
||||
ModifierNames, Modifiers, NumExt as _, Order, Painter, RawInput, Response, RichText,
|
||||
SafeAreaInsets, ScrollArea, Sense, Style, TextStyle, TextureHandle, TextureOptions, Ui,
|
||||
UiBuilder, ViewportBuilder, ViewportCommand, ViewportId, ViewportIdMap, ViewportIdPair,
|
||||
ViewportIdSet, ViewportOutput, Visuals, Widget as _, WidgetRect, WidgetText,
|
||||
Align2, CursorIcon, DeferredViewportUiCallback, FontDefinitions, GlyphRasterizer, GlyphSource,
|
||||
GlyphSourcePreference, Grid, Id, ImmediateViewport, ImmediateViewportRendererCallback, Key,
|
||||
KeyboardShortcut, Label, LayerId, Memory, ModifierNames, Modifiers, NumExt as _, Order,
|
||||
Painter, RawInput, Response, RichText, SafeAreaInsets, ScrollArea, Sense, Style, TextStyle,
|
||||
TextureHandle, TextureOptions, Ui, UiBuilder, ViewportBuilder, ViewportCommand, ViewportId,
|
||||
ViewportIdMap, ViewportIdPair, ViewportIdSet, ViewportOutput, Visuals, Widget as _, WidgetRect,
|
||||
WidgetText,
|
||||
animation_manager::AnimationManager,
|
||||
containers::{self, area::AreaState},
|
||||
data::output::PlatformOutput,
|
||||
@@ -375,6 +376,8 @@ impl ViewportRepaintInfo {
|
||||
struct ContextImpl {
|
||||
fonts: Option<Fonts>,
|
||||
font_definitions: FontDefinitions,
|
||||
glyph_rasterizer: Option<GlyphRasterizer>,
|
||||
glyph_source_preference: Option<GlyphSourcePreference>,
|
||||
|
||||
memory: Memory,
|
||||
animation_manager: AnimationManager,
|
||||
@@ -591,7 +594,15 @@ impl ContextImpl {
|
||||
|
||||
is_new = true;
|
||||
profiling::scope!("Fonts::new");
|
||||
Fonts::new(text_options, self.font_definitions.clone())
|
||||
let mut fonts = Fonts::new(text_options, self.font_definitions.clone());
|
||||
if let Some(glyph_rasterizer) = &self.glyph_rasterizer {
|
||||
fonts = fonts.with_glyph_rasterizer(glyph_rasterizer.clone());
|
||||
}
|
||||
if let Some(prefer) = &self.glyph_source_preference {
|
||||
let prefer = Arc::clone(prefer);
|
||||
fonts = fonts.with_glyph_source_preference(move |cluster| prefer(cluster));
|
||||
}
|
||||
fonts
|
||||
});
|
||||
|
||||
{
|
||||
@@ -761,6 +772,36 @@ impl Default for Context {
|
||||
}
|
||||
|
||||
impl Context {
|
||||
/// Set the platform glyph rasterizer, e.g. the browser on web.
|
||||
///
|
||||
/// It is used for grapheme clusters no installed font can render,
|
||||
/// and for clusters where the [`GlyphSourcePreference`] says so (color emoji by default).
|
||||
///
|
||||
/// `eframe` sets this on web. Pass `None` to only use the installed fonts.
|
||||
pub fn set_glyph_rasterizer(&self, glyph_rasterizer: Option<GlyphRasterizer>) {
|
||||
self.write(|ctx| {
|
||||
ctx.glyph_rasterizer = glyph_rasterizer;
|
||||
ctx.fonts = None;
|
||||
});
|
||||
}
|
||||
|
||||
/// Decide where to look first for the glyphs of each grapheme cluster:
|
||||
/// the fonts in the [`FontDefinitions`], or what the platform offers (e.g. the browser on web).
|
||||
///
|
||||
/// By default, color emoji come from the platform, and everything else from the fonts.
|
||||
/// Use `|_| GlyphSource::Fonts` to only use the platform for characters no installed font has.
|
||||
///
|
||||
/// See [`GlyphSourcePreference`].
|
||||
pub fn set_glyph_source_preference(
|
||||
&self,
|
||||
prefer: impl Fn(&str) -> GlyphSource + Send + Sync + 'static,
|
||||
) {
|
||||
self.write(|ctx| {
|
||||
ctx.glyph_source_preference = Some(Arc::new(prefer));
|
||||
ctx.fonts = None;
|
||||
});
|
||||
}
|
||||
|
||||
/// Do read-only (shared access) transaction on Context
|
||||
fn read<R>(&self, reader: impl FnOnce(&ContextImpl) -> R) -> R {
|
||||
reader(&self.0.read())
|
||||
|
||||
@@ -455,7 +455,11 @@ pub use emath::{
|
||||
pub use epaint::{
|
||||
ClippedPrimitive, ColorImage, CornerRadius, Direction, ImageData, Margin, Mesh, PaintCallback,
|
||||
PaintCallbackInfo, Shadow, Shape, Stroke, StrokeKind, TextureHandle, TextureId, mutex,
|
||||
text::{FontData, FontDefinitions, FontFamily, FontId, FontTweak},
|
||||
text::{
|
||||
FontData, FontDefinitions, FontFamily, FontId, FontTweak, GlyphRasterizer,
|
||||
GlyphRasterizerRequest, GlyphSource, GlyphSourcePreference, MAX_GLYPH_SIZE,
|
||||
RasterizedGlyph, default_glyph_source, has_emoji_presentation,
|
||||
},
|
||||
textures::{TextureFilter, TextureOptions, TextureWrapMode, TexturesDelta},
|
||||
};
|
||||
|
||||
|
||||
@@ -79,6 +79,7 @@ self_cell.workspace = true
|
||||
skrifa.workspace = true
|
||||
smallvec.workspace = true
|
||||
unicode-general-category.workspace = true
|
||||
unicode-properties.workspace = true
|
||||
unicode-segmentation.workspace = true
|
||||
vello_cpu.workspace = true
|
||||
|
||||
|
||||
@@ -2051,6 +2051,26 @@ impl Tessellator {
|
||||
|
||||
let index_offset = out.vertices.len() as u32;
|
||||
|
||||
// Color glyphs (e.g. color emoji) must keep their own color.
|
||||
// Rows rarely have any, so check once per row before searching per vertex.
|
||||
let row_has_color_glyphs = row.glyphs.iter().any(|glyph| glyph.is_color);
|
||||
let is_color_glyph_vertex = |vertex_index: usize| {
|
||||
if !row_has_color_glyphs || !row.visuals.glyph_vertex_range.contains(&vertex_index)
|
||||
{
|
||||
return false;
|
||||
}
|
||||
// `first_vertex` is non-decreasing along `glyphs`, so binary search for
|
||||
// the glyph owning this vertex. Glyphs without pixels emit no vertices
|
||||
// and share `first_vertex` with the next glyph, so take the last match.
|
||||
let glyph_index = row
|
||||
.glyphs
|
||||
.partition_point(|glyph| glyph.first_vertex as usize <= vertex_index);
|
||||
glyph_index
|
||||
.checked_sub(1)
|
||||
.and_then(|glyph_index| row.glyphs.get(glyph_index))
|
||||
.is_some_and(|glyph| glyph.is_color && !glyph.uv_rect.is_nothing())
|
||||
};
|
||||
|
||||
out.indices.extend(
|
||||
row.visuals
|
||||
.mesh
|
||||
@@ -2077,6 +2097,11 @@ impl Tessellator {
|
||||
color = *fallback_color;
|
||||
}
|
||||
|
||||
if is_color_glyph_vertex(i) {
|
||||
// Don't tint: keep the glyph's own color, but respect the text alpha.
|
||||
color = Color32::from_white_alpha(color.a());
|
||||
}
|
||||
|
||||
if *opacity_factor < 1.0 {
|
||||
color = color.gamma_multiply(*opacity_factor);
|
||||
}
|
||||
|
||||
@@ -1,5 +1,6 @@
|
||||
#![expect(clippy::mem_forget)]
|
||||
|
||||
use ahash::HashMap;
|
||||
use ecolor::Color32;
|
||||
use emath::{GuiRounding as _, OrderedFloat, Vec2, vec2};
|
||||
use self_cell::self_cell;
|
||||
@@ -10,11 +11,41 @@ use vello_cpu::{color, kurbo};
|
||||
use crate::{
|
||||
TextOptions, TextureAtlas,
|
||||
text::{
|
||||
FontTweak, VariationCoords,
|
||||
fonts::{Blob, CachedFamily, FontFaceKey},
|
||||
FontTweak, MAX_GLYPH_SIZE, VariationCoords,
|
||||
fonts::{Blob, CachedFamily, FontFaceKey, GlyphSourcePreference},
|
||||
},
|
||||
};
|
||||
|
||||
#[derive(Clone, Copy)]
|
||||
pub(crate) struct RasterGlyphAllocation {
|
||||
pub allocation: GlyphAllocation,
|
||||
pub advance_px: f32,
|
||||
pub is_color: bool,
|
||||
}
|
||||
|
||||
/// Hash of `(cluster, family, pixels_per_point, font_size)`,
|
||||
/// so that cache lookups do not allocate.
|
||||
#[derive(Hash, PartialEq, Eq)]
|
||||
pub(crate) struct RasterGlyphCacheKey(u64);
|
||||
|
||||
impl nohash_hasher::IsEnabled for RasterGlyphCacheKey {}
|
||||
|
||||
impl RasterGlyphCacheKey {
|
||||
fn new(
|
||||
cluster: &str,
|
||||
family: &crate::text::FontFamily,
|
||||
pixels_per_point: f32,
|
||||
font_size: f32,
|
||||
) -> Self {
|
||||
Self(crate::util::hash((
|
||||
cluster,
|
||||
family,
|
||||
pixels_per_point.to_bits(),
|
||||
font_size.to_bits(),
|
||||
)))
|
||||
}
|
||||
}
|
||||
|
||||
// ----------------------------------------------------------------------------
|
||||
|
||||
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
|
||||
@@ -364,15 +395,15 @@ pub struct FontFace {
|
||||
///
|
||||
/// Only depends on the font's charmap + `FontTweak`. A miss means the char
|
||||
/// is not in this face's repertoire and the fallback chain should be tried.
|
||||
glyph_id_cache: ahash::HashMap<char, GlyphIdResolution>,
|
||||
glyph_id_cache: HashMap<char, GlyphIdResolution>,
|
||||
|
||||
/// Location-dependent: `(char, LocationHash) → unscaled advance width`.
|
||||
///
|
||||
/// Variable fonts can vary advance widths per axis (HVAR table), so this
|
||||
/// must be re-keyed per resolved [`skrifa::instance::Location`].
|
||||
advance_width_cache: ahash::HashMap<(char, LocationHash), OrderedFloat<f32>>,
|
||||
advance_width_cache: HashMap<(char, LocationHash), OrderedFloat<f32>>,
|
||||
|
||||
glyph_alloc_cache: ahash::HashMap<GlyphCacheKey, GlyphAllocation>,
|
||||
glyph_alloc_cache: HashMap<GlyphCacheKey, GlyphAllocation>,
|
||||
}
|
||||
|
||||
impl FontFace {
|
||||
@@ -665,9 +696,81 @@ pub struct Font<'a> {
|
||||
pub(super) fonts_by_id: &'a mut nohash_hasher::IntMap<FontFaceKey, FontFace>,
|
||||
pub(super) cached_family: &'a mut CachedFamily,
|
||||
pub(super) atlas: &'a mut TextureAtlas,
|
||||
pub(super) family: crate::text::FontFamily,
|
||||
pub(super) glyph_rasterizer: Option<&'a crate::text::GlyphRasterizer>,
|
||||
|
||||
/// `None` means the rasterizer could not handle the cluster.
|
||||
pub(super) raster_glyph_cache:
|
||||
&'a mut nohash_hasher::IntMap<RasterGlyphCacheKey, Option<RasterGlyphAllocation>>,
|
||||
|
||||
pub(super) glyph_source_preference: &'a GlyphSourcePreference,
|
||||
}
|
||||
|
||||
impl Font<'_> {
|
||||
/// Rasterize a glyph using our fallback provider.
|
||||
///
|
||||
/// Failures are cached too, so the (potentially slow) rasterizer
|
||||
/// is asked at most once per cluster and size.
|
||||
pub(crate) fn rasterize_glyph(
|
||||
&mut self,
|
||||
cluster: &str,
|
||||
pixels_per_point: f32,
|
||||
font_size: f32,
|
||||
) -> Option<RasterGlyphAllocation> {
|
||||
let rasterizer = self.glyph_rasterizer?;
|
||||
let key = RasterGlyphCacheKey::new(cluster, &self.family, pixels_per_point, font_size);
|
||||
if let Some(allocation) = self.raster_glyph_cache.get(&key) {
|
||||
return *allocation;
|
||||
}
|
||||
let request = crate::text::GlyphRasterizerRequest {
|
||||
cluster,
|
||||
family: &self.family,
|
||||
font_size_px: font_size * pixels_per_point,
|
||||
subpixel_offset_px: 0.0,
|
||||
};
|
||||
let allocation = (rasterizer.rasterize)(&request)
|
||||
.and_then(|glyph| Self::allocate_raster_glyph(self.atlas, &glyph, pixels_per_point));
|
||||
self.raster_glyph_cache.insert(key, allocation);
|
||||
allocation
|
||||
}
|
||||
|
||||
fn allocate_raster_glyph(
|
||||
atlas: &mut TextureAtlas,
|
||||
glyph: &crate::text::RasterizedGlyph,
|
||||
pixels_per_point: f32,
|
||||
) -> Option<RasterGlyphAllocation> {
|
||||
let [width, height] = glyph.image.size;
|
||||
if width == 0 || height == 0 || MAX_GLYPH_SIZE < width || MAX_GLYPH_SIZE < height {
|
||||
return None;
|
||||
}
|
||||
// The transfer function assumes white coverage glyphs and discards color,
|
||||
// so color glyphs (e.g. emoji) must skip it.
|
||||
let transfer = if glyph.is_color {
|
||||
crate::FontColorTransferFunction::Off
|
||||
} else {
|
||||
atlas.options().color_transfer_function
|
||||
};
|
||||
let (glyph_pos, image) = atlas.allocate((width, height));
|
||||
for y in 0..height {
|
||||
for x in 0..width {
|
||||
image[(glyph_pos.0 + x, glyph_pos.1 + y)] =
|
||||
transfer.to_atlas_color(glyph.image[(x, y)]);
|
||||
}
|
||||
}
|
||||
Some(RasterGlyphAllocation {
|
||||
allocation: GlyphAllocation {
|
||||
uv_rect: UvRect {
|
||||
offset: glyph.offset_px / pixels_per_point,
|
||||
size: vec2(width as f32, height as f32) / pixels_per_point,
|
||||
min: [glyph_pos.0 as u16, glyph_pos.1 as u16],
|
||||
max: [(glyph_pos.0 + width) as u16, (glyph_pos.1 + height) as u16],
|
||||
},
|
||||
},
|
||||
advance_px: glyph.advance_px,
|
||||
is_color: glyph.is_color,
|
||||
})
|
||||
}
|
||||
|
||||
pub fn preload_characters(&mut self, s: &str) {
|
||||
for c in s.chars() {
|
||||
self.resolve_face(c);
|
||||
@@ -715,13 +818,18 @@ impl Font<'_> {
|
||||
glyph_info.advance_width_unscaled.0 * font_face.font.px_scale_factor(font_size)
|
||||
}
|
||||
|
||||
/// Can we display this glyph?
|
||||
/// Do the installed fonts have this glyph?
|
||||
///
|
||||
/// This does not consult the [`crate::text::GlyphRasterizer`], so it can return `false`
|
||||
/// for a character that would still render via the rasterizer (e.g. the browser on web).
|
||||
pub fn has_glyph(&mut self, c: char) -> bool {
|
||||
// TODO(emilk): this is a false negative if the user asks about the replacement character itself 🤦♂️
|
||||
self.resolve_face(c) != self.cached_family.replacement_face_key
|
||||
}
|
||||
|
||||
/// Can we display all the glyphs in this text?
|
||||
/// Do the installed fonts have all the glyphs in this text?
|
||||
///
|
||||
/// See [`Self::has_glyph`] for the caveat about the glyph rasterizer.
|
||||
pub fn has_glyphs(&mut self, s: &str) -> bool {
|
||||
s.chars().all(|c| self.has_glyph(c))
|
||||
}
|
||||
|
||||
+289
-15
@@ -2,10 +2,10 @@ use core::sync::atomic::{AtomicUsize, Ordering};
|
||||
use std::{borrow::Cow, collections::BTreeMap, sync::Arc};
|
||||
|
||||
use crate::{
|
||||
TextureAtlas,
|
||||
Color32, ColorImage, TextureAtlas,
|
||||
text::{
|
||||
ByteIndex, Galley, LayoutJob, LayoutSection, Tag, TextOptions, VariationCoords,
|
||||
font::{Font, FontFace},
|
||||
font::{Font, FontFace, RasterGlyphAllocation, RasterGlyphCacheKey},
|
||||
},
|
||||
};
|
||||
use emath::{NumExt as _, OrderedFloat, Rangef};
|
||||
@@ -15,6 +15,13 @@ use epaint_default_fonts::{EMOJI_ICON, HACK_REGULAR, NOTO_EMOJI_REGULAR, UBUNTU_
|
||||
|
||||
// ----------------------------------------------------------------------------
|
||||
|
||||
/// Maximum width or height of a glyph rasterized into the font atlas.
|
||||
///
|
||||
/// Must not exceed the minimum width of the [`TextureAtlas`] (1024).
|
||||
pub const MAX_GLYPH_SIZE: usize = 1024;
|
||||
|
||||
// ----------------------------------------------------------------------------
|
||||
|
||||
/// How to select a sized font.
|
||||
#[derive(Clone, Debug, PartialEq)]
|
||||
#[cfg_attr(feature = "serde", derive(serde::Deserialize, serde::Serialize))]
|
||||
@@ -27,6 +34,188 @@ pub struct FontId {
|
||||
// TODO(emilk): weight (bold), italics, …
|
||||
}
|
||||
|
||||
/// Input to a [`GlyphRasterizer`].
|
||||
pub struct GlyphRasterizerRequest<'a> {
|
||||
/// An unsupported grapheme cluster.
|
||||
pub cluster: &'a str,
|
||||
|
||||
/// The requested font family.
|
||||
pub family: &'a FontFamily,
|
||||
|
||||
/// Requested font size in physical pixels.
|
||||
pub font_size_px: f32,
|
||||
|
||||
/// Horizontal offset from the pixel grid in physical pixels.
|
||||
pub subpixel_offset_px: f32,
|
||||
}
|
||||
|
||||
/// A glyph rasterized by a platform fallback.
|
||||
pub struct RasterizedGlyph {
|
||||
/// Pixels in physical pixels. Color glyphs retain their original colors.
|
||||
pub image: ColorImage,
|
||||
|
||||
/// Offset from the baseline to the image top-left, in physical pixels.
|
||||
pub offset_px: emath::Vec2,
|
||||
|
||||
/// Horizontal advance, in physical pixels.
|
||||
pub advance_px: f32,
|
||||
|
||||
/// Do not tint this glyph with the text color.
|
||||
pub is_color: bool,
|
||||
}
|
||||
|
||||
type RasterizeFn =
|
||||
dyn for<'a> Fn(&GlyphRasterizerRequest<'a>) -> Option<RasterizedGlyph> + Send + Sync;
|
||||
|
||||
/// Where to look first for the glyphs of a grapheme cluster.
|
||||
///
|
||||
/// The other source is used as a fallback if the first one cannot render the cluster.
|
||||
///
|
||||
/// See [`GlyphSourcePreference`].
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
|
||||
pub enum GlyphSource {
|
||||
/// The fonts in [`FontDefinitions`].
|
||||
///
|
||||
/// Predictable: looks the same everywhere, both on native and on web.
|
||||
Fonts,
|
||||
|
||||
/// What the platform offers, e.g. the [`GlyphRasterizer`] (the browser on web).
|
||||
///
|
||||
/// Supports colored emojis.
|
||||
/// Unpredictable: may look different on different computers.
|
||||
Platform,
|
||||
}
|
||||
|
||||
/// Decides where to look first for the glyphs of each grapheme cluster.
|
||||
///
|
||||
/// Default: [`default_glyph_source`], so that color emoji come from the platform,
|
||||
/// while text-presentation symbols (e.g. ⏮︎) look the same on all platforms.
|
||||
///
|
||||
/// Use `|_| GlyphSource::Fonts` to only use the platform for clusters
|
||||
/// that no font in [`FontDefinitions`] can render.
|
||||
///
|
||||
/// Set with `egui::Context::set_glyph_source_preference` or [`Fonts::with_glyph_source_preference`].
|
||||
pub type GlyphSourcePreference = Arc<dyn Fn(&str) -> GlyphSource + Send + Sync>;
|
||||
|
||||
/// Rasterizes grapheme clusters using something other than the installed fonts,
|
||||
/// e.g. the browser on web.
|
||||
///
|
||||
/// Used for clusters no installed font can render,
|
||||
/// and for clusters where the [`GlyphSourcePreference`] says [`GlyphSource::Platform`].
|
||||
#[derive(Clone)]
|
||||
pub struct GlyphRasterizer {
|
||||
/// Rasterize one grapheme cluster.
|
||||
///
|
||||
/// Return `None` if the platform cannot render it either.
|
||||
pub rasterize: Arc<RasterizeFn>,
|
||||
}
|
||||
|
||||
impl GlyphRasterizer {
|
||||
pub fn new(
|
||||
rasterize: impl for<'a> Fn(&GlyphRasterizerRequest<'a>) -> Option<RasterizedGlyph>
|
||||
+ Send
|
||||
+ Sync
|
||||
+ 'static,
|
||||
) -> Self {
|
||||
Self {
|
||||
rasterize: Arc::new(rasterize),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// The default [`GlyphSourcePreference`]:
|
||||
/// [`GlyphSource::Platform`] for clusters with emoji presentation
|
||||
/// (see [`has_emoji_presentation`]), [`GlyphSource::Fonts`] for everything else.
|
||||
pub fn default_glyph_source(cluster: &str) -> GlyphSource {
|
||||
if has_emoji_presentation(cluster) {
|
||||
GlyphSource::Platform
|
||||
} else {
|
||||
GlyphSource::Fonts
|
||||
}
|
||||
}
|
||||
|
||||
impl core::fmt::Debug for GlyphRasterizer {
|
||||
fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
|
||||
f.write_str("GlyphRasterizer")
|
||||
}
|
||||
}
|
||||
|
||||
/// Does this grapheme cluster have emoji presentation, per Unicode (UTS #51)?
|
||||
///
|
||||
/// True for clusters that default to a color glyph (😀, 🦀, 🇸🇪, 👨👩👧),
|
||||
/// for clusters with an explicit emoji presentation selector (⏮️, U+FE0F),
|
||||
/// and for emoji modifier (skin tone) sequences (☝🏻).
|
||||
///
|
||||
/// False for text-presentation symbols (⏮, ✔, ♥) and for clusters
|
||||
/// with an explicit text presentation selector (⏮︎, U+FE0E).
|
||||
///
|
||||
/// Used by [`default_glyph_source`].
|
||||
pub fn has_emoji_presentation(cluster: &str) -> bool {
|
||||
use unicode_properties::emoji::{
|
||||
EmojiStatus, UnicodeEmoji as _, is_emoji_presentation_selector,
|
||||
is_text_presentation_selector,
|
||||
};
|
||||
|
||||
if cluster.is_ascii() {
|
||||
return false; // Fast path: no ASCII character has emoji presentation.
|
||||
}
|
||||
|
||||
let mut has_emoji_presentation = false;
|
||||
for c in cluster.chars() {
|
||||
if is_text_presentation_selector(c) {
|
||||
return false; // Explicit text presentation wins.
|
||||
}
|
||||
has_emoji_presentation |= is_emoji_presentation_selector(c)
|
||||
|| matches!(
|
||||
c.emoji_status(),
|
||||
EmojiStatus::EmojiPresentation
|
||||
| EmojiStatus::EmojiPresentationAndModifierBase
|
||||
| EmojiStatus::EmojiPresentationAndEmojiComponent
|
||||
| EmojiStatus::EmojiPresentationAndModifierAndEmojiComponent
|
||||
);
|
||||
}
|
||||
has_emoji_presentation
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod has_emoji_presentation_tests {
|
||||
use super::has_emoji_presentation;
|
||||
|
||||
#[test]
|
||||
fn emoji_presentation() {
|
||||
for cluster in [
|
||||
"😀",
|
||||
"🦀",
|
||||
"⏮\u{FE0F}", // explicit emoji presentation
|
||||
"☝🏻", // skin tone modifier sequence
|
||||
"🇸🇪", // flag
|
||||
"👨\u{200D}👩\u{200D}👧", // ZWJ sequence
|
||||
"1\u{FE0F}\u{20E3}", // keycap
|
||||
] {
|
||||
assert!(has_emoji_presentation(cluster), "{cluster:?}");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn text_presentation() {
|
||||
for cluster in [
|
||||
"",
|
||||
"a",
|
||||
"1",
|
||||
"⏮",
|
||||
"⏮\u{FE0E}", // explicit text presentation
|
||||
"😀\u{FE0E}", // explicit text presentation wins
|
||||
"✔",
|
||||
"♥",
|
||||
"©",
|
||||
"→",
|
||||
"√",
|
||||
] {
|
||||
assert!(!has_emoji_presentation(cluster), "{cluster:?}");
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl Default for FontId {
|
||||
#[inline]
|
||||
fn default() -> Self {
|
||||
@@ -707,18 +896,53 @@ impl CachedFamily {
|
||||
pub struct Fonts {
|
||||
pub fonts: FontsImpl,
|
||||
galley_cache: GalleyCache,
|
||||
glyph_rasterizer: Option<GlyphRasterizer>,
|
||||
}
|
||||
|
||||
impl Fonts {
|
||||
/// Create a new [`Fonts`] for text layout.
|
||||
///
|
||||
/// This call is expensive, so only create one [`Fonts`] and then reuse it.
|
||||
pub fn new(options: TextOptions, definitions: FontDefinitions) -> Self {
|
||||
Self {
|
||||
fonts: FontsImpl::new(options, definitions),
|
||||
galley_cache: Default::default(),
|
||||
glyph_rasterizer: None,
|
||||
}
|
||||
}
|
||||
|
||||
/// Use this platform glyph rasterizer, e.g. the browser on web.
|
||||
///
|
||||
/// See [`GlyphRasterizer`].
|
||||
#[inline]
|
||||
pub fn with_glyph_rasterizer(mut self, glyph_rasterizer: GlyphRasterizer) -> Self {
|
||||
self.set_glyph_rasterizer(Some(glyph_rasterizer));
|
||||
self
|
||||
}
|
||||
|
||||
/// Use this platform glyph rasterizer, e.g. the browser on web.
|
||||
///
|
||||
/// Pass `None` to only use the installed fonts.
|
||||
///
|
||||
/// See [`GlyphRasterizer`].
|
||||
pub fn set_glyph_rasterizer(&mut self, glyph_rasterizer: Option<GlyphRasterizer>) {
|
||||
self.glyph_rasterizer = glyph_rasterizer.clone();
|
||||
self.fonts.set_glyph_rasterizer(glyph_rasterizer);
|
||||
self.galley_cache = Default::default();
|
||||
}
|
||||
|
||||
/// Decide where to look first for the glyphs of each grapheme cluster.
|
||||
///
|
||||
/// See [`GlyphSourcePreference`].
|
||||
#[inline]
|
||||
pub fn with_glyph_source_preference(
|
||||
mut self,
|
||||
prefer: impl Fn(&str) -> GlyphSource + Send + Sync + 'static,
|
||||
) -> Self {
|
||||
self.fonts.set_glyph_source_preference(prefer);
|
||||
self
|
||||
}
|
||||
|
||||
/// Call at the start of each frame with the latest known [`TextOptions`].
|
||||
///
|
||||
/// Call after painting the previous frame, but before using [`Fonts`] for the new frame.
|
||||
@@ -732,10 +956,16 @@ impl Fonts {
|
||||
|
||||
if needs_recreate {
|
||||
let definitions = self.fonts.definitions.clone();
|
||||
let glyph_rasterizer = self.glyph_rasterizer.clone();
|
||||
|
||||
let mut fonts = FontsImpl::new(options, definitions);
|
||||
fonts.set_glyph_rasterizer(glyph_rasterizer.clone());
|
||||
fonts.glyph_source_preference = Arc::clone(&self.fonts.glyph_source_preference);
|
||||
|
||||
*self = Self {
|
||||
fonts: FontsImpl::new(options, definitions),
|
||||
fonts,
|
||||
galley_cache: Default::default(),
|
||||
glyph_rasterizer,
|
||||
};
|
||||
}
|
||||
|
||||
@@ -775,12 +1005,17 @@ impl Fonts {
|
||||
self.fonts.atlas.size()
|
||||
}
|
||||
|
||||
/// Can we display this glyph?
|
||||
/// Do the installed fonts have this glyph?
|
||||
///
|
||||
/// This does not consult the [`GlyphRasterizer`], so it can return `false`
|
||||
/// for a character that would still render via the rasterizer (e.g. the browser on web).
|
||||
pub fn has_glyph(&mut self, font_id: &FontId, c: char) -> bool {
|
||||
self.fonts.font(&font_id.family).has_glyph(c)
|
||||
}
|
||||
|
||||
/// Can we display all the glyphs in this text?
|
||||
/// Do the installed fonts have all the glyphs in this text?
|
||||
///
|
||||
/// See [`Self::has_glyph`] for the caveat about the [`GlyphRasterizer`].
|
||||
pub fn has_glyphs(&mut self, font_id: &FontId, s: &str) -> bool {
|
||||
self.fonts.font(&font_id.family).has_glyphs(s)
|
||||
}
|
||||
@@ -848,12 +1083,17 @@ impl FontsView<'_> {
|
||||
.glyph_width(c, font_id.size)
|
||||
}
|
||||
|
||||
/// Can we display this glyph?
|
||||
/// Do the installed fonts have this glyph?
|
||||
///
|
||||
/// This does not consult the [`GlyphRasterizer`], so it can return `false`
|
||||
/// for a character that would still render via the rasterizer (e.g. the browser on web).
|
||||
pub fn has_glyph(&mut self, font_id: &FontId, c: char) -> bool {
|
||||
self.fonts.font(&font_id.family).has_glyph(c)
|
||||
}
|
||||
|
||||
/// Can we display all the glyphs in this text?
|
||||
/// Do the installed fonts have all the glyphs in this text?
|
||||
///
|
||||
/// See [`Self::has_glyph`] for the caveat about the [`GlyphRasterizer`].
|
||||
pub fn has_glyphs(&mut self, font_id: &FontId, s: &str) -> bool {
|
||||
self.fonts.font(&font_id.family).has_glyphs(s)
|
||||
}
|
||||
@@ -917,7 +1157,7 @@ impl FontsView<'_> {
|
||||
&mut self,
|
||||
text: String,
|
||||
font_id: FontId,
|
||||
color: crate::Color32,
|
||||
color: Color32,
|
||||
wrap_width: f32,
|
||||
) -> Arc<Galley> {
|
||||
let job = LayoutJob::simple(text, font_id, color, wrap_width);
|
||||
@@ -928,12 +1168,7 @@ impl FontsView<'_> {
|
||||
///
|
||||
/// The implementation uses memoization so repeated calls are cheap.
|
||||
#[inline]
|
||||
pub fn layout_no_wrap(
|
||||
&mut self,
|
||||
text: String,
|
||||
font_id: FontId,
|
||||
color: crate::Color32,
|
||||
) -> Arc<Galley> {
|
||||
pub fn layout_no_wrap(&mut self, text: String, font_id: FontId, color: Color32) -> Arc<Galley> {
|
||||
let job = LayoutJob::simple(text, font_id, color, f32::INFINITY);
|
||||
self.layout_job(job)
|
||||
}
|
||||
@@ -948,7 +1183,7 @@ impl FontsView<'_> {
|
||||
font_id: FontId,
|
||||
wrap_width: f32,
|
||||
) -> Arc<Galley> {
|
||||
self.layout(text, font_id, crate::Color32::PLACEHOLDER, wrap_width)
|
||||
self.layout(text, font_id, Color32::PLACEHOLDER, wrap_width)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -966,6 +1201,9 @@ pub struct FontsImpl {
|
||||
|
||||
/// Recycled `harfrust` shaping buffer to avoid per-layout allocations.
|
||||
shape_buffer: Option<harfrust::UnicodeBuffer>,
|
||||
glyph_rasterizer: Option<GlyphRasterizer>,
|
||||
raster_glyph_cache: nohash_hasher::IntMap<RasterGlyphCacheKey, Option<RasterGlyphAllocation>>,
|
||||
glyph_source_preference: GlyphSourcePreference,
|
||||
}
|
||||
|
||||
impl FontsImpl {
|
||||
@@ -1000,9 +1238,41 @@ impl FontsImpl {
|
||||
fonts_by_name,
|
||||
family_cache: Default::default(),
|
||||
shape_buffer: Some(harfrust::UnicodeBuffer::new()),
|
||||
glyph_rasterizer: None,
|
||||
raster_glyph_cache: Default::default(),
|
||||
glyph_source_preference: Arc::new(default_glyph_source),
|
||||
}
|
||||
}
|
||||
|
||||
/// Use this platform glyph rasterizer, e.g. the browser on web.
|
||||
///
|
||||
/// See [`GlyphRasterizer`].
|
||||
#[inline]
|
||||
pub fn with_glyph_rasterizer(mut self, glyph_rasterizer: GlyphRasterizer) -> Self {
|
||||
self.set_glyph_rasterizer(Some(glyph_rasterizer));
|
||||
self
|
||||
}
|
||||
|
||||
/// Use this platform glyph rasterizer, e.g. the browser on web.
|
||||
///
|
||||
/// Pass `None` to only use the installed fonts.
|
||||
///
|
||||
/// See [`GlyphRasterizer`].
|
||||
pub fn set_glyph_rasterizer(&mut self, glyph_rasterizer: Option<GlyphRasterizer>) {
|
||||
self.glyph_rasterizer = glyph_rasterizer;
|
||||
self.raster_glyph_cache = Default::default();
|
||||
}
|
||||
|
||||
/// Decide where to look first for the glyphs of each grapheme cluster.
|
||||
///
|
||||
/// See [`GlyphSourcePreference`].
|
||||
pub fn set_glyph_source_preference(
|
||||
&mut self,
|
||||
prefer: impl Fn(&str) -> GlyphSource + Send + Sync + 'static,
|
||||
) {
|
||||
self.glyph_source_preference = Arc::new(prefer);
|
||||
}
|
||||
|
||||
pub fn options(&self) -> &TextOptions {
|
||||
self.atlas.options()
|
||||
}
|
||||
@@ -1040,6 +1310,10 @@ impl FontsImpl {
|
||||
fonts_by_id: &mut self.fonts_by_id,
|
||||
cached_family,
|
||||
atlas: &mut self.atlas,
|
||||
family: family.clone(),
|
||||
glyph_rasterizer: self.glyph_rasterizer.as_ref(),
|
||||
raster_glyph_cache: &mut self.raster_glyph_cache,
|
||||
glyph_source_preference: &self.glyph_source_preference,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -10,8 +10,9 @@ mod text_layout_types;
|
||||
pub use {
|
||||
fonts::{
|
||||
FontData, FontDefinitions, FontFamily, FontId, FontInsert, FontPriority, FontTweak,
|
||||
FontVariationAxis, Fonts, FontsImpl, FontsView, HintingTarget, InsertFontFamily,
|
||||
SmoothHinting,
|
||||
FontVariationAxis, Fonts, FontsImpl, FontsView, GlyphRasterizer, GlyphRasterizerRequest,
|
||||
GlyphSource, GlyphSourcePreference, HintingTarget, InsertFontFamily, MAX_GLYPH_SIZE,
|
||||
RasterizedGlyph, SmoothHinting, default_glyph_source, has_emoji_presentation,
|
||||
},
|
||||
index::{ByteIndex, ByteRange, ByteRangeExt, CharIndex, CharRange, CharRangeExt},
|
||||
text_layout::*,
|
||||
|
||||
@@ -16,9 +16,9 @@ use crate::{
|
||||
};
|
||||
|
||||
use super::{
|
||||
ByteRangeExt as _, FontsImpl, Galley, Glyph, LayoutJob, LayoutSection, PlacedRow, Row,
|
||||
RowVisuals, VariationCoords,
|
||||
font::{Font, FontFace, ShapedGlyph},
|
||||
ByteRangeExt as _, FontsImpl, Galley, Glyph, GlyphSource, LayoutJob, LayoutSection, PlacedRow,
|
||||
Row, RowVisuals, VariationCoords,
|
||||
font::{Font, FontFace, RasterGlyphAllocation, ShapedGlyph},
|
||||
};
|
||||
|
||||
// ----------------------------------------------------------------------------
|
||||
@@ -205,6 +205,7 @@ impl ShapingContext {
|
||||
font_height: self.font_metrics.row_height,
|
||||
font_ascent: self.font_metrics.ascent,
|
||||
uv_rect,
|
||||
is_color: false,
|
||||
section_index: self.section_index,
|
||||
first_vertex: 0,
|
||||
}
|
||||
@@ -219,6 +220,14 @@ struct TextRun {
|
||||
|
||||
/// Byte range within the section text.
|
||||
byte_range: ByteRange,
|
||||
|
||||
/// Where to look first for the glyphs.
|
||||
///
|
||||
/// [`GlyphSource::Fonts`]: shape the whole run with `font_key`.
|
||||
///
|
||||
/// [`GlyphSource::Platform`]: try the glyph rasterizer (if any) for each cluster,
|
||||
/// shaping with `font_key` only if that fails.
|
||||
source: GlyphSource,
|
||||
}
|
||||
|
||||
/// Emit shaped glyphs from a [`harfrust::GlyphBuffer`] into a [`Paragraph`].
|
||||
@@ -303,49 +312,62 @@ fn layout_shaped_run(
|
||||
ctx.prev_cluster = Some(cluster);
|
||||
|
||||
let glyph = if glyph_id == skrifa::GlyphId::NOTDEF {
|
||||
// The shaper couldn't map this character. Drop combining marks
|
||||
// (Unicode category M) and duplicate NOTDEF glyphs within the same
|
||||
// cluster — only the first base character gets a replacement glyph.
|
||||
// The shaper couldn't map this character. Drop combining marks and duplicate
|
||||
// NOTDEF glyphs within the same cluster. The first base character is rasterized,
|
||||
// or rendered as a replacement glyph if no rasterizer can handle the cluster.
|
||||
if is_combining_mark(chr) || !is_new_cluster {
|
||||
continue;
|
||||
}
|
||||
|
||||
// Use the fallback font face (not run.font_key which returned NOTDEF).
|
||||
let fallback_key = font.resolve_face(chr);
|
||||
let fallback_metrics = font
|
||||
.fonts_by_id
|
||||
.get(&fallback_key)
|
||||
.map(|ff| {
|
||||
ff.styled_metrics(ctx.pixels_per_point, ctx.font_size, &Default::default())
|
||||
let cluster_text = run_text
|
||||
.get(cluster as usize..)
|
||||
.and_then(|text| {
|
||||
unicode_segmentation::UnicodeSegmentation::graphemes(text, true).next()
|
||||
})
|
||||
.unwrap_or_default();
|
||||
let (_, glyph_info) = font.glyph_info(chr, &fallback_metrics);
|
||||
let advance_width_px =
|
||||
glyph_info.advance_width_unscaled.0 * fallback_metrics.px_scale_factor;
|
||||
let (glyph_alloc, physical_x) =
|
||||
if let Some(ff) = font.fonts_by_id.get_mut(&fallback_key) {
|
||||
ff.allocate_glyph(
|
||||
font.atlas,
|
||||
&fallback_metrics,
|
||||
&ShapedGlyph {
|
||||
glyph_id: glyph_info.id.unwrap_or(skrifa::GlyphId::NOTDEF),
|
||||
h_pos: paragraph.cursor_x_px,
|
||||
is_cjk: is_cjk(chr),
|
||||
},
|
||||
)
|
||||
} else {
|
||||
Default::default()
|
||||
};
|
||||
|
||||
paragraph.cursor_x_px += advance_width_px;
|
||||
if let Some(raster) =
|
||||
font.rasterize_glyph(cluster_text, ctx.pixels_per_point, ctx.font_size)
|
||||
{
|
||||
raster_glyph(ctx, paragraph, chr, &raster, face_metrics)
|
||||
} else {
|
||||
// Use the fallback font face (not run.font_key which returned NOTDEF).
|
||||
let fallback_key = font.resolve_face(chr);
|
||||
let fallback_metrics = font
|
||||
.fonts_by_id
|
||||
.get(&fallback_key)
|
||||
.map(|ff| {
|
||||
ff.styled_metrics(ctx.pixels_per_point, ctx.font_size, &Default::default())
|
||||
})
|
||||
.unwrap_or_default();
|
||||
let (_, glyph_info) = font.glyph_info(chr, &fallback_metrics);
|
||||
let advance_width_px =
|
||||
glyph_info.advance_width_unscaled.0 * fallback_metrics.px_scale_factor;
|
||||
let (glyph_alloc, physical_x) =
|
||||
if let Some(ff) = font.fonts_by_id.get_mut(&fallback_key) {
|
||||
ff.allocate_glyph(
|
||||
font.atlas,
|
||||
&fallback_metrics,
|
||||
&ShapedGlyph {
|
||||
glyph_id: glyph_info.id.unwrap_or(skrifa::GlyphId::NOTDEF),
|
||||
h_pos: paragraph.cursor_x_px,
|
||||
is_cjk: is_cjk(chr),
|
||||
},
|
||||
)
|
||||
} else {
|
||||
Default::default()
|
||||
};
|
||||
|
||||
ctx.glyph(
|
||||
chr,
|
||||
physical_x,
|
||||
advance_width_px,
|
||||
&fallback_metrics,
|
||||
glyph_alloc.uv_rect,
|
||||
)
|
||||
paragraph.cursor_x_px += advance_width_px;
|
||||
|
||||
ctx.glyph(
|
||||
chr,
|
||||
physical_x,
|
||||
advance_width_px,
|
||||
&fallback_metrics,
|
||||
glyph_alloc.uv_rect,
|
||||
)
|
||||
}
|
||||
} else {
|
||||
let (mut glyph_alloc, physical_x) =
|
||||
if let Some(ff) = font.fonts_by_id.get_mut(&run.font_key) {
|
||||
@@ -393,6 +415,98 @@ fn layout_shaped_run(
|
||||
}
|
||||
}
|
||||
|
||||
/// Emit one glyph for a rasterized cluster and advance the cursor.
|
||||
fn raster_glyph(
|
||||
ctx: &ShapingContext,
|
||||
paragraph: &mut Paragraph,
|
||||
chr: char,
|
||||
raster: &RasterGlyphAllocation,
|
||||
face_metrics: &StyledMetrics,
|
||||
) -> Glyph {
|
||||
let physical_x = paragraph.cursor_x_px.round() as i32;
|
||||
paragraph.cursor_x_px += raster.advance_px;
|
||||
let mut glyph = ctx.glyph(
|
||||
chr,
|
||||
physical_x,
|
||||
raster.advance_px,
|
||||
face_metrics,
|
||||
raster.allocation.uv_rect,
|
||||
);
|
||||
glyph.is_color = raster.is_color;
|
||||
glyph
|
||||
}
|
||||
|
||||
/// Lay out a run whose clusters prefer the glyph rasterizer over the font.
|
||||
///
|
||||
/// Clusters the rasterizer cannot handle are shaped with the run's font face instead.
|
||||
#[must_use]
|
||||
fn layout_raster_run(
|
||||
font: &mut Font<'_>,
|
||||
run: &TextRun,
|
||||
run_text: &str,
|
||||
coords: &VariationCoords,
|
||||
mut shape_buffer: harfrust::UnicodeBuffer,
|
||||
ctx: &mut ShapingContext,
|
||||
paragraph: &mut Paragraph,
|
||||
) -> harfrust::UnicodeBuffer {
|
||||
use unicode_segmentation::UnicodeSegmentation as _;
|
||||
|
||||
let Some(font_face) = font.fonts_by_id.get(&run.font_key) else {
|
||||
return shape_buffer;
|
||||
};
|
||||
let face_metrics = &font_face.styled_metrics(ctx.pixels_per_point, ctx.font_size, coords);
|
||||
|
||||
for (cluster_start, cluster) in run_text.grapheme_indices(true) {
|
||||
let Some(chr) = cluster.chars().next() else {
|
||||
continue;
|
||||
};
|
||||
|
||||
let Some(raster) = font.rasterize_glyph(cluster, ctx.pixels_per_point, ctx.font_size)
|
||||
else {
|
||||
// Shape this one cluster with the font instead.
|
||||
let Some(font_face) = font.fonts_by_id.get(&run.font_key) else {
|
||||
continue;
|
||||
};
|
||||
let glyph_buffer = shape_text(
|
||||
font_face,
|
||||
cluster,
|
||||
coords,
|
||||
shape_buffer,
|
||||
harfrust::BufferFlags::empty(),
|
||||
);
|
||||
let cluster_run = TextRun {
|
||||
font_key: run.font_key,
|
||||
byte_range: run.byte_range.start + cluster_start
|
||||
..run.byte_range.start + cluster_start + cluster.len(),
|
||||
source: GlyphSource::Fonts,
|
||||
};
|
||||
layout_shaped_run(
|
||||
font,
|
||||
&cluster_run,
|
||||
cluster,
|
||||
&glyph_buffer,
|
||||
face_metrics,
|
||||
ctx,
|
||||
paragraph,
|
||||
);
|
||||
shape_buffer = glyph_buffer.clear();
|
||||
continue;
|
||||
};
|
||||
|
||||
if !ctx.is_first_glyph_in_section {
|
||||
paragraph.cursor_x_px += ctx.extra_letter_spacing * ctx.pixels_per_point;
|
||||
}
|
||||
ctx.is_first_glyph_in_section = false;
|
||||
ctx.prev_cluster = None;
|
||||
|
||||
let glyph = raster_glyph(ctx, paragraph, chr, &raster, face_metrics);
|
||||
paragraph.glyphs.push(glyph);
|
||||
emit_continuation_glyphs(ctx, paragraph, cluster, 0..cluster.len(), 1, face_metrics);
|
||||
}
|
||||
|
||||
shape_buffer
|
||||
}
|
||||
|
||||
/// Emit zero-width continuation glyphs when a cluster has more characters than
|
||||
/// shaped glyphs.
|
||||
///
|
||||
@@ -492,28 +606,41 @@ fn layout_section(
|
||||
let face_metrics =
|
||||
font_face.styled_metrics(pixels_per_point, font_size, &format.coords);
|
||||
|
||||
// Set buffer flags for paragraph boundary context.
|
||||
let mut flags = harfrust::BufferFlags::empty();
|
||||
if run_idx == 0 {
|
||||
flags |= harfrust::BufferFlags::BEGINNING_OF_TEXT;
|
||||
if run.source == GlyphSource::Platform && font.glyph_rasterizer.is_some() {
|
||||
shape_buffer = layout_raster_run(
|
||||
font,
|
||||
run,
|
||||
run_text,
|
||||
&format.coords,
|
||||
shape_buffer,
|
||||
&mut ctx,
|
||||
paragraph,
|
||||
);
|
||||
} else {
|
||||
// Set buffer flags for paragraph boundary context.
|
||||
let mut flags = harfrust::BufferFlags::empty();
|
||||
if run_idx == 0 {
|
||||
flags |= harfrust::BufferFlags::BEGINNING_OF_TEXT;
|
||||
}
|
||||
if run_idx + 1 == num_runs {
|
||||
flags |= harfrust::BufferFlags::END_OF_TEXT;
|
||||
}
|
||||
|
||||
let glyph_buffer =
|
||||
shape_text(font_face, run_text, &format.coords, shape_buffer, flags);
|
||||
|
||||
layout_shaped_run(
|
||||
font,
|
||||
run,
|
||||
run_text,
|
||||
&glyph_buffer,
|
||||
&face_metrics,
|
||||
&mut ctx,
|
||||
paragraph,
|
||||
);
|
||||
|
||||
shape_buffer = glyph_buffer.clear();
|
||||
}
|
||||
if run_idx + 1 == num_runs {
|
||||
flags |= harfrust::BufferFlags::END_OF_TEXT;
|
||||
}
|
||||
|
||||
let glyph_buffer = shape_text(font_face, run_text, &format.coords, shape_buffer, flags);
|
||||
|
||||
layout_shaped_run(
|
||||
font,
|
||||
run,
|
||||
run_text,
|
||||
&glyph_buffer,
|
||||
&face_metrics,
|
||||
&mut ctx,
|
||||
paragraph,
|
||||
);
|
||||
|
||||
shape_buffer = glyph_buffer.clear();
|
||||
}
|
||||
}
|
||||
|
||||
@@ -834,6 +961,7 @@ fn replace_last_glyph_with_overflow_character(
|
||||
font_height: font_metrics.row_height,
|
||||
font_ascent: font_metrics.ascent,
|
||||
uv_rect: replacement_glyph_alloc.uv_rect,
|
||||
is_color: false,
|
||||
section_index,
|
||||
first_vertex: 0, // filled in later
|
||||
});
|
||||
@@ -1168,6 +1296,8 @@ fn tessellate_glyphs(point_scale: PointScale, job: &LayoutJob, row: &mut Row, me
|
||||
|
||||
let format = &job.sections[glyph.section_index as usize].format;
|
||||
|
||||
// Color glyphs (e.g. color emoji) are untinted by the tessellator,
|
||||
// which is also where `Color32::PLACEHOLDER` and `override_text_color` are resolved.
|
||||
let color = format.color;
|
||||
|
||||
if format.italics {
|
||||
@@ -1378,9 +1508,11 @@ fn segment_into_runs(font: &mut Font<'_>, text: &str, out: &mut Vec<TextRun>) {
|
||||
|
||||
let base_char = grapheme_str.chars().next().unwrap_or(' ');
|
||||
let font_key = font.resolve_face(base_char);
|
||||
let source = (font.glyph_source_preference)(grapheme_str);
|
||||
|
||||
if let Some(last_run) = out.last_mut()
|
||||
&& last_run.font_key == font_key
|
||||
&& last_run.source == source
|
||||
{
|
||||
last_run.byte_range.end = byte_end;
|
||||
continue;
|
||||
@@ -1388,6 +1520,7 @@ fn segment_into_runs(font: &mut Font<'_>, text: &str, out: &mut Vec<TextRun>) {
|
||||
out.push(TextRun {
|
||||
font_key,
|
||||
byte_range: byte_offset..byte_end,
|
||||
source,
|
||||
});
|
||||
}
|
||||
}
|
||||
@@ -1438,14 +1571,308 @@ fn shape_text(
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use core::iter;
|
||||
use std::sync::Arc;
|
||||
|
||||
use super::{super::*, *};
|
||||
use crate::text::cursor::CCursor;
|
||||
use crate::{ColorImage, text::cursor::CCursor};
|
||||
|
||||
fn test_fonts() -> FontsImpl {
|
||||
FontsImpl::new(TextOptions::default(), FontDefinitions::default())
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn color_raster_glyph_is_not_tinted() {
|
||||
let rasterizer = GlyphRasterizer::new(|request: &GlyphRasterizerRequest<'_>| {
|
||||
(request.cluster == "한").then(|| RasterizedGlyph {
|
||||
image: ColorImage::new([1, 1], vec![Color32::RED]),
|
||||
offset_px: Vec2::ZERO,
|
||||
advance_px: 10.0,
|
||||
is_color: true,
|
||||
})
|
||||
});
|
||||
let mut fonts = FontsImpl::new(TextOptions::default(), FontDefinitions::default())
|
||||
.with_glyph_rasterizer(rasterizer);
|
||||
|
||||
// Returns the tessellated vertex color of 'a' (a normal glyph) and '한' (a color glyph).
|
||||
let mut glyph_colors = |text_color: Color32, override_text_color: Option<Color32>| {
|
||||
let job = LayoutJob::simple(
|
||||
"a한".into(),
|
||||
FontId::proportional(14.0),
|
||||
text_color,
|
||||
f32::INFINITY,
|
||||
);
|
||||
let galley = layout(&mut fonts, 1.0, Arc::new(job));
|
||||
let row = &galley.rows[0].row;
|
||||
assert!(!row.glyphs[0].is_color);
|
||||
assert!(row.glyphs[1].is_color);
|
||||
let first_vertices = [
|
||||
row.glyphs[0].first_vertex as usize,
|
||||
row.glyphs[1].first_vertex as usize,
|
||||
];
|
||||
|
||||
let mut text_shape =
|
||||
crate::TextShape::new(Pos2::ZERO, Arc::new(galley), Color32::GREEN);
|
||||
text_shape.override_text_color = override_text_color;
|
||||
let mut mesh = crate::Mesh::default();
|
||||
crate::Tessellator::new(1.0, Default::default(), [1024, 1024], vec![])
|
||||
.tessellate_text(&text_shape, &mut mesh);
|
||||
first_vertices.map(|i| mesh.vertices[i].color)
|
||||
};
|
||||
|
||||
let half_alpha = Color32::from_white_alpha(128);
|
||||
|
||||
// Explicit text color:
|
||||
assert_eq!(
|
||||
glyph_colors(Color32::BLUE, None),
|
||||
[Color32::BLUE, Color32::WHITE]
|
||||
);
|
||||
|
||||
// Delayed text color, resolved by the tessellator (used by most widgets):
|
||||
assert_eq!(
|
||||
glyph_colors(Color32::PLACEHOLDER, None),
|
||||
[Color32::GREEN, Color32::WHITE]
|
||||
);
|
||||
|
||||
// Override, e.g. for disabled widgets. The alpha should still apply:
|
||||
assert_eq!(
|
||||
glyph_colors(Color32::BLUE, Some(Color32::from_black_alpha(128))),
|
||||
[Color32::from_black_alpha(128), half_alpha]
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn color_raster_glyph_keeps_color_in_atlas() {
|
||||
let rasterizer = GlyphRasterizer::new(|_: &GlyphRasterizerRequest<'_>| {
|
||||
Some(RasterizedGlyph {
|
||||
image: ColorImage::new([1, 1], vec![Color32::RED]),
|
||||
offset_px: Vec2::ZERO,
|
||||
advance_px: 10.0,
|
||||
is_color: true,
|
||||
})
|
||||
});
|
||||
// The default transfer function discards color for regular (white) glyphs:
|
||||
let options = TextOptions {
|
||||
color_transfer_function: crate::FontColorTransferFunction::TwoCoverageMinusCoverageSq,
|
||||
..Default::default()
|
||||
};
|
||||
let mut fonts =
|
||||
Fonts::new(options, FontDefinitions::default()).with_glyph_rasterizer(rasterizer);
|
||||
let galley = fonts.with_pixels_per_point(1.0).layout_no_wrap(
|
||||
"한".into(),
|
||||
FontId::proportional(14.0),
|
||||
Color32::WHITE,
|
||||
);
|
||||
|
||||
let [x, y] = galley.rows[0].row.glyphs[0].uv_rect.min;
|
||||
assert_eq!(fonts.image()[(x as usize, y as usize)], Color32::RED);
|
||||
}
|
||||
|
||||
/// A rasterizer that records the requests it gets and returns a fixed glyph.
|
||||
fn recording_rasterizer(
|
||||
requests: &Arc<crate::mutex::Mutex<Vec<(String, FontFamily)>>>,
|
||||
result: Option<RasterizedGlyph>,
|
||||
) -> GlyphRasterizer {
|
||||
let requests = Arc::clone(requests);
|
||||
GlyphRasterizer::new(move |request: &GlyphRasterizerRequest<'_>| {
|
||||
requests
|
||||
.lock()
|
||||
.push((request.cluster.to_owned(), request.family.clone()));
|
||||
result.as_ref().map(|glyph| RasterizedGlyph {
|
||||
image: glyph.image.clone(),
|
||||
offset_px: glyph.offset_px,
|
||||
advance_px: glyph.advance_px,
|
||||
is_color: glyph.is_color,
|
||||
})
|
||||
})
|
||||
}
|
||||
|
||||
fn white_raster_glyph() -> RasterizedGlyph {
|
||||
RasterizedGlyph {
|
||||
image: ColorImage::new([1, 1], vec![Color32::WHITE]),
|
||||
offset_px: Vec2::ZERO,
|
||||
advance_px: 10.0,
|
||||
is_color: false,
|
||||
}
|
||||
}
|
||||
|
||||
fn color_raster_glyph() -> RasterizedGlyph {
|
||||
RasterizedGlyph {
|
||||
image: ColorImage::new([1, 1], vec![Color32::RED]),
|
||||
is_color: true,
|
||||
..white_raster_glyph()
|
||||
}
|
||||
}
|
||||
|
||||
/// `(chr, is_color, has_pixels)` for each glyph.
|
||||
fn glyph_summary(galley: &Galley) -> Vec<(char, bool, bool)> {
|
||||
galley
|
||||
.rows
|
||||
.iter()
|
||||
.flat_map(|row| &row.row.glyphs)
|
||||
.map(|glyph| (glyph.chr, glyph.is_color, !glyph.uv_rect.is_nothing()))
|
||||
.collect()
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn preferred_clusters_use_rasterizer_before_fonts() {
|
||||
let requests = Arc::new(crate::mutex::Mutex::new(Vec::new()));
|
||||
let rasterizer = recording_rasterizer(&requests, Some(color_raster_glyph()));
|
||||
let mut fonts = FontsImpl::new(TextOptions::default(), FontDefinitions::default())
|
||||
.with_glyph_rasterizer(rasterizer);
|
||||
|
||||
// The bundled fonts have all of these, but 😀 has emoji presentation,
|
||||
// so it should be rasterized, while ⏮ should stay a font glyph.
|
||||
let job = LayoutJob::simple(
|
||||
"a😀⏮".into(),
|
||||
FontId::proportional(14.0),
|
||||
Color32::WHITE,
|
||||
f32::INFINITY,
|
||||
);
|
||||
let galley = layout(&mut fonts, 1.0, Arc::new(job));
|
||||
|
||||
assert_eq!(
|
||||
glyph_summary(&galley),
|
||||
[('a', false, true), ('😀', true, true), ('⏮', false, true)]
|
||||
);
|
||||
assert_eq!(
|
||||
*requests.lock(),
|
||||
[("😀".to_owned(), FontFamily::Proportional)]
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn preferred_cluster_falls_back_to_font_when_rasterizer_fails() {
|
||||
let requests = Arc::new(crate::mutex::Mutex::new(Vec::new()));
|
||||
let rasterizer = recording_rasterizer(&requests, None);
|
||||
let mut fonts = FontsImpl::new(TextOptions::default(), FontDefinitions::default())
|
||||
.with_glyph_rasterizer(rasterizer);
|
||||
let job = LayoutJob::simple(
|
||||
"a😀b".into(),
|
||||
FontId::proportional(14.0),
|
||||
Color32::WHITE,
|
||||
f32::INFINITY,
|
||||
);
|
||||
let galley = layout(&mut fonts, 1.0, Arc::new(job));
|
||||
|
||||
assert_eq!(
|
||||
glyph_summary(&galley),
|
||||
[('a', false, true), ('😀', false, true), ('b', false, true)]
|
||||
);
|
||||
assert_eq!(requests.lock().len(), 1);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn rasterized_sequence_keeps_one_glyph_per_char() {
|
||||
let requests = Arc::new(crate::mutex::Mutex::new(Vec::new()));
|
||||
let rasterizer = recording_rasterizer(&requests, Some(color_raster_glyph()));
|
||||
let mut fonts = FontsImpl::new(TextOptions::default(), FontDefinitions::default())
|
||||
.with_glyph_rasterizer(rasterizer);
|
||||
let family = "👨\u{200D}👩\u{200D}👧";
|
||||
let job = LayoutJob::simple(
|
||||
family.to_owned(),
|
||||
FontId::proportional(14.0),
|
||||
Color32::WHITE,
|
||||
f32::INFINITY,
|
||||
);
|
||||
let galley = layout(&mut fonts, 1.0, Arc::new(job));
|
||||
|
||||
// One visible glyph for the whole cluster, plus zero-width continuation glyphs:
|
||||
let summary = glyph_summary(&galley);
|
||||
assert_eq!(summary.len(), family.chars().count());
|
||||
assert_eq!(summary[0], ('👨', true, true));
|
||||
assert!(summary[1..].iter().all(|(_, _, has_pixels)| !has_pixels));
|
||||
assert_eq!(
|
||||
*requests.lock(),
|
||||
[(family.to_owned(), FontFamily::Proportional)]
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn custom_prefer_predicate() {
|
||||
let requests = Arc::new(crate::mutex::Mutex::new(Vec::new()));
|
||||
let rasterizer = recording_rasterizer(&requests, Some(color_raster_glyph()));
|
||||
let mut fonts = FontsImpl::new(TextOptions::default(), FontDefinitions::default())
|
||||
.with_glyph_rasterizer(rasterizer);
|
||||
fonts.set_glyph_source_preference(|cluster| {
|
||||
if cluster == "b" {
|
||||
GlyphSource::Platform
|
||||
} else {
|
||||
GlyphSource::Fonts
|
||||
}
|
||||
});
|
||||
let job = LayoutJob::simple(
|
||||
"ab😀".into(),
|
||||
FontId::proportional(14.0),
|
||||
Color32::WHITE,
|
||||
f32::INFINITY,
|
||||
);
|
||||
let galley = layout(&mut fonts, 1.0, Arc::new(job));
|
||||
|
||||
assert_eq!(
|
||||
glyph_summary(&galley),
|
||||
[('a', false, true), ('b', true, true), ('😀', false, true)]
|
||||
);
|
||||
assert_eq!(
|
||||
*requests.lock(),
|
||||
[("b".to_owned(), FontFamily::Proportional)]
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn raster_glyph_cache_is_keyed_by_family() {
|
||||
let requests = Arc::new(crate::mutex::Mutex::new(Vec::new()));
|
||||
let rasterizer = recording_rasterizer(&requests, Some(white_raster_glyph()));
|
||||
let mut fonts = FontsImpl::new(TextOptions::default(), FontDefinitions::default())
|
||||
.with_glyph_rasterizer(rasterizer);
|
||||
|
||||
for family in [FontFamily::Proportional, FontFamily::Monospace] {
|
||||
let job = LayoutJob::simple(
|
||||
"한".into(),
|
||||
FontId::new(14.0, family),
|
||||
Color32::WHITE,
|
||||
f32::INFINITY,
|
||||
);
|
||||
layout(&mut fonts, 1.0, Arc::new(job));
|
||||
}
|
||||
|
||||
assert_eq!(
|
||||
*requests.lock(),
|
||||
vec![
|
||||
("한".to_owned(), FontFamily::Proportional),
|
||||
("한".to_owned(), FontFamily::Monospace),
|
||||
]
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn raster_glyph_failure_is_cached_and_falls_back_to_replacement() {
|
||||
let requests = Arc::new(crate::mutex::Mutex::new(Vec::new()));
|
||||
let rasterizer = recording_rasterizer(&requests, None);
|
||||
let mut fonts = FontsImpl::new(TextOptions::default(), FontDefinitions::default())
|
||||
.with_glyph_rasterizer(rasterizer);
|
||||
let job = Arc::new(LayoutJob::simple(
|
||||
"한".into(),
|
||||
FontId::proportional(14.0),
|
||||
Color32::WHITE,
|
||||
f32::INFINITY,
|
||||
));
|
||||
|
||||
let galley = layout(&mut fonts, 1.0, Arc::clone(&job));
|
||||
layout(&mut fonts, 1.0, job);
|
||||
|
||||
assert_eq!(requests.lock().len(), 1, "Failures should be cached");
|
||||
let glyph = &galley.rows[0].row.glyphs[0];
|
||||
assert_eq!(glyph.chr, '한');
|
||||
assert!(
|
||||
!glyph.uv_rect.is_nothing(),
|
||||
"Should render the replacement glyph"
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_zero_max_width() {
|
||||
let pixels_per_point = 1.0;
|
||||
let mut fonts = FontsImpl::new(TextOptions::default(), FontDefinitions::default());
|
||||
let mut fonts = test_fonts();
|
||||
let mut layout_job = LayoutJob::single_section("W".into(), TextFormat::default());
|
||||
layout_job.wrap.max_width = 0.0;
|
||||
let galley = layout(&mut fonts, pixels_per_point, layout_job.into());
|
||||
@@ -1458,7 +1885,7 @@ mod tests {
|
||||
|
||||
let pixels_per_point = 1.0;
|
||||
|
||||
let mut fonts = FontsImpl::new(TextOptions::default(), FontDefinitions::default());
|
||||
let mut fonts = test_fonts();
|
||||
let text_format = TextFormat {
|
||||
font_id: FontId::monospace(12.0),
|
||||
..Default::default()
|
||||
@@ -1504,7 +1931,7 @@ mod tests {
|
||||
#[test]
|
||||
fn test_cjk() {
|
||||
let pixels_per_point = 1.0;
|
||||
let mut fonts = FontsImpl::new(TextOptions::default(), FontDefinitions::default());
|
||||
let mut fonts = test_fonts();
|
||||
let mut layout_job = LayoutJob::single_section(
|
||||
"日本語とEnglishの混在した文章".into(),
|
||||
TextFormat::default(),
|
||||
@@ -1520,7 +1947,7 @@ mod tests {
|
||||
#[test]
|
||||
fn test_pre_cjk() {
|
||||
let pixels_per_point = 1.0;
|
||||
let mut fonts = FontsImpl::new(TextOptions::default(), FontDefinitions::default());
|
||||
let mut fonts = test_fonts();
|
||||
let mut layout_job = LayoutJob::single_section(
|
||||
"日本語とEnglishの混在した文章".into(),
|
||||
TextFormat::default(),
|
||||
@@ -1536,7 +1963,7 @@ mod tests {
|
||||
#[test]
|
||||
fn test_truncate_width() {
|
||||
let pixels_per_point = 1.0;
|
||||
let mut fonts = FontsImpl::new(TextOptions::default(), FontDefinitions::default());
|
||||
let mut fonts = test_fonts();
|
||||
let mut layout_job =
|
||||
LayoutJob::single_section("# DNA\nMore text".into(), TextFormat::default());
|
||||
layout_job.wrap.max_width = f32::INFINITY;
|
||||
@@ -1555,7 +1982,7 @@ mod tests {
|
||||
|
||||
#[test]
|
||||
fn test_truncate_with_pixels_per_point() {
|
||||
let mut fonts = FontsImpl::new(TextOptions::default(), FontDefinitions::default());
|
||||
let mut fonts = test_fonts();
|
||||
|
||||
for pixels_per_point in [
|
||||
0.33, 0.5, 0.67, 1.0, 1.25, 1.33, 1.5, 1.75, 2.0, 3.0, 4.0, 5.0,
|
||||
@@ -1593,7 +2020,7 @@ mod tests {
|
||||
#[test]
|
||||
fn test_empty_row() {
|
||||
let pixels_per_point = 1.0;
|
||||
let mut fonts = FontsImpl::new(TextOptions::default(), FontDefinitions::default());
|
||||
let mut fonts = test_fonts();
|
||||
|
||||
let font_id = FontId::default();
|
||||
let font_height = fonts
|
||||
@@ -1626,7 +2053,7 @@ mod tests {
|
||||
#[test]
|
||||
fn test_end_with_newline() {
|
||||
let pixels_per_point = 1.0;
|
||||
let mut fonts = FontsImpl::new(TextOptions::default(), FontDefinitions::default());
|
||||
let mut fonts = test_fonts();
|
||||
|
||||
let font_id = FontId::default();
|
||||
let font_height = fonts
|
||||
@@ -1664,7 +2091,7 @@ mod tests {
|
||||
// Note: the default fonts don't contain U+0254, so the replacement glyph
|
||||
// is used. The key test is that the combining mark does NOT add extra width.
|
||||
let pixels_per_point = 1.0;
|
||||
let mut fonts = FontsImpl::new(TextOptions::default(), FontDefinitions::default());
|
||||
let mut fonts = test_fonts();
|
||||
|
||||
let job_combined = LayoutJob::simple(
|
||||
"ɔ\u{0303}".to_owned(),
|
||||
@@ -1699,7 +2126,7 @@ mod tests {
|
||||
fn test_shaping_basic_latin() {
|
||||
// Basic test: shaped Latin text should produce the same number of glyphs as characters.
|
||||
let pixels_per_point = 1.0;
|
||||
let mut fonts = FontsImpl::new(TextOptions::default(), FontDefinitions::default());
|
||||
let mut fonts = test_fonts();
|
||||
|
||||
let job = LayoutJob::simple(
|
||||
"Hello".to_owned(),
|
||||
@@ -1717,7 +2144,7 @@ mod tests {
|
||||
#[test]
|
||||
fn test_shaping_empty_string() {
|
||||
let pixels_per_point = 1.0;
|
||||
let mut fonts = FontsImpl::new(TextOptions::default(), FontDefinitions::default());
|
||||
let mut fonts = test_fonts();
|
||||
|
||||
let job = LayoutJob::simple(
|
||||
String::new(),
|
||||
@@ -1734,7 +2161,7 @@ mod tests {
|
||||
#[test]
|
||||
fn test_shaping_multiple_newlines() {
|
||||
let pixels_per_point = 1.0;
|
||||
let mut fonts = FontsImpl::new(TextOptions::default(), FontDefinitions::default());
|
||||
let mut fonts = test_fonts();
|
||||
|
||||
let job = LayoutJob::simple(
|
||||
"A\n\nB".to_owned(),
|
||||
@@ -1755,7 +2182,7 @@ mod tests {
|
||||
// Text with both Latin and emoji should work without panicking,
|
||||
// even though they use different font faces.
|
||||
let pixels_per_point = 1.0;
|
||||
let mut fonts = FontsImpl::new(TextOptions::default(), FontDefinitions::default());
|
||||
let mut fonts = test_fonts();
|
||||
|
||||
let job = LayoutJob::simple(
|
||||
"Hi 🎉 bye".to_owned(),
|
||||
@@ -1781,7 +2208,7 @@ mod tests {
|
||||
// only uses the legacy `kern` table, so these pairs had diff ≈ 0.
|
||||
// With harfrust, GPOS kerning applies proper negative adjustments.
|
||||
let pixels_per_point = 1.0;
|
||||
let mut fonts = FontsImpl::new(TextOptions::default(), FontDefinitions::default());
|
||||
let mut fonts = test_fonts();
|
||||
let font_id = FontId::proportional(14.0);
|
||||
|
||||
for pair in ["AV", "VA", "AT"] {
|
||||
@@ -1819,7 +2246,7 @@ mod tests {
|
||||
#[test]
|
||||
fn test_grapheme_cluster_glyph_count() {
|
||||
let pixels_per_point = 1.0;
|
||||
let mut fonts = FontsImpl::new(TextOptions::default(), FontDefinitions::default());
|
||||
let mut fonts = test_fonts();
|
||||
let font_id = FontId::default();
|
||||
|
||||
// Each test case: (input text, expected char count)
|
||||
@@ -1879,7 +2306,7 @@ mod tests {
|
||||
#[test]
|
||||
fn test_grapheme_cluster_cursor_roundtrip() {
|
||||
let pixels_per_point = 1.0;
|
||||
let mut fonts = FontsImpl::new(TextOptions::default(), FontDefinitions::default());
|
||||
let mut fonts = test_fonts();
|
||||
let font_id = FontId::default();
|
||||
|
||||
// "A" + flag emoji (2 codepoints) + "B" = 4 chars
|
||||
|
||||
@@ -915,6 +915,9 @@ pub struct Glyph {
|
||||
/// Position and size of the glyph in the font texture, in texels.
|
||||
pub uv_rect: UvRect,
|
||||
|
||||
/// Whether this glyph carries its own color, e.g. a color emoji.
|
||||
pub is_color: bool,
|
||||
|
||||
/// Index into [`LayoutJob::sections`]. Decides color etc.
|
||||
///
|
||||
/// Only used during layout, then set to an invalid value in order to
|
||||
|
||||
Reference in new issue
Block a user